@ai-matrx/records-ui 0.116.111 → 0.116.113
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 +35 -2
- package/dist/{SaveToTable-PDRY5OXB.js → SaveToTable-GRDFTAC4.js} +3 -3
- package/dist/{chunk-266JKBAS.js → chunk-DZ4KNUSS.js} +1 -1
- package/dist/chunk-DZ4KNUSS.js.map +1 -0
- package/dist/{chunk-HTZPVHDG.js → chunk-LGQLATW5.js} +7 -7
- package/dist/{chunk-HTZPVHDG.js.map → chunk-LGQLATW5.js.map} +1 -1
- package/dist/{chunk-FD4GYJX6.js → chunk-N76I4VXM.js} +4 -3
- package/dist/{chunk-FD4GYJX6.js.map → chunk-N76I4VXM.js.map} +1 -1
- package/dist/entity-ref.cjs +1 -1
- package/dist/entity-ref.cjs.map +1 -1
- package/dist/entity-ref.d.cts +4 -1
- package/dist/entity-ref.d.ts +4 -1
- package/dist/entity-ref.js +1 -1
- package/dist/entity-ref.js.map +1 -1
- package/dist/helpers.cjs +4 -4
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +11 -3
- package/dist/helpers.d.ts +11 -3
- package/dist/helpers.js +4 -4
- package/dist/helpers.js.map +1 -1
- package/dist/index.cjs +76 -71
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.js +73 -69
- package/dist/index.js.map +1 -1
- package/dist/pickers.cjs.map +1 -1
- package/dist/pickers.js +2 -2
- package/package.json +2 -2
- package/dist/chunk-266JKBAS.js.map +0 -1
- /package/dist/{SaveToTable-PDRY5OXB.js.map → SaveToTable-GRDFTAC4.js.map} +0 -0
package/dist/helpers.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dataSource.ts","../src/personZone.ts","../src/rights.ts","../src/tableRights.ts","../src/names.ts","../src/whoChanged.ts","../src/withheldNotice.ts","../src/choiceLooks.ts","../src/docs.ts","../src/fieldTypes.ts","../src/parity.ts","../src/tablePickerEntries.ts","../src/presentation.ts","../src/pages.ts","../src/interfaces.ts","../src/tableLanes.ts","../src/bodyField.ts","../src/viewKeys.ts","../src/viewLook.ts","../src/views.ts","../src/viewAddressParams.ts","../src/calendarFeed.ts","../src/enumLabels.ts","../src/standardFieldChoices.ts","../src/plainWords.ts","../src/codeDependsRefusal.ts","../src/announceTableArchived.ts","../src/skeletonLayout.ts","../src/gridAgentContext.ts","../src/objectActions.ts","../src/recordActions.ts"],"names":["globalSlot","setColorRuleTimeZone","setDisplayTimeZone","setReadersTimeZone","atLeast","humanizeIdentifier","isUuidShape","formatRelativeTime","DECLARABLE_FIELD_KINDS","NEWER_FIELD_KINDS","KERNEL_TABLES","PARITY_FIELD_TYPES","fieldKindFor","isButtonField","newerKindOf","momentZoneOptions","parseTableStyle","tableStyleIsEmpty","raw","base","PLATFORM_TABLE_PREFIX","state","toDelimited","formatTapShortcut"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,SAAS,YAAY,MAAA,EAA+C;AACzE,EAAA,OAAO,MAAA,GAAS,EAAE,KAAA,EAAO,MAAA,EAAQ,SAAS,MAAA,EAAO,GAAI,EAAE,KAAA,EAAO,MAAA,EAAO;AACvE;AA4CA,IAAM,cAAcA,qBAAA,CAAW,kCAAA,EAAoC,sBAAM,IAAI,SAAiD,CAAA;AAEvH,SAAS,iBAAA,CAAkB,MAAA,EAAgB,cAAA,GAAiB,QAAA,EAA6B;AAC9F,EAAA,IAAI,QAAA,GAAW,WAAA,CAAY,GAAA,CAAI,MAAM,CAAA;AACrC,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,QAAA,uBAAe,GAAA,EAAI;AACnB,IAAA,WAAA,CAAY,GAAA,CAAI,QAAQ,QAAQ,CAAA;AAAA,EAClC;AACA,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,GAAA,CAAI,cAAc,CAAA;AAC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I,aAAA,EAAe,KAAA,EAAO,uBAAkB,IAAA,EAAM,QAAA,EAAU,KAAA,EAAO,UAAA,IAAc,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,IAAA,EAAM,MAAM,CAAC,CAAA;AAAA;AAAA,IAEhI,OAAO,EAAE,EAAA,EAAI,cAAA,EAAgB,KAAA,EAAO,2BAAsB,IAAA,EAAM,WAAA,EAAa,KAAA,EAAO,UAAA,IAAc,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,WAAA,EAAa,MAAM,CAAC,CAAA;AAAA,IAC/I,OAAO,EAAE,EAAA,EAAI,WAAW,KAAA,EAAO,SAAA,EAAW,MAAM,SAAA,EAAW,KAAA,EAAO,UAAU,IAAA,EAAM,SAAA,IAAa,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,OAAA,EAAS,MAAM,CAAC,CAAA;AAAA,IACxI,MAAA;AAAA,MACE,EAAE,EAAA,EAAI,SAAA,EAAW,KAAA,EAAO,gBAAA,EAAkB,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,QAAA,EAAU,WAAA,EAAa,IAAA,EAAM,IAAA,EAAM,SAAA,EAAU;AAAA,MAC/G,QAAA;AAAA,MACA,KAAA;AAAA,MACA,IAAA,CAAK,IAAA,CAAK,OAAA,EAAS,MAAM;AAAA;AAC3B,GACF;AACA,EAAA,OAAO,cAAA,CAAe,KAAA,EAAO,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,KAAA,CAAM,MAAM,CAAA,GAAI,EAAE,CAAA;AACnF","file":"helpers.cjs","sourcesContent":["// src/dataSource.ts — @ai-matrx/records-ui (pure; also served alone by `@ai-matrx/records-ui/helpers`)\n//\n// The two helpers every host calls before it draws anything: who is acting (`personActor`) and the\n// store's data seam over a supabase-js client (`recordsDataSource`). No React and no screen here, so\n// a service, a registry or a server module that needs only these never pulls the package's screens.\n// `RecordsMount` re-exports both, so the root entry keeps them.\n\nimport type { RecordsActor, RecordsDataSource, Uuid } from \"@ai-matrx/records\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\nexport function personActor(userId: Uuid | null | undefined): RecordsActor {\n return userId ? { actor: \"user\", user_id: userId } : { actor: \"user\" };\n}\n\n/**\n * A supabase-js client AS this package's data seam.\n *\n * `RecordsDataSource` is deliberately a small structural subset of\n * `SupabaseClient` — the package holds no key and opens no connection, the host\n * hands it a client that already carries the person's session.\n *\n * IT IS NOT AN IDENTITY CAST, and it cost a live screen to learn why\n * (2026-09-19, /data's first load): the port's `rpc(fn, args, { schema })`\n * says the schema OUT LOUD, because every door of this store is `custom.<name>`\n * and every door of the trust layer is `iam.<name>`. supabase-js's own\n * `rpc(fn, args, options)` has no `schema` option at all — its third argument is\n * `{ head, get, count }` — so a client passed straight through silently asked\n * its default PostgREST profile and the store answered, correctly and uselessly,\n * \"Could not find the function public.table_kernel_id ... PGRST202\". The schema\n * is chosen the one way supabase-js offers: `client.schema(name).rpc(...)`.\n *\n * `schema(name).from(table)` already agrees structurally and is passed through.\n *\n * `fallbackSchema` is the profile a call that says NOTHING is sent to. No caller\n * in `@ai-matrx/records` omits the option — `callDoor` always says `custom` and\n * `trustDoor` always says `iam` — so it never fires today; it exists so that a\n * call which one day forgets lands on the store rather than silently on\n * `public`. It is a FALLBACK and not the answer: a version of this adapter that\n * sent EVERY door to one fixed schema would route the `iam` trust doors (the\n * external principal, the publish binding) into `custom` and get a PGRST202\n * naming the wrong schema.\n *\n * The cast itself stays HERE, once, where it is explained: a generated\n * `Database` type makes `schema().from().select()` enormous, and a host app that\n * passes its client straight into `config` gets `TS2589: Type instantiation is\n * excessively deep and possibly infinite` in its own build (matrx-frontend,\n * 2026-09-18, on all three campaign routes at once).\n */\n/*\n * ONE DATA SOURCE PER SUPABASE CLIENT (owner, 2026-10-02). The record store's data layer keys its\n * cache by the data source object, so a host that builds this adapter again on every mount (a\n * board tile woken or brought back by Undo) must get the SAME object back for the same client —\n * otherwise every remount is a stranger to the answers the last mount read.\n */\n// One cache per realm, never per bundle copy: this module ships in BOTH the root entry and\n// `@ai-matrx/records-ui/helpers` (`splitting: false`), and a module `let` would split it in two.\nconst dataSources = globalSlot(\"ai-matrx.records-ui.data-sources\", () => new WeakMap<object, Map<string, RecordsDataSource>>());\n\nexport function recordsDataSource(client: object, fallbackSchema = \"custom\"): RecordsDataSource {\n let bySchema = dataSources.get(client);\n if (!bySchema) {\n bySchema = new Map();\n dataSources.set(client, bySchema);\n }\n const held = bySchema.get(fallbackSchema);\n if (held) return held;\n const made = makeRecordsDataSource(client, fallbackSchema);\n bySchema.set(fallbackSchema, made);\n return made;\n}\n\nfunction makeRecordsDataSource(client: object, fallbackSchema: string): RecordsDataSource {\n const supabase = client as unknown as {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n schema: (name: string) => {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n from: (table: string) => unknown;\n };\n auth?: { getSession?: () => Promise<{ data?: { session?: unknown } | null }> };\n };\n return {\n // PAGE-BUNDLE: the real adapter opens a table page with one `custom.table_page_bundle` call.\n opensInOneCall: true,\n async rpc(fn, args, options) {\n const schema = options?.schema ?? fallbackSchema;\n // 🚨 NO STORE DOOR LEAVES WITHOUT A PERSON (lane MONITOR-TRIAGE, 2026-10-01). `anon` holds\n // no USAGE on schema `custom`, so a door called with no session can only come back\n // \"42501 permission denied for schema custom\" (HTTP 401) — seven of them per signed-out\n // /data load (inbox, counts, home, portals…), every one a red row in ops.system_error.\n // A `custom` door with no session is answered HERE, with the store's own signed-out\n // sentence and no network call. Other schemas (`iam`, `platform`) serve guests by design\n // and are never short-circuited. A client without `auth` (a server or test seam) is\n // passed straight through.\n const getSession = schema === \"custom\" ? sessionReader(supabase) : undefined;\n if (getSession && !(await hasSession(getSession))) {\n return { data: null, error: SIGNED_OUT } as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n }\n const on = supabase.schema(schema);\n return (await on.rpc(fn, args)) as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n },\n schema(name) {\n return supabase.schema(name) as ReturnType<RecordsDataSource[\"schema\"]>;\n },\n };\n}\n\n/**\n * THE CLIENT'S OWN SESSION READER, or none. A TOKEN-ONLY client (supabase-js `createClient(url,\n * key, { accessToken })`: Matrx 2's window, any host whose session lives elsewhere) carries the\n * person on EVERY request and has no auth of its own: supabase-js answers any read of `client.auth`\n * on it by THROWING (\"accessing supabase.auth.getSession is not possible\"). Read bare, that throw\n * left every door of the store before a single request was sent and each one was shown as \"We\n * could not reach your data\" (Matrx 2 Data › Tables, 2026-10-21). Such a client is passed through\n * and the database's answer stands, as for a client without `auth`.\n */\nfunction sessionReader(supabase: { auth?: { getSession?: () => Promise<{ data?: { session?: unknown } | null }> } }): (() => Promise<{ data?: { session?: unknown } | null }>) | undefined {\n try {\n const auth = supabase.auth;\n const getSession = auth?.getSession;\n return typeof getSession === \"function\" ? () => getSession.call(auth) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The read door's own sentence for a call with nobody signed in (`custom.read_records_page`, DOOR-1). */\nconst SIGNED_OUT = {\n code: \"42501\",\n message: \"Nobody is signed in, so there is nothing to read.\",\n hint: \"Sign in, then try again.\",\n details: null,\n} as const;\n\nasync function hasSession(getSession: () => Promise<{ data?: { session?: unknown } | null }>): Promise<boolean> {\n try {\n const answer = await getSession();\n return Boolean(answer?.data?.session);\n } catch {\n // Auth could not say: let the request go and the database's answer stand.\n return true;\n }\n}\n","// The person's time zone, as the app saved it (userPreferences.display.timeZone).\n//\n// The host app tells this package once (`setPersonTimeZone(\"America/Los_Angeles\")`); every \"today\" and\n// \"now\" a screen draws (the calendar's today marker and now-line, a timeline's today, a date picker's\n// today) is read in that zone instead of the device's. With nothing set the device zone applies, as before.\n// Nothing here stores a zone: the host's saved preference is the one place, this is its mirror.\n\nimport { setColorRuleTimeZone, setDisplayTimeZone } from \"@ai-matrx/design-system/data-table/table-style\";\nimport { setReadersTimeZone } from \"@ai-matrx/records\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\n// No React here: `@ai-matrx/records-ui/helpers` serves this file alone (the host sets the zone at\n// boot), and the root entry carries its own copy — so the zone lives in ONE realm-wide slot that\n// both copies read, never a module `let` that would split in two. The hook is `./personTime`.\nconst state = globalSlot(\"ai-matrx.records-ui.person-time-zone\", () => ({\n zone: null as string | null,\n listeners: new Set<() => void>(),\n}));\n\nfunction valid(z: unknown): z is string {\n if (typeof z !== \"string\" || !z.trim()) return false;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: z });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The host app's saved zone (IANA). `null` / junk clears it: the device zone applies. */\nexport function setPersonTimeZone(next: string | null | undefined): void {\n const clean = valid(next) ? next : null;\n if (clean === state.zone) return;\n state.zone = clean;\n // \"Today\" in a color rule is the person's day, not the device's (lane NOTION-SMALL-2).\n setColorRuleTimeZone(clean);\n // And every moment a screen prints (grid cell, panel, card, export) reads in it too: ONE zone, one slot.\n setDisplayTimeZone(clean);\n // And a relative day (\"Today\", \"Overdue\") a view asks the store is cut in it before it is sent (ADVERSARIAL-11 F3).\n setReadersTimeZone(clean);\n state.listeners.forEach((l) => l());\n}\n\nexport function getPersonTimeZone(): string | null {\n return state.zone;\n}\n\n/** Calls `listener` whenever the zone changes; returns the unsubscribe. */\nexport function subscribePersonTimeZone(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => {\n state.listeners.delete(listener);\n };\n}\n\n/**\n * `at` as a Date whose LOCAL fields (getFullYear, getHours, ...) read the wall clock in the person's zone.\n * For day / hour math only: never compare it with a stored instant.\n */\nexport function personWallNow(at: Date = new Date()): Date {\n const zone = state.zone;\n if (!zone) return at;\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(at);\n const n = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n return new Date(n(\"year\"), n(\"month\") - 1, n(\"day\"), n(\"hour\"), n(\"minute\"), n(\"second\"));\n}\n\n/**\n * The inverse of `personWallNow`: the INSTANT at which the person's wall clock reads the local fields\n * of `wall` (getFullYear, getHours, ...). A calendar drop at \"9:30 on Nov 3\" writes this, so the card\n * reads 9:30 on Nov 3 again in the person's zone. With no zone set it is `wall` itself (device zone).\n */\nexport function instantFromPersonWall(wall: Date): Date {\n const zone = state.zone;\n if (!zone) return wall;\n const target = Date.UTC(wall.getFullYear(), wall.getMonth(), wall.getDate(), wall.getHours(), wall.getMinutes(), wall.getSeconds(), wall.getMilliseconds());\n let guess = target;\n for (let i = 0; i < 3; i += 1) {\n const seen = personWallNow(new Date(guess));\n const shown = Date.UTC(seen.getFullYear(), seen.getMonth(), seen.getDate(), seen.getHours(), seen.getMinutes(), seen.getSeconds(), wall.getMilliseconds());\n guess -= shown - target;\n }\n return new Date(guess);\n}\n","// src/rights.ts — @ai-matrx/records-ui\n//\n// THE ONE PLACE A LEVEL BECOMES A SCREEN.\n//\n// WHAT A PERSON HIT (independent verdict, sixth pass, 19-20 September). A\n// colleague who had been shared a table at viewer opened it, double-clicked a\n// cell, got a live editor, typed a value and pressed Enter — and only THEN was\n// told she may not write. \"The permission is right; the screen told her she\n// could.\" Measured against Airtable, Notion and Linear the verdict called it\n// out by name: \"None of these three products lets you start an action it\n// already knows it will reject.\"\n//\n// WHY THE SCREEN COULD NOT KNOW. The rights question was a PORT with two honest\n// answers and no third: `NO_RIGHTS` (every administering control absent, which\n// is useless for a host whose authority IS the store's) and\n// `storeDecidesRights` — `{admin: true, comment: true, write: true}` for every\n// non-kernel table, for everybody. That second one is the defect, written down:\n// it is the screen ASSUMING the answer and letting the door say no afterwards.\n//\n// WHAT REPLACES IT. The store already answers this, and the client now carries\n// it: `custom.read_records` returns the reader's level on the TABLE on every\n// row (so `Table.your_level` costs nothing), and `custom.my_levels` — the door\n// this lane added — answers the caller's level on any subject they name, one\n// call for a whole page. This file is the only place in the package that turns\n// one of those four words into what a screen may DRAW.\n//\n// THE LADDER IS THE STORE'S, NOT OURS: viewer < commenter < editor < admin, and\n// which rung each door requires is read from the doors themselves —\n// `custom.record_update` asserts `editor` on the record, `custom.field_declare`\n// asserts `admin` on the TABLE (\"the SHAPE of this table, which is an admin's\n// right and not an editor's\"), `custom.io_comment_write` admits a commenter.\n// Nothing here invents a rule; it mirrors the four assertions those doors make\n// and is wrong the moment they change, which is what the suite is for.\n//\n// ABSENT OR HONEST, NEVER DEAD. Every `false` here carries the sentence that\n// says why and what to do about it, so a control can be left out AND explained.\n// A screen that hid a control with nothing to say is the silent half of the\n// same defect.\n\nimport { atLeast, type PermissionLevel } from \"@ai-matrx/records/field-kinds\";\nimport type { Table } from \"@ai-matrx/records\";\n\n/** The six things a person does to a record or a table, as the screens offer them. */\nexport type Capability = \"read\" | \"comment\" | \"write\" | \"organise\" | \"remove\" | \"share\" | \"structure\";\n\nexport interface WhatYouMayDo {\n /** The word the store answered, or null when it answered nothing. */\n level: PermissionLevel | null;\n /**\n * Whether the store has ANSWERED yet. `false` is a third state and not a\n * refusal: a screen that drew \"you may not\" while the answer was in flight\n * would blink every control off on every reload, which is its own lie.\n */\n known: boolean;\n read: boolean;\n comment: boolean;\n write: boolean;\n /** Duplicate, merge, restore, make a layout the default: the doors that ask `editor`, above content. */\n organise: boolean;\n remove: boolean;\n share: boolean;\n structure: boolean;\n /** Why this person may not do that, in one sentence naming the way in. */\n why: (what: Capability) => string;\n}\n\n/** What each rung of the ladder is called where a person reads it. */\nexport const LEVEL_WORD: Record<PermissionLevel, string> = {\n viewer: \"View access\",\n commenter: \"Comment access\",\n edit_content: \"Edit access\",\n editor: \"Edit access\",\n admin: \"Full access\",\n};\n\n/**\n * WHICH RUNG EACH DOOR ASKS FOR. Read off the doors themselves, in one place,\n * so a screen never re-decides it and the suite has one thing to check.\n */\nconst NEEDS: Record<Capability, PermissionLevel> = {\n read: \"viewer\",\n // custom.io_comment_write\n comment: \"commenter\",\n // custom.record_update / custom.record_write — `edit_content` changes rows and page content;\n // columns, views and settings (structure) stay with admin below, and sharing with admin.\n write: \"edit_content\",\n // custom.view_designate / view_declare / migrate_merge / record_restore — all ask `editor`: more than\n // changing content (`edit_content`), less than changing columns (`admin`).\n organise: \"editor\",\n // custom.record_delete\n remove: \"editor\",\n // custom.share_grant — ONE-LADDER (2026-10-10): Edit may pass View / Comment / Edit on inside the\n // organization (iam.may_grant_as, knobs access.sharing/*). Which levels, and to whom, is the share\n // dialog's own question (iam.my_grantable_levels); the Share button only has to open for Edit.\n share: \"editor\",\n // custom.field_declare / field_update / field_retire / table settings\n structure: \"admin\",\n};\n\n/** The rung a capability asks for — so a short \"Needs Full access\" never re-decides the ladder. */\nexport function levelNeededFor(what: Capability): PermissionLevel {\n return NEEDS[what];\n}\n\nconst NOT_YET =\n \"Checking what you may do here. Nothing is offered until then.\";\n\nconst NOTHING_AT_ALL =\n \"You have not been given this. Ask somebody with Full access on it to share it with you.\";\n\n/** The sentence for one refusal: what the level is, what it would have to be. */\nfunction sentenceFor(what: Capability, level: PermissionLevel | null): string {\n if (level === null) return NOTHING_AT_ALL;\n const need = LEVEL_WORD[NEEDS[what]];\n const have = LEVEL_WORD[level];\n const doing: Record<Capability, string> = {\n read: \"open this\",\n comment: \"leave a comment\",\n write: \"change anything here\",\n organise: \"organize this\",\n remove: \"delete this\",\n share: \"pass this on to somebody else\",\n structure: \"change the columns of this table\",\n };\n return `You have ${have} here, and it takes ${need} to ${doing[what]}. Ask somebody with Full access on it to move you up.`;\n}\n\n/**\n * WHAT ONE LEVEL LETS A PERSON DO. `level` null and `known` true means the\n * store said \"nothing\" — a real answer. `known` false means it has not said.\n */\nexport function whatYouMayDo(level: PermissionLevel | null, known = true): WhatYouMayDo {\n const may = (what: Capability) => known && atLeast(level, NEEDS[what]);\n return {\n level: known ? level : null,\n known,\n read: may(\"read\"),\n comment: may(\"comment\"),\n write: may(\"write\"),\n organise: may(\"organise\"),\n remove: may(\"remove\"),\n share: may(\"share\"),\n structure: may(\"structure\"),\n why: (what) => (known ? sentenceFor(what, level) : NOT_YET),\n };\n}\n\n/** Nothing offered, because nothing is known yet. */\nexport const NOT_ANSWERED_YET: WhatYouMayDo = whatYouMayDo(null, false);\n\n/**\n * REC-27. The nine Tables the platform ships are not administered from a\n * person's screen whatever level they hold on them — so the structure controls\n * are absent for a kernel Table and say why, and everything else follows the\n * level as usual.\n */\nexport const KERNEL_REASON =\n \"This is one of the tables the platform ships, so its columns are not changed from a screen. \" +\n \"Make your own table to change columns.\";\n\nexport function whatYouMayDoWithTable(\n table: Table | null | undefined,\n level: PermissionLevel | null,\n known: boolean,\n): WhatYouMayDo {\n const base = whatYouMayDo(level, known);\n // A LOCKED DATABASE (lane NOTION-SMALL-2): the columns and the table's settings stay as they are until\n // somebody unlocks it. An editing convenience, never a permission — the lock changes what is OFFERED, the\n // store's ladder is untouched and anyone who may edit the table may unlock it.\n if (!table?.is_kernel) return table && tableIsLocked(table) ? lockedStructure(base) : base;\n return {\n ...base,\n structure: false,\n why: (what) => (what === \"structure\" ? KERNEL_REASON : base.why(what)),\n };\n}\n\n/** Is this table locked against column and settings changes? Kept on the table's own metadata. */\nexport function tableIsLocked(table: Pick<Table, \"metadata\"> | null | undefined): boolean {\n return table?.metadata?.[\"locked\"] === true;\n}\n\nexport const DATABASE_LOCKED_REASON = \"This database is locked, so its columns and settings are read-only. Unlock it to change them.\";\n\nfunction lockedStructure(base: WhatYouMayDo): WhatYouMayDo {\n return { ...base, structure: false, why: (what) => (what === \"structure\" ? DATABASE_LOCKED_REASON : base.why(what)) };\n}\n","// src/tableRights.ts — @ai-matrx/records-ui (pure; also served by `@ai-matrx/records-ui/helpers`)\n//\n// What a person may do to one table, as the screens read it. `./host.tsx` (the React context the\n// screens ask) re-exports everything here; a host that builds rights by hand (`tableRightsAt`) at\n// boot reads this file alone and never pulls a screen.\n\nimport type { PermissionLevel } from \"@ai-matrx/records\";\nimport { NOT_ANSWERED_YET, whatYouMayDo, type WhatYouMayDo } from \"./rights\";\n\n/**\n * What a person may do to one table. The four words and the ladder are the\n * store's (`rights.ts`), not ours.\n *\n * `admin`, `comment` and `write` are kept with the names they have always had,\n * because every screen in this package and in the host apps reads them; they\n * are now the store's ANSWER rather than a host's guess.\n */\nexport interface TableRights extends WhatYouMayDo {\n /** SCR-2: holders of `admin` on the table see the \"+\" and the settings panel. */\n admin: boolean;\n /**\n * Why this answer, in one sentence. Kept for callers that show a single\n * reason; `why(what)` is the per-control sentence and is what the screens use.\n */\n reason: string;\n}\n\n/** Internal: the rights record for an answer (`host.tsx` folds the store's answers through it). */\nexport function tableRights(may: WhatYouMayDo, overallReason?: string): TableRights {\n return {\n ...may,\n admin: may.structure,\n reason: overallReason ?? (may.structure ? \"\" : may.why(\"structure\")),\n };\n}\n\n/**\n * Kept so a host that imported it still compiles. It is no longer any screen's\n * default: the store answers this question now, and a package that said \"I\n * assume nothing\" while holding the answer would be hiding controls from the\n * people who hold them.\n */\nexport const NO_RIGHTS: TableRights = tableRights(NOT_ANSWERED_YET);\n\n/**\n * THE ONE WAY TO BUILD A `TableRights` BY HAND — for a host with its own\n * authority, and for a suite that wants to mount one seat's screen. It takes\n * the LEVEL, never six booleans, so nobody can hand a screen a combination the\n * ladder cannot produce (write without read, share without edit).\n */\nexport function tableRightsAt(level: PermissionLevel | null): TableRights {\n return tableRights(whatYouMayDo(level, true));\n}\n","// src/names.ts — @ai-matrx/records-ui\n//\n// WHAT A PERSON READS, NEVER WHAT THE MACHINE STORES.\n//\n// Measured on the real screens (independent verdict, 19 September): a table row\n// read `Saved views · 9 fields · records_ui_view`, a relation cell read a bare\n// `8f2c…` identifier, a header read `stage` because the Field's label was\n// blank, and the type word on a column tooltip read `long_text`. Airtable,\n// Notion and Linear never show a person an internal name; the verdict called\n// this one of the three things a first-time user feels within a minute.\n//\n// So every place this package prints something a person reads goes through one\n// of these three functions. They are deliberately dumb: they choose the best\n// human string that IS AVAILABLE and, when none is, say what the thing is\n// rather than printing the token. No screen in this package formats a name of\n// its own any more.\n\nimport type { Field, ReadRow, RecordDocument, Table } from \"@ai-matrx/records\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\n\n/** The name of one Field, as a header, a form label or a peek's term. */\nexport function fieldName(field: Field): string {\n const label = (field.label ?? \"\").trim();\n // A LABEL THAT IS ONLY A MACHINE KEY is not a name (merged-grid review 2026-09-26): a table made\n // by an import or an agent kept `label: \"job_no\"`, and the header read `job_no`. A key joined by\n // underscores is written the way a person writes it (\"Job no\"). A single lowercase word the\n // owner typed (\"mobile\", \"title\") is their own words and is shown as they wrote it.\n if (label !== \"\" && label === field.key && /^[a-z0-9]+(?:[_.-][a-z0-9]+)+$/.test(label)) return humanizeIdentifier(label);\n if (label !== \"\") return label;\n const name = (field.name ?? \"\").trim();\n if (name !== \"\") return name;\n return humanizeIdentifier(field.key);\n}\n\n/** The name of one Table, as a card, a heading or a breadcrumb. */\nexport function tableName(table: Table): string {\n const name = (table.name ?? \"\").trim();\n if (name !== \"\") return name;\n const singular = (table.label_singular ?? \"\").trim();\n if (singular !== \"\") return singular;\n return humanizeIdentifier(table.slug ?? \"\");\n}\n\n/**\n * The name of one RECORD, for a chip, a card, a relation cell or a peek title.\n *\n * `titleKey` is the Table's own `title_field` when the caller knows the Table —\n * that is the store's answer to \"what makes this record a chip\" (REC-2) — and\n * the conventional keys are tried after it. A record with nothing readable is\n * NOT shown as a truncated uuid: it says it has no name yet, because \"8f2c1b0a\"\n * tells a person nothing and looks like a bug.\n */\nexport function recordName(\n document: RecordDocument | undefined,\n titleKey?: string | null,\n fallback = \"Untitled\",\n): string {\n const data = (document ?? {}) as Record<string, unknown>;\n const keys = [titleKey, \"title\", \"name\", \"label\", \"full_name\", \"subject\", \"summary\"].filter(\n (key): key is string => typeof key === \"string\" && key !== \"\",\n );\n for (const key of keys) {\n const value = data[key];\n // AN ID IS NEVER A NAME, AND THIS FUNCTION USED TO RETURN ONE (TAILS-2, 2026-09-21).\n // A Table's title column may be a RELATION, and a relation's stored value IS the other\n // record's id (FLD-6 / REL-1) — so `recordName` handed every caller a bare uuid for\n // every Table titled that way, which is how the board's unplaced list came to read\n // \"11 records are not in any of these columns — ca5f1ac7-…\". A caller that can resolve\n // the id resolves it (`scalarText` with the label lookup); a caller that cannot is\n // better off reading the next column, and then the fallback, than a hex number.\n if (typeof value === \"string\" && value.trim() !== \"\" && !looksLikeId(value.trim())) {\n return value.trim();\n }\n if (typeof value === \"number\") return String(value);\n }\n return fallback;\n}\n\n\n/**\n * Is this string the store's id for something, rather than words a person wrote?\n *\n * The same question `custom._card_words` asks on the database, with the same regex, so the\n * screen and the store agree about what is a name (TAILS-2, 2026-09-21).\n */\nexport function looksLikeId(value: unknown): boolean {\n return typeof value === \"string\" && isUuidShape(value.trim());\n}\n\n/** The same question for a row the read door returned. */\nexport function rowName(row: ReadRow | undefined, titleKey?: string | null, fallback = \"Untitled\"): string {\n return recordName(row?.document, titleKey, fallback);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// NAMING A RECORD WHOSE TABLE YOU ALREADY HOLD — ONE CALL, NOT A COPY PER SCREEN.\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// 🚨 WHY THESE TWO EXIST (lane RELATION-DISPLAY-2, 2026-09-21).\n//\n// `check:one-reference-builder` shipped with a baseline of SIX, and its own header said the\n// number was not zero because \"moving six surfaces onto the store door is real work\". Three\n// of the six were not asking the store's question at all. `Grid.tsx` names the row a person\n// is looking at for the Talk action; `Peek.tsx` names the record being peeked at;\n// `PortalsPanel.tsx` names the rows of the portal's own client Table; and this repo's\n// `TryEverythingScreen.tsx` does the same in two places. NONE of them is resolving a\n// RELATION — they hold the Table and they hold the document, and there is nothing to ask a\n// door about. What they were each doing by hand was the two-line join between them:\n//\n// recordName(row.document, table.title_field)\n//\n// Written out five times in four files, which is how a Table whose title column is `cname`\n// came to read \"Untitled\" on one screen and correctly on the next. It is the same question\n// as the store's, one rung down the ladder, and the same one answer should serve it — so it\n// lives HERE, in the file the guard exempts BY CONSTRUCTION as the primitive itself, and\n// every screen calls it instead of re-deriving it.\n//\n// WHAT THESE ARE NOT. They are not a second resolver and must never become one. They take a\n// Table a caller ALREADY HAS and a document it ALREADY HAS. The moment a caller is holding\n// an ID and wants words, that is the store's question and the answer is\n// `client.relationWords` / `client.relationWordsMany` — which ask the read-access ladder\n// BEFORE they read a name, apply that column's own display spec, and return the withheld\n// sentence for a record the reader may not open. Nothing in here can do any of that, and\n// nothing in here should try.\n\n/** A Table as far as naming is concerned — its own declared title column (REC-2). */\ntype TitledTable = Pick<Table, \"title_field\"> | null | undefined;\n\n/**\n * THE NAME OF A RECORD WHOSE TABLE YOU ALREADY HOLD.\n *\n * `table` is the Table the record belongs to; its `title_field` is the store's answer to\n * \"what makes this record a chip\" (REC-2) and is tried first, then the conventional keys,\n * then the fallback. A Table that has not loaded yet is `null` and the conventional keys\n * still answer — a name arriving a tick late is better than a screen that shows nothing.\n */\nexport function recordNameIn(\n table: TitledTable,\n document: RecordDocument | undefined,\n fallback = \"Untitled\",\n): string {\n return recordName(document, table?.title_field ?? null, fallback);\n}\n\n/**\n * THE NAME A CHANGE NOTICE USES — the record as it is AFTER the change (merged-grid tails,\n * 2026-09-26). Typing a first name into a row's label column read \"Changed Title on Untitled\":\n * the notice named the row from the document held before the write. The row is called what it is\n * called now; only when the change emptied its name does the notice use the name it had.\n */\nexport function changedRecordName(\n table: TitledTable,\n document: RecordDocument | undefined,\n key: string,\n after: unknown,\n): string {\n const now = recordName({ ...((document ?? {}) as Record<string, unknown>), [key]: after } as RecordDocument, table?.title_field ?? null, \"\");\n return now !== \"\" ? now : recordNameIn(table, document);\n}\n\n/** The same, for a row the read door returned. */\nexport function rowNameIn(table: TitledTable, row: ReadRow | undefined, fallback = \"Untitled\"): string {\n return recordName(row?.document, table?.title_field ?? null, fallback);\n}\n\n/**\n * WHAT A RELATION CHIP SAYS WHEN THE RECORD IT POINTS AT IS NOT YOURS.\n *\n * A relation joins two records in two tables, and holding one end says nothing\n * about the other: a Job shared with you may point at a Client nobody shared.\n * The chip then has three possible answers and only one of them is honest —\n * the target's TITLE is a leak, a bare id is a bug with a hex number in it, and\n * a permanent \"Loading…\" is a lie that never resolves.\n *\n * This is the SAME sentence `platform.relation_withheld_label()` answers on the\n * database, word for word, so a person reads one wording whether the screen or\n * the store worked it out. Changing it changes both (RELATION-DECLARE,\n * 2026-09-20).\n */\nexport const WITHHELD_RECORD_LABEL = \"A record you have not been given access to\";\n/**\n * WHEN THE STORE COULD NOT BE ASKED (a 503, a dropped connection) the name is UNREAD, not\n * withheld: saying \"not given access\" for a failed read lies about the data (W1.1 verifier,\n * 2026-10-02). This is what a reference reads until a later read answers.\n */\nexport const UNREAD_RECORD_LABEL = \"Couldn't load this name\";\n\n/**\n * THE PLURAL A PERSON READS, NEVER A MACHINE'S \"…ss\" (VERIFIER-16 M3 / VERIFIER-17 M3).\n *\n * A table the store or the mover never gave a real plural carries `name + \"s\"` — so a table\n * already named in the plural reads \"Customerss\", \"Status optionss\". That word was made by a\n * machine appending one letter, and it says nothing the name does not; it is never shown.\n * Returns the table's own plural when a person (or the example library) wrote one, and `null`\n * when the only plural on record is that appended letter.\n */\nexport function realPlural(table: { name?: string | null; label_singular?: string | null; label_plural?: string | null }): string | null {\n const plural = (table.label_plural ?? \"\").trim();\n if (plural === \"\") return null;\n for (const base of [table.name, table.label_singular]) {\n const b = (base ?? \"\").trim();\n if (b !== \"\" && plural === `${b}s`) return null;\n }\n return plural;\n}\n\n/**\n * ONE RECORD'S NOUN, IN A SENTENCE (\"Book a 30-minute visit\") — lane HANDOVER, 2026-09-28.\n *\n * Cedar Ridge Physical Therapy's booking page was titled \"Book a 30-minute Visits appointment\":\n * the table's NAME (a plural, a heading) was put where one record's noun goes. The noun is the\n * table's own singular (\"Visit\"), else its name, else the fallback; a Title-case word is written\n * the way a sentence writes it (\"visit\"), an acronym is kept (\"MRI scan\").\n */\nexport function singularNoun(\n table: { name?: string | null; label_singular?: string | null } | null | undefined,\n fallback = \"record\",\n): string {\n const word = (table?.label_singular ?? \"\").trim() || (table?.name ?? \"\").trim() || fallback;\n return word\n .split(/\\s+/)\n .map((w) => (/^[A-Z][a-z'’-]*$/.test(w) ? w.toLowerCase() : w))\n .join(\" \");\n}\n\n/**\n * A plural for a sentence (\"Check in ran on 2 appointments\"): the table's real plural, else the\n * singular with an \"s\" only when that does not double a final \"s\".\n */\nexport function pluralNoun(table: { name?: string | null; label_singular?: string | null; label_plural?: string | null } | null | undefined, fallback = \"record\"): string {\n const real = table ? realPlural(table) : null;\n if (real) return real;\n const singular = (table?.label_singular ?? \"\").trim() || fallback;\n return /s$/i.test(singular) ? singular : `${singular}s`;\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// WHAT A CARD IS TITLED BY (lane UI-FIX-18, VERIFIER-18 H5).\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// MEASURED 2026-09-24 on production: *ZZZ UI-QUICK-1 Rincon-style Jobs* (title column `title`)\n// grouped by Stage titled every kanban card \"false\" or \"true\". The board took the FIRST Field\n// the read door answered that was not the group column — here the *Urgent* checkbox — as the\n// title. A card is named by what names its record: the Table's own `title_field` first (REC-2),\n// then the conventional name keys, then the first words column in declared order. A yes/no\n// column, the column the board is grouped by and the store's own stamps never title a card.\n\nconst CONVENTIONAL_TITLE_KEYS = [\"title\", \"name\", \"label\", \"full_name\", \"subject\", \"summary\"];\n\nfunction canTitle(field: Field, excluded: ReadonlySet<string>): boolean {\n if (excluded.has(field.key)) return false;\n if (field.type === \"boolean\") return false;\n if (field.type === \"formula\" && (field.config ?? {})[\"system\"]) return false;\n return true;\n}\n\n/**\n * THE FIELD A CARD IS TITLED BY — kanban, calendar, gallery and pipeline alike.\n *\n * Order: the Table's `title_field` → a conventional name key (`title`, `name`, …) → the first\n * text column in declared `sort` order → the first other column that can title (never a\n * checkbox, never the group column, never a system stamp). `undefined` when nothing can, and\n * the card falls back to `rowName`, which says \"Untitled\" rather than \"false\".\n */\nexport function cardTitleField(\n fields: readonly Field[],\n titleKey: string | null | undefined,\n exclude: readonly (string | null | undefined)[] = [],\n): Field | undefined {\n const excluded = new Set(exclude.filter((k): k is string => typeof k === \"string\" && k !== \"\"));\n const ordered = [...fields].sort((a, b) => (a.sort ?? 100) - (b.sort ?? 100) || a.key.localeCompare(b.key));\n const byKey = (key: string) => ordered.find((f) => f.key === key && canTitle(f, excluded));\n if (titleKey) {\n const declared = byKey(titleKey);\n if (declared) return declared;\n }\n for (const key of CONVENTIONAL_TITLE_KEYS) {\n const found = byKey(key);\n if (found) return found;\n }\n return (\n ordered.find((f) => f.type === \"text\" && canTitle(f, excluded)) ?? ordered.find((f) => canTitle(f, excluded))\n );\n}\n","import { formatRelativeTime } from \"@ai-matrx/kit/format\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\n// src/whoChanged.ts — @ai-matrx/records-ui · SCR-17, the cell's half\n//\n// \"WHO?\" IS A QUESTION. A SCREEN IS SUPPOSED TO ANSWER IT.\n//\n// 🚨 WHAT A CLINIC SAW (crew B2, 2026-09-21, ten real patients on the live app):\n//\n// \"Every single cell shows a small 'who?' hover badge next to its value instead\n// of a resolved author name, an agent/rule label, or even 'system' — the\n// attribution feature is visibly wired up (it renders on every cell) but never\n// resolves to anything readable.\"\n//\n// They were right that it never resolved, and the reason was that nothing ever\n// asked. The badge opened a panel; it never looked anything up. Meanwhile the\n// store had the answer the whole time: `custom.field_history` on those exact ten\n// patients answers `kind: user, name: admin` on every one of them, and has since\n// they were written.\n//\n// So the badge asks, on the gesture that already reaches it — a hover or a Tab —\n// for the ONE cell being asked about. Nothing is fetched for a page of two\n// hundred cells nobody points at.\n//\n// THE THREE WORDS, AND NEVER A UUID. VAL-8 fixes the vocabulary at `user`,\n// `agent`, `system` and there is no fourth. An agent ALWAYS names the person it\n// acted for (AGT-N-4: it carries exactly that person's authority, so a screen\n// showing the machine without the person would be hiding who is answerable). The\n// system is \"the system\" — a platform word a person can read, not a null. And a\n// person whose name the door did not carry is resolved through the app's ONE\n// organization-scoped roster (the `members` port, FIX-7B's rule: the people of\n// THIS organization and nobody else). If even that cannot name them, the sentence\n// says so in words. It never prints an id: SCR-N-5 forbids showing one to a\n// person, and \"87a6e699…\" answers nobody's question anyway.\n\nimport type { FieldHistoryEntry, HistoryActor, Uuid } from \"@ai-matrx/records\";\n\n// Read the same realm-wide slot set by design-system's setDisplayTimeZone. This\n// helper is also exported by the light /data-source entry, so it cannot import\n// design-system's field-format bundle merely to read the saved zone.\nconst displayZone = globalSlot<{ zone: string | null }>(\"ai-matrx.design-system.display-time-zone\", () => ({ zone: null }));\n\n/** What the roster can tell us about a user id. `null` when it cannot. */\nexport type ResolveName = (userId: Uuid) => string | null;\n\n/** The honest stand-in when nobody and nothing can put a name to the author. */\nexport const SOMEBODY = \"somebody in this organization\";\n\n/** The platform's own word for itself. Never \"null\", never \"system_user\". */\nexport const THE_SYSTEM = \"Matrx\";\n\n/**\n * WHO, in the words a person reads. One place, so the grid cell, the record\n * timeline and the column history cannot drift into three different answers.\n */\nexport function actorWords(actor: HistoryActor, resolve?: ResolveName | undefined): string {\n if (actor.kind === \"system\") return THE_SYSTEM;\n const named = actor.name?.trim() || (actor.user_id && resolve ? resolve(actor.user_id)?.trim() : null) || null;\n if (actor.kind === \"agent\") {\n // An agent without the person it acted for cannot happen at the door — the\n // store refuses that write — but a screen still says something true if it does.\n const on = actor.on_behalf_of;\n const person = on?.name?.trim() || (on?.user_id && resolve ? resolve(on.user_id)?.trim() : null) || SOMEBODY;\n const approver = actor.approved_by\n ? actor.approved_by.name?.trim() || (resolve ? resolve(actor.approved_by.user_id)?.trim() : null) || SOMEBODY\n : null;\n return `${named ?? \"an assistant\"}, for ${person}${approver ? `, approved by ${approver}` : \"\"}`;\n }\n return named ?? SOMEBODY;\n}\n\n/** How long ago, in the words a person uses out loud. */\nexport function whenWords(at: string, now: Date = new Date()): string {\n const then = new Date(at);\n const age = now.getTime() - then.getTime();\n if (!Number.isFinite(age)) return \"at an unknown time\";\n if (age < 30 * 86_400_000) return formatRelativeTime(then, { style: \"intl\", now: now.getTime() });\n return then.toLocaleDateString(undefined, displayZone.zone ? { timeZone: displayZone.zone } : undefined);\n}\n\n/**\n * THE WHOLE ANSWER, as one sentence, ending in what to do to see the rest.\n * `null` is a real state and gets its own sentence: this column has never been\n * changed on this record since the store started keeping versions, which is not\n * the same as \"we could not find out\".\n */\n/**\n * WHAT HAPPENED, IN A PERSON'S WORDS (BREAKER-2 B2-29). The store words four operations and\n * lowercases any other (`RETYPE` → \"retype\"), so the panel read \"retype · admin · part of a bigger\n * change\". Every word the store can send is worded here; an unknown one is still written the way\n * a person writes it, never as a token. A soft delete is an archive, and says so.\n */\nconst OPERATION_WORDS: Record<string, string> = {\n created: \"Created\",\n edited: \"Edited\",\n deleted: \"Archived\",\n archived: \"Archived\",\n restored: \"Restored\",\n retype: \"Column type changed\",\n delete: \"Removed\",\n soft_delete: \"Archived\",\n insert: \"Created\",\n update: \"Edited\",\n restore: \"Restored\",\n};\n\nexport function operationWords(label: string | null | undefined): string {\n const raw = (label ?? \"\").trim();\n if (raw === \"\") return \"Changed\";\n const known = OPERATION_WORDS[raw.toLowerCase()];\n if (known) return known;\n const words = humanizeIdentifier(raw).toLowerCase();\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\nexport function lastChangeSentence(\n fieldLabel: string,\n entry: FieldHistoryEntry | null,\n resolve?: ResolveName | undefined,\n): string {\n if (!entry) {\n return `Nothing is recorded against ${fieldLabel} on this record yet. Press H for the whole history of this column.`;\n }\n const verb = operationWords(entry.operation_label).toLowerCase();\n return `${fieldLabel} — ${verb} by ${actorWords(entry.actor, resolve)}, ${whenWords(entry.occurred_at)}. Press H for the whole history.`;\n}\n\n/**\n * The SHORT form the badge wears once it knows: a name a person recognizes at a\n * glance, in the width of a cell corner. Never a uuid, never an email's domain.\n */\nexport function actorBadge(actor: HistoryActor, resolve?: ResolveName | undefined): string {\n if (actor.kind === \"system\") return THE_SYSTEM;\n const words = actorWords(actor, resolve);\n if (words === SOMEBODY) return \"somebody\";\n const first = words.split(\",\")[0]!.trim();\n const at = first.indexOf(\"@\");\n return at > 0 ? first.slice(0, at) : first;\n}\n","// The withheld value's WORDS, with no React (`@ai-matrx/records-ui/helpers` serves this file alone).\n// The cell that shows them is `./withheld.tsx`, which re-exports these.\nimport type { Field, HiddenFieldNotice } from \"@ai-matrx/records\";\nimport { fieldName } from \"./names\";\n\n/** The word a withheld cell shows in place of a value. Never \"—\", which means empty. */\nexport const WITHHELD_WORD = \"Withheld\";\n\ntype Hidden = Readonly<Record<string, HiddenFieldNotice | undefined>> | null | undefined;\n\n/** The store's notice for this column of this row, when the store withheld it. */\nexport function withheldNoticeOf(hidden: Hidden, key: string): HiddenFieldNotice | null {\n const notice = hidden?.[key];\n return notice && typeof notice === \"object\" ? notice : null;\n}\n\n/**\n * THE SENTENCE, in the store's own words: the notice's `says` when the store wrote one (a\n * worked-out column names what it reads), else the notice's reason, the level it needs and the\n * other way in.\n */\nexport function withheldSentence(field: Pick<Field, \"key\" | \"label\" | \"name\">, notice: HiddenFieldNotice): string {\n const extra = notice as HiddenFieldNotice & { says?: unknown; part?: unknown; who?: unknown };\n if (typeof extra.says === \"string\" && extra.says.trim() !== \"\") return extra.says.trim();\n const name = fieldName(field as Field);\n // A PART'S NOTICE (access-setup PLAN §12.1): \"Hourly rate is in Pay — people with Record admin on this row see it.\"\n if (typeof extra.part === \"string\" && extra.part.trim() !== \"\" && typeof extra.who === \"string\" && extra.who.trim() !== \"\") {\n return `${name} is in ${extra.part.trim()} — ${extra.who.trim()} see it.`;\n }\n const reason = notice.reason ? ` It is ${notice.reason}` : \"\";\n const needs = notice.needs ? `${reason ? \",\" : \" It\"} and reading it needs ${notice.needs}` : \"\";\n const or = notice.or ? `${needs || reason ? \", or\" : \" It needs\"} ${notice.or}` : \"\";\n return `${name} is withheld from you.${reason}${needs}${or}${reason || needs || or ? \".\" : \"\"}`;\n}\n","// src/choiceLooks.ts — @ai-matrx/records-ui · merge tranche 6f (early)\n//\n// A CHOICE WEARS THE COLOR ITS OWNER GAVE IT.\n//\n// The older /data grid let a person paint each choice of a list (\"Completed\" green, \"Scheduled\"\n// blue), and those colors are kept on the Field itself: `display_format.options.choices`, the\n// document `custom.field_update` writes (the /data Sheet's seam writes it the same way, and a\n// column's settings here write it back). The grid used to ignore it and HASH THE WORD into a\n// color, so a column painted green on /data came up amber here, and a color a person set in the\n// settings changed nothing on screen — the silent half of a setting.\n//\n// Pure: no React, no store call. The Field the grid already holds carries everything.\n\nimport { newerKindOf } from \"@ai-matrx/records/field-kinds\";\nimport type { Field } from \"@ai-matrx/records\";\n// The values from the pure `table-style` subpath (no \"use client\", no grid): `@ai-matrx/records-ui/helpers`\n// reaches this file through `fieldTypeLabel`, and the data-table root would drag the whole grid with it.\nimport { CHOICE_CHIP_CLASS, NEUTRAL_CHIP_CLASS, STYLE_COLORS } from \"@ai-matrx/design-system/data-table/table-style\";\nimport type { ChoiceColorLookup, StyleColor } from \"@ai-matrx/design-system/data-table\";\n\n/** One choice's look, as the Field keeps it. */\nexport interface ChoiceLook {\n value: string;\n label?: string;\n color?: StyleColor;\n}\n\n/** The Field's display document, which the store keeps beside its declared keys. */\nexport function displayFormatOf(field: Field): { id: string; options: Record<string, unknown> } | null {\n const raw = (field as unknown as { display_format?: unknown }).display_format;\n if (!raw || typeof raw !== \"object\") return null;\n const id = (raw as { id?: unknown }).id;\n if (typeof id !== \"string\" || id === \"\") return null;\n const options = (raw as { options?: unknown }).options;\n return { id, options: options && typeof options === \"object\" ? (options as Record<string, unknown>) : {} };\n}\n\nfunction isStyleColor(v: unknown): v is StyleColor {\n return typeof v === \"string\" && (STYLE_COLORS as readonly string[]).includes(v);\n}\n\n/** Every choice look the Field keeps, in its own order. A color outside the palette is dropped. */\nexport function choiceLooksOf(field: Field): ChoiceLook[] {\n const display = displayFormatOf(field);\n const choices = display?.options[\"choices\"];\n if (!Array.isArray(choices)) return [];\n const out: ChoiceLook[] = [];\n for (const c of choices) {\n if (!c || typeof c !== \"object\") continue;\n const value = (c as { value?: unknown }).value;\n if (typeof value !== \"string\" || value.trim() === \"\") continue;\n const color = (c as { color?: unknown }).color;\n const label = (c as { label?: unknown }).label;\n out.push({\n value: value.trim(),\n ...(typeof label === \"string\" && label.trim() !== \"\" ? { label: label.trim() } : {}),\n ...(isStyleColor(color) ? { color } : {}),\n });\n }\n return out;\n}\n\n/**\n * ONE WORD, HOWEVER IT WAS WRITTEN. A moved list keeps its words as `completed` / `truck_4` and\n * shows them as `Completed` / `Truck 4`; a color kept against either spelling is the same choice.\n */\nexport function choiceWord(value: unknown): string {\n return String(value ?? \"\")\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/**\n * NOTION'S STATUS COLORS, BY GROUP: To-do gray, In progress blue, Complete green. A status choice\n * the column paints nothing for wears its group's color, so a fresh Status column reads the way\n * Notion's does with nobody picking a color. A choice with a color of its own keeps it\n * (`storedChoiceColor` asks the column first).\n */\nexport const STATUS_GROUP_COLOR = { todo: \"gray\", in_progress: \"blue\", done: \"green\" } as const satisfies Record<string, StyleColor>;\n\n/** The color a status choice's GROUP gives it, or `undefined` when the column is not a Status. */\nexport function statusGroupColor(field: Field, value: unknown): StyleColor | undefined {\n if (newerKindOf(field) !== \"status\" || value === null || value === undefined || value === \"\") return undefined;\n const word = choiceWord(value);\n if (word === \"\") return undefined;\n const groups = ((field.config ?? {}) as Record<string, unknown>)[\"status_groups\"];\n if (groups && typeof groups === \"object\") {\n // the group is kept under the choice's KEY; the cell may hold its WORDS (\"In progress\" ↔ in_progress)\n for (const [key, group] of Object.entries(groups as Record<string, unknown>)) {\n if (choiceWord(key) !== word) continue;\n return group === \"in_progress\" ? STATUS_GROUP_COLOR.in_progress : group === \"done\" ? STATUS_GROUP_COLOR.done : STATUS_GROUP_COLOR.todo;\n }\n }\n return STATUS_GROUP_COLOR.todo;\n}\n\n/** The color this Field keeps for this value, or `undefined` when it keeps none. */\nexport function storedChoiceColor(field: Field, value: unknown): StyleColor | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n const word = choiceWord(value);\n if (word === \"\") return undefined;\n for (const look of choiceLooksOf(field)) {\n if (!look.color) continue;\n if (choiceWord(look.value) === word || (look.label && choiceWord(look.label) === word)) return look.color;\n }\n return statusGroupColor(field, value);\n}\n\n/**\n * THE COLOR-BY LOOKUP, STORED COLORS FIRST. A value whose column keeps a color for it wears\n * that color; any other value still paints, deterministically, through `fallback` — a color-by\n * that silently did nothing would be the screen lying about a setting a person just changed.\n */\nexport function storedChoiceColorLookup(\n fields: readonly Field[],\n fallback: ChoiceColorLookup,\n): ChoiceColorLookup {\n const byKey = new Map(fields.map((f) => [f.key, f] as const));\n return (fieldKey, value) => {\n const field = byKey.get(fieldKey);\n return (field ? storedChoiceColor(field, value) : undefined) ?? fallback(fieldKey, value);\n };\n}\n\n/**\n * THE ORDER A NEW CHOICE IS PAINTED IN (Airtable): each choice added to a list takes the next\n * palette color the list does not wear yet, so a fresh list reads as distinct chips with nobody\n * picking a color. Gray last — it reads as \"no color\".\n */\nexport const NEW_CHOICE_PALETTE: readonly StyleColor[] = [\"blue\", \"green\", \"amber\", \"red\", \"violet\", \"teal\", \"slate\"];\n\n/** The color the next choice of a list takes, given the colors its choices already wear. */\nexport function nextChoiceColor(worn: ReadonlyArray<StyleColor | null | undefined>): StyleColor {\n const taken = new Set(worn.filter((c): c is StyleColor => Boolean(c)));\n const free = NEW_CHOICE_PALETTE.find((c) => !taken.has(c));\n return free ?? NEW_CHOICE_PALETTE[worn.length % NEW_CHOICE_PALETTE.length]!;\n}\n\n/**\n * THE ONE CHIP A CHOICE IS DRAWN AS — the grid cell, the picker's list and its chip, a form's\n * pills: the color the column keeps for the value (by any of the words given — its key, its\n * label), else the neutral chip. One answer, so no surface paints a choice its own way.\n */\nexport function choiceChipLookOf(field: Field, ...words: unknown[]): { className: string; color: StyleColor | null } {\n for (const word of words) {\n const color = storedChoiceColor(field, word);\n if (color) return { className: CHOICE_CHIP_CLASS[color], color };\n }\n return { className: NEUTRAL_CHIP_CLASS, color: null };\n}\n","// src/docs.ts — @ai-matrx/records-ui · SCR-20, SCR-21, SCR-22\n//\n// DOCUMENTS OVER RECORDS. A template is a body whose tokens point at Fields BY\n// ID; a render is written ONCE and frozen with the SHA-256 of its own text; a\n// signature seals that exact version and is immutable once made.\n//\n// Three things this package refuses to re-implement, because the store already\n// does them and doing them twice is how two answers appear:\n// · which tokens a body contains — `custom.doc_tokens`;\n// · which of them this Table cannot answer, and why — `custom.doc_unresolved_tokens`;\n// · whether a signature still holds — `custom.doc_signature_intact`.\n//\n// The token syntax is the store's own: `{{field:<the field's id>}}`. A name\n// would be a token that silently stops resolving the day somebody renames a\n// Field, which is the exact failure REC-17 exists to prevent.\n\nimport type { Field, Uuid } from \"@ai-matrx/records\";\n\n/** The one token form, written the way the store's own pattern reads it. */\nexport function fieldToken(fieldId: Uuid): string {\n return `{{field:${fieldId}}}`;\n}\n\n/** THE DECLARATIVE SPEC an agent writes. One template, whole, in one object. */\nexport interface DocTemplateSpec {\n name: string;\n /** The body, tokens and all. */\n body: string;\n}\n\n/**\n * A template written in terms of Field KEYS — which is how an agent thinks and\n * how a person reads — turned into the store's id-based tokens. The agent writes\n * `{{title}}`; what is stored points at the Field's id, so a rename never\n * silently empties the document.\n *\n * A key this Table does not have is LEFT EXACTLY AS IT IS, so\n * `custom.doc_unresolved_tokens` names it and the screen shows the store's own\n * reason — it is never quietly deleted from the body.\n */\nexport function bodyFromKeys(body: string, fields: Field[]): string {\n const byKey = new Map(fields.map((f) => [f.key, f.id]));\n return body.replace(/\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g, (whole, key: string) => {\n const id = byKey.get(key);\n return id ? fieldToken(id) : whole;\n });\n}\n\n/** The reverse, for a person reading a stored body: ids shown as the Field's label. */\nexport function bodyForReading(body: string, fields: Field[]): string {\n const byId = new Map(fields.map((f) => [f.id, f.label || f.key]));\n return body.replace(/\\{\\{\\s*field:([0-9a-fA-F-]{36})\\s*\\}\\}/g, (whole, id: string) => {\n const label = byId.get(id);\n return label ? `{{${label}}}` : whole;\n });\n}\n\n/** VAL-10: a signature is a Value on a text Field whose format is `signature`. */\nexport function isSignatureField(field: Field): boolean {\n return field.type === \"text\" && (field.format ?? \"\").toLowerCase() === \"signature\";\n}\n","// src/fieldTypes.ts — @ai-matrx/records-ui\n//\n// EVERY KIND OF COLUMN THE STORE TAKES, IN THE WORDS A PERSON USES.\n//\n// The store publishes fourteen parity types and, for each, a sentence about what\n// it is MADE OF — \"REC-31: a File record reached through a relation, target the\n// kernel `File` Table\", \"FLD-9: a declared computation, on read or on write,\n// evaluated by custom.rule_eval\", \"config.via names the relation field,\n// config.pick the Value on the far side\". Those sentences are true and they are\n// for us. The 19 September verdict found them printed at the person choosing a\n// column type, alongside contract row ids, and called it what it is: machine\n// identity where a person is looking.\n//\n// So this file holds the OTHER sentence — what the type is FOR — and the field\n// panel shows that one. The store's own `made_of` stays where it belongs, in\n// `PARITY_MADE_OF`, for an engineer reading the package.\n//\n// The LIST itself is still the store's: `PARITY_FIELD_TYPES` is generated from\n// `custom.parity_field_types()`, and `assertEveryParityTypeIsExplained` (run by\n// the suite) fails the moment the store ships a fourteenth and nobody wrote a\n// sentence for it. A type with no explanation would otherwise appear with a\n// blank line under it, which is the silent version of the same defect. It caught the\n// fourteenth — `checkbox`, 2026-09-21 — exactly as it was written to.\n\nimport { DECLARABLE_FIELD_KINDS, NEWER_FIELD_KINDS, PARITY_FIELD_TYPES, type DeclarableFieldKind, type NewerFieldKind, type ParityFieldType } from \"@ai-matrx/records/field-kinds\";\n\n/** The three behaviors that carry no parity type of their own. */\nexport type PlainFieldType = \"text\" | \"long_text\" | \"number\";\n\n/**\n * THE ONE A PERSON COMING FROM AIRTABLE REACHES FOR FIRST, AND IT WAS NOT HERE.\n *\n * The list above offered `member` (a Person) and `attachment` (a File) — the two\n * relations whose target is a Table the PLATFORM keeps — and nothing at all for\n * \"this job belongs to that customer\". The store has taken it since 2026-09-20\n * (`custom.field_declare` with `type: \"relation\"` and a `relation_target`), the\n * Field type has named it since the same day, and `editorKindFor` has answered\n * `\"relation\"` for one since long before that. Only the menu did not offer it,\n * so the guide's section 3 told a person to pick a kind that did not exist.\n *\n * It is NOT a parity type of its own. `custom.parity_field_types()` ships\n * fourteen (the fourteenth is `checkbox`) and a relation is a BEHAVIOR — the same behavior `member` and\n * `attachment` are made of — so it sits beside the three plain ones as its own\n * word, and `parityTypesWithNoExplanation()` is unaffected by it in both\n * directions: it does not appear there, and it cannot hide a real gap there.\n */\nexport type RelationFieldType = \"relation\";\n\n/**\n * What a person picks in the panel — AND IT IS THE STORE'S OWN LIST, not a union\n * assembled here.\n *\n * 🚨 THE CLASS FIX (FIX-10B-F6, VERIFIER-10). This used to read\n * `ParityFieldType | PlainFieldType | RelationFieldType` — the parity floor plus two words\n * this file knew about — and that union was the whole defect. `custom.doc_sign` accepts\n * exactly one field, a text column whose format is `signature`, and it is granted to\n * `authenticated`; the Documents screen told a person in so many words to go and declare\n * one; and no list any screen could read named it, so the control did not exist and the\n * e-sign half of Documents was unreachable from the product. A kind the store takes and no\n * screen offers is invisible, and nothing failed — which is the only reason it survived.\n *\n * `custom.field_kinds()` is now the ONE registry and `DECLARABLE_FIELD_KINDS` is generated\n * from it, so the next kind the store learns arrives here as a TYPE ERROR in\n * `FIELD_TYPE_CHOICES`'s coverage and as a red `kindsWithNoChoice()` below — never as a\n * silence.\n */\nexport type PickableFieldType = DeclarableFieldKind | SystemFieldKind | \"entity_reference\" | NewerFieldKind | LookFieldKind;\n\n/**\n * A KIND THAT IS A PLAIN COLUMN WEARING A LOOK (grids review 3, lane H item 5). The store keeps a\n * column's \"Shows as\" on the Field (`display_format`, `custom.display_format_ids()` has `rating` and\n * `time`), so a Rating is a whole number shown as stars and a Time is a time of day kept as its\n * 24-hour text — declared through the ordinary door (`{ plain, display_format }`) the same way the\n * \"Shows as\" picker makes one. Offered whenever the store does not yet publish the kind as its own\n * word (`custom.field_kinds()`): a Rating the store publishes goes as `{ type: \"rating\", max }`.\n */\nexport type LookFieldKind = \"time\" | \"color_pair\" | \"measure\" | \"type_style\" | \"shadow\";\n\nexport interface LookKind {\n plain: \"number\" | \"text\";\n look: (args: { ratingMax: number }) => { id: string; options?: Record<string, unknown> };\n}\n\nexport const LOOK_KINDS: Partial<Record<PickableFieldType, LookKind>> = {\n rating: { plain: \"number\", look: ({ ratingMax }) => ({ id: \"rating\", options: { ratingMax } }) },\n time: { plain: \"text\", look: () => ({ id: \"time\" }) },\n // PLUG-IN DESIGN LOOKS (2026-10-17, `looks/designLooks.tsx`): a structured token is JSON text in a text column.\n color_pair: { plain: \"text\", look: () => ({ id: \"color_pair\" }) },\n measure: { plain: \"number\", look: () => ({ id: \"measure\", options: { unit: \"px\" } }) },\n type_style: { plain: \"text\", look: () => ({ id: \"type_style\" }) },\n shadow: { plain: \"text\", look: () => ({ id: \"shadow\" }) },\n};\n\n/** Is this kind declared as a plain column wearing a look (because the store does not publish it)? */\nexport function declaredAsLook(kind: string): boolean {\n return kind in LOOK_KINDS && !storePublishesKind(kind);\n}\n\n/**\n * LANE 10 P4: THE NINE NEWER KINDS (rating, duration, created by, last changed by, status, address,\n * barcode, formatted text, count). Each is listed in `FIELD_TYPE_CATALOGUE` below, so every reader\n * (Settings, the column panel, every layout) names a column of one by its own word; the MENU offers\n * one only once `custom.field_kinds()` publishes it (after the chair's apply and\n * `pnpm records:generate`), so a person is never offered a kind the live store would refuse.\n */\nexport function storePublishesKind(kind: string): boolean {\n return DECLARABLE_FIELD_KINDS.some((row) => (row.kind as string) === kind);\n}\n\n/**\n * LANE SC-R: a column that points at a PLATFORM thing (a note, a web site, an agent). Its menu entry\n * is drawn only once `custom.field_kinds()` publishes `entity_reference` (after the chair's apply\n * and `pnpm records:generate`), so the menu never offers a kind the live store would refuse.\n */\nexport const STORE_PUBLISHES_ENTITY_REFERENCE = DECLARABLE_FIELD_KINDS.some(\n (row) => (row.kind as string) === \"entity_reference\",\n);\n\n/**\n * THE STORE'S OWN STAMPS AS COLUMNS (GRID-PRIMITIVES G5; TABLE-PARITY H2 H3, lane\n * DEFAULT-GRID-PARITY). `custom.field_declare` takes these three WORDS and makes each a formula\n * Field whose expression is the system node (`fx.autonumber`, `fx.created_time`,\n * `fx.modified_time`, `config.system` naming which), so nobody types into them and every reader\n * that serves a worked-out value serves them. `custom.field_kinds()` does not publish them,\n * because each is a formula, not a behavior of its own. So they are named here, sent as their\n * word through the `{ type }` arm, and a new autonumber column numbers the records already in\n * the table through `custom.autonumber_backfill`.\n */\nexport type SystemFieldKind = \"autonumber\" | \"created_time\" | \"modified_time\";\n\nexport const SYSTEM_FIELD_KINDS: readonly SystemFieldKind[] = [\"autonumber\", \"created_time\", \"modified_time\"];\n\nexport function isSystemFieldKind(id: string): id is SystemFieldKind {\n return (SYSTEM_FIELD_KINDS as readonly string[]).includes(id);\n}\n\nexport interface FieldTypeChoice {\n id: PickableFieldType;\n /** The word on the menu. */\n label: string;\n /** One line, under the word, saying what it is FOR. Never what it is made of. */\n explanation: string;\n /** The heading it sits under, so seventeen choices read as four short lists. */\n group: \"Words\" | \"Numbers and dates\" | \"Choices and people\" | \"Worked out\";\n}\n\n/**\n * EVERY KIND THIS PACKAGE CAN NAME AND DRAW, in menu order. The menu (`FIELD_TYPE_CHOICES`) is this\n * list less the kinds the live store does not take yet; every reader names a column from this one.\n */\nexport const FIELD_TYPE_CATALOGUE: FieldTypeChoice[] = [\n { id: \"text\", group: \"Words\", label: \"Text\", explanation: \"A short line of writing — a name, a reference, a title.\" },\n { id: \"long_text\", group: \"Words\", label: \"Long text\", explanation: \"Several lines — a description, notes, an address.\" },\n { id: \"rich_text\", group: \"Words\", label: \"Formatted text\", explanation: \"Notes with bold, lists and links.\" },\n { id: \"email\", group: \"Words\", label: \"Email address\", explanation: \"An email address, checked as you type and ready to write to.\" },\n { id: \"phone\", group: \"Words\", label: \"Phone number\", explanation: \"A phone number, checked as you type.\" },\n { id: \"url\", group: \"Words\", label: \"Link\", explanation: \"A web address that opens in a new tab when you click it.\" },\n { id: \"address\", group: \"Words\", label: \"Address\", explanation: \"A street address in parts, opened in maps.\" },\n { id: \"color_pair\", group: \"Words\", label: \"Color\", explanation: \"A color for light and dark, with a readability check.\" },\n { id: \"type_style\", group: \"Words\", label: \"Type style\", explanation: \"A font, weight and size, shown as a sample.\" },\n { id: \"shadow\", group: \"Words\", label: \"Shadow\", explanation: \"A shadow, shown on a card.\" },\n { id: \"json\", group: \"Words\", label: \"JSON\", explanation: \"Structured data — a list or a set of named values — shown folded.\" },\n { id: \"barcode\", group: \"Words\", label: \"Barcode\", explanation: \"A code a scanner reads, like a wristband or a box.\" },\n { id: \"button\", group: \"Words\", label: \"Button\", explanation: \"A button on each record that opens a link or runs an action.\" },\n\n { id: \"number\", group: \"Numbers and dates\", label: \"Number\", explanation: \"A plain number you can total up and sort by.\" },\n { id: \"currency\", group: \"Numbers and dates\", label: \"Money\", explanation: \"An amount of money, shown with its currency wherever it appears.\" },\n { id: \"percent\", group: \"Numbers and dates\", label: \"Percentage\", explanation: \"A number out of a hundred, kept between 0 and 100.\" },\n { id: \"rating\", group: \"Numbers and dates\", label: \"Rating\", explanation: \"A score in stars, set with one click.\" },\n { id: \"duration\", group: \"Numbers and dates\", label: \"Duration\", explanation: \"A length of time, typed as 45 min or 1:30.\" },\n { id: \"time\", group: \"Numbers and dates\", label: \"Time\", explanation: \"A time of day with no date — a shift start, opening hours.\" },\n { id: \"measure\", group: \"Numbers and dates\", label: \"Size\", explanation: \"A number with a unit: 16 px, 1.5 rem, 200 ms.\" },\n { id: \"datetime\", group: \"Numbers and dates\", label: \"Date\", explanation: \"A day, or a day and a time. Dates are what the calendar view reads.\" },\n\n { id: \"select\", group: \"Choices and people\", label: \"Choice\", explanation: \"One answer from a list you write here. Choices are what the board view groups by.\" },\n { id: \"multi_select\", group: \"Choices and people\", label: \"Several choices\", explanation: \"Any number of answers from a list you write here.\" },\n { id: \"status\", group: \"Choices and people\", label: \"Status\", explanation: \"Choices grouped into To do, In progress and Done.\" },\n { id: \"checkbox\", group: \"Choices and people\", label: \"Yes / no\", explanation: \"A box you tick. Left alone it stays unanswered, which is not the same as a no.\" },\n { id: \"member\", group: \"Choices and people\", label: \"Person\", explanation: \"Somebody in this organization, picked from the people who are in it.\" },\n { id: \"attachment\", group: \"Choices and people\", label: \"File\", explanation: \"A file or a picture kept with the record.\" },\n { id: \"signature\", group: \"Choices and people\", label: \"Signature\", explanation: \"Somebody's sign-off on a document made from this record. Nobody types in it — it fills in when they sign.\" },\n { id: \"relation\", group: \"Choices and people\", label: \"Points at another record\", explanation: \"A link to records in another of your tables — the customer a job is for, the lines on an invoice.\" },\n {\n id: \"entity_reference\",\n group: \"Choices and people\",\n label: \"Points at something else on the platform\",\n explanation: \"A note, a web site, an agent, a workbook — anything you keep here that is not one of your tables.\",\n },\n\n { id: \"lookup\", group: \"Worked out\", label: \"Borrowed value\", explanation: \"A value read from a record this one points at, kept in step with it.\" },\n { id: \"rollup\", group: \"Worked out\", label: \"Total of linked records\", explanation: \"A count or a total worked out from the records this one points at.\" },\n { id: \"count\", group: \"Worked out\", label: \"Count of linked records\", explanation: \"How many records this one points at.\" },\n { id: \"formula\", group: \"Worked out\", label: \"Worked out from other columns\", explanation: \"A value this record works out for itself from its own other columns.\" },\n { id: \"autonumber\", group: \"Worked out\", label: \"Record number\", explanation: \"A number the table gives each record, one after another, never reused. Records already here are numbered in the order they were made.\" },\n { id: \"created_time\", group: \"Worked out\", label: \"Created time\", explanation: \"When each record was made. Nobody types it.\" },\n { id: \"modified_time\", group: \"Worked out\", label: \"Last changed time\", explanation: \"When each record last changed. Nobody types it.\" },\n { id: \"created_by\", group: \"Worked out\", label: \"Created by\", explanation: \"Who made each record. Nobody types it.\" },\n { id: \"modified_by\", group: \"Worked out\", label: \"Last changed by\", explanation: \"Who last changed each record. Nobody types it.\" },\n];\n\n/** The kinds the menu offers only once the live store publishes them. */\nconst GATED_KINDS = new Set<string>([\"entity_reference\", ...NEWER_FIELD_KINDS]);\n\nexport const FIELD_TYPE_CHOICES: FieldTypeChoice[] = FIELD_TYPE_CATALOGUE.filter(\n (c) => !GATED_KINDS.has(c.id) || storePublishesKind(c.id) || c.id in LOOK_KINDS,\n);\n\nexport const FIELD_TYPE_GROUPS: FieldTypeChoice[\"group\"][] = [\n \"Words\",\n \"Numbers and dates\",\n \"Choices and people\",\n \"Worked out\",\n];\n\nconst BY_ID = new Map<string, FieldTypeChoice>(FIELD_TYPE_CATALOGUE.map((c) => [c.id, c]));\n\nexport function fieldTypeChoice(id: string): FieldTypeChoice | undefined {\n return BY_ID.get(id);\n}\n\n/** The three that are a plain behavior rather than one of the fourteen. */\nexport function isPlainFieldType(id: string): id is PlainFieldType {\n return id === \"text\" || id === \"long_text\" || id === \"number\";\n}\n\n/**\n * The one that is a relation a person aims themselves. It is neither plain nor\n * one of the thirteen, so every caller that branched on `isPlainFieldType`\n * alone has to answer this question too — which is why it is a named function\n * and not an inline string comparison at four call sites.\n */\nexport function isRelationFieldType(id: string): id is RelationFieldType {\n return id === \"relation\";\n}\n\n/**\n * One of FLD-11's fourteen, which is what `parity_type` on a declaration means.\n *\n * Read from the store's own generated floor, never from a list here — because a kind that\n * is NOT one of the fourteen (plain text, a person-aimed relation, a signature) has to be\n * declared by its WORD (`type`) and a panel that sent `parity_type` for it would be refused\n * \"There is no field type called …\". That is the shape of the F6 defect: the panel's `save`\n * had exactly two branches, relation and plain, and everything else fell into `parity_type`.\n */\nexport function isParityFieldType(id: string): id is ParityFieldType {\n return PARITY_FIELD_TYPES.some((row) => row.parity_type === id);\n}\n\n/**\n * THE GUARD THIS FILE NEEDS, because the list it explains is generated.\n *\n * Returns the parity types the store ships that nothing here explains. The\n * suite asserts it is empty; a fourteenth type would otherwise reach the menu\n * with a blank line under it and nobody would notice until a person did.\n *\n * `relation` is deliberately NOT one of the thirteen and therefore never\n * appears in this answer: `PARITY_FIELD_TYPES` is the store's own generated\n * list and a behavior that carries no parity type is not in it.\n */\nexport function parityTypesWithNoExplanation(): string[] {\n return PARITY_FIELD_TYPES.map((row) => row.parity_type).filter((type) => !BY_ID.has(type));\n}\n\n/**\n * 🚨 THE GUARD THAT CLOSES THE CLASS (FIX-10B-F6).\n *\n * `parityTypesWithNoExplanation()` above watches the parity FLOOR, and the floor was never\n * the whole list: the store also declares plain text, long text, number, a person-aimed\n * relation and a signature, and for months nothing anywhere compared the panel's menu with\n * THAT. So `signature` — the one field `custom.doc_sign` accepts, on a door granted to\n * every signed-in person, named to the person by the Documents screen itself — was absent\n * from the menu and every check stayed green.\n *\n * This returns the kinds `custom.field_kinds()` publishes that this panel does not offer.\n * The suite asserts it is empty, so a kind the store learns tomorrow either reaches the\n * person or turns a test red the same day. It is the class, not the instance: it would have\n * caught `signature`, and it will catch the twentieth kind nobody has thought of yet.\n */\nexport function kindsWithNoChoice(): string[] {\n return DECLARABLE_FIELD_KINDS.map((row) => row.kind).filter((kind) => !BY_ID.has(kind));\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// THE WORDS ON THE TWO BUTTONS, IN ONE PLACE — because they used to be the SAME\n// WORDS in two places, and that cost somebody their column.\n//\n// 🚨 THE DEFECT (TAILS-5, 2026-09-21, measured while driving the panel headless\n// on Rincon Plumbing's Summerland branch). The Jobs toolbar's control that OPENS\n// the field panel read exactly \"Add field\", and the panel's own SAVE button read\n// exactly \"Add field\" too — `FieldEditor` says \"Save field\" only when EDITING an\n// existing column, so on the create path the two were character-identical. The\n// toolbar control is a TOGGLE: pressing it while the panel is open closes the\n// panel and throws away everything typed into it. So a person who typed a column\n// name, chose a type, picked the target table and its display columns, then\n// looked up at the words they were told to press, could lose all of it — with no\n// sentence, no request sent, and nothing to say it had happened. A walk written\n// by an agent lost the column twice that way and spent a round diagnosing the\n// store before reading the two labels side by side.\n//\n// WHY THEY LIVE HERE AND NOT IN `@ai-matrx/design-system`. The words are RECORDS\n// vocabulary — \"field\", \"column\" — and the design system knows nothing about\n// either; a labels module there would be a domain word in a generic package, and\n// the next person adding a button would not find it. This file is already the\n// one place that owns what a person READS about a column (`FIELD_TYPE_CHOICES`\n// is right above), and both surfaces that draw these buttons are in this\n// package. One module, one import each, and `fieldTypes.test.ts` asserts the two\n// can never be the same string again.\n//\n// THE RULE: the control that OPENS a panel and the control that COMMITS it never\n// read the same words. The opener is an invitation; the committer says what it\n// will make.\n\n/** The toolbar control that OPENS the add-a-column panel. An invitation. */\nexport const ADD_FIELD_OPEN_LABEL = \"Add column\";\n\n/** The panel's own primary, on the CREATE path. It says what pressing it makes. */\nexport const ADD_FIELD_SAVE_LABEL = \"Create column\";\n\n/** The panel's own primary when an existing column is being changed. */\nexport const EDIT_FIELD_SAVE_LABEL = \"Save column\";\n","// src/parity.ts — @ai-matrx/records-ui\n//\n// FLD-11, the parity floor. A Field stores a BEHAVIOR (one of five) plus\n// modifiers, unit and format; a person picked one of THIRTEEN parity types in\n// the UI. This resolves the second from the first, using the same facts the\n// store's own `custom.parity_field_types()` describes — which is generated into\n// `@ai-matrx/records` and imported here, never retyped.\n//\n// Nothing in this file decides policy. It decides which editor to draw.\n\nimport { displayFormatOf } from \"./choiceLooks\";\nimport {\n KERNEL_TABLES,\n PARITY_FIELD_TYPES,\n fieldKindFor,\n newerKindOf,\n isButtonField,\n type FieldKind,\n type KernelTargets,\n type ParityFieldType,\n} from \"@ai-matrx/records/field-kinds\";\nimport type { Field } from \"@ai-matrx/records\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { isSignatureField } from \"./docs\";\nimport { fieldTypeChoice, isSystemFieldKind, type PickableFieldType } from \"./fieldTypes\";\n\n/** The kernel ids come from the store's own kernel rows, never from a literal here. */\nconst kernelId = (name: string): string =>\n KERNEL_TABLES.find((t) => t.name === name)?.id ?? \"\";\nconst KERNEL_FILE_TABLE = kernelId(\"File\");\nconst KERNEL_PERSON_TABLE = kernelId(\"Person\");\n\nexport const PARITY_LABEL: Record<ParityFieldType, string> = {\n attachment: \"Attachment\",\n checkbox: \"Yes / no\",\n currency: \"Currency\",\n datetime: \"Date\",\n email: \"Email\",\n formula: \"Formula\",\n lookup: \"Lookup\",\n member: \"Person\",\n multi_select: \"Multi-select\",\n percent: \"Percent\",\n phone: \"Phone\",\n rollup: \"Rollup\",\n select: \"Select\",\n url: \"Link\",\n};\n\n/** The \"made of\" sentence the store itself publishes, for the field editor's help text. */\nexport const PARITY_MADE_OF: Record<string, string> = Object.fromEntries(\n PARITY_FIELD_TYPES.map((p) => [p.parity_type, p.made_of]),\n);\n\n/**\n * Plain text and plain number are behaviors with no parity type of their own.\n *\n * 🚨 THIS IS NOW AN ALIAS, AND THAT IS THE POINT (TAILS-3, 2026-09-21). The\n * classifier moved into `@ai-matrx/records` as `FieldKind` so that the editor a\n * person types into and the COERCION applied to what they typed are decided by\n * one body. They were decided by two, and the public booking page paid for it:\n * \"Vehicle Year takes a number, and it was given a string\" on every table with\n * a number field.\n */\nexport type EditorKind = FieldKind;\n\n/** The kernel ids come from the store's own kernel rows, never from a literal here. */\nconst KERNEL: KernelTargets = { file: KERNEL_FILE_TABLE, person: KERNEL_PERSON_TABLE };\n\n/**\n * Which editor one Field wants. Reads the Field's own declaration only — the\n * behavior, the modifiers, the format, the relation target and the config —\n * because those are what the store stores, and a screen that guessed from a\n * value would draw a different editor for an empty record.\n *\n * It is `fieldKindFor` with this package's kernel ids bound. Nothing here\n * decides anything the core does not.\n */\nexport function editorKindFor(field: Field): EditorKind {\n return fieldKindFor(field, KERNEL);\n}\n\n/**\n * WHICH KIND A PERSON PICKED, read back off the Field the store keeps — the ONE reader every\n * \"what does this column hold\" answer goes through (the Settings column list, the column panel).\n *\n * `editorKindFor` answers which EDITOR to draw, and for two families that is not the kind a\n * person picked: a Signature is a text Field whose format is `signature` (it draws a line of\n * text), and the store's stamps — Record number, Created time, Last changed time — are formula\n * Fields whose `config.system` names the stamp. Read through the editor classifier alone, the\n * Settings list called a Signature \"Text\" and a Record number \"Worked out from other columns\"\n * (lane 10 W1-A, guard `every-pickable-kind-reads-back-as-itself.test.tsx`).\n *\n * `undefined` when the Field is none of the kinds the menu offers.\n */\nexport function pickableTypeOf(field: Field): PickableFieldType | undefined {\n if (isSignatureField(field)) return \"signature\";\n // NOTION-PROPS-3: a button is text wearing the format `button`.\n if (isButtonField(field)) return \"button\";\n // LANE 10 P4: the nine newer kinds, each a base type wearing a format (`newerKindOf`).\n const newer = newerKindOf(field);\n if (newer) return newer;\n // A RATING OR A TIME made as a plain column wearing its look (`LOOK_KINDS`): named by that kind.\n const look = displayFormatOf(field)?.id;\n if (look === \"rating\" && field.type === \"range\") return \"rating\";\n if (look === \"time\" && field.type === \"text\") return \"time\";\n if ((look === \"color_pair\" || look === \"type_style\" || look === \"shadow\") && field.type === \"text\") return look;\n if (look === \"measure\" && field.type === \"range\") return \"measure\";\n const system = (field.config as Record<string, unknown> | undefined)?.[\"system\"];\n if (field.type === \"formula\" && typeof system === \"string\" && isSystemFieldKind(system)) return system;\n const kind = editorKindFor(field);\n return fieldTypeChoice(kind) ? (kind as PickableFieldType) : undefined;\n}\n\n/**\n * The type word a person sees in a header or a settings row — and it is the\n * SAME word the field panel offers, read from `FIELD_TYPE_CHOICES`, so a column\n * added as \"Money\" is never described anywhere else as \"Currency\".\n */\nexport function fieldTypeLabel(field: Field): string {\n const kind = pickableTypeOf(field) ?? editorKindFor(field);\n const known = fieldTypeChoice(kind)?.label;\n if (known) return field.multi && kind !== \"multi_select\" ? `${known} (many)` : known;\n const plain: Record<string, string> = {\n // `boolean` is the BEHAVIOR word; `checkbox` is the type a person picks. Both are\n // written the way a person writes them, never as a raw token.\n boolean: \"Yes / no\",\n date: \"Date\",\n json: \"Structured data\",\n relation: \"Link to a record\",\n };\n // Never a raw token on a screen: an editor kind this table has not named is\n // still written the way a person writes it.\n return plain[kind] ?? humanizeIdentifier(kind);\n}\n","// src/tablePickerEntries.ts — @ai-matrx/records-ui (pure; also served by `@ai-matrx/records-ui/helpers`)\nimport { momentZoneOptions } from \"@ai-matrx/design-system/field-formats\";\n//\n// THE RULE for which tables a \"choose a table\" control offers (the full reasoning heads\n// `./tablePicking.tsx`, which re-exports everything here and adds the hook and the toggle).\n// No React, no store call: a host's picker data and a server read ask the same answer.\n\n/** The facts a picker needs about one table, whichever list it came from. */\nexport interface PickerTable {\n id: string;\n name: string;\n platform_owned?: boolean | null | undefined;\n /** The Table document's own key for the same fact (`tableList()` spreads the document onto the Table). */\n kept_by_the_app?: boolean | null | undefined;\n /** `custom.table_facts`: which feature keeps it (`choices` for a value set). */\n kept_for?: string | null | undefined;\n /** `custom.data_home_tables`: the store's one word for what it is (`list` for a value set). */\n kind?: string | null | undefined;\n /** The table a value set belongs to (`custom.table_facts.used_in_table_id`). */\n used_in_table_id?: string | null | undefined;\n /** A checklist's steps, a booking page's slots, a workflow's states. */\n work_kind?: unknown;\n slug?: string | null | undefined;\n /** When the table was made — what tells two lists apart once their column is gone. */\n created_at?: string | null | undefined;\n}\n\n/** The slug prefix of the tables this package keeps for its own bookkeeping (saved views, forms …). */\nconst PLATFORM_TABLE_PREFIX = \"records_ui_\";\n\n/** The store's flag (`platform_owned`) or the Table document's own key (`kept_by_the_app`) — either says the app keeps it. */\nfunction keptByPlatform(table: PickerTable): boolean {\n return table.platform_owned === true || table.kept_by_the_app === true;\n}\n\n/** A value set: the List a choice column keeps its choices in. */\nexport function isValueSet(table: PickerTable): boolean {\n if (table.kept_for === \"choices\") return true;\n return table.kept_for == null && table.kind === \"list\" && keptByPlatform(table);\n}\n\n/** Anything the app keeps for itself rather than a table a person keeps. */\nexport function isKeptTable(table: PickerTable): boolean {\n return (\n keptByPlatform(table) ||\n isValueSet(table) ||\n Boolean(table.work_kind) ||\n (table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX)\n );\n}\n\nexport interface TablePickerEntry<T extends PickerTable> {\n table: T;\n id: string;\n /** Unique among the entries returned. */\n label: string;\n /** A value set (shown only with \"Show lists\", or because it is the chosen one). */\n isList: boolean;\n}\n\nexport interface TablePickerEntries<T extends PickerTable> {\n entries: TablePickerEntry<T>[];\n /** How many value sets \"Show lists\" would add — 0 means the control is not worth drawing. */\n listCount: number;\n}\n\nconst CHOICES_SUFFIX = / choices$/i;\n\n/**\n * THE ONE RULE. Tables first (by name), then — with `showLists` — the value sets, each named\n * \"<column> — <owning table>\". Any names still equal get \" (2)\", \" (3)\" so no two entries match.\n */\nexport function tablePickerEntries<T extends PickerTable>(\n tables: readonly T[],\n options: { showLists?: boolean; keep?: string | null | undefined } = {},\n): TablePickerEntries<T> {\n const byId = new Map(tables.map((t) => [t.id, t]));\n const lists = tables.filter(isValueSet);\n const listLabel = (t: T): string => {\n const column = t.name.replace(CHOICES_SUFFIX, \"\");\n // A LIST WHOSE COLUMN IS GONE: `custom.table_facts` names the list itself (or nothing) as where\n // it is used. Said so, and told apart by the day it was made — never by a counter.\n if (!t.used_in_table_id || t.used_in_table_id === t.id) {\n const made = madeOn(t.created_at);\n return made ? `${column} — no column · ${made}` : `${column} — no column`;\n }\n const owner = byId.get(t.used_in_table_id);\n // Owned by a table this person cannot see: its own name, as the store gave it.\n if (!owner) return t.name;\n return `${column} — ${owner.name}`;\n };\n const plain = tables\n .filter((t) => !isKeptTable(t) || (t.id === options.keep && !isValueSet(t)))\n .map((t) => ({ table: t, id: t.id, label: t.name, isList: false }))\n .sort((a, b) => a.label.localeCompare(b.label));\n const shownLists = lists\n .filter((t) => options.showLists || t.id === options.keep)\n .map((t) => ({ table: t, id: t.id, label: listLabel(t), isList: true }))\n .sort((a, b) => a.label.localeCompare(b.label));\n const entries = [...plain, ...shownLists];\n const seen = new Map<string, number>();\n for (const entry of entries) {\n const key = entry.label.toLowerCase();\n const n = (seen.get(key) ?? 0) + 1;\n seen.set(key, n);\n if (n > 1) entry.label = `${entry.label} (${n})`;\n }\n return { entries, listCount: lists.length };\n}\n\n/** \"Sep 3, 2026\" in the reader's own locale, or null when the store gave no date. */\nfunction madeOn(stamp: string | null | undefined): string | null {\n if (!stamp) return null;\n const at = new Date(stamp);\n if (Number.isNaN(at.getTime())) return null;\n return new Intl.DateTimeFormat(undefined, { month: \"short\", day: \"numeric\", year: \"numeric\", ...momentZoneOptions(at) }).format(at);\n}\n","/**\n * The Gantt mode of a timeline view, by Field key. `mode` turns the left task list on; `critical` paints the longest\n * chain; `progress` is a percent/number column; `milestone` a yes/no column; `baselineStart` / `baselineEnd` the two\n * date columns \"Save baseline\" writes; `dependency` the link column that dependencies are written to.\n */\nexport interface GanttLook {\n mode?: boolean;\n critical?: boolean;\n progress?: string;\n milestone?: string;\n baselineStart?: string;\n baselineEnd?: string;\n dependency?: string;\n}\n\n/** Read a stored Gantt look; unknown keys and wrong shapes are dropped. */\nexport function parseGanttLook(raw: unknown): GanttLook | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const v = raw as Record<string, unknown>;\n const out: GanttLook = {};\n if (v[\"mode\"] === true) out.mode = true;\n if (v[\"critical\"] === true) out.critical = true;\n for (const k of [\"progress\", \"milestone\", \"baselineStart\", \"baselineEnd\", \"dependency\"] as const) {\n const x = v[k];\n if (typeof x === \"string\" && x !== \"\") out[k] = x;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * HOW A TABLE LOOKS — colors, formats and the frozen column.\n *\n * THE SPLIT, AND WHY IT IS THIS ONE. A Field declares WHAT it holds: a\n * currency, a percent, a date, a person. A VIEW declares HOW that reads and\n * what it is worth looking at: two decimal places or none, tint the row when\n * Status is Blocked, keep Name in place while the rest scrolls. Airtable draws\n * the line in exactly this place, and it has to be here: two people read one\n * table two different ways, and neither reading is a fact about the records.\n *\n * So nothing in this module is a new column on a Field and nothing here needed\n * a migration. A presentation lives on the saved-view record (`views.ts`), which\n * is an ordinary record of an ordinary Table — which means an agent sets it\n * through the same `records` tool it uses for everything else, and it travels\n * with the table the way every other record does.\n *\n * A FIELD STILL GETS ITS MONEY RIGHT WITH NO CONFIGURATION. `formatForField`\n * reads the Field's OWN declaration — a `currency` parity type with unit `$`, a\n * `percent`, a `datetime` with `config.kind` — and returns the format that\n * follows from it. The view's `formats` map only OVERRIDES that. A table nobody\n * has ever styled still shows `$1,250.50` and `45%`.\n */\n\n// The style parser from its own client-free subpath (lane SSR-ROWS): `@ai-matrx/records-ui/first-page`\n// runs in a host's SERVER component, and every export of the \"use client\" `data-table` entry is a\n// client reference there — calling `parseTableStyle` through it threw on the server.\nimport { COLOR_ROTATION, parseTableStyle, tableStyleIsEmpty } from \"@ai-matrx/design-system/data-table/table-style\";\nimport type {\n ChoiceColorLookup,\n GroupAggregateKind,\n GroupAggregateSpec,\n GroupOrder,\n StyleColor,\n TableStyle,\n} from \"@ai-matrx/design-system/data-table\";\nimport { getFieldFormat, type FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\nimport type { ColorRule } from \"@ai-matrx/design-system/data-table\";\nimport { newerKindOf, ratingMaxOf } from \"@ai-matrx/records/field-kinds\";\nimport type { Field, TableDecorations } from \"@ai-matrx/records\";\n\nimport { editorKindFor } from \"./parity\";\nimport { dateFormatFor } from \"./dates\";\n\n/**\n * SECTIONS BY A FIELD — the view's own grouping.\n *\n * `field` is a Field KEY, exactly like `frozen` and the keys of `formats`,\n * because a view is written against the Table's declaration and never against\n * whatever id a screen happened to build its columns with.\n *\n * `aggregates` is keyed by Field key too, and `collapsed` holds the data\n * table's own group keys (`s:Blocked`, `n:3`, `empty`), which is what the\n * primitive emits and the only thing that survives a value rendering the same\n * text as another.\n *\n * NOTHING HERE IS EVER CALLED `valueOf`, `toString` or `hasOwnProperty`: every\n * object in JavaScript already has all three, so an optional field by one of\n * those names is NEVER absent and a `config.valueOf ? … : …` check silently\n * reads `Object.prototype`. It cost the primitive a whole grouping once.\n */\nexport type GridGrouping = {\n /** The Field key whose value makes the sections. */\n field: string;\n /** Per-Field-key subtotal on every section header. */\n aggregates?: Record<string, GroupAggregateSpec>;\n /** Section order. The primitive's default is `value-asc`; blanks sort last. */\n order?: GroupOrder;\n /** The sections this view keeps shut, by the primitive's own group key. */\n collapsed?: string[];\n /** The grouped column stays drawn as a column (Airtable). Absent = shown; `false` = the person stepped it aside. */\n showColumn?: boolean;\n /**\n * SUB-GROUPS (lane S1-PRIME VIEW-KEYS; ui-bench LISTS \"sub-grouping\"): up to two more levels\n * inside each section, by Field key. At most three levels in all — the store refuses a fourth\n * (`custom.view_declare`). A layout that draws one level ignores the rest; it never drops them,\n * because this list is parsed and written back whole with the rest of the look.\n */\n then?: GridSubGroup[];\n /**\n * DRILL (lane DRILL-TABLE-PRIMITIVE): the Dimension pivoted across the top — a Field key, or\n * `<key>:<grain>` for a date cut into periods.\n */\n across?: string;\n /** DRILL: the period `field` is cut into when it is a date (`month`); the store keeps `field` a Field key. */\n grain?: string;\n /** The Measures shown (\"what to display\"), by the store's own keys (`count`, `sum_quantity`). */\n show?: string[];\n /** The drill trail, in order: each crumb a Dimension reference and the value it narrowed to. */\n trail?: GridDrillStep[];\n};\n\n/** One crumb of a saved drill trail. `value: null` is \"no value\". */\nexport type GridDrillStep = { dim: string; value: string | null };\n\n/** One sub-group level: a Field key and its section order. */\nexport type GridSubGroup = { field: string; order?: GroupOrder; grain?: string };\n\n/** Everything a view says about how its table LOOKS. */\nexport type GridPresentation = {\n /** Color-by-a-column, rules and manual highlights. */\n style?: TableStyle;\n /** Per-column format overrides, by the Field's key. */\n formats?: Record<string, FieldFormatConfig>;\n /**\n * The columns that stay in place while the table scrolls sideways, by Field\n * key. Only the LEADING run of the view's column order can actually freeze —\n * the data table decides that, and declines rather than pinning a column at a\n * guessed offset.\n */\n frozen?: string[];\n /** Collapsible sections by one Field, with subtotals on each header. */\n grouping?: GridGrouping;\n /**\n * The width a person dragged a column to, by Field key. SPARSE on purpose —\n * a view saved before widths existed carries none and still parses, and a\n * column nobody resized is left to the table's own measurement.\n */\n widths?: Record<string, number>;\n /** The body row height this view remembers, in px. */\n rowHeight?: number;\n /**\n * Field keys hidden from this view — the SAME hidden-column list the grid's\n * own column picker holds, now given a place on the view so it survives a\n * reload and a layout switch reads the identical set gallery and grid agree\n * on, rather than a second \"fields shown\" list nobody kept in sync.\n */\n hiddenFields?: string[];\n /**\n * THE FIELDS A CARD LEAVES OFF (board, list, gallery, calendar, timeline), by Field key — the\n * card's own choice, kept apart from `hiddenFields` so a board's \"Card fields\" never hides the\n * grid's columns when the view switches layout (v7 TABLE-EXPERIENCE, walk 2026-10-05). An empty\n * list is a choice (every field shown); absent means the card never chose.\n */\n cardHidden?: string[];\n /**\n * THE ORDER A PERSON DRAGGED THE COLUMNS INTO, by Field key (merge tranche 6a). Sparse like\n * `widths`: a key it does not name keeps its Field's own place after the named ones, and a key\n * whose Field is gone is skipped — a column order can never hide or invent a column.\n */\n columnOrder?: string[];\n /**\n * The gallery's card size, remembered the same way the grid remembers its\n * row height — a per-view look, not a global default.\n */\n gallerySize?: \"small\" | \"medium\" | \"large\";\n /**\n * THE BOARD'S OWN LOOK (lane BOARD-SWIMLANES, Notion's board options). All kept on the view, all\n * read only by the kanban layout. Absent means the board's default: columns wear their choice's\n * color, each heading shows its count, empty columns and lanes are drawn, cards are medium with\n * no preview.\n * boardSize card size: sets the column width, the preview's height and, small, drops the card's extras\n * boardPreview the FILE field drawn as a cover at the top of each card (absent = no preview)\n * boardHideEmpty leave out a column or a lane that holds no card\n * boardColorColumns false = neutral headings, no accent bar on the cards\n * boardCounts false = no count beside the heading\n * boardLanesShut the swimlanes kept shut to a strip, by the lane's name\n */\n boardSize?: \"small\" | \"medium\" | \"large\";\n boardPreview?: string;\n boardHideEmpty?: boolean;\n boardColorColumns?: boolean;\n boardCounts?: boolean;\n boardLanesShut?: string[];\n /**\n * A CHART VIEW'S MENU (PIVOT-VIEW): `chartLabels` draws each mark's value on it (the chart menu's \"Data labels\"\n * switch); `chartLegend: false` leaves the legend off. Read only by the chart layout.\n */\n chartLabels?: boolean;\n chartLegend?: boolean;\n /**\n * A LOCKED VIEW (lane NOTION-SMALL-2): its layout, filters, sorts and settings are not saved over until\n * somebody unlocks it. An editing convenience against an accidental change, never a permission.\n */\n locked?: boolean;\n /**\n * THIS VIEW'S OWN LAYOUT CHOICES, over the organization's `custom/grid_layout` knob (lane\n * DEFAULT-GRID-PARITY, TABLE-PARITY D1 D5 D6). Absent means \"whatever the organization\n * says\"; present is the view's word. `freezeFirst: false` is an explicit NO over an\n * organization that freezes the first column — an empty `frozen` cannot say that.\n */\n wrap?: boolean;\n /** AIRTABLE'S \"WRAP FIELD HEADERS\": column titles take a second line instead of being cut. Absent = one line. */\n headerWrap?: boolean;\n /** NOTION'S \"WRAP COLUMN\" (N5): the columns that wrap their text when the view as a whole does not. */\n wrapColumns?: string[];\n fit?: \"auto\" | \"fit\" | \"scroll\";\n freezeFirst?: boolean;\n /**\n * THE SUMMARY BAR (TABLE-PARITY F1): Field key → the store measure shown under that column\n * (`count`, `sum`, `avg`, `min`, `max`, `median`, `filled`, `empty`, `unique`), worked out\n * by `custom.record_aggregate` over the whole table.\n */\n summaries?: Record<string, string>;\n /** THE TIMELINE'S GANTT MODE (kept as `presentation.gantt`): see `GanttLook`. */\n gantt?: GanttLook;\n /**\n * WHERE THE FOOTER SITS (lane TABLE-PAGE-CHROME, owner 2026-09-25) — the row count and the\n * pages: `sticky`, pinned to the bottom of the screen while the rows scroll (the older grid's\n * way, and the default when a view says nothing), or `inline`, right after the last row with\n * the page scrolling. Read by the Grid and a host's Sheet.\n */\n footer?: FooterPlacement;\n};\n\n/** Where a grid's footer sits. */\nexport type FooterPlacement = \"sticky\" | \"inline\";\n\n/** What a view that says nothing gets — the older grid's pinned footer. */\nexport const DEFAULT_FOOTER: FooterPlacement = \"sticky\";\n\n/** Where THIS view's footer sits, said or defaulted. */\nexport function footerOf(p: GridPresentation | null | undefined): FooterPlacement {\n return p?.footer ?? DEFAULT_FOOTER;\n}\n\nexport const EMPTY_PRESENTATION: GridPresentation = {};\n\n/** A frozen column needs a known width, or the table declines to freeze at all. */\nexport const FROZEN_COLUMN_WIDTH = 200;\n\n/**\n * WHAT A ROW HEIGHT IS ALLOWED TO BE. Below the floor the text is clipped and\n * no editor fits; above the ceiling one record fills the screen. A view asking\n * for anything outside it is DROPPED rather than obeyed, because a saved look\n * must not be able to make a table unreadable — and the Fields' own heights\n * still draw, which is the tolerant half.\n */\nexport const MIN_ROW_HEIGHT = 24;\nexport const MAX_ROW_HEIGHT = 240;\n\n/**\n * The aggregate kinds and orders the primitive actually implements. Listed here\n * because they are the tolerant parser's allow-list and a view is hostile input:\n * `satisfies` ties them to the primitive's own union, so a kind it renames stops\n * this file compiling instead of quietly parsing into a subtotal nobody draws.\n */\nconst AGGREGATE_KINDS = [\n \"count\",\n \"sum\",\n \"average\",\n \"min\",\n \"max\",\n \"empty\",\n \"filled\",\n \"unique\",\n \"checked\",\n \"unchecked\",\n \"percentFilled\",\n] as const satisfies readonly GroupAggregateKind[];\n\nconst GROUP_ORDERS = [\n \"value-asc\",\n \"value-desc\",\n \"count-desc\",\n \"first-seen\",\n] as const satisfies readonly GroupOrder[];\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * Read a presentation out of whatever the view record holds — an object, or the\n * JSON string a text field stores.\n *\n * Tolerant in exactly the way `parseTableStyle` is: an unreadable half is\n * dropped and the rest still applies, because a table must keep drawing when\n * one piece of its styling goes out of date.\n */\nexport function parseGridPresentation(raw: unknown): GridPresentation {\n let value = raw;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed === \"\") return {};\n try {\n value = JSON.parse(trimmed);\n } catch {\n return {};\n }\n }\n if (!isRecord(value)) return {};\n\n const out: GridPresentation = {};\n\n const style = parseTableStyle(value[\"style\"]);\n if (!tableStyleIsEmpty(style)) out.style = style;\n\n if (isRecord(value[\"formats\"])) {\n const formats: Record<string, FieldFormatConfig> = {};\n for (const [key, cfg] of Object.entries(value[\"formats\"])) {\n if (!isRecord(cfg)) continue;\n const id = cfg[\"id\"];\n if (typeof id !== \"string\") continue;\n const options = cfg[\"options\"];\n formats[key] = isRecord(options)\n ? {\n id: id as FieldFormatConfig[\"id\"],\n options: options as NonNullable<FieldFormatConfig[\"options\"]>,\n }\n : { id: id as FieldFormatConfig[\"id\"] };\n }\n if (Object.keys(formats).length > 0) out.formats = formats;\n }\n\n if (Array.isArray(value[\"frozen\"])) {\n const frozen = value[\"frozen\"].filter((k): k is string => typeof k === \"string\");\n if (frozen.length > 0) out.frozen = frozen;\n }\n\n const grouping = parseGrouping(value[\"grouping\"]);\n if (grouping) out.grouping = grouping;\n\n if (isRecord(value[\"widths\"])) {\n const widths: Record<string, number> = {};\n for (const [key, raw] of Object.entries(value[\"widths\"])) {\n // A width that is not a usable number is one column's loss, never the\n // view's: the rest of the widths still apply and that column is measured.\n if (typeof raw !== \"number\" || !Number.isFinite(raw) || raw <= 0) continue;\n widths[key] = Math.round(raw);\n }\n if (Object.keys(widths).length > 0) out.widths = widths;\n }\n\n const rowHeight = value[\"rowHeight\"];\n if (\n typeof rowHeight === \"number\" &&\n Number.isFinite(rowHeight) &&\n rowHeight >= MIN_ROW_HEIGHT &&\n rowHeight <= MAX_ROW_HEIGHT\n ) {\n out.rowHeight = Math.round(rowHeight);\n }\n\n if (Array.isArray(value[\"hiddenFields\"])) {\n const hiddenFields = value[\"hiddenFields\"].filter((k): k is string => typeof k === \"string\");\n if (hiddenFields.length > 0) out.hiddenFields = hiddenFields;\n }\n if (Array.isArray(value[\"cardHidden\"])) {\n out.cardHidden = value[\"cardHidden\"].filter((k): k is string => typeof k === \"string\");\n }\n\n if (Array.isArray(value[\"columnOrder\"])) {\n const columnOrder = value[\"columnOrder\"].filter((k): k is string => typeof k === \"string\");\n if (columnOrder.length > 0) out.columnOrder = columnOrder;\n }\n\n const gallerySize = value[\"gallerySize\"];\n if (gallerySize === \"small\" || gallerySize === \"medium\" || gallerySize === \"large\") {\n out.gallerySize = gallerySize;\n }\n\n const boardSize = value[\"boardSize\"];\n if (boardSize === \"small\" || boardSize === \"medium\" || boardSize === \"large\") out.boardSize = boardSize;\n if (typeof value[\"boardPreview\"] === \"string\" && value[\"boardPreview\"] !== \"\") out.boardPreview = value[\"boardPreview\"];\n if (typeof value[\"boardHideEmpty\"] === \"boolean\") out.boardHideEmpty = value[\"boardHideEmpty\"];\n if (typeof value[\"boardColorColumns\"] === \"boolean\") out.boardColorColumns = value[\"boardColorColumns\"];\n if (typeof value[\"boardCounts\"] === \"boolean\") out.boardCounts = value[\"boardCounts\"];\n if (typeof value[\"chartLabels\"] === \"boolean\") out.chartLabels = value[\"chartLabels\"];\n if (typeof value[\"chartLegend\"] === \"boolean\") out.chartLegend = value[\"chartLegend\"];\n if (value[\"locked\"] === true) out.locked = true;\n if (Array.isArray(value[\"boardLanesShut\"])) {\n const shut = value[\"boardLanesShut\"].filter((k): k is string => typeof k === \"string\");\n if (shut.length > 0) out.boardLanesShut = shut;\n }\n\n if (typeof value[\"wrap\"] === \"boolean\") out.wrap = value[\"wrap\"];\n if (typeof value[\"headerWrap\"] === \"boolean\") out.headerWrap = value[\"headerWrap\"];\n if (Array.isArray(value[\"wrapColumns\"])) {\n const wrapColumns = value[\"wrapColumns\"].filter((k): k is string => typeof k === \"string\");\n if (wrapColumns.length > 0) out.wrapColumns = wrapColumns;\n }\n const fit = value[\"fit\"];\n if (fit === \"auto\" || fit === \"fit\" || fit === \"scroll\") out.fit = fit;\n if (typeof value[\"freezeFirst\"] === \"boolean\") out.freezeFirst = value[\"freezeFirst\"];\n const footer = value[\"footer\"];\n if (footer === \"sticky\" || footer === \"inline\") out.footer = footer;\n {\n const gantt = parseGanttLook(value[\"gantt\"]);\n if (gantt) out.gantt = gantt;\n }\n if (isRecord(value[\"summaries\"])) {\n const summaries: Record<string, string> = {};\n for (const [key, op] of Object.entries(value[\"summaries\"])) {\n // A measure name is judged by the store when it is asked; a non-string is nobody's.\n if (typeof op === \"string\" && op.trim() !== \"\") summaries[key] = op;\n }\n if (Object.keys(summaries).length > 0) out.summaries = summaries;\n }\n\n return out;\n}\n\n/**\n * A grouping, or nothing. A grouping with no Field to group BY is not a partial\n * grouping — it is no grouping at all, so it is dropped whole; an unreadable\n * subtotal or a section order this primitive does not have costs only itself.\n */\nfunction parseGrouping(raw: unknown): GridGrouping | undefined {\n if (!isRecord(raw)) return undefined;\n const field = raw[\"field\"];\n if (typeof field !== \"string\" || field.trim() === \"\") return undefined;\n\n const out: GridGrouping = { field };\n\n if (isRecord(raw[\"aggregates\"])) {\n const aggregates: Record<string, GroupAggregateSpec> = {};\n for (const [key, spec] of Object.entries(raw[\"aggregates\"])) {\n if (!isRecord(spec)) continue;\n const kind = spec[\"kind\"];\n if (typeof kind !== \"string\") continue;\n if (!(AGGREGATE_KINDS as readonly string[]).includes(kind)) continue;\n const label = spec[\"label\"];\n aggregates[key] =\n typeof label === \"string\"\n ? { kind: kind as GroupAggregateKind, label }\n : { kind: kind as GroupAggregateKind };\n }\n if (Object.keys(aggregates).length > 0) out.aggregates = aggregates;\n }\n\n const order = raw[\"order\"];\n if (typeof order === \"string\" && (GROUP_ORDERS as readonly string[]).includes(order)) {\n out.order = order as GroupOrder;\n }\n\n if (Array.isArray(raw[\"collapsed\"])) {\n const collapsed = raw[\"collapsed\"].filter((k): k is string => typeof k === \"string\");\n if (collapsed.length > 0) out.collapsed = collapsed;\n }\n\n if (typeof raw[\"showColumn\"] === \"boolean\") out.showColumn = raw[\"showColumn\"];\n\n if (Array.isArray(raw[\"then\"])) {\n const then: GridSubGroup[] = [];\n for (const level of raw[\"then\"]) {\n if (!isRecord(level)) continue;\n const sub = level[\"field\"];\n if (typeof sub !== \"string\" || sub.trim() === \"\") continue;\n const subOrder = level[\"order\"];\n const subGrain = level[\"grain\"];\n then.push({\n field: sub,\n ...(typeof subOrder === \"string\" && (GROUP_ORDERS as readonly string[]).includes(subOrder)\n ? { order: subOrder as GroupOrder }\n : {}),\n ...(typeof subGrain === \"string\" && subGrain !== \"\" ? { grain: subGrain } : {}),\n });\n }\n if (then.length > 0) out.then = then.slice(0, 2);\n }\n\n const grain = raw[\"grain\"];\n if (typeof grain === \"string\" && grain !== \"\") out.grain = grain;\n const across = raw[\"across\"];\n if (typeof across === \"string\" && across.trim() !== \"\") out.across = across;\n if (Array.isArray(raw[\"show\"])) {\n const show = raw[\"show\"].filter((k): k is string => typeof k === \"string\" && k !== \"\");\n if (show.length > 0) out.show = show;\n }\n if (Array.isArray(raw[\"trail\"])) {\n const trail: GridDrillStep[] = [];\n for (const step of raw[\"trail\"]) {\n if (!isRecord(step) || typeof step[\"dim\"] !== \"string\" || step[\"dim\"] === \"\") continue;\n const value = step[\"value\"];\n if (value !== null && typeof value !== \"string\") continue;\n trail.push({ dim: step[\"dim\"], value });\n }\n if (trail.length > 0) out.trail = trail;\n }\n\n return out;\n}\n\n/** True when nothing here would change how anything looks. */\nexport function presentationIsEmpty(p: GridPresentation): boolean {\n return (\n (p.style === undefined || tableStyleIsEmpty(p.style)) &&\n Object.keys(p.formats ?? {}).length === 0 &&\n (p.frozen?.length ?? 0) === 0 &&\n p.grouping === undefined &&\n Object.keys(p.widths ?? {}).length === 0 &&\n p.rowHeight === undefined &&\n (p.hiddenFields?.length ?? 0) === 0 &&\n p.cardHidden === undefined &&\n (p.columnOrder?.length ?? 0) === 0 &&\n p.gallerySize === undefined &&\n p.boardSize === undefined &&\n p.boardPreview === undefined &&\n p.boardHideEmpty === undefined &&\n p.boardColorColumns === undefined &&\n p.boardCounts === undefined &&\n (p.boardLanesShut?.length ?? 0) === 0 &&\n p.chartLabels === undefined &&\n p.chartLegend === undefined &&\n p.locked === undefined &&\n p.wrap === undefined &&\n p.headerWrap === undefined &&\n p.fit === undefined &&\n p.freezeFirst === undefined &&\n p.footer === undefined &&\n Object.keys(p.summaries ?? {}).length === 0 &&\n p.gantt === undefined\n );\n}\n\n/** The string a view record stores. Empty string for \"this view styles nothing\". */\nexport function presentationDocument(p: GridPresentation): string {\n return presentationIsEmpty(p) ? \"\" : JSON.stringify(p);\n}\n\n/** Kinds whose value is a control the record renderer draws, never a formatter's string. */\nconst DRAWN_KINDS = new Set([\"select\", \"multi_select\", \"relation\", \"member\", \"person\", \"attachment\", \"file\", \"entity_reference\", \"checkbox\", \"boolean\", \"signature\", \"json\"]);\n\n/**\n * The display format a column's settings chose for it, when it is one the platform registry\n * knows and the column is not one the record renderer draws itself. `undefined` otherwise.\n */\nexport function shownAsOf(field: Field): FieldFormatConfig | undefined {\n if (DRAWN_KINDS.has(String(editorKindFor(field)))) return undefined;\n const raw = (field as unknown as { display_format?: unknown }).display_format;\n if (!raw || typeof raw !== \"object\") return undefined;\n const id = (raw as { id?: unknown }).id;\n // `formula` is the column's KIND, never a look: a worked-out column shows as its result format.\n if (typeof id !== \"string\" || id === \"formula\" || !getFieldFormat(id)) return undefined;\n const options = (raw as { options?: unknown }).options;\n return options && typeof options === \"object\" && Object.keys(options).length > 0\n ? ({ id, options } as FieldFormatConfig)\n : ({ id } as FieldFormatConfig);\n}\n\n/**\n * The format a Field's OWN declaration implies, before any view says anything.\n *\n * Returns `undefined` for a Field whose value the record renderer already draws\n * better than a formatter could — a relation chip, a person, an attachment, a\n * choice — because handing those to a text formatter would REPLACE a working\n * control with a string.\n */\n/**\n * A COLUMN THAT HOLDS YEARS (\"Founded\", \"Year\", \"Year built\", \"Established\", \"Model year\"…).\n * A year is a number that is never grouped: \"Founded 2,008\" read as a quantity (lane RECORD-PAGE-UI,\n * 2026-10-15). Known by its name; a value is printed as a year only when it is also a whole number\n * from 1000 to 2999 (`isYearValue`).\n */\nconst YEAR_NAMES = /(^|[\\s_-])(year|founded|established|incorporated|vintage)([\\s_-]|$)/i;\nexport function isYearField(field: Pick<Field, \"key\" | \"label\">): boolean {\n return YEAR_NAMES.test(String(field.label ?? \"\")) || YEAR_NAMES.test(field.key);\n}\nexport function isYearValue(value: unknown): boolean {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1000 && value <= 2999;\n}\n/** A number format with its grouping off for a year column, unless the column chose grouping itself. */\nfunction ungroupedForYears(field: Field, format: FieldFormatConfig): FieldFormatConfig {\n if (format.id !== \"number\" || !isYearField(field)) return format;\n const options = (format.options ?? {}) as Record<string, unknown>;\n if (options[\"useGrouping\"] !== undefined) return format;\n return { ...format, options: { ...options, useGrouping: false } };\n}\n\nexport function formatForField(field: Field): FieldFormatConfig | undefined {\n // \"SHOWS AS\" — THE FORMAT THE COLUMN'S OWN SETTINGS CHOSE (merge tranche 6a/6e). The column\n // keeps it on the Field (`display_format`, written by `custom.field_update`), so the grid, the\n // record panel and the export read one answer. A column the record renderer draws better than\n // a formatter (a choice, a link, a person, a file) keeps its own drawing.\n const shownAs = shownAsOf(field);\n // A RATING'S TOP STAR IS ITS MAX RULE (lane 10 P4), so changing the rule changes the stars.\n if (newerKindOf(field) === \"rating\" && (!shownAs || shownAs.id === \"rating\")) {\n return { id: \"rating\", options: { ...(shownAs?.options ?? {}), ratingMax: ratingMaxOf(field) } };\n }\n if (shownAs) return ungroupedForYears(field, shownAs);\n // THE STORE'S OWN STAMPS (Created time, Last changed time) are instants and print like\n // every other date-and-time cell — `dates.ts` answers, the same helper every card reads.\n const stamp = dateFormatFor(field);\n if (stamp && editorKindFor(field) !== \"datetime\") return stamp;\n switch (editorKindFor(field)) {\n case \"currency\":\n return {\n id: \"currency\",\n options: { currency: currencyCodeFor(field.unit) },\n };\n case \"percent\":\n return { id: \"percent\" };\n case \"datetime\":\n // The COLUMN's declaration: a `kind: \"date\"` column is a date column, anything else can\n // hold a moment. Each VALUE is still printed in its own shape (`RecordValue` →\n // `dates.dateFormatFor(field, value)`), so a bare date in a datetime column reads as a date.\n return String(field.config?.[\"kind\"] ?? \"\") === \"date\" ? { id: \"date\" } : { id: \"datetime\" };\n case \"email\":\n return { id: \"email\" };\n case \"url\":\n return { id: \"url\" };\n case \"phone\":\n return { id: \"phone\" };\n case \"number\":\n return ungroupedForYears(field, { id: \"number\" });\n default:\n return undefined;\n }\n}\n\n/**\n * THE FORMAT ONE CELL OF A COLUMN IS DRAWN IN — the grid's cell and the gallery's card alike\n * (guard G4 \"one format\", lane VIEWS-AND-FIELDS W1-B): the view's own format for the column when\n * it set one, else the Field's own (`formatForField`). One function, so no layout formats money\n * (or a date, or a percent) its own way.\n */\nexport function cellFormatFor(field: Field, viewFormat?: FieldFormatConfig | undefined): FieldFormatConfig | undefined {\n return viewFormat ?? formatForField(field);\n}\n\n/**\n * The store lets a person type the SYMBOL they think in (`$`, `€`), and\n * `Intl.NumberFormat` wants the ISO code. The symbols people actually enter are\n * mapped; anything else is passed straight through, because a real ISO code is\n * the other thing that lands in this field, and an unknown code still renders\n * (`1,234.00 XYZ`) rather than blanking — THE FALLBACK LAW.\n */\nconst SYMBOL_TO_CODE: Record<string, string> = {\n $: \"USD\",\n \"£\": \"GBP\",\n \"€\": \"EUR\",\n \"¥\": \"JPY\",\n \"₹\": \"INR\",\n \"₽\": \"RUB\",\n \"₩\": \"KRW\",\n \"R$\": \"BRL\",\n \"C$\": \"CAD\",\n \"A$\": \"AUD\",\n};\n\nexport function currencyCodeFor(unit: string | null | undefined): string {\n const raw = (unit ?? \"\").trim();\n if (raw === \"\") return \"USD\";\n return SYMBOL_TO_CODE[raw] ?? raw.toUpperCase();\n}\n\n/**\n * The color a value paints with when a view colors BY a column.\n *\n * NOTHING FAILS SILENTLY, so this never returns \"no color\" for a value that\n * exists. The store keeps a list column's choices as records of another Table,\n * and this grid has not read that Table's option colors, so the color is\n * derived from the value's own text: the same word always gets the same color,\n * different words get different ones, and `true` is green the way every\n * checklist reads. When those option colors do land, this is the ONE function\n * that changes and every screen follows.\n */\nexport const colorFromTheValue: ChoiceColorLookup = (_fieldKey, value) => {\n if (value === true) return \"green\";\n if (value === false || value === null || value === undefined) return undefined;\n const text = String(value).trim().toLowerCase();\n if (text === \"\") return undefined;\n let hash = 0;\n for (let i = 0; i < text.length; i += 1) {\n hash = (hash * 31 + text.charCodeAt(i)) >>> 0;\n }\n return COLOR_ROTATION[hash % COLOR_ROTATION.length] as StyleColor;\n};\n\n/**\n * G1's TABLE-LEVEL COLORS (`custom.table_decorations` / `client.tableDecorations`),\n * TRANSLATED INTO A `TableStyle` — the same document a saved view's own `presentation.style`\n * is, so one resolver (`resolveTableStyle`, below) can treat \"the table's colors\" and \"this\n * view's colors\" as two layers of the SAME thing instead of two unrelated systems.\n *\n * THE TRANSLATION IS NECESSARY AND IT IS THE ONLY ONE. G1 addresses a Field by its ID\n * (REC-17 — a column renamed keeps its color), because it is the STORE's own door; a\n * `TableStyle` addresses a Field by its KEY, because it reads straight off `row.document`,\n * which is keyed by Field key. A rule or a color-by whose Field has been deleted (its id no\n * longer resolves to a key) is dropped rather than crashing the whole style — a defect in\n * one rule costs that rule, never the read.\n */\nexport function styleFromDecorations(\n decorations: TableDecorations | null | undefined,\n fields: readonly Field[],\n): TableStyle {\n if (!decorations) return { version: 1 };\n const keyOf = (id: string) => fields.find((f) => f.id === id)?.key;\n const style: TableStyle = { version: 1 };\n\n if (decorations.color_by?.field) {\n const field = keyOf(decorations.color_by.field);\n if (field) style.colorBy = { field, target: decorations.color_by.target };\n }\n\n if (Array.isArray(decorations.rules) && decorations.rules.length > 0) {\n const rules: ColorRule[] = [];\n decorations.rules.forEach((rule, index) => {\n const field = keyOf(rule.field);\n if (!field) return;\n rules.push({\n id: rule.id ?? `decoration:${index}`,\n field,\n op: rule.op,\n color: rule.color,\n target: rule.target,\n ...(rule.value === undefined || rule.value === null ? {} : { value: String(rule.value) }),\n });\n });\n if (rules.length > 0) style.rules = rules;\n }\n\n if (decorations.rows && Object.keys(decorations.rows).length > 0) {\n style.rows = { ...decorations.rows };\n }\n\n const columns: Record<string, StyleColor> = {};\n for (const [id, color] of Object.entries(decorations.columns ?? {})) {\n const key = keyOf(id);\n if (key) columns[key] = color;\n }\n if (Object.keys(columns).length > 0) style.columns = columns;\n\n const cells: Record<string, Record<string, StyleColor>> = {};\n for (const [rowId, byField] of Object.entries(decorations.cells ?? {})) {\n for (const [id, color] of Object.entries(byField ?? {})) {\n const key = keyOf(id);\n if (!key) continue;\n (cells[rowId] ??= {})[key] = color;\n }\n }\n if (Object.keys(cells).length > 0) style.cells = cells;\n\n return style;\n}\n\n/**\n * THE ONE PRESENTATION RESOLVER every colored surface in this package reads —\n * `Grid`, and (via `Card`) the kanban board, the calendar and the gallery.\n *\n * THE CLASS THIS CLOSES (lane UI-QUICK-1, TABLE-PARITY review, 2026-09-24). Threading\n * `view.presentation.style` into `Card` closed the instance the CALENDAR-GALLERY bench\n * found — a VIEW that had its own color-by looked right everywhere — but it left the\n * class open: a table whose colors are the ORGANIZATION's decorations (G1's\n * `custom.table_decorations` — \"color rows by Account Type\", \"MAXED and NEAR rules\" on\n * Arman's own Coding Accounts table) and whose views never set a `presentation.style` of\n * their own drew NOTHING, on the grid exactly as much as on every other layout, because\n * nothing in this package had ever read G1's door at all.\n *\n * TWO LAYERS, ONE DOCUMENT. The table's decorations are the base coat — what every view\n * of this table shows until a view says otherwise. A view's OWN `presentation.style` is\n * an override, piece by piece: a view that only ever set manual row highlights still\n * inherits the table's color-by and rules for everything it never touched, and a view\n * that fully redecorated (its own `colorBy` AND its own `rules`) is not haunted by a\n * table rule it meant to replace. Per-piece, never all-or-nothing, because a view is a\n * LOOK on top of the table, not a wholesale substitute for it.\n */\nexport function resolveTableStyle(\n decorations: TableDecorations | null | undefined,\n fields: readonly Field[],\n viewStyle: TableStyle | undefined,\n): TableStyle {\n const base = styleFromDecorations(decorations, fields);\n if (!viewStyle) return base;\n const colorBy = viewStyle.colorBy ?? base.colorBy;\n const rules = viewStyle.rules ?? base.rules;\n const rows = viewStyle.rows ?? base.rows;\n const columns = viewStyle.columns ?? base.columns;\n const cells = viewStyle.cells ?? base.cells;\n return {\n version: 1,\n ...(colorBy !== undefined ? { colorBy } : {}),\n ...(rules !== undefined ? { rules } : {}),\n ...(rows !== undefined ? { rows } : {}),\n ...(columns !== undefined ? { columns } : {}),\n ...(cells !== undefined ? { cells } : {}),\n };\n}\n","// src/pages.ts — @ai-matrx/records-ui\n//\n// A PAGE BUILT FROM TABLES (v6 lane 11, wave D; DASHBOARDS-AND-PAGES-MODEL §0). A Page is NOT a new\n// record type: it is a dashboard record (`custom.record`, `data_class = 'dashboard'`) whose\n// `presentation.kind` is `\"page\"`. `custom.dashboard_declare` stores `presentation` exactly as given\n// (read on the clone, 2026-10-03), so no new store door is needed:\n//\n// · chart blocks stay in `blocks` — judged by `dashboard_block_normalize`, answered by `dashboard_run`;\n// · every other block lives in `presentation.page_blocks`, each with a stable `id`;\n// · `presentation.page_blocks` is ALSO the page's reading order: a chart appears there as\n// `{ kind: \"chart\", id }`, where `id` is the chart's own block id in `blocks`.\n//\n// Every data block reads through the existing client doors under the viewer's own principal\n// (list / read / form / action), so a column the store hides from a viewer never reaches a block.\n// Champion: Airtable Interfaces — list, record detail, buttons and filters as elements on one page.\n\nimport type { DashboardSummary, RecordFilter, RuleExpression, StoreFilter, Uuid } from \"@ai-matrx/records\";\nimport { isRuleFilter } from \"@ai-matrx/records/views\";\n\n/** Every kind of block a page holds. `chart` points at a block in the dashboard's own `blocks`. */\nexport const PAGE_BLOCK_KINDS = [\n \"list\",\n \"layout\",\n \"review\",\n \"record\",\n \"number\",\n \"button\",\n \"form\",\n \"filter\",\n \"chart\",\n \"heading\",\n \"text\",\n \"image\",\n \"embed\",\n \"applet\",\n] as const;\nexport type PageBlockKind = (typeof PAGE_BLOCK_KINDS)[number];\n\n/** What \"Add block\" reads for each kind. */\nexport const PAGE_BLOCK_LABEL: Record<PageBlockKind, string> = {\n list: \"List\",\n layout: \"Layout\",\n review: \"Record review\",\n record: \"Record panel\",\n number: \"Number\",\n button: \"Button\",\n form: \"Form\",\n filter: \"Filter\",\n chart: \"Chart\",\n heading: \"Heading\",\n text: \"Text\",\n image: \"Image\",\n embed: \"Embed\",\n applet: \"Applet\",\n};\n\n/**\n * AT-INTERFACE — the table layouts a page element draws, each through the ONE renderer of that layout\n * (`ViewSwitcher`), never a page copy of a board or a calendar.\n */\nexport const ELEMENT_LAYOUTS = [\"grid\", \"gallery\", \"kanban\", \"calendar\", \"timeline\", \"map\", \"orgchart\"] as const;\nexport type ElementLayout = (typeof ELEMENT_LAYOUTS)[number];\nexport const ELEMENT_LAYOUT_LABEL: Record<ElementLayout, string> = {\n grid: \"Grid\",\n gallery: \"Gallery\",\n kanban: \"Kanban\",\n calendar: \"Calendar\",\n timeline: \"Timeline\",\n map: \"Map\",\n orgchart: \"Org chart\",\n};\n\n/** What \"Add element\" offers, in Airtable's order: data views first, then numbers, actions and layout pieces. */\nexport type AddChoice = PageBlockKind | `layout:${ElementLayout}`;\nexport const ADD_CHOICES: readonly { value: AddChoice; label: string }[] = [\n { value: \"list\", label: \"List\" },\n ...ELEMENT_LAYOUTS.map((l) => ({ value: `layout:${l}` as AddChoice, label: ELEMENT_LAYOUT_LABEL[l] })),\n { value: \"review\", label: \"Record review\" },\n { value: \"record\", label: \"Record panel\" },\n { value: \"number\", label: \"Number\" },\n { value: \"chart\", label: \"Chart\" },\n { value: \"button\", label: \"Button\" },\n { value: \"form\", label: \"Form\" },\n { value: \"filter\", label: \"Filter\" },\n { value: \"heading\", label: \"Heading\" },\n { value: \"text\", label: \"Text\" },\n { value: \"image\", label: \"Image\" },\n { value: \"embed\", label: \"Embed\" },\n { value: \"applet\", label: \"Applet\" },\n];\n\n/** A titled group of fields on a record detail (Airtable's field groups). */\nexport interface FieldGroup {\n title: string;\n fields: string[];\n}\n\n/**\n * Who sees which rows. `me_field` names a person / email / relation column (Airtable's \"current user\"\n * filter): a viewer OUTSIDE the organization always sees only the rows that point at her (the store applies\n * it, `custom.interface_rows`); `me_only` applies the same rule to members too.\n */\ninterface ScopedRows {\n table_id: Uuid;\n view_id?: Uuid | null;\n filter?: RecordFilter;\n columns?: string[];\n me_field?: string | null;\n me_only?: boolean;\n}\n\ninterface PageBlockBase {\n /** Stable across saves, moves and resizes. */\n id: string;\n /** Width in twelfths from 640 px up (`dashboardLayout.ts`); full width on a phone. */\n span?: number;\n title?: string;\n}\n\nexport interface ListPageBlock extends PageBlockBase {\n kind: \"list\";\n /** \"Current user\": only the viewer's rows, always (see `ScopedRows`). */\n me_only?: boolean;\n table_id: Uuid;\n /** A saved view of the table: its filter and sort shape the list. */\n view_id?: Uuid | null;\n /** The block's own question, the store's flat filter (field key → value). */\n filter?: RecordFilter;\n /** The columns shown, by field key; left out, the first few the table declares. */\n columns?: string[];\n /** A person column. Offers \"Assigned to me\": the viewer's own Person record against it. */\n me_field?: string | null;\n /** Whether \"Assigned to me\" starts on. */\n me_default?: boolean;\n limit?: number;\n}\n\nexport interface RecordPageBlock extends PageBlockBase {\n kind: \"record\";\n /** The list block whose selected row this panel shows. */\n source: string;\n /** Shown as titled groups instead of the whole record. */\n field_groups?: FieldGroup[];\n}\n\n/** A table drawn as one layout on the page. */\nexport interface LayoutPageBlock extends PageBlockBase, ScopedRows {\n kind: \"layout\";\n layout: ElementLayout;\n group_field?: string | null;\n date_field?: string | null;\n end_field?: string | null;\n image_field?: string | null;\n /** Map: the address or latitude column, and the longitude column when it is a latitude. */\n map_field?: string | null;\n map_lng_field?: string | null;\n /** Org chart: the link column to this table that says who a record reports to. */\n parent_field?: string | null;\n}\n\n/** Record review: the records on one side, the chosen one beside it, with next and previous. */\nexport interface ReviewPageBlock extends PageBlockBase, ScopedRows {\n kind: \"review\";\n field_groups?: FieldGroup[];\n}\n\n/** One number: how many records answer the element's question. */\nexport interface NumberPageBlock extends PageBlockBase, ScopedRows {\n kind: \"number\";\n}\n\nexport interface ImagePageBlock extends PageBlockBase {\n kind: \"image\";\n url: string;\n alt?: string;\n}\n\nexport interface EmbedPageBlock extends PageBlockBase {\n kind: \"embed\";\n url: string;\n}\n\nexport interface ButtonPageBlock extends PageBlockBase {\n kind: \"button\";\n /** The list block whose selected row the action runs on. */\n source: string;\n table_id: Uuid;\n /** An existing row action of that table (`custom.row_actions`). */\n action_id: Uuid;\n}\n\nexport interface FormPageBlock extends PageBlockBase {\n kind: \"form\";\n table_id: Uuid;\n form_id: Uuid;\n}\n\nexport interface FilterPageBlock extends PageBlockBase {\n kind: \"filter\";\n table_id: Uuid;\n /** A choice (or yes/no) column of that table. */\n field: string;\n /** The list blocks it narrows. Empty = every list on the page over the same table. */\n targets?: string[];\n}\n\nexport interface ChartPageBlock extends PageBlockBase {\n kind: \"chart\";\n}\n\nexport interface HeadingPageBlock extends PageBlockBase {\n kind: \"heading\";\n text: string;\n}\n\nexport interface TextPageBlock extends PageBlockBase {\n kind: \"text\";\n text: string;\n}\n\n/**\n * AN APPLET ON THE PAGE (v7 APPS-ON-DATA item 3 — Arman's endgame, 2026-10-02: one custom start page\n * per person, built on the applets system, nested applets). The host draws it (`RecordsUiHost.applets`);\n * this package only keeps which one, so a page can mix a person's own data with platform features.\n */\nexport interface AppletPageBlock extends PageBlockBase {\n kind: \"applet\";\n /** The applet (agent app) id; empty until chosen. */\n app_id: string;\n}\n\nexport type PageBlock =\n | ListPageBlock\n | LayoutPageBlock\n | ReviewPageBlock\n | NumberPageBlock\n | ImagePageBlock\n | EmbedPageBlock\n | RecordPageBlock\n | ButtonPageBlock\n | FormPageBlock\n | FilterPageBlock\n | ChartPageBlock\n | HeadingPageBlock\n | TextPageBlock\n | AppletPageBlock;\n\n/** The `presentation.kind` that makes a dashboard record a Page. */\nexport const PAGE_KIND = \"page\";\n\n/** Is this dashboard row a Page? Every row with no kind is a dashboard (the store's default). */\nexport function isPage(row: Pick<DashboardSummary, \"presentation\"> | { presentation?: unknown }): boolean {\n const p = row.presentation as Record<string, unknown> | null | undefined;\n return !!p && typeof p === \"object\" && p[\"kind\"] === PAGE_KIND;\n}\n\nfunction isBlock(value: unknown): value is PageBlock {\n if (!value || typeof value !== \"object\") return false;\n const b = value as Record<string, unknown>;\n return typeof b[\"id\"] === \"string\" && typeof b[\"kind\"] === \"string\" && (PAGE_BLOCK_KINDS as readonly string[]).includes(b[\"kind\"] as string);\n}\n\n/**\n * The page's blocks in reading order, read strictly out of `presentation`. A chart the store holds\n * in `blocks` but the order does not name is appended (it was added by an agent or the old canvas),\n * and a `chart` entry whose block is gone is dropped — the page never draws a block it cannot answer.\n */\nexport function pageBlocksOf(presentation: Record<string, unknown> | null | undefined, chartIds: readonly string[]): PageBlock[] {\n const raw = presentation?.[\"page_blocks\"];\n const listed = (Array.isArray(raw) ? raw : []).filter(isBlock);\n const charts = new Set(chartIds);\n const kept = listed.filter((b) => b.kind !== \"chart\" || charts.has(b.id));\n const named = new Set(kept.filter((b) => b.kind === \"chart\").map((b) => b.id));\n return [...kept, ...chartIds.filter((id) => !named.has(id)).map((id): ChartPageBlock => ({ id, kind: \"chart\" }))];\n}\n\n/** The presentation a page is saved with: its kind and its blocks, everything else it held kept. */\nexport function pagePresentation(presentation: Record<string, unknown> | null | undefined, blocks: readonly PageBlock[]): Record<string, unknown> {\n return { ...(presentation ?? {}), kind: PAGE_KIND, page_blocks: blocks };\n}\n\n/** A fresh block id. */\nexport function newBlockId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * THE STARTER PAGE on one table, the way Airtable's record-review layout starts: the table's records\n * on the left, the chosen one on the right. One press makes a page that already works.\n */\nexport function starterPageBlocks(tableId: Uuid): PageBlock[] {\n const list = newBlockId();\n return [\n { id: list, kind: \"list\", table_id: tableId, span: 6 },\n { id: newBlockId(), kind: \"record\", source: list, span: 6 },\n ];\n}\n\n/** The list blocks a filter block narrows: those it names, or every list over its table. */\nexport function filterTargets(filter: FilterPageBlock, blocks: readonly PageBlock[]): string[] {\n if (filter.targets && filter.targets.length > 0) return filter.targets;\n return blocks.filter((b): b is ListPageBlock => b.kind === \"list\" && b.table_id === filter.table_id).map((b) => b.id);\n}\n\n/**\n * ONE QUESTION FOR A LIST BLOCK, in the store's own filter shapes. `base` is the view's question —\n * its `where` Rule or its flat `filters` — and `extra` the page's own (the block's filter, the\n * filter blocks, \"Assigned to me\"), all equalities by key. Both flat: one merged map (the page's\n * value wins). The view asks a Rule: the extras join it under `and`, by field id, which is the only\n * way the Rule shape names a column (REC-17). An extra whose key has no id is left out and named.\n */\nexport function combineFilter(\n base: StoreFilter | null | undefined,\n extra: RecordFilter,\n fieldIdOf: (key: string) => string | undefined,\n): { filter: StoreFilter | null; dropped: string[] } {\n const extraKeys = Object.keys(extra);\n if (!base || (!isRuleFilter(base) && Object.keys(base).length === 0)) {\n return { filter: extraKeys.length > 0 ? { ...extra } : null, dropped: [] };\n }\n if (!isRuleFilter(base)) return { filter: { ...(base as RecordFilter), ...extra }, dropped: [] };\n const dropped: string[] = [];\n let rule: RuleExpression = base;\n for (const key of extraKeys) {\n const id = fieldIdOf(key);\n if (!id) {\n dropped.push(key);\n continue;\n }\n const value = extra[key];\n const leaf: RuleExpression =\n value === null\n ? { op: \"not\", args: [{ op: \"present\", args: [{ field: id }] }] }\n : { op: \"eq\", args: [{ field: id }, { const: value }] };\n rule = { op: \"and\", args: [rule, leaf] };\n }\n return { filter: rule, dropped };\n}\n\n/** The kinds of element that read rows of a table (and so may be read through the interface door). */\nexport const ROW_ELEMENT_KINDS: ReadonlySet<PageBlockKind> = new Set([\"list\", \"layout\", \"review\", \"number\"]);\n\n/**\n * A NEW ELEMENT of one kind, on the page's first table. A chart also returns its spec (charts live in the\n * dashboard's own `blocks`). `ChartSpec` is passed in by the caller so this module stays free of chart code.\n */\nexport function newElement(\n choice: AddChoice,\n blocks: readonly PageBlock[],\n subject: Uuid,\n): PageBlock {\n const firstList = blocks.find((b): b is ListPageBlock => b.kind === \"list\");\n const firstTable = blocks.find((b): b is ListPageBlock | LayoutPageBlock | ReviewPageBlock =>\n b.kind === \"list\" || b.kind === \"layout\" || b.kind === \"review\",\n );\n const table = (firstTable?.table_id ?? subject) as Uuid;\n const id = newBlockId();\n if (choice.startsWith(\"layout:\")) {\n return { id, kind: \"layout\", layout: choice.slice(7) as ElementLayout, table_id: table, span: 12 };\n }\n switch (choice as PageBlockKind) {\n case \"list\":\n return { id, kind: \"list\", table_id: table, span: 6 };\n case \"review\":\n return { id, kind: \"review\", table_id: table, span: 12 };\n case \"record\":\n return { id, kind: \"record\", source: firstList?.id ?? \"\", span: 6 };\n case \"number\":\n return { id, kind: \"number\", table_id: table, span: 3, title: \"Records\" };\n case \"button\":\n return { id, kind: \"button\", source: firstList?.id ?? \"\", table_id: table, action_id: \"\" as Uuid, span: 4 };\n case \"form\":\n return { id, kind: \"form\", table_id: table, form_id: \"\" as Uuid, span: 6 };\n case \"filter\":\n return { id, kind: \"filter\", table_id: table, field: \"\", span: 4 };\n case \"heading\":\n return { id, kind: \"heading\", text: \"Heading\", span: 12 };\n case \"applet\":\n return { id, kind: \"applet\", app_id: \"\", span: 12 };\n case \"image\":\n return { id, kind: \"image\", url: \"\", span: 6 };\n case \"embed\":\n return { id, kind: \"embed\", url: \"\", span: 12 };\n case \"chart\":\n return { id, kind: \"chart\", span: 6 };\n case \"text\":\n default:\n return { id, kind: \"text\", text: \"\", span: 12 };\n }\n}\n","// src/interfaces.ts — @ai-matrx/records-ui · AT-INTERFACE\n//\n// AN INTERFACE IS A NAMED SET OF PAGES (Airtable's Interface Designer), built on the Page model, never beside\n// it. Like a Page it is a dashboard record (`custom.record`, data_class `dashboard`); its `presentation.kind`\n// is `\"interface\"` and its pages live INSIDE it, so one record is one thing to share, archive and restore:\n//\n// presentation = {\n// kind: \"interface\", icon, color,\n// draft: { pages: InterfacePage[] } ← what builders edit\n// published: { pages: InterfacePage[], version, at, by } | null ← what everybody else sees\n// versions: InterfaceVersion[] ← every publish, newest first (restore)\n// }\n//\n// Each page holds the SAME `PageBlock`s a Page holds (one canvas, `PageCanvas`), plus its own chart specs.\n// The record's `blocks` (what `custom.dashboard_run` answers) is every chart the draft or the published\n// version uses, so a builder previews a draft chart while viewers keep the published one. A published chart is\n// never edited in place: the draft gets a copy under a new id (`withDraftChart`).\n//\n// A person the interface is shared with reads it through `custom.interface_read` / `custom.interface_rows`\n// — only the published pages, only what each element exposes.\n\nimport type { DashboardSummary, Uuid } from \"@ai-matrx/records\";\nimport type { ChartSpec } from \"./charts\";\nimport { newBlockId, type PageBlock } from \"./pages\";\n\nexport const INTERFACE_KIND = \"interface\";\n\n/** How many published versions an interface keeps to restore from. */\nexport const INTERFACE_VERSIONS_KEPT = 20;\n\nexport interface InterfacePage {\n id: string;\n name: string;\n /** A lucide icon name. */\n icon?: string;\n blocks: PageBlock[];\n charts: ChartSpec[];\n}\n\nexport interface InterfacePublished {\n pages: InterfacePage[];\n version: number;\n at: string;\n by?: string | null;\n}\n\nexport interface InterfaceVersion extends InterfacePublished {}\n\nexport interface InterfaceShape {\n icon: string;\n color: string;\n draft: { pages: InterfacePage[] };\n published: InterfacePublished | null;\n versions: InterfaceVersion[];\n}\n\n/** The interface colors, by token name (`INTERFACE_COLOR_CLASS` paints them). */\nexport const INTERFACE_COLORS = [\"blue\", \"green\", \"amber\", \"rose\", \"violet\", \"slate\"] as const;\nexport const INTERFACE_ICONS = [\"layout-dashboard\", \"kanban\", \"calendar\", \"users\", \"briefcase\", \"megaphone\", \"clipboard-check\", \"star\"] as const;\n\nexport function isInterface(row: Pick<DashboardSummary, \"presentation\"> | { presentation?: unknown }): boolean {\n const p = row.presentation as Record<string, unknown> | null | undefined;\n return !!p && typeof p === \"object\" && p[\"kind\"] === INTERFACE_KIND;\n}\n\nfunction pagesOf(value: unknown): InterfacePage[] {\n if (!Array.isArray(value)) return [];\n return value\n .filter((p): p is Record<string, unknown> => !!p && typeof p === \"object\" && typeof (p as Record<string, unknown>)[\"id\"] === \"string\")\n .map((p) => ({\n id: p[\"id\"] as string,\n name: typeof p[\"name\"] === \"string\" && p[\"name\"] ? (p[\"name\"] as string) : \"Page\",\n ...(typeof p[\"icon\"] === \"string\" ? { icon: p[\"icon\"] as string } : {}),\n blocks: Array.isArray(p[\"blocks\"]) ? (p[\"blocks\"] as PageBlock[]) : [],\n charts: Array.isArray(p[\"charts\"]) ? (p[\"charts\"] as ChartSpec[]) : [],\n }));\n}\n\nfunction publishedOf(value: unknown): InterfacePublished | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n return {\n pages: pagesOf(v[\"pages\"]),\n version: typeof v[\"version\"] === \"number\" ? v[\"version\"] : 1,\n at: typeof v[\"at\"] === \"string\" ? v[\"at\"] : \"\",\n by: typeof v[\"by\"] === \"string\" ? v[\"by\"] : null,\n };\n}\n\n/** The interface read strictly out of a presentation. A viewer's copy has no draft: she sees the published pages. */\nexport function interfaceOf(presentation: Record<string, unknown> | null | undefined): InterfaceShape {\n const p = presentation ?? {};\n const published = publishedOf(p[\"published\"]);\n const draftRaw = p[\"draft\"] as Record<string, unknown> | undefined;\n const draftPages = draftRaw && typeof draftRaw === \"object\" ? pagesOf(draftRaw[\"pages\"]) : (published?.pages ?? []);\n return {\n icon: typeof p[\"icon\"] === \"string\" ? (p[\"icon\"] as string) : \"layout-dashboard\",\n color: typeof p[\"color\"] === \"string\" ? (p[\"color\"] as string) : \"blue\",\n draft: { pages: draftPages },\n published,\n versions: Array.isArray(p[\"versions\"]) ? (p[\"versions\"] as unknown[]).map(publishedOf).filter((v): v is InterfaceVersion => !!v) : [],\n };\n}\n\n/** The presentation an interface is saved with. */\nexport function interfacePresentation(shape: InterfaceShape): Record<string, unknown> {\n return {\n kind: INTERFACE_KIND,\n icon: shape.icon,\n color: shape.color,\n draft: shape.draft,\n published: shape.published,\n versions: shape.versions,\n };\n}\n\n/** Every chart the draft or the published version uses, once: what the record's `blocks` holds. */\nexport function interfaceCharts(shape: InterfaceShape): ChartSpec[] {\n const out: ChartSpec[] = [];\n const seen = new Set<string>();\n for (const page of [...shape.draft.pages, ...(shape.published?.pages ?? [])]) {\n for (const chart of page.charts) {\n if (!chart.id || seen.has(chart.id)) continue;\n seen.add(chart.id);\n out.push(chart);\n }\n }\n return out;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/** Does the draft differ from what viewers see? (Never published counts as a change once there is a page.) */\nexport function hasUnpublishedChanges(shape: InterfaceShape): boolean {\n if (!shape.published) return shape.draft.pages.length > 0;\n return !same(shape.draft.pages, shape.published.pages);\n}\n\n/** PUBLISH: the draft becomes what viewers see, and a version is kept to restore. */\nexport function publish(shape: InterfaceShape, at: string, by: string | null): InterfaceShape {\n const version = Math.max(shape.published?.version ?? 0, ...shape.versions.map((v) => v.version), 0) + 1;\n const published: InterfacePublished = { pages: shape.draft.pages, version, at, by };\n return { ...shape, published, versions: [published, ...shape.versions].slice(0, INTERFACE_VERSIONS_KEPT) };\n}\n\n/** CLEAR UNPUBLISHED CHANGES: the draft goes back to what viewers see. */\nexport function clearUnpublished(shape: InterfaceShape): InterfaceShape {\n if (!shape.published) return shape;\n return { ...shape, draft: { pages: shape.published.pages } };\n}\n\n/** RESTORE a version INTO THE DRAFT (Airtable's way): the builder looks, then publishes. */\nexport function restoreInterfaceVersion(shape: InterfaceShape, version: number): InterfaceShape {\n const found = shape.versions.find((v) => v.version === version);\n return found ? { ...shape, draft: { pages: found.pages } } : shape;\n}\n\n/** Replace one draft page. */\nexport function withDraftPage(shape: InterfaceShape, page: InterfacePage): InterfaceShape {\n return { ...shape, draft: { pages: shape.draft.pages.map((p) => (p.id === page.id ? page : p)) } };\n}\n\n/**\n * A CHART EDITED IN THE DRAFT. A chart the published version also shows, with different settings, is copied\n * under a new id so viewers keep theirs until Publish; the page's block order follows the new id.\n */\nexport function withDraftChart(shape: InterfaceShape, page: InterfacePage, chart: ChartSpec): InterfacePage {\n const published = (shape.published?.pages ?? []).flatMap((p) => p.charts).find((c) => c.id === chart.id);\n if (!published || same(published, chart)) {\n return { ...page, charts: page.charts.map((c) => (c.id === chart.id ? chart : c)) };\n }\n const id = newBlockId();\n return {\n ...page,\n charts: page.charts.map((c) => (c.id === chart.id ? { ...chart, id } : c)),\n blocks: page.blocks.map((b) => (b.kind === \"chart\" && b.id === chart.id ? { ...b, id } : b)),\n };\n}\n\n/** A new page, empty or with one starter element. */\nexport function newInterfacePage(name: string, blocks: PageBlock[] = [], charts: ChartSpec[] = []): InterfacePage {\n return { id: newBlockId(), name, blocks, charts };\n}\n\n/** A fresh interface on one table: an Overview page with that table's records, nothing published yet. */\nexport function newInterfaceShape(tableId: Uuid): InterfaceShape {\n const list = newBlockId();\n return {\n icon: \"layout-dashboard\",\n color: \"blue\",\n draft: {\n pages: [\n newInterfacePage(\"Overview\", [\n { id: list, kind: \"list\", table_id: tableId, span: 6 },\n { id: newBlockId(), kind: \"record\", source: list, span: 6 },\n ]),\n ],\n },\n published: null,\n versions: [],\n };\n}\n\n/** The page a viewer is on: by id, else the first one. */\nexport function pageById(pages: readonly InterfacePage[], id: string | null | undefined): InterfacePage | null {\n return pages.find((p) => p.id === id) ?? pages[0] ?? null;\n}\n","// src/tableLanes.ts — @ai-matrx/records-ui · which lane of the tables home one Table sits in, with no React\n//\n// Pure, so `/helpers` carries `laneFor` and a host's table switcher sorts tables before it loads any\n// screen (records-ui front door, 2026-10-16). `TablesHome.tsx` re-exports it. Why the platform's own\n// tables get a lane of their own: the comment above `LANE_EMPTY` in `TablesHome.tsx`.\n\nimport type { Table } from \"@ai-matrx/records\";\n\nexport type TableLane = \"mine\" | \"organization\" | \"system\" | \"community\" | \"app\";\n\n/** The slug prefix of the tables this package keeps for itself (saved views, comments). */\nexport const PLATFORM_TABLE_PREFIX = \"records_ui_\";\n\n/**\n * WHETHER THE STORE ITSELF KEEPS THIS TABLE FOR THE APP — a choice list made per\n * choice field, for one. The Table record's document carries `kept_by_the_app:\n * true`, and `tableList()` spreads the whole document onto the Table; the\n * `Table` interface does not declare it yet, so it is read through this one\n * narrow cast.\n *\n * 🚨 MEASURED ON RINCON PLUMBING CO (VERIFIER-15): 13 \"Crew choices\" and 14\n * \"Status choices\" tables sat under My organization here, beside Jobs and\n * Invoices, while the organization hub above them already counted them as the\n * app's. Two lists on one page disagreed about the same 27 tables. They go to\n * the app's lane, with the saved views.\n */\nexport function platformOwned(table: Table): boolean {\n // `platform_owned` is the store's answer (the facts door); `kept_by_the_app` is the stored document key.\n const t = table as unknown as { platform_owned?: unknown; kept_by_the_app?: unknown };\n return t.platform_owned === true || t.kept_by_the_app === true;\n}\n\n/** Which lane one Table belongs to, from the record's own columns. */\nexport function laneFor(table: Table): TableLane {\n if (table.is_kernel) return \"system\";\n if ((table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX) || platformOwned(table)) return \"app\";\n if (publishedToWeb(table)) return \"community\";\n if (shownToOnlyMe(table)) return \"mine\";\n return \"organization\";\n}\n\n/** Published to the web — the store's own column, else its old lane word. */\nexport function publishedToWeb(table: Table): boolean {\n if (typeof table.published_to_web === \"boolean\") return table.published_to_web;\n return table.visibility === \"public\" || table.visibility === \"link\";\n}\n\n/** Shown to \"Only me\" — the store's own column, else its old lane word. */\nexport function shownToOnlyMe(table: Table): boolean {\n if (table.shown_to !== undefined) return table.shown_to === \"only_me\";\n return table.visibility === \"personal\";\n}\n","// src/bodyField.ts — @ai-matrx/records-ui · which column a record page writes its body in, with no React\n//\n// Pure, so `/helpers` carries it (records-ui front door, 2026-10-16). `RecordBody.tsx` re-exports it.\n\nimport type { Field } from \"@ai-matrx/records\";\nimport { newerKindOf } from \"@ai-matrx/records/field-kinds\";\n\n/** The names a page's body goes by (Notion's page content), in a person's words. */\nconst BODY_NAMES = /^(notes?|page|body|content|page content|details|description)$/i;\n\n/**\n * The column a record page writes its body in: the formatted-text column NAMED like a page's body\n * (\"Notes\", \"Page content\"…), else the table's first formatted-text column. A \"Caption\" before a\n * \"Notes\" stays a field (walk 2026-10-05: the body took the Caption).\n */\nexport function bodyFieldOf(fields: readonly Field[]): Field | undefined {\n const rich = fields.filter((field) => newerKindOf(field) === \"rich_text\");\n return rich.find((field) => BODY_NAMES.test((field.label ?? field.key).trim()) || BODY_NAMES.test(field.key.replace(/_/g, \" \"))) ?? rich[0];\n}\n","// src/viewKeys.ts — @ai-matrx/records-ui · lane S1-PRIME VIEW-KEYS\n//\n// THE VIEW-KEY REGISTRY MOVED TO `@ai-matrx/records/views` (step 10, 2026-10-08): the declared keys, the one\n// reader and the one writer are headless there. What stays here is this package's LOOK: the grid\n// presentation (colors, formats, frozen columns — `presentation.ts`, built on design-system) bound as the\n// view's presentation codec. Every name this file exported is unchanged.\n\nimport * as base from \"@ai-matrx/records/views\";\nimport { parseGridPresentation, presentationDocument, presentationIsEmpty, type GridPresentation } from \"./presentation\";\n\nexport {\n STORE_KEEPS_SWIPE,\n STORE_KEEPS_TIMELINE,\n STORE_KEPT_LAYOUTS,\n VIEW_KEYS,\n storeKeepsLayout,\n viewKeysFor,\n viewSettingsFor,\n type ViewKeyDeclaration,\n type ViewKeyLayout,\n type ViewKeyWriter,\n type ViewSortKey,\n} from \"@ai-matrx/records/views\";\n\n/** This package's look, as the view's presentation codec. */\nexport const gridPresentationCodec: base.ViewPresentationCodec<GridPresentation> = {\n parse: parseGridPresentation,\n isEmpty: presentationIsEmpty,\n toDocument: (presentation) => JSON.parse(presentationDocument(presentation)) as Record<string, unknown>,\n};\n\n/** EVERY DECLARED KEY OF A VIEW, TYPED, with this package's grid look. */\nexport type ViewSettings = base.ViewSettings<GridPresentation>;\nexport type ViewSettingsPatch = base.ViewSettingsPatch<GridPresentation>;\n\n/** Every view and look door with this package's grid look bound — bindings of records' one definition. */\nexport const boundViews = base.bindViewCodec<GridPresentation>(gridPresentationCodec);\n\n/** THE READER (a stored `definition` and the row's flat `filters` in, every declared key out) and THE WRITER'S SHAPE. */\nexport const { viewSettings, viewSettingsPatch } = boundViews;\n","// src/viewLook.ts — @ai-matrx/records-ui · lane VIEW-STATE-PERSONAL (VERIFIER-23 item 1, 2026-09-25)\n//\n// A LOOK AT A VIEW IS YOURS UNTIL YOU SAVE IT.\n//\n// On production the owner of a maintenance-requests table grouped its board by Status, and the\n// tenant liaison's board came up grouped by Status the next time she opened it: every pick was\n// written onto the shared view. Airtable and Notion keep the two apart — how you are looking at a\n// shared view (its grouping, its date field, its sort, its filter, hidden columns, widths, the\n// layout) is YOUR look, it persists for you, and the view changes only when you press \"Save to\n// view\" (Notion's \"Save for everyone\"), save it as a new view, or \"Reset to view\".\n//\n// The store keeps one look per (person, view) through `custom.view_look_set` / `view_look_read`\n// (viewer on the table, never written onto the view row). This file is the look's shape on this\n// side: the keys a look may hold, how it reads back, how it lays over the view, and what \"Save to\n// view\" sends.\n\nimport * as base from \"@ai-matrx/records/views\";\n\nimport type { GridPresentation } from \"./presentation\";\nimport { boundViews } from \"./viewKeys\";\n\n// The look's logic moved to `@ai-matrx/records/views` (step 10, 2026-10-08); this package binds its grid look.\nexport { applyLook, lookDiffers, lookPart, saveToViewPlan } from \"@ai-matrx/records/views\";\n\n/** What a look may hold, with this package's grid look. */\nexport type ViewLook = base.ViewLook<GridPresentation>;\n\nexport const { lookDocument, lookFromDocument, readLooks, keepLook } = boundViews;\n\n/** The words of the look bar. One sentence, then the doors. */\nexport const LOOK_WORDS = {\n /** The reason, for a tooltip or a screen reader — never a line on the page (interface-text). */\n yours: \"You changed how this view looks. Only you see it.\",\n /** The visible label for the same fact. */\n yoursLabel: \"Only you see this\",\n saveToView: \"Save to view\",\n saveAsNew: \"Save as new view\",\n reset: \"Reset to view\",\n /** The one button your look's doors fold into when the toolbar row has no room for three. */\n folded: \"Your look\",\n newName: \"Name for the new view\",\n} as const;\n\n/**\n * WHAT \"RESET VIEW\" KEEPS (member walk, 2026-10-10). Reset puts back the saved view's QUESTION — search,\n * sort, filter and grouping — and keeps how the person has laid the columns out: their order, widths,\n * frozen columns, hidden columns, row height and layout (Notion's \"Reset\" on unsaved view changes\n * reverts the filters and sorts and leaves the property layout alone; Airtable's per-person column\n * arrangement likewise survives clearing a filter). `null` when nothing of the look is left to keep.\n */\nconst QUESTION_KEYS = [\"sorts\", \"where\", \"groupField\", \"swimlaneField\"] as const;\nexport function lookAfterReset(look: ViewLook | null | undefined): ViewLook | null {\n if (!look) return null;\n const kept: Record<string, unknown> = { ...look };\n for (const key of QUESTION_KEYS) delete kept[key];\n // Grouping lives on the look's presentation (the Group control writes `presentation.grouping`): Reset clears it too.\n const presentation = kept[\"presentation\"];\n if (presentation && typeof presentation === \"object\") {\n const { grouping: _grouping, ...layout } = presentation as Record<string, unknown>;\n if (Object.keys(layout).length > 0) kept[\"presentation\"] = layout;\n else delete kept[\"presentation\"];\n }\n for (const key of Object.keys(kept)) if (kept[key] === undefined) delete kept[key];\n return Object.keys(kept).length > 0 ? (kept as ViewLook) : null;\n}\n","// src/views.ts — @ai-matrx/records-ui · SCR-6, SCR-7, SCR-N-6\n//\n// SAVED VIEWS MOVED TO `@ai-matrx/records/views` (step 10, 2026-10-08): the spec, the layouts, the page-view\n// words and the doors that keep a view (`declareView`, `saveViewPatch`, `designateView`) are headless there.\n// This file binds this package's grid look (`gridPresentationCodec`, viewKeys.ts) so every name it exported\n// keeps its signature: `SavedViewSpec.presentation` is a `GridPresentation` here.\n\nimport * as base from \"@ai-matrx/records/views\";\nimport type { GridPresentation } from \"./presentation\";\nimport { boundViews } from \"./viewKeys\";\n\nexport {\n STORE_KEEPS_TIMELINE,\n STORE_KEPT_LAYOUTS,\n storeKeepsLayout,\n VIEW_LAYOUTS,\n LAYOUT_LABEL,\n wordsList,\n VIEW_NEEDS,\n freeColumnName,\n viewOrderOf,\n defaultViewOf,\n LAYOUT_FIELD_KIND,\n PAGE_VIEWS,\n PAGE_VIEW_LABEL,\n pageViewFromParam,\n unknownViewLine,\n makeDefaultLabel,\n designateView,\n viewPatchFor,\n groupViewsBySection,\n planViewDrop,\n sectionDropId,\n type ViewDropWrite,\n sectionNames,\n sectionNameOk,\n reassignSection,\n type ViewSection,\n type ViewLayout,\n type ViewNeedKind,\n type ViewNeed,\n type ViewSort,\n type ViewOrder,\n type PageView,\n} from \"@ai-matrx/records/views\";\n\n/** THE DECLARATIVE SPEC, with this package's grid look. */\nexport type SavedViewSpec = base.SavedViewSpec<GridPresentation>;\n/** A saved view as it comes back out of the store, with its row's own id. */\nexport type SavedView = base.SavedView<GridPresentation>;\n\n/** The view's doors with this package's grid look bound — bindings of records' one definition. */\nexport const { viewDocument, viewFromRow, declareView, saveViewPatch, viewPatchDocument } = boundViews;\n","// src/viewAddressParams.ts — @ai-matrx/records-ui · the view in the address bar, as words, with no React\n//\n// Pure, so `/helpers` carries it and a host route reads and writes the address before it loads any\n// screen (records-ui front door, 2026-10-16). `viewAddress.ts` re-exports all of it beside its context.\n\n/** The words this feature owns in an address. A host must not use them for anything else. */\nexport const VIEW_ADDRESS_KEYS = [\"sort\", \"cf\", \"q\", \"hide\", \"page\"] as const;\n\nexport type ViewAddressSort = { field: string; direction: \"asc\" | \"desc\" };\n\n/** What the address says about a look. Absent keys say nothing. */\nexport type ViewAddressState = {\n sort?: ViewAddressSort | null;\n /** The grid's column filters, in the grid's own shape (field key → its filter value). */\n filters?: Record<string, unknown>;\n search?: string;\n /** Field keys hidden on this look. */\n hidden?: string[];\n /** 1-based page; 1 is never written. */\n page?: number;\n};\n\nexport function isViewAddressEmpty(state: ViewAddressState | null | undefined): boolean {\n if (!state) return true;\n return (\n !state.sort &&\n Object.keys(state.filters ?? {}).length === 0 &&\n !(state.search ?? \"\").trim() &&\n (state.hidden?.length ?? 0) === 0 &&\n !(state.page && state.page > 1)\n );\n}\n\n/** The state as flat address words. Empty parts are left out, so a plain view has a plain address. */\nexport function viewAddressToParams(state: ViewAddressState | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!state) return out;\n if (state.sort) out[\"sort\"] = `${state.sort.field}:${state.sort.direction}`;\n const filters = Object.fromEntries(Object.entries(state.filters ?? {}).filter(([, v]) => v !== undefined && v !== null));\n if (Object.keys(filters).length > 0) out[\"cf\"] = JSON.stringify(filters);\n if ((state.search ?? \"\").trim()) out[\"q\"] = (state.search ?? \"\").trim();\n if (state.hidden && state.hidden.length > 0) out[\"hide\"] = JSON.stringify(state.hidden);\n if (state.page && state.page > 1) out[\"page\"] = String(Math.floor(state.page));\n return out;\n}\n\n/** The address words back into a state; null when the address says nothing (or only nonsense). */\nexport function viewAddressFromParams(get: (key: string) => string | null | undefined): ViewAddressState | null {\n const out: ViewAddressState = {};\n const sort = get(\"sort\");\n if (sort) {\n const at = sort.lastIndexOf(\":\");\n const field = at > 0 ? sort.slice(0, at) : \"\";\n const dir = at > 0 ? sort.slice(at + 1) : \"\";\n if (field && (dir === \"asc\" || dir === \"desc\")) out.sort = { field, direction: dir };\n }\n const cf = get(\"cf\");\n if (cf) {\n try {\n const parsed: unknown = JSON.parse(cf);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) out.filters = parsed as Record<string, unknown>;\n } catch {\n /* a broken filter word says nothing */\n }\n }\n const q = get(\"q\");\n if (q && q.trim()) out.search = q.trim();\n const hide = get(\"hide\");\n if (hide) {\n try {\n const parsed: unknown = JSON.parse(hide);\n if (Array.isArray(parsed)) {\n const keys = parsed.filter((k): k is string => typeof k === \"string\");\n if (keys.length > 0) out.hidden = keys;\n }\n } catch {\n /* ditto */\n }\n }\n const page = Number(get(\"page\"));\n if (Number.isInteger(page) && page > 1) out.page = page;\n return isViewAddressEmpty(out) ? null : out;\n}\n\n/** Two states that say the same thing — so a report that changes nothing is never sent. */\nexport function sameViewAddress(a: ViewAddressState | null | undefined, b: ViewAddressState | null | undefined): boolean {\n return JSON.stringify(viewAddressToParams(a)) === JSON.stringify(viewAddressToParams(b));\n}\n","// src/calendarFeed.ts — @ai-matrx/records-ui · CAL-FEED-UI\n//\n// THE PRIVATE CALENDAR LINK, as the screens see it. The doors (create / rotate / revoke / list) are\n// the host's: they live in the `users` schema, not in the records store, so the host binds them as\n// ONE port (`RecordsUiHost.calendarFeed`). A host without the port has no link to give, so the menu\n// entry is absent, never dead. The token is shown ONCE — only its first characters are ever listed.\n\nimport type { ObjectAction } from \"./objectActions\";\n\n/** What a door answers when it mints or changes a link. The token is the only time it is seen. */\nexport interface CalendarFeedMade {\n id: string;\n token: string;\n expires_at: string | null;\n}\n\n/** One line of the person's list. Never a token — `token_prefix` is its first characters. */\nexport interface CalendarFeedRow {\n id: string;\n title: string;\n organization_id: string;\n table_id: string;\n view_id: string | null;\n token_prefix: string;\n time_zone: string;\n created_at: string;\n expires_at: string | null;\n last_read_at: string | null;\n read_count: number;\n expired: boolean;\n}\n\nexport interface CalendarFeedPort {\n create(args: {\n organizationId: string;\n tableId: string;\n viewId: string;\n title: string;\n timeZone: string;\n }): Promise<CalendarFeedMade>;\n rotate(id: string): Promise<CalendarFeedMade>;\n revoke(id: string): Promise<void>;\n list(): Promise<CalendarFeedRow[]>;\n /** The https address a calendar app reads for this token (the host's route). */\n urlFor(token: string): string;\n}\n\n/** webcal:// is the same address, asking the calendar app to subscribe. */\nexport function webcalUrl(httpsUrl: string): string {\n return httpsUrl.replace(/^https?:\\/\\//i, \"webcal://\");\n}\n\n/** Google Calendar's \"add by URL\": the webcal address, encoded whole into `cid`. */\nexport function googleCalendarUrl(httpsUrl: string): string {\n return `https://calendar.google.com/calendar/r?cid=${encodeURIComponent(webcalUrl(httpsUrl))}`;\n}\n\nexport const SUBSCRIBE_ACTION_ID = \"subscribe-calendar\";\n\n/** \"Subscribe in your calendar…\" in the table's one action list. */\nexport function subscribeCalendarAction(args: {\n disabledReason?: string | undefined;\n run: () => void | Promise<void>;\n}): ObjectAction {\n return {\n id: SUBSCRIBE_ACTION_ID,\n label: \"Subscribe in your calendar…\",\n icon: \"calendar-clock\",\n group: \"share\",\n ...(args.disabledReason ? { disabledReason: args.disabledReason } : {}),\n run: args.run,\n };\n}\n","// src/enumLabels.ts — @ai-matrx/records-ui\n//\n// ONE LABEL MAP PER ENUM. NOTHING ELSE IN THIS PACKAGE OWNS A COPY.\n//\n// Lane FRONT-DOOR's finding (2026-09-21): about twenty sites in this package\n// turned an enum VALUE the store already canonicalizes into a person-facing\n// word, each one on its own — worst example, `ChecklistRunner.tsx` called the\n// work-due state \"finished\" **\"Done\"** while `ActionInbox.tsx`, reading the\n// SAME `WorkDueState` off the SAME `custom.work_inbox`/`checklist_run` doors,\n// called it **\"Finished\"**. A person moving between a table's checklist tab\n// and her inbox saw two different words for one fact about her own work.\n//\n// So every enum this package draws a label for is named ONCE, here, keyed by\n// its canonical values — imported from `@ai-matrx/records` wherever the store\n// exports a named type/const for it, and named locally (with the reason) where\n// it does not. A panel imports the map; it never writes its own.\n//\n// THE GUARD: `enumLabels.test.tsx` renders every converted panel's label\n// function over the FULL canonical value list of its enum (pulled from\n// `@ai-matrx/records`, not retyped) and fails the moment a value has no entry\n// or a caller falls through to the raw token. See that file for RED/GREEN.\n\nimport type {\n ChecklistRequirementKind,\n ContextPolicy,\n FieldSensitivity,\n StageRuleOnFail,\n SubscriptionCadence,\n WorkDueState,\n WorkInboxKind,\n WorkApprovalState,\n} from \"@ai-matrx/records\";\n\n/**\n * An array literal checked, AT COMPILE TIME, to name every member of `T` and no\n * extra one. `WorkDueState`, `WorkInboxKind`, `ChecklistRequirementKind` and\n * `SubscriptionCadence` are typed unions in `@ai-matrx/records` with no\n * runtime array exported alongside them — so this is how the four `*_VALUES`\n * lists below stay tied to the PACKAGE'S OWN TYPE instead of drifting from it\n * by hand: add a sixth `WorkDueState` in `@ai-matrx/records` and `tsc` refuses\n * this file until the array is updated to name it too. The census test below\n * imports these arrays rather than the store's raw union so it is exercising\n * the same list this file's label maps are keyed against.\n */\nfunction exhaustiveValuesOf<T extends string>() {\n return function <const U extends readonly T[]>(values: [T] extends [U[number]] ? U : never): U {\n return values as U;\n };\n}\n\n// ── work due state — WorkDueState (packages/records/src/work.ts) ───────────\n//\n// Shared by a checklist step (`checklist_run().due_state`) and a work-inbox\n// row (`work_inbox().due_state`, `work_list().due_state`) — ONE enum, drawn in\n// both a checklist runner and an approvals inbox. This is the pair the finding\n// named: \"finished\" read \"Done\" in one and \"Finished\" in the other. **\"Done\"\n// wins** — it is the word a non-technical business owner actually says out\n// loud about a piece of work (\"is that job done yet?\"), it is one syllable\n// shorter than the other four words in this set are used to being read\n// alongside (\"Overdue\", \"Today\", \"Scheduled\", \"No date\"), and \"Finished\" reads\n// more like a formal status report than a plain answer to \"is it done\".\nexport const WORK_DUE_STATES = exhaustiveValuesOf<WorkDueState>()([\n \"overdue\",\n \"due_today\",\n \"scheduled\",\n \"undated\",\n \"finished\",\n]);\nexport const DUE_STATE_LABEL: Record<WorkDueState, string> = {\n overdue: \"Overdue\",\n due_today: \"Today\",\n scheduled: \"Scheduled\",\n undated: \"No date\",\n finished: \"Done\",\n};\n\n// ── work inbox kind — WorkInboxKind (packages/records/src/work.ts) ─────────\nexport const WORK_INBOX_KINDS = exhaustiveValuesOf<WorkInboxKind>()([\"assignment\", \"approval\", \"proposal\"]);\n// UI-FIX-19 (VERIFIER-19 #6): a kind is a NOUN. \"Approve\" in the row's bordered kind badge read as\n// a live Approve control on every withdrawn and decided item; only a control may be a verb.\nexport const WORK_INBOX_KIND_LABEL: Record<WorkInboxKind, string> = {\n assignment: \"Assigned\",\n approval: \"Approval\",\n proposal: \"Agent proposal\",\n};\n/** The heading an inbox grouped by kind reads (lane S5-PRIME) — plural, the way Linear groups. */\nexport const WORK_INBOX_KIND_GROUP_LABEL: Record<WorkInboxKind, string> = {\n approval: \"Approvals\",\n proposal: \"Agent proposals\",\n assignment: \"Assigned to you\",\n};\n\n// ── approval state — WorkApprovalState (packages/records/src/work.ts) ──────\n// Lane S5-PRIME: a closed item says what happened to it. `withdrawn` is the store's own close —\n// the thing it would change was archived — never a person's decision.\nexport const WORK_APPROVAL_STATES = exhaustiveValuesOf<WorkApprovalState>()([\"pending\", \"approved\", \"declined\", \"withdrawn\"]);\nexport const WORK_APPROVAL_STATE_LABEL: Record<WorkApprovalState, string> = {\n pending: \"Waiting\",\n approved: \"Approved\",\n declined: \"Declined\",\n withdrawn: \"Withdrawn\",\n};\n\n// ── checklist requirement kind — ChecklistRequirementKind (checklist.ts) ───\nexport const CHECKLIST_REQUIREMENT_KINDS = exhaustiveValuesOf<ChecklistRequirementKind>()([\n \"none\",\n \"note\",\n \"answer\",\n \"record_field\",\n \"form\",\n \"document\",\n]);\nexport const CHECKLIST_REQUIREMENT_LABEL: Record<ChecklistRequirementKind, string> = {\n none: \"\",\n note: \"Say what you did\",\n answer: \"Fill this in\",\n record_field: \"This has to be filled in on the record\",\n form: \"This step is a form\",\n document: \"This step is a document\",\n};\n\n// ── field sensitivity — FieldSensitivity (vocabulary.ts, FLD-12/AGT-7) ─────\n// THE WORDS MATCH THE STORE'S OWN RULE (knob `custom/field_sensitivity_levels`, read live 2026-10-21):\n// internal reads at Viewer, confidential and restricted at ADMIN (Arman, 2026-10-20: a Confidential column is hidden\n// below admin unless someone is granted it; lane CONFIDENTIAL-DEFAULT moved confidential from Editor). Every member\n// starts as an Editor (`custom/member_default_level`), so both words hide a column from members; a share of the\n// column itself opens it. Organizations may override the knob; the column-access screen reads it live.\n// Guard: `a-sensitivity-word-says-who-it-hides-from.test.tsx` reads these against the store's knob.\nexport const FIELD_SENSITIVITY_LABEL: Record<FieldSensitivity, string> = {\n public: \"Anyone who can open the record\",\n internal: \"People in this organization\",\n confidential: \"Administrators and anyone granted it\",\n restricted: \"Administrators only\",\n};\n\n// ── context policy — ContextPolicy (vocabulary.ts, FLD-12) ─────────────────\n// Whether an agent may see a Field's values at all — not `Delivery` (how much\n// of a merge field's value reaches a turn), a different vocabulary entirely.\nexport const CONTEXT_POLICY_LABEL: Record<ContextPolicy, string> = {\n include: \"Yes, an assistant can read it\",\n summarize: \"Only a summary of it\",\n on_request: \"Only on request\",\n exclude: \"No, keep it away from assistants\",\n};\n\n// ── stage-rule on_fail — StageRuleOnFail (pipeline.ts) ──────────────────────\nexport const STAGE_RULE_ON_FAIL_LABEL: Record<StageRuleOnFail, string> = {\n refuse: \"Turn it away\",\n require_approval: \"Ask for approval\",\n};\n\n// ── subscription cadence — SubscriptionCadence (subscription.ts) ───────────\n//\n// `DigestScheduler.tsx` carries its own copy of this enum's words as a\n// grammatical FRAGMENT dropped into a sentence (\"arrives the moment something\n// arrives\") rather than a standalone label (\"hourly summary\") — a different\n// job for the same four values. That file is owned by another lane right now\n// (lane preamble's do-not-touch list) so it is left exactly as it is; this map\n// is the standalone-label form used by every OTHER site that names a cadence.\nexport const SUBSCRIPTION_CADENCES = exhaustiveValuesOf<SubscriptionCadence>()([\"instant\", \"hourly\", \"daily\", \"weekly\"]);\nexport const SUBSCRIPTION_CADENCE_LABEL: Record<SubscriptionCadence, string> = {\n instant: \"as it happens\",\n hourly: \"hourly summary\",\n daily: \"daily summary\",\n weekly: \"weekly summary\",\n};\n\n// ── subscription channel — no named export in @ai-matrx/records ───────────\n//\n// `Subscription.channel` is typed inline as `\"in_app\" | \"email\" | \"sms\"`\n// (subscription.ts) with no exported const array, so the value list below IS\n// the canonical list — the same three literals the store's type carries.\nexport const SUBSCRIPTION_CHANNEL_VALUES = [\"in_app\", \"email\", \"sms\"] as const;\nexport type SubscriptionChannel = (typeof SUBSCRIPTION_CHANNEL_VALUES)[number];\n// `NotifyRuleEditor.tsx` used to say plain \"by email\" / \"by text\" with no\n// caveat; `SubscriptionsPanel.tsx` (and the untouched `DigestScheduler.tsx`)\n// say \"only if an address/number is on the account\". **The caveat wins** — a\n// person choosing email delivery needs to know up front that it silently does\n// nothing without an address on file, the way Linear and Notion surface a\n// precondition next to the control rather than failing quietly later.\nexport const SUBSCRIPTION_CHANNEL_LABEL: Record<SubscriptionChannel, string> = {\n in_app: \"in the app\",\n email: \"by email — only if an address is on the account\",\n sms: \"by text — only if a number is on the account\",\n};\n\n// ── rollup aggregate operation — NewFieldDeclaration[\"agg\"] (field.ts) ─────\n//\n// `field.ts` types this inline (`agg?: \"sum\" | \"count\" | \"min\" | \"max\" |\n// \"avg\"`) with no exported const array, so — same as the channel above — the\n// list below IS the canonical list.\nexport const ROLLUP_AGG_VALUES = [\n \"count\", \"sum\", \"avg\", \"min\", \"max\",\n // AIRTABLE PARITY (lane AT-FORMULA): the aggregates that read the linked values as they are.\n \"countall\", \"counta\", \"and\", \"or\", \"xor\", \"arrayjoin\", \"concatenate\", \"arrayunique\", \"arraycompact\",\n] as const;\nexport type RollupAgg = (typeof ROLLUP_AGG_VALUES)[number];\nexport const ROLLUP_AGG_LABEL: Record<RollupAgg, string> = {\n count: \"How many there are\",\n sum: \"The total of\",\n avg: \"The average of\",\n min: \"The smallest\",\n max: \"The largest\",\n countall: \"How many values, empty ones too\",\n counta: \"How many values are filled in\",\n and: \"Yes when every value is yes\",\n or: \"Yes when any value is yes\",\n xor: \"Yes when an odd number are yes\",\n arrayjoin: \"All the values, joined with commas\",\n concatenate: \"All the values, run together\",\n arrayunique: \"Each different value once\",\n arraycompact: \"The values that are filled in\",\n};\n\n// ── formula operation — the FormulaOperations menu (FieldEditor.tsx) ───────\n//\n// No `@ai-matrx/records` type names this set at all; it is this package's own\n// menu of what a two-column formula field can do, so this file is its one\n// canonical home.\nexport const FORMULA_OP_VALUES = [\"concat\", \"add\", \"sub\", \"mul\", \"div\"] as const;\nexport type FormulaOp = (typeof FORMULA_OP_VALUES)[number];\nexport const FORMULA_OP_LABEL: Record<FormulaOp, string> = {\n concat: \"Join them together\",\n add: \"Add them up\",\n sub: \"Take the second from the first\",\n mul: \"Multiply them\",\n div: \"Divide the first by the second\",\n};\n/** Whether this operation reads naturally as \"X and Y and Z…\" over more than two columns. */\nexport const FORMULA_OP_JOINS: Record<FormulaOp, boolean> = {\n concat: true,\n add: true,\n sub: false,\n mul: true,\n div: false,\n};\n\n// ── field validation-rule kind — FieldRule[\"kind\"] (field.ts) ──────────────\n//\n// `field.ts` types this inline with no exported const array; canonical here.\nexport const FIELD_RULE_KIND_VALUES = [\"min\", \"max\", \"length\", \"pattern\", \"equals_field\", \"differs_from_field\"] as const;\nexport type FieldRuleKindValue = (typeof FIELD_RULE_KIND_VALUES)[number];\nexport const FIELD_RULE_KIND_LABEL: Record<FieldRuleKindValue, string> = {\n min: \"At least\",\n max: \"At most\",\n length: \"Number of characters\",\n pattern: \"Looks like\",\n equals_field: \"Same as the column\",\n differs_from_field: \"Different from the column\",\n};\n\n// ── proposed-change act — `ProposedChange[\"act\"]` (ProposalRow.tsx, package-local) ──\n//\n// This type is not in `@ai-matrx/records` (`ProposalRow.tsx` declares it\n// itself, for an agent's field/table proposal), so it is canonical here.\nexport const PROPOSED_CHANGE_ACT_VALUES = [\"add\", \"update\", \"remove\"] as const;\nexport type ProposedChangeAct = (typeof PROPOSED_CHANGE_ACT_VALUES)[number];\nexport const PROPOSED_CHANGE_ACT_LABEL: Record<ProposedChangeAct, string> = {\n add: \"Add\",\n update: \"Update\",\n remove: \"Remove\",\n};\n\n// ── booking-page state — `FormSummary[\"state\"]` / `BookingSummary` (rule.ts) ──\n//\n// `rule.ts` types this inline (`\"draft\" | \"open\" | \"closed\" | \"full\"`) with no\n// exported const array; canonical here.\nexport const BOOKING_PAGE_STATE_VALUES = [\"draft\", \"open\", \"closed\", \"full\"] as const;\nexport type BookingPageState = (typeof BOOKING_PAGE_STATE_VALUES)[number];\nexport const BOOKING_PAGE_STATE_LABEL: Record<BookingPageState, string> = {\n draft: \"Not open yet — nobody can book until you open it.\",\n open: \"Open. Anyone with the link can book a time.\",\n closed: \"Closed. The link still works and says you are not taking bookings.\",\n full: \"Every time you offered is taken.\",\n};\n\n// ── value-envelope absence word — `ValueEnvelope.absent` (record.ts) ───────\n//\n// Kept for completeness of the census: `values.tsx` mapped each absence word\n// to itself (`\"none\" → \"none\"`), which is a passthrough with a safe fallback\n// rather than a wording decision, so there is no conflict to resolve — this is\n// still its one home so a future word change happens in one place.\nexport const ABSENCE_WORD_VALUES = [\"never asked\", \"none\", \"refused\", \"conflicting\"] as const;\nexport type AbsenceWord = (typeof ABSENCE_WORD_VALUES)[number];\nexport const ABSENCE_WORD_LABEL: Record<AbsenceWord, string> = {\n \"never asked\": \"never asked\",\n none: \"none\",\n refused: \"refused\",\n conflicting: \"conflicting\",\n};\n","// src/standardFieldChoices.ts — @ai-matrx/records-ui · what a field of a standard table can be, with no React\n//\n// Pure, so `/helpers` carries `CUSTOM_FIELD_ADDABLE_TYPES` and a host settings page lists the\n// addable types before it loads any screen (records-ui front door, 2026-10-16). `FieldEditor.tsx`\n// and `CustomFieldsSection.tsx` re-export these.\n\nimport { DECLARABLE_FIELD_KINDS } from \"@ai-matrx/records/field-kinds\";\nimport { FIELD_TYPE_CHOICES, isSystemFieldKind, type FieldTypeChoice } from \"./fieldTypes\";\n\n/**\n * WHAT A FIELD OF A STANDARD TABLE CAN BE — every kind that HOLDS a value there (lane 7 W1, fix\n * round 1). The store's own kind registry (`custom.field_kinds()`, generated into\n * `DECLARABLE_FIELD_KINDS`) says what each kind is made of; a kind whose behavior is `formula` —\n * Borrowed value, Total, Count, Worked out, and the stamps (Record number, Created / Last changed\n * time), which are formula words — is worked out by `custom.rule_eval` over a custom record, and a\n * standard row is never worked out. Measured on the clone 2026-10-02 (a CRM company; every kind\n * declared, a realistic value written through `custom.entity_row_write`, read back through\n * `custom.entity_record_read`): every other kind came back holding its value; every formula kind\n * came back null. So a record page offers exactly the kinds that hold a value, read from the\n * store's registry — one source, no hand list. A kind the registry does not publish is not offered.\n */\nconst STORE_BEHAVIOUR = new Map<string, string>(DECLARABLE_FIELD_KINDS.map((row) => [row.kind as string, row.behavior as string]));\n\n/** True when a field of this kind holds a value on a standard table's row. */\nexport function holdsAValueOnAStandardTable(kind: string): boolean {\n if (isSystemFieldKind(kind)) return false;\n const behaviour = STORE_BEHAVIOUR.get(kind);\n return behaviour !== undefined && behaviour !== \"formula\";\n}\n\n/** What a record page's Add field offers: `fieldTypes.ts`'s choices, less what cannot hold a value there. */\nexport const STANDARD_TABLE_FIELD_CHOICES: FieldTypeChoice[] = FIELD_TYPE_CHOICES.filter((c) =>\n holdsAValueOnAStandardTable(c.id),\n);\n\n\n/**\n * WHAT A PERSON CAN ADD FROM A RECORD PAGE: EVERYTHING A TABLE'S COLUMN CAN BE.\n *\n * 🚨 G3 — ONE PALETTE (lane 7 STANDARD-TABLES, wave 1). This used to be a hand-kept list of\n * eleven types (`ADDABLE_TYPE_IDS`) \"that need nothing more than a name\", so a CRM contact could\n * not get a Choice, a Yes / no or a link to another record, and none of the column's governance —\n * while `custom.entity_field_declare` resolves its spec through the very `custom._field_document_for`\n * a custom table's column goes through. A standard table and a custom table are one primitive, so\n * the record page opens the table's own `FieldEditor` and offers `fieldTypes.ts`'s pickable set\n * less the kinds that cannot hold a value on a standard row (`STANDARD_TABLE_FIELD_CHOICES`, read\n * from the store's kind registry). `a-record-page-adds-a-field-with-the-tables-own-palette.test.tsx`\n * fails the moment this list and that set differ.\n */\nexport const ADDABLE_TYPES = STANDARD_TABLE_FIELD_CHOICES.map((choice) => ({\n value: choice.id as string,\n label: choice.label,\n}));\n","// src/plainWords.ts — @ai-matrx/records-ui\n//\n// THE ONE FORMATTER EVERY REFUSAL PASSES THROUGH.\n//\n// WHAT A PERSON READ (independent verdict, sixth pass, 19-20 September):\n//\n// \"You do not have access to this table, so custom.applicable_fields has\n// nothing to show you.\"\n// \"config.via names a relation Field of this same table, by its key… The\n// store's code for this was 23514.\"\n//\n// The verdict's third measured gap against Airtable, Notion and Linear was\n// exactly this: \"The machinery still shows through… two column types answer\n// with a contract row id and a SQL error number. Airtable, Notion and Linear\n// never show a person an internal name.\"\n//\n// WHY FILTERING THE HINT WAS NOT ENOUGH. The previous pass filtered the store's\n// HINT — the half written for whoever fixes the caller — and printed the\n// MESSAGE verbatim, because the store writes good messages. Most of them are\n// good. But the store's access refusals are built by `format()` from the DOOR'S\n// OWN NAME (`assert_client_may_change`: \"…so % may not write to it\", with the\n// door name substituted in), so the machine identity is IN the sentence a\n// person reads and no amount of hint-filtering reaches it.\n//\n// SO: ONE function, here, and every screen in this package renders what it\n// returns and nothing else. It does three things and refuses to do a fourth:\n//\n// 1. It KEEPS the store's own words wherever they are a person's words. The\n// store writes the best sentences in this feature (\"Being a member of the\n// organization is not by itself permission to rewrite somebody else's\n// row\") and this package does not rewrite them.\n// 2. It DROPS the clause that carries machine identity, by SHAPE — a\n// schema-qualified object, a document path, a contract row id, a SQLSTATE,\n// a uuid, a bare snake_case token. Dropped, never deleted: it joins the\n// SQLSTATE on the notice for whoever has to debug it.\n// 3. It ADDS a REMEDY — the sentence that says what to do now — keyed off the\n// store's own refusal code, because a refusal with nothing to do about it\n// is a dead end with an explanation.\n//\n// 4. It does NOT invent a diagnosis. When every clause of a message is\n// machine identity there is nothing honest left to say about the specifics,\n// so it says what happened in general terms and offers the remedy. Making\n// something up would be worse than the identifier it replaced.\n//\n// The guard for all of this is `demo/plain-words.test.tsx` plus the sweep in\n// `demo/honest.test.tsx`, which reads the RENDERED text of the real screens and\n// fails on any of the shapes below. A formatter nobody is forced through is a\n// formatter somebody bypasses next week.\n\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n/**\n * MACHINE IDENTITY, BY SHAPE — never by a list of the sentences we happen to\n * have seen, because the next refusal is one nobody has read yet.\n *\n * `FLD-11:` / `REC-29:` / `AGT-7:` a contract row id\n * `custom.field_declare` a schema-qualified database object\n * `config.via` / `data.fields` a path inside a stored document\n * `retention_days` a document key, snake_case\n * `8f2c1b0a-…` a uuid\n * `23514` / `PT409` a SQLSTATE\n * `STORE-TAILS-3:` / `UI-FIX-19:` a build lane's tag (UI-FIX-19)\n */\nexport const MACHINE_IDENTITY: RegExp[] = [\n /\\b[A-Z]{2,4}-\\d{1,3}\\b/,\n // A build lane's tag: capital words joined by hyphens, then a colon (\"STORE-TAILS-3:\",\n // \"MOVE-AND-OUTSIDER:\"). A person never reads which lane wrote a sentence.\n /\\b[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+:/,\n /\\b(?:custom|platform|iam|history|public|auth|campaign_watch)\\.[a-z_]+/,\n /\\b(?:config|data|document|spec|patch)\\.[a-z_]+/,\n /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/i,\n /\\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\\b/,\n // Five characters of digits and capitals, at least one a digit — so `23514`\n // and `PT409` match and an emphatic `NEVER` does not.\n /\\b(?=[0-9A-Z]{5}\\b)(?=[0-9A-Z]*\\d)[0-9A-Z]{5}\\b/,\n];\n\n/** Whether any shape above appears in this text. */\nexport function isMachineIdentity(text: string): boolean {\n return MACHINE_IDENTITY.some((shape) => shape.test(text));\n}\n\n/**\n * Every fragment of `text` that a person should never have been shown. Used by\n * the suite to say WHAT it found rather than only that it found something.\n */\nexport function machineIdentityIn(text: string): string[] {\n const found: string[] = [];\n for (const shape of MACHINE_IDENTITY) {\n const all = new RegExp(shape.source, shape.flags.includes(\"g\") ? shape.flags : `${shape.flags}g`);\n for (const hit of text.matchAll(all)) if (hit[0]) found.push(hit[0]);\n }\n return [...new Set(found)];\n}\n\n/** What the notice is called. The store's code, in the words of what went wrong. */\nconst TITLE: Record<string, string> = {\n stale_write: \"Someone else wrote first\",\n door: \"You do not have access to this\",\n door_absent: \"That is not built yet\",\n refused_by_rule: \"That value was not accepted\",\n invalid_argument: \"That was not accepted\",\n not_found: \"Not there any more\",\n missing_reference: \"That points at something that is not there\",\n already_exists: \"That already exists\",\n not_supported: \"That cannot be done here\",\n store_limit: \"This has got as big as it can\",\n // 🚨 NOT \"THE SWITCH IS OFF\" (lane 7 W1 fix round 1). PGRST202 / PGRST205 land here, and the\n // commonest cause is a door this screen asks for that the database it talks to does not serve\n // YET — a release in flight. Telling the person her organization has its store switched off was\n // false (the switch is answered by its own door, `platform.unified_data_store_on`). Honest:\n // nothing happened, and it is ours, and it passes.\n store_not_served: \"This isn't available right now\",\n unreachable: \"We could not reach your data\",\n needs_approval: \"This is waiting on someone's approval\",\n stale_read: \"Your view of this is a moment behind\",\n timed_out: \"That took too long to answer\",\n internal: \"Something went wrong at our end\",\n};\n\n/**\n * WHAT TO DO NOW. One sentence per refusal code, and it is the whole reason\n * this file exists rather than a regular expression in `Refusal.tsx`: a\n * sentence that names what went wrong and nothing to do about it is a dead end.\n */\nconst REMEDY: Record<string, string> = {\n stale_write:\n \"Look at what they wrote. Keep theirs, or try again and yours goes on top.\",\n door:\n \"Ask somebody who administers this to share it with you at the level you need.\",\n door_absent:\n \"There is nothing to do here yet. It is on our list, not yours.\",\n refused_by_rule: \"Change the value so it passes, then try again.\",\n invalid_argument: \"Change what you entered, then try again.\",\n not_found:\n \"It may have been deleted. Go back to the list and open it again from there.\",\n missing_reference: \"Pick something that is still there.\",\n already_exists: \"Use a different name.\",\n not_supported: \"There is another way to do this — ask, and we will point you at it.\",\n store_limit: \"Split it up, or ask us to raise the ceiling for your organization.\",\n store_not_served: \"Nothing was changed. Try again in a few minutes.\",\n // 🚨 NOTHING WAS WRITTEN AND NOTHING WAS REFUSED (lane TAILS-6). The call\n // never arrived, so \"try again\" is the honest instruction rather than a\n // consolation — and saying nothing changed is the half a person actually\n // worries about.\n unreachable:\n \"Nothing was changed. Check your connection and open this again.\",\n needs_approval:\n \"Nothing was changed yet. The people who can approve it have been asked.\",\n stale_read: \"Open this again in a moment and it will be up to date.\",\n // 🚨 ONE REMEDY THAT IS TRUE OF EVERY DOOR (lane CHAIR-STORE-PERF, 2026-10-03). The store cancels the\n // WHOLE statement at its clock, so a timed-out door wrote nothing — a create, a column add and a page\n // read alike. \"Try a smaller page\" was written for the page read and was printed to a person adding\n // one row to a three-row table (clone walk, 2026-10-03; the clock was a lock another lane's\n // rehearsal held, not the row). A door whose page can shrink says so in its own hint, which wins here.\n // ONE SENTENCE, NOT TWO (lane TIMEOUT-ONE-SENTENCE, 2026-10-19): the shared timed-out sentence (\"That took too long.\n // Nothing was lost; try again.\") already says what happened and what to do, so the table adds NO second remedy\n // (\"Nothing was changed\" was also wrong on a read). Empty = the notice prints no remedy line and the one-line\n // form is the sentence alone. A door's own hint still wins.\n timed_out: \"\",\n internal:\n \"Nothing you did caused this. Try again, and tell us if it keeps happening.\",\n};\n\n/**\n * 🚨 A HINT THIS PACKAGE OR ITS CLIENT WROTE IS NOT A PERSON'S REMEDY.\n *\n * `refusalForAPerson` prefers the DOOR's own hint over the table above, because\n * the door that refused knows more about the way out than a code does. That is\n * right — but it assumed every hint came from the store. It did not: until\n * `@ai-matrx/records` 0.47.0 the client appended its OWN note to `hint` when it\n * met a SQLSTATE it did not know, and the machine-identity filter let it\n * through whenever the code was not exactly five characters (an empty code from\n * a dropped connection, or an HTTP status like `404`). So the Checklists tab of\n * a plumbing company's jobs table told its owner:\n *\n * @ai-matrx/records did not recognize SQLSTATE from checklistTemplates\n *\n * The client no longer writes there. This is the guard on the other side, by\n * SHAPE and not by that one sentence: a hint that talks about a package, a\n * SQLSTATE, or a `camelCaseDoor` is engineer text wherever it came from, and it\n * joins the engineer's line instead of a person's screen.\n */\nexport const ENGINEER_TEXT: RegExp[] = [\n /@ai-matrx\\//,\n /\\bSQLSTATE\\b/i,\n /\\bPostgREST\\b/i,\n /\\bIndexedDB\\b/i,\n // `<RecordsUiProvider>` — a component, on a screen.\n /<\\/?[A-Z][A-Za-z0-9]*\\s*\\/?>/,\n // `savedViews`, `openRecords`, `onReask` — an identifier, however it is\n // quoted. English does not write camelCase; code does.\n /\\b[a-z][a-z0-9]*[A-Z][A-Za-z0-9]*\\b/,\n // A backticked token is a thing you type into an editor, not a thing you do.\n /`[A-Za-z_][A-Za-z0-9_.]*`/,\n // \"bind X on Y\", \"pass X\", \"import X\" — an instruction to whoever maintains\n // the app, arriving on the screen of somebody who cannot act on it.\n /\\bbind\\s+[`'\"A-Za-z]/i,\n];\n\n/**\n * THE ONE GUARD ON A DOOR'S HINT. True when the hint is developer text and must never be\n * printed at a person: engineer shapes (package, SQLSTATE, component, camelCase, backticked\n * token), a code fence, stack-like lines, or a block too long to be one remedy (over 600).\n * Machine clauses INSIDE an otherwise plain hint are cut by `plainSentence`, not by this.\n */\nexport function isDeveloperHint(hint: string): boolean {\n const text = hint.trim();\n if (text === \"\") return false;\n if (text.includes(\"```\")) return true;\n if (/\\n\\s+at\\s+\\S+/.test(text)) return true;\n if (text.length > 600) return true;\n return isEngineerText(text);\n}\n\n/** The hint a person may read: cleaned to people's sentences, or null. The one place that decides. */\nexport function peopleHint(hint: string | null | undefined): string | null {\n const said = (hint ?? \"\").trim();\n if (said === \"\" || isDeveloperHint(said)) return null;\n return plainSentence(said).kept;\n}\n\n/** Whether this sentence was written for whoever maintains the code. */\nexport function isEngineerText(text: string): boolean {\n return ENGINEER_TEXT.some((shape) => shape.test(text));\n}\n\n/** The one shape every screen in this package renders a refusal from. */\nexport interface PlainRefusal {\n /** The heading. Never the store's code. */\n title: string;\n /**\n * What happened, in the store's own words where they are a person's words\n * and in ours where they are not. Never empty.\n */\n sentence: string;\n /** What to do now. Never empty. */\n remedy: string;\n /**\n * TRUE when `sentence` is the store's own words (UI-FIX-19): a notice is then HEADED by that\n * sentence, never by the generic `title` over it.\n */\n storeSaid: boolean;\n /**\n * Everything a person should not read, kept for whoever has to debug it: the\n * SQLSTATE, the hint written for a caller, and any clause dropped above.\n * Kept on the notice's `data-for-engineers` attribute only (UI-FIX-19): never a\n * tooltip, never text a screen can copy or read aloud; never deleted.\n */\n forEngineers: string;\n}\n\n/**\n * A sentence with its machine clauses taken out — or null when nothing honest\n * is left. Clauses are split on the joins the store's own `format()` templates\n * use (\"…, so custom.x may not write to it\", \"… — FLD-11: …\").\n */\nfunction withoutMachineClauses(sentence: string): { kept: string | null; dropped: string[] } {\n const dropped: string[] = [];\n // 🚨 A PARENTHETICAL ID IS EXCISED, NOT A REASON TO BIN THE SENTENCE AROUND IT\n // (lane LIMITS-FIX-UI, 2026-09-21). The store's own way out for a colleague who\n // is not in the organization — \"Invite them to the organization, share with\n // their organization instead (VIS-23), or, if they are a client rather than a\n // colleague, put them in a portal\" — was thrown away WHOLE because of those\n // eight characters, so a plumbing company trying to show one customer her own\n // jobs was told nothing at all about what to do instead. A contract id in\n // brackets is a footnote: lift it out and the sentence around it is a person's\n // sentence. It is still kept for the engineer, below.\n const footnotes: string[] = [];\n const withoutFootnotes = sentence.replace(/\\s*\\((?:see\\s+)?[A-Z]{2,5}-[A-Z0-9-]{1,8}\\)/g, (hit) => {\n footnotes.push(hit.trim());\n return \"\";\n });\n dropped.push(...footnotes);\n const clauses = withoutFootnotes\n .split(/(?:,\\s+so\\s+|\\s+—\\s+|\\s+--\\s+|\\s*\\|\\s*)/)\n .map((clause) => clause.trim())\n .filter((clause) => clause !== \"\");\n const kept = clauses.filter((clause) => {\n if (!isMachineIdentity(clause)) return true;\n dropped.push(clause);\n return false;\n });\n if (kept.length === 0) return { kept: null, dropped };\n // 🚨 A CLEANER THAT DROPPED NOTHING CHANGES NOTHING (same lane, same day).\n //\n // The split above is on the joins the store's `format()` templates use, and\n // \", so \" is one of them — which is also how ordinary English joins two\n // clauses. So \"That person is not in this organization, so they cannot be\n // given access to this table yet.\" came back out as \"That person is not in\n // this organization. they cannot be given access to this table yet.\" — a\n // sentence nobody wrote, with a lower-case word after a full stop, shown to\n // every person every time. Nothing was dropped from it; there was nothing to\n // clean. When that is true the sentence is returned exactly as the store wrote\n // it, and this function's re-joining only ever runs on a sentence it actually\n // took something out of.\n if (dropped.length === 0) return { kept: sentence.trim(), dropped };\n let joined = kept.join(\". \").replace(/\\.\\.+/g, \".\").trim();\n if (!/[.!?]$/.test(joined)) joined = `${joined}.`;\n return { kept: joined, dropped };\n}\n\n/**\n * THE PEOPLE-FACING SENTENCE OF A STORE MESSAGE, AND NOTHING AFTER IT (lane\n * RECORDS-UI-REFUSAL-TEXT, 2026-10-01). A refusal's message is one plain sentence,\n * then ` — ` and developer detail, or a second sentence written for whoever fixes the\n * caller. A person reads the first sentence only; the rest rides `forEngineers`.\n */\nfunction peopleSentence(message: string): { kept: string | null; dropped: string[] } {\n const [lead = \"\", ...tail] = message.split(/\\s+—\\s+|\\s+--\\s+/);\n // A full stop after an abbreviation or an initial (\"Ask Dr. Whitfield\", \"e.g. a quote\") is not an end.\n const sentences = lead.trim().split(/(?<=(?<!\\b(?:Dr|Mr|Mrs|Ms|St|vs|No|e\\.g|i\\.e|etc|[A-Z]))[.!?])\\s+/);\n const first = sentences[0] ?? \"\";\n const rest = [...sentences.slice(1), ...tail].map((part) => part.trim()).filter((part) => part !== \"\");\n const cleaned = plainSentence(first);\n return { kept: cleaned.kept, dropped: [...cleaned.dropped, ...rest] };\n}\n\n/**\n * THE ONE SENTENCE A PERSON READS FOR A REFUSAL — the store's first sentence, or the\n * title when nothing of it is a person's words. Never the hint, details, code or\n * SQLSTATE. Every place that needs a refusal as a string (a toast, a cell, a banner)\n * calls this and nothing else; `check:records-ui-refusal-text` fails on a raw\n * `error.message` / `error.hint` render anywhere else.\n */\nexport function refusalSentence(error: Pick<RecordsError, \"message\"> & Partial<RecordsError>): string {\n return refusalForAPerson(error as RecordsError).sentence;\n}\n\n// A BUILD LABEL OPENING A SENTENCE (lane CLOSE-LINK, CD-LINK-07): the acceptance test or the lane/rule tag the store was\n// built against — \"Test 3 (Reparent):\", \"REC-21:\", \"T5 / VAL-4:\", \"CLOSE-LINK:\". A person never reads it, and it is\n// never a reason to drop the remedy after it (which is what the machine-identity filter did to the whole sentence).\nconst BUILD_LABEL = String.raw`(?:Test \\d+ \\([^)]{1,40}\\)|[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+|[A-Z]{1,5}\\d+[a-z]?)`;\nconst LEADING_BUILD_LABEL = new RegExp(String.raw`^${BUILD_LABEL}(?:\\s*\\/\\s*${BUILD_LABEL})*:\\s+`);\n\n/** The sentence with any build label lifted off its start, the label kept for engineers. */\nfunction withoutBuildLabel(sentence: string): { label: string | null; rest: string } {\n const hit = LEADING_BUILD_LABEL.exec(sentence);\n if (!hit) return { label: null, rest: sentence };\n const rest = sentence.slice(hit[0].length).trim();\n return { label: hit[0].trim(), rest: rest.charAt(0).toUpperCase() + rest.slice(1) };\n}\n\n/** Every sentence of a message, cleaned; the ones that cannot be cleaned are dropped. */\nfunction plainSentence(message: string): { kept: string | null; dropped: string[] } {\n const dropped: string[] = [];\n const kept: string[] = [];\n for (const raw of message.split(/(?<=[.!?])\\s+/)) {\n const labelled = withoutBuildLabel(raw.trim());\n if (labelled.label) dropped.push(labelled.label);\n const sentence = labelled.rest;\n if (sentence === \"\") continue;\n const cleaned = withoutMachineClauses(sentence);\n dropped.push(...cleaned.dropped);\n if (cleaned.kept) kept.push(cleaned.kept);\n }\n return { kept: kept.length === 0 ? null : kept.join(\" \"), dropped };\n}\n\n/** A remedy is a sentence, not the one word left after a build label was lifted off (\"FLD-1: text.\" keeps \"Text.\"). */\nfunction readsAsASentence(text: string | null): boolean {\n return (text ?? \"\").trim().split(/\\s+/).filter(Boolean).length >= 2;\n}\n\n/** The example a pattern refusal carries in its detail, when it carries one. */\nfunction exampleOf(error: RecordsError): string | null {\n const detail = (error as { detail?: unknown }).detail;\n if (!detail || typeof detail !== \"object\") return null;\n const example = (detail as { example?: unknown }).example;\n return typeof example === \"string\" && example.trim() !== \"\" ? example.trim() : null;\n}\n\n/** What a statement timeout says of itself, in place of the database's own words. */\n// ONE SENTENCE EVERYWHERE: the same words as design-system's `TIMED_OUT_SENTENCE` (what every screen prints through\n// `refusalSaid`) and records' `TIMED_OUT_MESSAGE`. This file is the light helpers door, so it cannot import either\n// (design-system's root is heavy); `a-timeout-reads-as-the-platforms-sentence.test.tsx` fails if the three drift.\nconst TIMED_OUT_SAID = \"That took too long. Nothing was lost; try again.\";\n\n/**\n * THE FORMATTER. Every refusal a screen in this package shows goes through\n * here, and nothing in this package renders `error.message` directly.\n */\nexport function refusalForAPerson(error: RecordsError): PlainRefusal {\n const code = error.code ?? \"internal\";\n // A STATEMENT TIMEOUT is the database's words, never a person's (AT-SNAPJOB-2, 2026-10-19: a base rename showed\n // \"canceling statement due to statement timeout\"). Whatever way it arrived (the package's `timed_out`, SQLSTATE\n // 57014, or only Postgres' sentence on an error with no code) it reads as the timed-out refusal: its title and\n // remedy below, and a sentence of our own in place of the database's.\n const timedOut =\n code === \"timed_out\" ||\n (error as { sqlstate?: string }).sqlstate === \"57014\" ||\n /canceling statement due to statement timeout/i.test(String(error.message ?? \"\"));\n // A refusal THIS package wrote (`refusals.ts` marks it `ours`) is whole people-facing prose, a\n // count then a reason; only a door's message is cut after its first sentence.\n const ours = (error as { ours?: unknown }).ours === true;\n const hint = plainSentence(String(error.hint ?? \"\"));\n const message = ours ? plainSentence(String(error.message ?? \"\")) : peopleSentence(String(error.message ?? \"\"));\n\n const title = timedOut ? TITLE[\"timed_out\"]! : (TITLE[code] ?? \"That was refused\");\n\n // 🚨 ONE REMEDY, AND IT IS THE DOOR'S OWN WHEN THE DOOR HAS ONE (lane\n // LIMITS-FIX-UI, 2026-09-21).\n //\n // The table below is a FALLBACK, not an answer. `custom.share_grant` refuses a\n // colleague who is not in the organization with its own three ways forward —\n // *\"Invite them to the organization, share with their organization instead, or,\n // if they are a client rather than a colleague, put them in a portal\"* — and\n // this formatter used to print that AND then \"Change the value so it passes,\n // then try again\", which is not a thing anybody can do about a membership. Two\n // remedies, one of them wrong, is worse than one: a person follows the last\n // sentence they read. The door that refused knows more about the way out than\n // a table keyed on a code does, so its hint wins whenever it survived the\n // machine-identity filter, and the table answers when it did not.\n // 🚨 THE DOOR'S HINT IS THE REMEDY WHEN IT READS AS A PERSON'S SENTENCE (chair ruling,\n // 2026-10-01, restoring the 2026-09-21 one-remedy ruling). A hint that is developer text (a\n // SQL state, a snake_case name, a uuid, a code fence, a stack, a package or component name)\n // is never printed: it rides `forEngineers` and the code's table sentence is the remedy.\n const hintIsForEngineers = isDeveloperHint(String(error.hint ?? \"\"));\n // STORE-RULE-GAPS: a pattern that carries an example hands it over as DATA\n // (`detail.example`), because an example is the person's own shape of value.\n const example = exampleOf(error);\n const remedy =\n (example ? `Enter it like ${example}.` : null) ??\n (hintIsForEngineers || !readsAsASentence(hint.kept) ? null : hint.kept) ??\n (timedOut ? REMEDY[\"timed_out\"] : REMEDY[code]) ??\n REMEDY[\"internal\"]!;\n\n // The store's own sentence for what happened. Its hint is the REMEDY above\n // rather than more of this, so the two halves never say the same thing twice.\n // A STORE MESSAGE IS NEVER ENGINEER TEXT; a stand-in written by a client can\n // be, and a person must not read it. It still reaches the engineer's line.\n const messageIsForEngineers = isEngineerText(String(error.message ?? \"\"));\n const said = timedOut ? TIMED_OUT_SAID : (messageIsForEngineers ? \"\" : (message.kept ?? \"\")).trim();\n\n const forEngineers = [\n error.sqlstate ? `SQLSTATE ${error.sqlstate}.` : null,\n // The client's own note about a class it did not recognize, or a call that\n // never reached the store. It is rendered out of sight, never as a sentence.\n error.diagnostic ? error.diagnostic : null,\n messageIsForEngineers || timedOut ? `Message: ${error.message}` : null,\n error.hint && (hintIsForEngineers || hint.kept !== error.hint) ? `Hint: ${error.hint}` : null,\n message.dropped.length > 0 || hint.dropped.length > 0\n ? `Dropped from the person's view: ${[...message.dropped, ...hint.dropped].join(\" | \")}`\n : null,\n ]\n .filter(Boolean)\n .join(\" \");\n\n return {\n title,\n // Nothing invented. When every clause was machine identity the title says\n // what happened and the remedy says what to do; a made-up diagnosis would\n // be worse than the identifier it replaced.\n sentence: said === \"\" ? `${title}.` : said,\n remedy,\n storeSaid: said !== \"\",\n forEngineers,\n };\n}\n\n/**\n * The same answer as one line, for a cell or a field where a block would break\n * the layout. Still one sentence and one remedy — never the sentence alone,\n * because half of this formatter's job is the thing to do next.\n */\nexport function refusalLineForAPerson(error: RecordsError): string {\n const plain = refusalForAPerson(error);\n // TWO SENTENCES, NOT ONE RUN-ON (VERIFIER-15/16): the store's rule message has no\n // full stop (\"Pressure (psi) has to be at least 0\"), and joining it to the remedy\n // read \"…at least 0 Send this column somewhere else\". A line ends its sentence.\n const sentence = plain.sentence.trim();\n const ended = sentence === \"\" || /[.!?…:]$/.test(sentence) ? sentence : `${sentence}.`;\n return `${ended} ${plain.remedy}`.trim();\n}\n\n/** The store refused because the request was missing something (22023 / invalid_argument): a decision, never text to print. */\nexport function refusalIsMissingInput(error: Partial<RecordsError>): boolean {\n return error.sqlstate === \"22023\" || error.code === \"invalid_argument\";\n}\n\n/**\n * A STORED SENTENCE WITHOUT ITS INTERNAL CODES (lane F2, D11). The store's older sentences — a kept-aside\n * reason, a migration note — end with the spec codes they were written against (\"(FLD-4 / T12)\",\n * \"(VAL-1)\"). Those codes are for the people who wrote the store; the store no longer writes them, and the\n * ones already saved come off here, wherever a person reads them.\n */\nexport function withoutInternalCodes(text: string): string {\n return text\n .replace(/\\s*\\((?:[A-Z]{2,}-\\d+[A-Za-z]?|T\\d+)(?:\\s*\\/\\s*(?:[A-Z]{2,}-\\d+[A-Za-z]?|T\\d+))*\\)/g, \"\")\n .replace(/\\s+([.,;])/g, \"$1\")\n .trim();\n}\n","// src/codeDependsRefusal.ts — @ai-matrx/records-ui · the \"an app's code depends on this table\" refusal, read\n//\n// Pure, so `/helpers` carries it and a host's archive action reads the refusal before it loads the\n// deliberate-archive dialog (records-ui front door, 2026-10-16). `ArchiveDeliberately.tsx` re-exports it.\n\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n/** What a \"the app's code depends on this table\" refusal names, or null for any other refusal. */\nexport function codeDependsRefusal(error: RecordsError | null | undefined): { slug: string; declaredIn: string | null } | null {\n if (!error) return null;\n const d = error.detail as Record<string, unknown> | undefined;\n if (!d || d[\"code_depends\"] !== true || typeof d[\"slug\"] !== \"string\") return null;\n const where = d[\"declared_in\"];\n const declaredIn = Array.isArray(where) ? where.map(String).join(\", \") : typeof where === \"string\" ? where : null;\n return { slug: d[\"slug\"], declaredIn };\n}\n","// src/announceTableArchived.ts — @ai-matrx/records-ui · the reversible action, for a table\n//\n// A TABLE ARCHIVED IS ANNOUNCED ONE WAY, WHEREVER IT WAS ARCHIVED FROM — the settings panel, the\n// table action list's Archive, any later surface. The package says what happened and how to undo\n// it; the host's `notify.reversible` (`@ai-matrx/kit/reversible`) decides how loud to be for this\n// person and answers ⌘Z.\n//\n// UNDO BRINGS THE WHOLE TABLE BACK. `custom.table_archive` writes every pass of one archive into ONE\n// archive event (STORE-TAILS-3), and `custom.table_restore` restores exactly that event — the table\n// and its columns first, then every record, then its forms, saved views and dashboards — in passes\n// (`client.tableRestoreWhole` loops them; one call timed out on a big table, TABLE-ACTIONS 2026-10-03).\n\nimport type { RecordsError, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport type { RecordsUiHost } from \"./host\";\nimport { refusalSentence } from \"./plainWords\";\n\nexport interface AnnounceTableArchived {\n notify: RecordsUiHost[\"notify\"];\n client: Pick<RecordsClient, \"tableRestoreWhole\">;\n tableId: Uuid;\n /** The table's name as the store gave it. */\n name: string;\n /** Called once the table is back, so the surface can show it again. */\n onRestored?: (() => void) | undefined;\n}\n\n/** Thrown by the undo when the store refuses it; its message is the store's one sentence. */\nexport class TableRestoreRefused extends Error {\n readonly refusal: RecordsError;\n readonly sentence: string;\n constructor(refusal: RecordsError) {\n const sentence = refusalSentence(refusal);\n super(sentence);\n this.name = \"TableRestoreRefused\";\n this.refusal = refusal;\n this.sentence = sentence;\n }\n}\n\nexport function announceTableArchived({ notify, client, tableId, name, onRestored }: AnnounceTableArchived): void {\n const undo = async () => {\n const back = await client.tableRestoreWhole({ table_id: tableId });\n if (!back.ok) throw new TableRestoreRefused(back.error);\n onRestored?.();\n };\n if (notify?.reversible) {\n notify.reversible({ verb: \"archive\", noun: \"table\", subject: name, undo });\n return;\n }\n // A host without the announcer: the sentence and one Undo, as before.\n notify?.success(`Archived “${name}”`, {\n label: \"Undo\",\n run: () => {\n void undo().then(\n () => notify?.success(`Restored “${name}”`),\n // The store's refusal is already a person's sentence; anything else never prints raw.\n (thrown: unknown) =>\n notify?.error(thrown instanceof TableRestoreRefused ? thrown.sentence : `Couldn’t restore “${name}”`),\n );\n },\n });\n}\n","// src/skeletonLayout.ts — @ai-matrx/records-ui · the skeleton's layout words, with no React\n//\n// Pure, so `/helpers` carries `skeletonLayoutFor` and a host can choose a loading frame before it\n// loads any screen (records-ui front door, 2026-10-16). `RecordsSkeleton.tsx` re-exports all of it.\n\n/** Every place a records surface shows while its first read is out. */\nexport type RecordsSkeletonLayout =\n | \"grid\"\n | \"kanban\"\n | \"gallery\"\n | \"list\"\n | \"calendar\"\n | \"timeline\"\n | \"map\"\n | \"orgchart\"\n | \"pivot\"\n | \"swipe\"\n | \"form\"\n | \"record\"\n | \"chart\"\n | \"home\";\n\nexport const RECORDS_SKELETON_LAYOUTS: readonly RecordsSkeletonLayout[] = [\n \"grid\",\n \"kanban\",\n \"gallery\",\n \"list\",\n \"calendar\",\n \"timeline\",\n \"map\",\n \"orgchart\",\n \"pivot\",\n \"swipe\",\n \"form\",\n \"record\",\n \"chart\",\n \"home\",\n];\n\n/** A layout word the address or a view carries, as the skeleton that stands for it. */\nexport function skeletonLayoutFor(layout: string | null | undefined): RecordsSkeletonLayout {\n if (layout === \"board\" || layout === \"pipeline\") return \"kanban\";\n return (RECORDS_SKELETON_LAYOUTS as readonly string[]).includes(layout ?? \"\")\n ? (layout as RecordsSkeletonLayout)\n : \"grid\";\n}\n\n/**\n * THE GEOMETRY OF AN EMBEDDED GRID, MEASURED ON A LIVE SPACES PAGE (lane SKELETON-HEIGHT, 2026-10-17).\n * A loading frame that is not the loaded frame moves everything under it when the rows land. The\n * embedded grid is: a 12px wrap (the body's 4px padding twice plus its 4px gap), the data table's 36px\n * header, one 37px row per record, and the footer line (44.5px: the add-row line) when there is a row.\n * Pure numbers, so a host can size a frame before it loads any screen.\n */\nexport const EMBEDDED_ROW_PX = 37;\nexport const EMBEDDED_HEADER_PX = 36;\nexport const EMBEDDED_FOOTER_PX = 44.5;\nexport const EMBEDDED_WRAP_PX = 12;\n/** An embedded table reads this many rows at a time (the same number as `EMBEDDED_PAGE_SIZE`, firstPage.ts; a test holds them equal). */\nexport const SKELETON_EMBEDDED_PAGE_ROWS = 50;\n/** A full page's grid reads this many rows at a time (the page's own `pageSize`). */\nexport const SKELETON_PAGE_ROWS = 100;\n\n/**\n * THE ROWS A LOADING FRAME DRAWS WHEN THE SERVER KNOWS HOW MANY THE PERSON SEES: min(rows, page size).\n * `rowsVisible` is the count the store gave (`custom.where_id_opens` / the table bundle: the caller's own\n * visible rows, capped), `pageSize` the rows the surface reads first. Null/undefined/invalid = not known.\n */\nexport function skeletonRowsFor(rowsVisible: number | null | undefined, pageSize: number): number | null {\n if (typeof rowsVisible !== \"number\" || !Number.isFinite(rowsVisible) || rowsVisible < 0) return null;\n return Math.min(Math.floor(rowsVisible), pageSize);\n}\n\n/** The height (px) of an embedded grid's body with `rows` rows drawn: the loaded body's own height. */\nexport function embeddedGridBodyPx(rows: number): number {\n return EMBEDDED_WRAP_PX + EMBEDDED_HEADER_PX + EMBEDDED_ROW_PX * rows + (rows > 0 ? EMBEDDED_FOOTER_PX : 0);\n}\n\n/**\n * THE CARDS EACH BOARD COLUMN DRAWS WHEN THE SERVER KNOWS THEM (lane SKELETON-HEIGHT-2): the store's\n * per-group counts (`opening_view.groups`), each min(cards, page size). Null = not known (empty or invalid),\n * so the board skeleton keeps its stand-in columns. A column with no card still draws (its header).\n */\nexport function skeletonColumnsFor(groups: readonly number[] | null | undefined, pageSize: number): number[] | null {\n if (!Array.isArray(groups) || groups.length === 0) return null;\n const out: number[] = [];\n for (const g of groups) {\n if (typeof g !== \"number\" || !Number.isFinite(g) || g < 0) return null;\n out.push(Math.min(Math.floor(g), pageSize));\n }\n return out;\n}\n","// src/gridAgentContext.ts — @ai-matrx/records-ui · merge tranche 6l (inventory H1 / H2)\n//\n// WHAT AN AGENT BESIDE THE GRID IS TOLD.\n//\n// The older /data grid published a live scope for the `matrx-user/data-tables` surface: the table,\n// its columns with their formats and choices, the row label, the row actions, the current cell and\n// row, the selected block as TSV, the ticked rows, the rows on screen and the search. An agent in\n// the side chat read it and could write ONE confirmed cell. The merged grid tells the host the same\n// facts through `RecordsUiHost.onGridContext`, in the store's own shapes (`Field`, the masked\n// document), and the host builds its surface scope from it — this package ships no chat.\n//\n// Pure: `gridContextSnapshot` assembles, `gridContextKey` says whether anything changed, so the\n// host is told once per change and never on an unrelated render.\n\nimport type { Field, ReadRow, RecordDocument, RowAction, Table, Uuid } from \"@ai-matrx/records\";\n\nimport { recordNameIn, tableName } from \"./names\";\nimport { toDelimited } from \"@ai-matrx/kit/delimited\";\n\n/** One record as the grid shows it: its id, its name (the row label) and its masked document. */\nexport interface GridContextRecord {\n id: Uuid;\n title: string;\n document: RecordDocument;\n}\n\nexport interface GridContextSnapshot {\n tableId: Uuid;\n tableName: string;\n /** The table's own description (`metadata.description`), when it has one. */\n tableDescription: string | null;\n /** The Field key that names each record (`title_field`), or null. */\n titleField: string | null;\n /** The columns in the order the grid draws them (hidden columns left out). */\n fields: Field[];\n /** The table's row actions as the store lists them (update and agent). */\n rowActions: RowAction[];\n /** May this person change records here at all. */\n canWrite: boolean;\n /** The cell the cursor is on: its record, its Field key and the value drawn in it. */\n currentCell: { rowId: Uuid; key: string; value: unknown } | null;\n /** The record the cursor is on (or whose editor is open). */\n currentRow: GridContextRecord | null;\n /** A block of more than one cell: Excel/Sheets TSV with a header line of Field keys. */\n selectedRange: { tsv: string; cellCount: number; rowIds: Uuid[]; keys: string[] } | null;\n /** The rows ticked with the row boxes. */\n selectedRows: GridContextRecord[];\n /** The page of records on screen, in screen order. */\n visibleRows: GridContextRecord[];\n /** How many records match the search and filters, when the store said. */\n total: number | null;\n search: string;\n}\n\n/** Where the cursor is, as the data table tells it (`spreadsheet.onSelectionChange`). */\nexport interface GridCursor {\n active: { rowId: string; columnId: string };\n rowIds: string[];\n columnIds: string[];\n cellCount: number;\n tsv: string;\n}\n\nfunction recordOf(table: Table | null, row: ReadRow): GridContextRecord {\n const document = (row.document ?? {}) as RecordDocument;\n return { id: row.id, title: recordNameIn(table, document as Record<string, unknown>), document };\n}\n\nexport function gridContextSnapshot(args: {\n tableId: Uuid;\n table: Table | null;\n fields: readonly Field[];\n /** The Field keys on screen, in order. */\n shownKeys: readonly string[];\n rows: readonly ReadRow[];\n rowActions: readonly RowAction[];\n canWrite: boolean;\n cursor: GridCursor | null;\n /** The cell whose editor is open, which wins over the cursor. */\n editing: { rowId: Uuid; key: string; draft: unknown } | null;\n selectedIds: readonly string[];\n total: number | null;\n search: string;\n}): GridContextSnapshot {\n const { table, rows } = args;\n const byKey = new Map(args.fields.map((f) => [f.key, f] as const));\n const fields = args.shownKeys.map((k) => byKey.get(k)).filter((f): f is Field => f !== undefined);\n const byId = new Map(rows.map((r) => [r.id as string, r] as const));\n\n let currentCell: GridContextSnapshot[\"currentCell\"] = null;\n if (args.editing) {\n currentCell = { rowId: args.editing.rowId, key: args.editing.key, value: args.editing.draft ?? null };\n } else if (args.cursor && byId.has(args.cursor.active.rowId) && byKey.has(args.cursor.active.columnId)) {\n const row = byId.get(args.cursor.active.rowId)!;\n const key = args.cursor.active.columnId;\n currentCell = { rowId: row.id, key, value: ((row.document ?? {}) as Record<string, unknown>)[key] ?? null };\n }\n const currentRowSource = currentCell ? byId.get(currentCell.rowId) : undefined;\n\n let selectedRange: GridContextSnapshot[\"selectedRange\"] = null;\n if (args.cursor && args.cursor.cellCount > 1) {\n const keys = args.cursor.columnIds.filter((k) => byKey.has(k));\n selectedRange = {\n tsv: `${toDelimited([keys], { format: \"tsv\", spreadsheetSafe: false })}\\n${args.cursor.tsv}`,\n cellCount: args.cursor.cellCount,\n rowIds: args.cursor.rowIds.filter((id) => byId.has(id)) as Uuid[],\n keys,\n };\n }\n\n const description = table?.metadata?.[\"description\"];\n return {\n tableId: args.tableId,\n tableName: table ? tableName(table) : \"\",\n tableDescription: typeof description === \"string\" && description.trim() ? description : null,\n titleField: table?.title_field ?? null,\n fields,\n rowActions: [...args.rowActions],\n canWrite: args.canWrite,\n currentCell,\n currentRow: currentRowSource ? recordOf(table, currentRowSource) : null,\n selectedRange,\n selectedRows: args.selectedIds\n .map((id) => byId.get(id))\n .filter((r): r is ReadRow => r !== undefined)\n .map((r) => recordOf(table, r)),\n visibleRows: rows.map((r) => recordOf(table, r)),\n total: args.total,\n search: args.search,\n };\n}\n\n/** A snapshot's identity: two snapshots with the same key say the same thing. */\nexport function gridContextKey(snapshot: GridContextSnapshot): string {\n return JSON.stringify([\n snapshot.tableId,\n snapshot.tableName,\n snapshot.tableDescription,\n snapshot.titleField,\n snapshot.fields.map((f) => [f.id, f.key, f.version ?? null]),\n snapshot.rowActions.map((a) => [a.id, a.name]),\n snapshot.canWrite,\n snapshot.currentCell,\n snapshot.selectedRange,\n snapshot.selectedRows.map((r) => r.id),\n snapshot.visibleRows.map((r) => [r.id, r.document]),\n snapshot.total,\n snapshot.search,\n ]);\n}\n","// src/objectActions.ts — @ai-matrx/records-ui\n//\n// THE ONE ACTION LIST FOR A RECORD-STORE TABLE (lane TABLE-ACTIONS, v6 lane 1).\n//\n// Every menu a person meets on a table — the header ⋯, a row ⋯ on the Data\n// home, right-click, a card, the phone sheet, later ⌘K — is drawn from the\n// array `tableActions()` returns. Before this there were three hand-made lists\n// (`TABLE_MENU` in TablePage, `dataHomeRowActions` in matrx-frontend, the\n// Sheet's own v3 sections) and they drifted: no Archive, no Copy link, no\n// Duplicate, Rename and Share only as hand JSX beside the list.\n//\n// THE SHAPE IS COPIED, NOT INVENTED. It is the in-house registry pattern of\n// `features/agents/browse/agentActionRegistry.tsx` and `conversationActionRegistry.tsx`\n// in matrx-frontend: a context of HOST HANDLERS in, one ordered list out, every\n// renderer reading the same list. The one difference is deliberate: those two\n// build matrx-frontend's `ItemMenuConfig` directly, which this package cannot\n// import, so the list here is renderer-neutral (`ObjectAction[]`) and each\n// renderer has a pure adapter (`toDropdownEntries` / `toStripAndRows` here;\n// `toItemMenuConfig` and `toExtraSections` in matrx-frontend\n// `features/unified-data/actions/`).\n//\n// TWO INVARIANTS, each with a guard (`one-table-action-list-*.test.tsx`,\n// `rights-never-change-the-table-menus-shape.test.tsx`):\n// G1 — every renderer draws the same ids — none hidden, none added, disabled ones\n// drawn disabled with their reason — for every seat and with handlers missing.\n// G2 — rights change only `disabledReason`, never which ids appear, their order,\n// their verb or their rank (Airtable hides items from members; we beat it).\n// A missing host handler is the same: the action stays, disabled, with its reason.\n//\n// THE ORDER (handoff §4, the same everywhere):\n// Open · Open in new tab · Copy link | Rename · Duplicate · Move to… · Favorite |\n// Share… · Export… · Import… | Add column · Settings · History · Make … the default |\n// Built on it ▸ (Forms, Bookings, Checklists, Notifications, Portals, Inbox,\n// Dashboards, Archived records) | Archive table (last, destructive).\n// \"Add column\" and \"Make … the default\" are the header ⋯'s own entries before the\n// registry (TABLE_MENU and the designate item); they sit with Settings.\n//\n// VERB AND RANK — for the icon-strip menu. An action with a `verb` is one of the\n// platform's standard verbs (a strip icon); every other action has a `rank`, its\n// place among the feature rows. Neither changes the list's order: `toStripAndRows`\n// is a renderer that splits the same list, and G1 holds it to the same ids.\n//\n// No JSX here: this file is the `./object-actions` subpath, light enough for a\n// list row's menu to import without pulling every screen of the package.\n\nimport type { Table } from \"@ai-matrx/records\";\nimport { formatTapShortcut } from \"@ai-matrx/design-system/tap-shortcut\";\nimport { ADD_FIELD_OPEN_LABEL } from \"./fieldTypes\";\nimport { LEVEL_WORD, levelNeededFor, type Capability, type WhatYouMayDo } from \"./rights\";\n\n/**\n * A Lucide icon NAME, kebab-case — the same currency `Table.icon` already uses.\n * Closed on purpose: each renderer maps every member to its own glyph, and a\n * new member fails that renderer's typecheck until it is mapped.\n */\nexport type ObjectActionIcon =\n | \"folder-open\"\n | \"external-link\"\n | \"link\"\n | \"pencil\"\n | \"copy\"\n | \"folder-input\"\n | \"star\"\n | \"star-off\"\n | \"share-2\"\n | \"download\"\n | \"upload\"\n | \"columns-3\"\n | \"settings\"\n | \"history\"\n | \"blocks\"\n | \"file-text\"\n | \"calendar-clock\"\n | \"list-checks\"\n | \"bell\"\n | \"door-open\"\n | \"inbox\"\n | \"layout-dashboard\"\n | \"archive-restore\"\n | \"archive\"\n | \"link-2\"\n | \"layout-grid\"\n | \"git-merge\"\n | \"split\"\n | \"arrow-up-from-line\"\n | \"corner-down-right\"\n | \"lock\"\n | \"lock-open\"\n | \"eraser\"\n | \"printer\";\n\n/** The groups, in their one order. Separators fall out of group boundaries. */\nexport type ObjectActionGroup = \"open\" | \"organize\" | \"share\" | \"manage\" | \"built-on\" | \"danger\";\n\n/**\n * THE STANDARD VERBS every object's menu shares — what the icon strip draws. One\n * per meaning; an object maps its action onto the verb, never a second \"share\".\n */\nexport type StandardVerbId =\n | \"open\"\n | \"open-new-tab\"\n | \"copy-link\"\n | \"rename\"\n | \"duplicate\"\n | \"move\"\n | \"favorite\"\n | \"share\"\n | \"export\"\n | \"import\"\n | \"settings\"\n | \"history\"\n | \"archive\";\n\nexport const STANDARD_VERBS: readonly StandardVerbId[] = [\n \"open\",\n \"open-new-tab\",\n \"copy-link\",\n \"rename\",\n \"duplicate\",\n \"move\",\n \"favorite\",\n \"share\",\n \"export\",\n \"import\",\n \"settings\",\n \"history\",\n \"archive\",\n];\n\nexport interface ObjectActionGroupDef {\n id: ObjectActionGroup;\n /** Present only on a group that renders as a submenu. */\n label?: string;\n icon?: ObjectActionIcon;\n /** Rendered as ONE submenu entry holding the group's actions. */\n submenu: boolean;\n}\n\nexport const OBJECT_ACTION_GROUPS: readonly ObjectActionGroupDef[] = [\n { id: \"open\", submenu: false },\n { id: \"organize\", submenu: false },\n { id: \"share\", submenu: false },\n { id: \"manage\", submenu: false },\n { id: \"built-on\", label: \"Built on it\", icon: \"blocks\", submenu: true },\n { id: \"danger\", submenu: false },\n];\n\nconst GROUP_IDS = new Set<string>(OBJECT_ACTION_GROUPS.map((g) => g.id));\n\n/** One thing a person can do to an object, for any renderer. */\nexport interface ObjectAction {\n /** Stable within the object's list. React key, test handle, future ⌘K id. */\n id: string;\n label: string;\n icon: ObjectActionIcon;\n group: ObjectActionGroup;\n /** The standard verb this action IS (a strip icon). Absent = a feature row. */\n verb?: StandardVerbId;\n /** A feature row's place among the rows, 1 first. Ignored when `verb` is set. */\n rank?: number;\n /** Display-only hint (\"⌘D\"). */\n shortcut?: string;\n destructive?: boolean;\n /** Present = shown disabled with this line (≤ 60 chars). Absent = enabled. */\n disabledReason?: string;\n /** Called only when enabled. The host owns the side effect and its feedback. */\n run: () => void | Promise<void>;\n}\n\n/** What the list needs to know about the table. A full `Table` satisfies it. */\nexport type TableActionSubject = Pick<Table, \"id\" | \"name\"> & Partial<Pick<Table, \"is_kernel\">>;\n\n/** The places built on a table, in their one order. */\nexport type BuiltOnDestination =\n | \"forms\"\n | \"bookings\"\n | \"checklists\"\n | \"notifications\"\n | \"portals\"\n | \"inbox\"\n | \"dashboards\"\n | \"archived\";\n\ntype Handler = (table: TableActionSubject) => void | Promise<void>;\n\n/**\n * THE SIDE EFFECTS THIS PACKAGE CANNOT OWN. Every handler is optional: one the\n * host leaves out keeps its action in the list, disabled, saying so.\n */\nexport interface TableActionHost {\n /** Origin for Copy link and Open in new tab. Default `https://www.aimatrx.com`. */\n origin?: string;\n open?: Handler;\n /** Receives the table's link (`<origin>/data/<id>`). */\n openInNewTab?: (url: string, table: TableActionSubject) => void;\n /** Receives the table's link. Runs inside the click (clipboard needs the gesture). */\n copyText?: (text: string, table: TableActionSubject) => void | Promise<void>;\n rename?: Handler;\n duplicate?: Handler;\n move?: Handler;\n /** Current favorite state; flips the Favorite label. Unknown = \"Add to favorites\". */\n isFavorite?: boolean;\n toggleFavorite?: Handler;\n share?: Handler;\n export?: Handler;\n import?: Handler;\n addColumn?: Handler;\n settings?: Handler;\n history?: Handler;\n /** Make the layout on screen the table's default. Leave out when it already is. */\n makeDefault?: Handler;\n /** The layout on screen, for \"Make Kanban the default\". */\n layoutLabel?: string;\n /** The \"Built on it\" destinations, one handler for all eight. */\n openBuiltOn?: (destination: BuiltOnDestination, table: TableActionSubject) => void;\n archive?: Handler;\n /**\n * Why an action whose handler is left out is unavailable here, by action id\n * (≤ 60 chars) — e.g. `make-default: \"Already the default\"`. Unnamed ids say\n * \"Not available here\". Never used when rights already refuse.\n */\n unavailableReasons?: Readonly<Record<string, string>>;\n /**\n * ANOTHER LANE'S ENTRIES (\"Link a record…\", a hub tile's verbs, a feature's own\n * row such as \"When a row changes, run an agent…\"). Return the same ids whatever\n * `rights` say — express rights as `disabledReason`. Each entry lands at the END\n * of its named group, in the order returned. Refused, loudly: the `danger` group\n * (Archive is always last), a group that does not exist, and an id already in\n * the list.\n */\n extend?: (table: TableActionSubject, rights: WhatYouMayDo) => readonly ObjectAction[];\n}\n\nexport interface TableActionsInput {\n table: TableActionSubject;\n rights: WhatYouMayDo;\n host: TableActionHost;\n}\n\nexport const DEFAULT_ACTION_ORIGIN = \"https://www.aimatrx.com\";\n\n/** The one link to a table: `<origin>/data/<tableId>`. */\nexport function tableLink(tableId: string, origin: string = DEFAULT_ACTION_ORIGIN): string {\n return `${origin.replace(/\\/+$/, \"\")}/data/${encodeURIComponent(tableId)}`;\n}\n\n/** The designate entry's words, matching `makeDefaultLabel` in views.ts. */\nfunction makeDefaultWords(layoutLabel: string | undefined): string {\n return layoutLabel ? `Make ${layoutLabel} the default` : \"Make this the default\";\n}\n\n// Reasons — one line, ≤ 60 characters, said on the action itself.\nexport const ACTION_NOT_HERE_REASON = \"Not available here\";\nexport const ACTION_CHECKING_ACCESS_REASON = \"Checking your access…\";\nexport const ACTION_NO_ACCESS_REASON = \"You don't have access\";\nexport const ACTION_PLATFORM_TABLE_REASON = \"Platform tables can't be changed here\";\n\n/** Why `rights` refuse `what`, in one short line — or null when they allow it. */\nexport function rightsReason(\n rights: WhatYouMayDo,\n what: Capability,\n table?: TableActionSubject,\n): string | null {\n if (!rights.known) return ACTION_CHECKING_ACCESS_REASON;\n if (what === \"structure\" && table?.is_kernel) return ACTION_PLATFORM_TABLE_REASON;\n if (rights[what]) return null;\n if (rights.level === null) return ACTION_NO_ACCESS_REASON;\n return `Needs ${LEVEL_WORD[levelNeededFor(what)]}`;\n}\n\n// Feature rows' ranks: what the strip menu shows as its first rows. Lower is first.\nconst BUILT_ON: ReadonlyArray<{ destination: BuiltOnDestination; label: string; icon: ObjectActionIcon; rank: number }> = [\n { destination: \"forms\", label: \"Forms\", icon: \"file-text\", rank: 2 },\n { destination: \"bookings\", label: \"Bookings\", icon: \"calendar-clock\", rank: 6 },\n { destination: \"checklists\", label: \"Checklists\", icon: \"list-checks\", rank: 7 },\n { destination: \"notifications\", label: \"Notifications\", icon: \"bell\", rank: 8 },\n { destination: \"portals\", label: \"Portals\", icon: \"door-open\", rank: 9 },\n { destination: \"inbox\", label: \"Inbox\", icon: \"inbox\", rank: 10 },\n { destination: \"dashboards\", label: \"Dashboards\", icon: \"layout-dashboard\", rank: 3 },\n { destination: \"archived\", label: \"Archived records\", icon: \"archive-restore\", rank: 5 },\n];\n\nconst NOOP = () => {};\n\n/**\n * THE TABLE'S KEYBOARD CHORDS (lane TABLE-ACTIONS wave 4, item 17): ⌥⇧ + one key, the same on\n * every surface that runs the list. Chosen because nothing else owns them: ⌘D is the browser's\n * bookmark, ⌘S save, ⌘P print, ⌘K the command bar, ⌘⇧K the menu's palette, ⌘Z undo — and the\n * app binds no ⌥⇧ chord. A chord is never taken while the person types in a field\n * (`objectActionForKey`). `code` is the KeyboardEvent.code, so ⌥ on a Mac (which changes\n * `key` to a symbol) still matches.\n */\nexport const TABLE_ACTION_CHORDS: Readonly<Record<string, { code: string; chord: string }>> = {\n \"copy-link\": { code: \"KeyL\", chord: \"alt+shift+l\" },\n rename: { code: \"KeyR\", chord: \"alt+shift+r\" },\n duplicate: { code: \"KeyD\", chord: \"alt+shift+d\" },\n move: { code: \"KeyM\", chord: \"alt+shift+m\" },\n favorite: { code: \"KeyF\", chord: \"alt+shift+f\" },\n share: { code: \"KeyS\", chord: \"alt+shift+s\" },\n export: { code: \"KeyE\", chord: \"alt+shift+e\" },\n import: { code: \"KeyI\", chord: \"alt+shift+i\" },\n settings: { code: \"Comma\", chord: \"alt+shift+,\" },\n history: { code: \"KeyH\", chord: \"alt+shift+h\" },\n archive: { code: \"Backspace\", chord: \"alt+shift+backspace\" },\n};\n\n/**\n * The chords with their LABEL in this platform's words — \"⌥⇧S\" on a Mac, \"Alt+Shift+S\" on Windows\n * and Linux — through the design system's one shortcut formatter (`formatTapShortcut`, the tap\n * button's tooltip), so a menu entry and the ⌘K bar read alike everywhere.\n */\nexport const TABLE_ACTION_KEYS: Readonly<Record<string, { code: string; label: string }>> = Object.fromEntries(\n Object.entries(TABLE_ACTION_CHORDS).map(([id, { code, chord }]) => [id, { code, label: formatTapShortcut(chord) }]),\n);\n\n/** The fields of a keyboard event a chord reads (a DOM KeyboardEvent satisfies it). */\nexport interface ChordEvent {\n code: string;\n altKey: boolean;\n shiftKey: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n target?: EventTarget | null;\n}\n\nfunction typingIn(target: EventTarget | null | undefined): boolean {\n const el = target as { tagName?: string; isContentEditable?: boolean } | null | undefined;\n if (!el || typeof el.tagName !== \"string\") return false;\n return el.isContentEditable === true || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName);\n}\n\n/**\n * The action a key press asks for, or null: ⌥⇧ + its key, no ⌘/Ctrl, never inside a field. A\n * disabled action is still RETURNED (the caller says its reason instead of doing nothing).\n */\nexport function objectActionForKey(actions: readonly ObjectAction[], event: ChordEvent): ObjectAction | null {\n if (!event.altKey || !event.shiftKey || event.metaKey || event.ctrlKey) return null;\n if (typingIn(event.target)) return null;\n const id = Object.keys(TABLE_ACTION_KEYS).find((k) => TABLE_ACTION_KEYS[k]!.code === event.code);\n return id ? (actions.find((a) => a.id === id) ?? null) : null;\n}\n\n/**\n * One action, from its needs: the capability it asks for and the host handler\n * that performs it. Rights speak first; a missing handler second.\n */\nfunction action(\n base: Omit<ObjectAction, \"run\" | \"disabledReason\">,\n needs: Capability,\n input: TableActionsInput,\n perform: (() => void | Promise<void>) | undefined,\n): ObjectAction {\n const chord = TABLE_ACTION_KEYS[base.id];\n if (chord && base.shortcut === undefined) base = { ...base, shortcut: chord.label };\n const refused = rightsReason(input.rights, needs, input.table);\n if (refused !== null) return { ...base, disabledReason: refused, run: NOOP };\n if (perform === undefined) {\n return { ...base, disabledReason: input.host.unavailableReasons?.[base.id] ?? ACTION_NOT_HERE_REASON, run: NOOP };\n }\n return { ...base, run: perform };\n}\n\nfunction bind(handler: Handler | undefined, table: TableActionSubject): (() => void | Promise<void>) | undefined {\n return handler ? () => handler(table) : undefined;\n}\n\n/**\n * THE TABLE'S ACTIONS, in the one order. Same ids, same order, same verbs and\n * ranks, for every seat and every host — only `disabledReason` varies.\n */\nexport function tableActions(input: TableActionsInput): ObjectAction[] {\n const { table, host } = input;\n const url = tableLink(table.id, host.origin);\n const favorite = host.isFavorite === true;\n const openInNewTab = host.openInNewTab;\n const copyText = host.copyText;\n const openBuiltOn = host.openBuiltOn;\n\n const built: ObjectAction[] = [\n action({ id: \"open\", label: \"Open\", icon: \"folder-open\", group: \"open\", verb: \"open\" }, \"read\", input, bind(host.open, table)),\n action(\n { id: \"open-new-tab\", label: \"Open in new tab\", icon: \"external-link\", group: \"open\", verb: \"open-new-tab\" },\n \"read\",\n input,\n openInNewTab ? () => openInNewTab(url, table) : undefined,\n ),\n action(\n { id: \"copy-link\", label: \"Copy link\", icon: \"link\", group: \"open\", verb: \"copy-link\" },\n \"read\",\n input,\n copyText ? () => copyText(url, table) : undefined,\n ),\n action({ id: \"rename\", label: \"Rename…\", icon: \"pencil\", group: \"organize\", verb: \"rename\" }, \"structure\", input, bind(host.rename, table)),\n action({ id: \"duplicate\", label: \"Duplicate\", icon: \"copy\", group: \"organize\", verb: \"duplicate\" }, \"read\", input, bind(host.duplicate, table)),\n action({ id: \"move\", label: \"Move to…\", icon: \"folder-input\", group: \"organize\", verb: \"move\" }, \"structure\", input, bind(host.move, table)),\n action(\n {\n id: \"favorite\",\n label: favorite ? \"Remove from favorites\" : \"Add to favorites\",\n icon: favorite ? \"star-off\" : \"star\",\n group: \"organize\",\n verb: \"favorite\",\n },\n \"read\",\n input,\n bind(host.toggleFavorite, table),\n ),\n action({ id: \"share\", label: \"Share…\", icon: \"share-2\", group: \"share\", verb: \"share\" }, \"share\", input, bind(host.share, table)),\n action({ id: \"export\", label: \"Export…\", icon: \"download\", group: \"share\", verb: \"export\" }, \"read\", input, bind(host.export, table)),\n action({ id: \"import\", label: \"Import…\", icon: \"upload\", group: \"share\", verb: \"import\" }, \"structure\", input, bind(host.import, table)),\n action({ id: \"add-column\", label: ADD_FIELD_OPEN_LABEL, icon: \"columns-3\", group: \"manage\", rank: 1 }, \"structure\", input, bind(host.addColumn, table)),\n action({ id: \"settings\", label: \"Settings\", icon: \"settings\", group: \"manage\", verb: \"settings\" }, \"structure\", input, bind(host.settings, table)),\n action({ id: \"history\", label: \"History\", icon: \"history\", group: \"manage\", verb: \"history\" }, \"read\", input, bind(host.history, table)),\n // custom.view_designate asks editor on the table — `canDesignate` in TablePage.\n action(\n { id: \"make-default\", label: makeDefaultWords(host.layoutLabel), icon: \"layout-grid\", group: \"manage\", rank: 4 },\n \"organise\",\n input,\n bind(host.makeDefault, table),\n ),\n ...BUILT_ON.map(({ destination, label, icon, rank }) =>\n action(\n { id: `built-on.${destination}`, label, icon, group: \"built-on\", rank },\n \"read\",\n input,\n openBuiltOn ? () => openBuiltOn(destination, table) : undefined,\n ),\n ),\n action(\n { id: \"archive\", label: \"Archive table\", icon: \"archive\", group: \"danger\", destructive: true, verb: \"archive\" },\n \"structure\",\n input,\n bind(host.archive, table),\n ),\n ];\n\n return withExtensions(built, host.extend ? host.extend(table, input.rights) : []);\n}\n\n/**\n * Another lane's entries, placed deterministically: each at the end of its\n * group, in the order given. Loud on every mistake that would break the\n * invariants — a `danger` entry (Archive must stay last), a group that does not\n * exist (it would be dropped by every renderer) and a duplicate id.\n */\nexport function withExtensions(base: readonly ObjectAction[], extra: readonly ObjectAction[]): ObjectAction[] {\n if (extra.length === 0) return [...base];\n const seen = new Set(base.map((a) => a.id));\n for (const entry of extra) {\n if (entry.group === \"danger\") {\n throw new Error(`Object action \"${entry.id}\": the danger group is closed to extensions.`);\n }\n if (!GROUP_IDS.has(entry.group)) {\n throw new Error(`Object action \"${entry.id}\": \"${String(entry.group)}\" is not a group.`);\n }\n if (seen.has(entry.id)) {\n throw new Error(`Object action \"${entry.id}\" is already in the list.`);\n }\n seen.add(entry.id);\n }\n const out: ObjectAction[] = [];\n for (const group of OBJECT_ACTION_GROUPS) {\n out.push(...base.filter((a) => a.group === group.id), ...extra.filter((a) => a.group === group.id));\n }\n return out;\n}\n\n/** A run of actions that renders together: a plain section, or one submenu. */\nexport interface ObjectActionSection {\n group: ObjectActionGroupDef;\n actions: ObjectAction[];\n}\n\n/**\n * THE ONE GROUPING every adapter uses: the list cut at group boundaries, in\n * group order, empty groups dropped, the order inside a group kept.\n */\nexport function groupObjectActions(actions: readonly ObjectAction[]): ObjectActionSection[] {\n const sections: ObjectActionSection[] = [];\n for (const group of OBJECT_ACTION_GROUPS) {\n const inGroup = actions.filter((a) => a.group === group.id);\n if (inGroup.length > 0) sections.push({ group, actions: inGroup });\n }\n return sections;\n}\n\n/** The header ⋯ dropdown's entries — records-ui's own renderer reads these. */\nexport type ObjectActionDropdownEntry =\n | { kind: \"separator\"; id: string }\n | { kind: \"item\"; action: ObjectAction }\n | { kind: \"submenu\"; id: string; label: string; icon: ObjectActionIcon | undefined; actions: ObjectAction[] };\n\nexport function toDropdownEntries(actions: readonly ObjectAction[]): ObjectActionDropdownEntry[] {\n const entries: ObjectActionDropdownEntry[] = [];\n groupObjectActions(actions).forEach(({ group, actions: inGroup }, index) => {\n if (index > 0) entries.push({ kind: \"separator\", id: `separator:${group.id}` });\n if (group.submenu) {\n entries.push({ kind: \"submenu\", id: group.id, label: group.label ?? group.id, icon: group.icon, actions: inGroup });\n } else {\n for (const a of inGroup) entries.push({ kind: \"item\", action: a });\n }\n });\n return entries;\n}\n\n/** The actions a dropdown draws, in order — what G1 compares. */\nexport function dropdownActions(entries: readonly ObjectActionDropdownEntry[]): ObjectAction[] {\n return entries.flatMap((e) => (e.kind === \"item\" ? [e.action] : e.kind === \"submenu\" ? e.actions : []));\n}\n\n/** The action ids a dropdown draws, in order. */\nexport function dropdownActionIds(entries: readonly ObjectActionDropdownEntry[]): string[] {\n return dropdownActions(entries).map((a) => a.id);\n}\n\n/** The icon-strip menu: standard verbs as icons, then the first feature rows, then the rest. */\nexport interface StripAndRows {\n /** Every action with a `verb`, in the list's order. */\n strip: ObjectAction[];\n /** The first `rowCount` feature actions by rank (ties keep list order). */\n rows: ObjectAction[];\n /** The remaining feature actions, behind \"More … options\", same ordering. */\n more: ObjectAction[];\n}\n\nexport const STRIP_FEATURE_ROWS = 4;\n\n/**\n * THE STRIP RENDERER'S SPLIT of the same list. Nothing is added or dropped: every\n * id lands in exactly one of strip / rows / more (G1). Unranked feature actions\n * (an extension that gave none) follow every ranked one.\n */\nexport function toStripAndRows(actions: readonly ObjectAction[], rowCount: number = STRIP_FEATURE_ROWS): StripAndRows {\n const strip = actions.filter((a) => a.verb !== undefined);\n const features = actions\n .map((a, index) => ({ a, index }))\n .filter(({ a }) => a.verb === undefined)\n .sort((x, y) => (x.a.rank ?? Infinity) - (y.a.rank ?? Infinity) || x.index - y.index)\n .map(({ a }) => a);\n return { strip, rows: features.slice(0, rowCount), more: features.slice(rowCount) };\n}\n","// src/recordActions.ts — @ai-matrx/records-ui\n//\n// THE ONE ACTION LIST FOR A RECORD (lane TABLE-ACTIONS, v6 lane 1, item 14).\n//\n// Every menu a person meets on ONE RECORD — a Gallery card's ⋯ and right-click, a Kanban card's,\n// a Pipeline card's, the grid row's — is drawn from the array `recordActions()` returns. It is\n// built exactly the way `tableActions()` is (`objectActions.ts`): host handlers in, one ordered\n// `ObjectAction[]` out, every renderer reading the same list through the same adapters\n// (`toDropdownEntries`, `ObjectActionMenuItems`, `RecordActionMenu`).\n//\n// The same two invariants hold, with their guard (`one-record-action-list-*.test.tsx`):\n// G1 — every renderer draws the same ids, none hidden, none added.\n// G2 — rights change only `disabledReason`, never which ids appear or their order.\n//\n// THE ORDER: Open · Open in new tab · Copy link | Duplicate · Merge with… · Split… · Extract parent… · Move to another table… · Link a record… | Print with layout… | History |\n// Archive record (last, red).\n\nimport type { Uuid } from \"@ai-matrx/records\";\nimport {\n ACTION_NOT_HERE_REASON,\n DEFAULT_ACTION_ORIGIN,\n rightsReason,\n withExtensions,\n type ObjectAction,\n} from \"./objectActions\";\nimport type { Capability, WhatYouMayDo } from \"./rights\";\n\n/** What the list needs to know about the record. */\nexport interface RecordActionSubject {\n id: Uuid;\n tableId: Uuid;\n /** The record's name as every card reads it (`recordNameIn` / `cardWords`). */\n name: string;\n}\n\ntype RecordHandler = (record: RecordActionSubject) => void | Promise<void>;\n\n/** THE SIDE EFFECTS THIS LIST CANNOT OWN. A handler left out keeps its action, disabled. */\nexport interface RecordActionHost {\n /** Origin for Copy link and Open in new tab. Default `https://www.aimatrx.com`. */\n origin?: string;\n /**\n * The record's own page (the host's `hrefForRecord`), absolute or root-relative. When given, Copy\n * link and Open in new tab carry it instead of the table page with `?record=`.\n */\n href?: string;\n open?: RecordHandler;\n openInNewTab?: (url: string, record: RecordActionSubject) => void;\n /** Runs inside the click (the clipboard needs the gesture). */\n copyText?: (text: string, record: RecordActionSubject) => void | Promise<void>;\n duplicate?: RecordHandler;\n /** Merge another record of the same table into this one (`MergeRecordDialog`). */\n merge?: RecordHandler;\n /** Move some of this record's values to a new record of the same table (`SplitRecordDialog`). */\n split?: RecordHandler;\n /** Copy some values up into a new record of a parent table and put this one under it (`ExtractParentDialog`). */\n extractParent?: RecordHandler;\n /** Put this record under another record you pick (`MoveUnderDialog`, `custom.record_reparent`, test 3). */\n moveUnder?: RecordHandler;\n /** Move this record to another table of its organization, keeping its id (`MoveRecordDialog`, test 9). */\n moveToTable?: RecordHandler;\n /** Open the host's one record picker pointed at this record (`RecordsUiHost.linkRecord`). */\n link?: RecordHandler;\n /** Open the print-with-layout dialog for this record (`PrintWithLayoutDialog`). */\n printLayout?: RecordHandler;\n history?: RecordHandler;\n archive?: RecordHandler;\n /** Why an action whose handler is left out is unavailable here, by id (≤ 60 chars). */\n unavailableReasons?: Readonly<Record<string, string>>;\n /** Another lane's record entries; same rules as `TableActionHost.extend`. */\n extend?: (record: RecordActionSubject, rights: WhatYouMayDo) => readonly ObjectAction[];\n}\n\nexport interface RecordActionsInput {\n record: RecordActionSubject;\n /** The person's rights on the record (its row level), or on the table when that is all there is. */\n rights: WhatYouMayDo;\n host: RecordActionHost;\n}\n\n/** The one link to a record: the table page with the record open, `<origin>/data/<table>?record=<id>`. */\nexport function recordLink(tableId: string, recordId: string, origin: string = DEFAULT_ACTION_ORIGIN): string {\n return `${origin.replace(/\\/+$/, \"\")}/data/${encodeURIComponent(tableId)}?record=${encodeURIComponent(recordId)}`;\n}\n\nconst NOOP = () => {};\n\nfunction action(\n base: Omit<ObjectAction, \"run\" | \"disabledReason\">,\n needs: Capability,\n input: RecordActionsInput,\n perform: (() => void | Promise<void>) | undefined,\n): ObjectAction {\n const refused = rightsReason(input.rights, needs);\n if (refused !== null) return { ...base, disabledReason: refused, run: NOOP };\n if (perform === undefined) {\n return { ...base, disabledReason: input.host.unavailableReasons?.[base.id] ?? ACTION_NOT_HERE_REASON, run: NOOP };\n }\n return { ...base, run: perform };\n}\n\nfunction bind(handler: RecordHandler | undefined, record: RecordActionSubject) {\n return handler ? () => handler(record) : undefined;\n}\n\n/**\n * THE RECORD'S ACTIONS, in the one order. Same ids, same order, same verbs for every seat and every\n * host — only `disabledReason` varies.\n */\nexport function recordActions(input: RecordActionsInput): ObjectAction[] {\n const { record, host } = input;\n const origin = (host.origin ?? DEFAULT_ACTION_ORIGIN).replace(/\\/+$/, \"\");\n const url = host.href ? (/^https?:/.test(host.href) ? host.href : `${origin}${host.href}`) : recordLink(record.tableId, record.id, host.origin);\n const openInNewTab = host.openInNewTab;\n const copyText = host.copyText;\n const built: ObjectAction[] = [\n action({ id: \"open\", label: \"Open\", icon: \"folder-open\", group: \"open\", verb: \"open\" }, \"read\", input, bind(host.open, record)),\n action(\n { id: \"open-new-tab\", label: \"Open in new tab\", icon: \"external-link\", group: \"open\", verb: \"open-new-tab\" },\n \"read\",\n input,\n openInNewTab ? () => openInNewTab(url, record) : undefined,\n ),\n action(\n { id: \"copy-link\", label: \"Copy link\", icon: \"link\", group: \"open\", verb: \"copy-link\" },\n \"read\",\n input,\n copyText ? () => copyText(url, record) : undefined,\n ),\n action({ id: \"duplicate\", label: \"Duplicate\", icon: \"copy\", group: \"organize\", verb: \"duplicate\" }, \"organise\", input, bind(host.duplicate, record)),\n action(\n { id: \"merge\", label: \"Merge with…\", icon: \"git-merge\", group: \"organize\" },\n \"organise\",\n input,\n bind(host.merge, record),\n ),\n action({ id: \"split\", label: \"Split…\", icon: \"split\", group: \"organize\" }, \"organise\", input, bind(host.split, record)),\n action(\n { id: \"extract-parent\", label: \"Extract parent…\", icon: \"arrow-up-from-line\", group: \"organize\" },\n \"organise\",\n input,\n bind(host.extractParent, record),\n ),\n // Moving a record under another changes who it inherits access from — Full (admin) on the record, the store's level for record_reparent.\n action({ id: \"move-under\", label: \"Move under…\", icon: \"corner-down-right\", group: \"organize\" }, \"structure\", input, bind(host.moveUnder, record)),\n // Moving a record changes what table it is — Full (admin) on the record, the store's own level for the verb.\n action({ id: \"move-to-table\", label: \"Move to another table…\", icon: \"folder-input\", group: \"organize\" }, \"structure\", input, bind(host.moveToTable, record)),\n // A link is an edge beside the record, never a change to it: reading the record is enough.\n action({ id: \"link-record\", label: \"Link a record…\", icon: \"link-2\", group: \"organize\" }, \"read\", input, bind(host.link, record)),\n // Printing is reading, never a change: whoever can read the record can print it through a layout.\n action({ id: \"print-layout\", label: \"Print with layout…\", icon: \"file-text\", group: \"organize\" }, \"read\", input, bind(host.printLayout, record)),\n action({ id: \"history\", label: \"History\", icon: \"history\", group: \"manage\", verb: \"history\" }, \"read\", input, bind(host.history, record)),\n action(\n { id: \"archive\", label: \"Archive record\", icon: \"archive\", group: \"danger\", destructive: true, verb: \"archive\" },\n \"remove\",\n input,\n bind(host.archive, record),\n ),\n ];\n return withExtensions(built, host.extend ? host.extend(record, input.rights) : []);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/dataSource.ts","../src/personZone.ts","../src/rights.ts","../src/tableRights.ts","../src/names.ts","../src/whoChanged.ts","../src/withheldNotice.ts","../src/choiceLooks.ts","../src/docs.ts","../src/fieldTypes.ts","../src/parity.ts","../src/tablePickerEntries.ts","../src/presentation.ts","../src/pages.ts","../src/interfaces.ts","../src/tableLanes.ts","../src/bodyField.ts","../src/viewKeys.ts","../src/viewLook.ts","../src/views.ts","../src/viewAddressParams.ts","../src/calendarFeed.ts","../src/enumLabels.ts","../src/standardFieldChoices.ts","../src/plainWords.ts","../src/codeDependsRefusal.ts","../src/announceTableArchived.ts","../src/skeletonLayout.ts","../src/gridAgentContext.ts","../src/objectActions.ts","../src/recordActions.ts"],"names":["globalSlot","setColorRuleTimeZone","setDisplayTimeZone","setReadersTimeZone","atLeast","humanizeIdentifier","isUuidShape","formatRelativeTime","DECLARABLE_FIELD_KINDS","NEWER_FIELD_KINDS","KERNEL_TABLES","PARITY_FIELD_TYPES","fieldKindFor","isButtonField","newerKindOf","momentZoneOptions","parseTableStyle","tableStyleIsEmpty","raw","base","PLATFORM_TABLE_PREFIX","state","toDelimited","formatTapShortcut"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,SAAS,YAAY,MAAA,EAA+C;AACzE,EAAA,OAAO,MAAA,GAAS,EAAE,KAAA,EAAO,MAAA,EAAQ,SAAS,MAAA,EAAO,GAAI,EAAE,KAAA,EAAO,MAAA,EAAO;AACvE;AA4CA,IAAM,cAAcA,qBAAA,CAAW,kCAAA,EAAoC,sBAAM,IAAI,SAAiD,CAAA;AAEvH,SAAS,iBAAA,CAAkB,MAAA,EAAgB,cAAA,GAAiB,QAAA,EAA6B;AAC9F,EAAA,IAAI,QAAA,GAAW,WAAA,CAAY,GAAA,CAAI,MAAM,CAAA;AACrC,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,QAAA,uBAAe,GAAA,EAAI;AACnB,IAAA,WAAA,CAAY,GAAA,CAAI,QAAQ,QAAQ,CAAA;AAAA,EAClC;AACA,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,GAAA,CAAI,cAAc,CAAA;AACxC,EAAA,IAAI,MAAM,OAAO,IAAA;AACjB,EAAA,MAAM,IAAA,GAAO,qBAAA,CA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AAI,aAAA,EAAe,KAAA,EAAO,uBAAkB,IAAA,EAAM,QAAA,EAAU,KAAA,EAAO,UAAA,IAAc,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,IAAA,EAAM,MAAM,CAAC,CAAA;AAAA;AAAA,IAEhI,OAAO,EAAE,EAAA,EAAI,cAAA,EAAgB,KAAA,EAAO,2BAAsB,IAAA,EAAM,WAAA,EAAa,KAAA,EAAO,UAAA,IAAc,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,WAAA,EAAa,MAAM,CAAC,CAAA;AAAA,IAC/I,OAAO,EAAE,EAAA,EAAI,WAAW,KAAA,EAAO,SAAA,EAAW,MAAM,SAAA,EAAW,KAAA,EAAO,UAAU,IAAA,EAAM,SAAA,IAAa,MAAA,EAAQ,KAAA,EAAO,KAAK,IAAA,CAAK,OAAA,EAAS,MAAM,CAAC,CAAA;AAAA,IACxI,MAAA;AAAA,MACE,EAAE,EAAA,EAAI,SAAA,EAAW,KAAA,EAAO,gBAAA,EAAkB,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,QAAA,EAAU,WAAA,EAAa,IAAA,EAAM,IAAA,EAAM,SAAA,EAAU;AAAA,MAC/G,QAAA;AAAA,MACA,KAAA;AAAA,MACA,IAAA,CAAK,IAAA,CAAK,OAAA,EAAS,MAAM;AAAA;AAC3B,GACF;AACA,EAAA,OAAO,cAAA,CAAe,KAAA,EAAO,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,KAAA,CAAM,MAAM,CAAA,GAAI,EAAE,CAAA;AACnF","file":"helpers.cjs","sourcesContent":["// src/dataSource.ts — @ai-matrx/records-ui (pure; also served alone by `@ai-matrx/records-ui/helpers`)\n//\n// The two helpers every host calls before it draws anything: who is acting (`personActor`) and the\n// store's data seam over a supabase-js client (`recordsDataSource`). No React and no screen here, so\n// a service, a registry or a server module that needs only these never pulls the package's screens.\n// `RecordsMount` re-exports both, so the root entry keeps them.\n\nimport type { RecordsActor, RecordsDataSource, Uuid } from \"@ai-matrx/records\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\nexport function personActor(userId: Uuid | null | undefined): RecordsActor {\n return userId ? { actor: \"user\", user_id: userId } : { actor: \"user\" };\n}\n\n/**\n * A supabase-js client AS this package's data seam.\n *\n * `RecordsDataSource` is deliberately a small structural subset of\n * `SupabaseClient` — the package holds no key and opens no connection, the host\n * hands it a client that already carries the person's session.\n *\n * IT IS NOT AN IDENTITY CAST, and it cost a live screen to learn why\n * (2026-09-19, /data's first load): the port's `rpc(fn, args, { schema })`\n * says the schema OUT LOUD, because every door of this store is `custom.<name>`\n * and every door of the trust layer is `iam.<name>`. supabase-js's own\n * `rpc(fn, args, options)` has no `schema` option at all — its third argument is\n * `{ head, get, count }` — so a client passed straight through silently asked\n * its default PostgREST profile and the store answered, correctly and uselessly,\n * \"Could not find the function public.table_kernel_id ... PGRST202\". The schema\n * is chosen the one way supabase-js offers: `client.schema(name).rpc(...)`.\n *\n * `schema(name).from(table)` already agrees structurally and is passed through.\n *\n * `fallbackSchema` is the profile a call that says NOTHING is sent to. No caller\n * in `@ai-matrx/records` omits the option — `callDoor` always says `custom` and\n * `trustDoor` always says `iam` — so it never fires today; it exists so that a\n * call which one day forgets lands on the store rather than silently on\n * `public`. It is a FALLBACK and not the answer: a version of this adapter that\n * sent EVERY door to one fixed schema would route the `iam` trust doors (the\n * external principal, the publish binding) into `custom` and get a PGRST202\n * naming the wrong schema.\n *\n * The cast itself stays HERE, once, where it is explained: a generated\n * `Database` type makes `schema().from().select()` enormous, and a host app that\n * passes its client straight into `config` gets `TS2589: Type instantiation is\n * excessively deep and possibly infinite` in its own build (matrx-frontend,\n * 2026-09-18, on all three campaign routes at once).\n */\n/*\n * ONE DATA SOURCE PER SUPABASE CLIENT (owner, 2026-10-02). The record store's data layer keys its\n * cache by the data source object, so a host that builds this adapter again on every mount (a\n * board tile woken or brought back by Undo) must get the SAME object back for the same client —\n * otherwise every remount is a stranger to the answers the last mount read.\n */\n// One cache per realm, never per bundle copy: this module ships in BOTH the root entry and\n// `@ai-matrx/records-ui/helpers` (`splitting: false`), and a module `let` would split it in two.\nconst dataSources = globalSlot(\"ai-matrx.records-ui.data-sources\", () => new WeakMap<object, Map<string, RecordsDataSource>>());\n\nexport function recordsDataSource(client: object, fallbackSchema = \"custom\"): RecordsDataSource {\n let bySchema = dataSources.get(client);\n if (!bySchema) {\n bySchema = new Map();\n dataSources.set(client, bySchema);\n }\n const held = bySchema.get(fallbackSchema);\n if (held) return held;\n const made = makeRecordsDataSource(client, fallbackSchema);\n bySchema.set(fallbackSchema, made);\n return made;\n}\n\nfunction makeRecordsDataSource(client: object, fallbackSchema: string): RecordsDataSource {\n const supabase = client as unknown as {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n schema: (name: string) => {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n from: (table: string) => unknown;\n };\n auth?: { getSession?: () => Promise<{ data?: { session?: unknown } | null }> };\n };\n return {\n // PAGE-BUNDLE: the real adapter opens a table page with one `custom.table_page_bundle` call.\n opensInOneCall: true,\n async rpc(fn, args, options) {\n const schema = options?.schema ?? fallbackSchema;\n // 🚨 NO STORE DOOR LEAVES WITHOUT A PERSON (lane MONITOR-TRIAGE, 2026-10-01). `anon` holds\n // no USAGE on schema `custom`, so a door called with no session can only come back\n // \"42501 permission denied for schema custom\" (HTTP 401) — seven of them per signed-out\n // /data load (inbox, counts, home, portals…), every one a red row in ops.system_error.\n // A `custom` door with no session is answered HERE, with the store's own signed-out\n // sentence and no network call. Other schemas (`iam`, `platform`) serve guests by design\n // and are never short-circuited. A client without `auth` (a server or test seam) is\n // passed straight through.\n const getSession = schema === \"custom\" ? sessionReader(supabase) : undefined;\n if (getSession && !(await hasSession(getSession))) {\n return { data: null, error: SIGNED_OUT } as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n }\n const on = supabase.schema(schema);\n return (await on.rpc(fn, args)) as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n },\n schema(name) {\n return supabase.schema(name) as ReturnType<RecordsDataSource[\"schema\"]>;\n },\n };\n}\n\n/**\n * THE CLIENT'S OWN SESSION READER, or none. A TOKEN-ONLY client (supabase-js `createClient(url,\n * key, { accessToken })`: Matrx 2's window, any host whose session lives elsewhere) carries the\n * person on EVERY request and has no auth of its own: supabase-js answers any read of `client.auth`\n * on it by THROWING (\"accessing supabase.auth.getSession is not possible\"). Read bare, that throw\n * left every door of the store before a single request was sent and each one was shown as \"We\n * could not reach your data\" (Matrx 2 Data › Tables, 2026-10-21). Such a client is passed through\n * and the database's answer stands, as for a client without `auth`.\n */\nfunction sessionReader(supabase: { auth?: { getSession?: () => Promise<{ data?: { session?: unknown } | null }> } }): (() => Promise<{ data?: { session?: unknown } | null }>) | undefined {\n try {\n const auth = supabase.auth;\n const getSession = auth?.getSession;\n return typeof getSession === \"function\" ? () => getSession.call(auth) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The read door's own sentence for a call with nobody signed in (`custom.read_records_page`, DOOR-1). */\nconst SIGNED_OUT = {\n code: \"42501\",\n message: \"Nobody is signed in, so there is nothing to read.\",\n hint: \"Sign in, then try again.\",\n details: null,\n} as const;\n\nasync function hasSession(getSession: () => Promise<{ data?: { session?: unknown } | null }>): Promise<boolean> {\n try {\n const answer = await getSession();\n return Boolean(answer?.data?.session);\n } catch {\n // Auth could not say: let the request go and the database's answer stand.\n return true;\n }\n}\n","// The person's time zone, as the app saved it (userPreferences.display.timeZone).\n//\n// The host app tells this package once (`setPersonTimeZone(\"America/Los_Angeles\")`); every \"today\" and\n// \"now\" a screen draws (the calendar's today marker and now-line, a timeline's today, a date picker's\n// today) is read in that zone instead of the device's. With nothing set the device zone applies, as before.\n// Nothing here stores a zone: the host's saved preference is the one place, this is its mirror.\n\nimport { setColorRuleTimeZone, setDisplayTimeZone } from \"@ai-matrx/design-system/data-table/table-style\";\nimport { setReadersTimeZone } from \"@ai-matrx/records\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\n// No React here: `@ai-matrx/records-ui/helpers` serves this file alone (the host sets the zone at\n// boot), and the root entry carries its own copy — so the zone lives in ONE realm-wide slot that\n// both copies read, never a module `let` that would split in two. The hook is `./personTime`.\nconst state = globalSlot(\"ai-matrx.records-ui.person-time-zone\", () => ({\n zone: null as string | null,\n listeners: new Set<() => void>(),\n}));\n\nfunction valid(z: unknown): z is string {\n if (typeof z !== \"string\" || !z.trim()) return false;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: z });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The host app's saved zone (IANA). `null` / junk clears it: the device zone applies. */\nexport function setPersonTimeZone(next: string | null | undefined): void {\n const clean = valid(next) ? next : null;\n if (clean === state.zone) return;\n state.zone = clean;\n // \"Today\" in a color rule is the person's day, not the device's (lane NOTION-SMALL-2).\n setColorRuleTimeZone(clean);\n // And every moment a screen prints (grid cell, panel, card, export) reads in it too: ONE zone, one slot.\n setDisplayTimeZone(clean);\n // And a relative day (\"Today\", \"Overdue\") a view asks the store is cut in it before it is sent (ADVERSARIAL-11 F3).\n setReadersTimeZone(clean);\n state.listeners.forEach((l) => l());\n}\n\nexport function getPersonTimeZone(): string | null {\n return state.zone;\n}\n\n/** Calls `listener` whenever the zone changes; returns the unsubscribe. */\nexport function subscribePersonTimeZone(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => {\n state.listeners.delete(listener);\n };\n}\n\n/**\n * `at` as a Date whose LOCAL fields (getFullYear, getHours, ...) read the wall clock in the person's zone.\n * For day / hour math only: never compare it with a stored instant.\n */\nexport function personWallNow(at: Date = new Date()): Date {\n const zone = state.zone;\n if (!zone) return at;\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(at);\n const n = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n return new Date(n(\"year\"), n(\"month\") - 1, n(\"day\"), n(\"hour\"), n(\"minute\"), n(\"second\"));\n}\n\n/**\n * The inverse of `personWallNow`: the INSTANT at which the person's wall clock reads the local fields\n * of `wall` (getFullYear, getHours, ...). A calendar drop at \"9:30 on Nov 3\" writes this, so the card\n * reads 9:30 on Nov 3 again in the person's zone. With no zone set it is `wall` itself (device zone).\n */\nexport function instantFromPersonWall(wall: Date): Date {\n const zone = state.zone;\n if (!zone) return wall;\n const target = Date.UTC(wall.getFullYear(), wall.getMonth(), wall.getDate(), wall.getHours(), wall.getMinutes(), wall.getSeconds(), wall.getMilliseconds());\n let guess = target;\n for (let i = 0; i < 3; i += 1) {\n const seen = personWallNow(new Date(guess));\n const shown = Date.UTC(seen.getFullYear(), seen.getMonth(), seen.getDate(), seen.getHours(), seen.getMinutes(), seen.getSeconds(), wall.getMilliseconds());\n guess -= shown - target;\n }\n return new Date(guess);\n}\n","// src/rights.ts — @ai-matrx/records-ui\n//\n// THE ONE PLACE A LEVEL BECOMES A SCREEN.\n//\n// WHAT A PERSON HIT (independent verdict, sixth pass, 19-20 September). A\n// colleague who had been shared a table at viewer opened it, double-clicked a\n// cell, got a live editor, typed a value and pressed Enter — and only THEN was\n// told she may not write. \"The permission is right; the screen told her she\n// could.\" Measured against Airtable, Notion and Linear the verdict called it\n// out by name: \"None of these three products lets you start an action it\n// already knows it will reject.\"\n//\n// WHY THE SCREEN COULD NOT KNOW. The rights question was a PORT with two honest\n// answers and no third: `NO_RIGHTS` (every administering control absent, which\n// is useless for a host whose authority IS the store's) and\n// `storeDecidesRights` — `{admin: true, comment: true, write: true}` for every\n// non-kernel table, for everybody. That second one is the defect, written down:\n// it is the screen ASSUMING the answer and letting the door say no afterwards.\n//\n// WHAT REPLACES IT. The store already answers this, and the client now carries\n// it: `custom.read_records` returns the reader's level on the TABLE on every\n// row (so `Table.your_level` costs nothing), and `custom.my_levels` — the door\n// this lane added — answers the caller's level on any subject they name, one\n// call for a whole page. This file is the only place in the package that turns\n// one of those four words into what a screen may DRAW.\n//\n// THE LADDER IS THE STORE'S, NOT OURS: viewer < commenter < editor < admin, and\n// which rung each door requires is read from the doors themselves —\n// `custom.record_update` asserts `editor` on the record, `custom.field_declare`\n// asserts `admin` on the TABLE (\"the SHAPE of this table, which is an admin's\n// right and not an editor's\"), `custom.io_comment_write` admits a commenter.\n// Nothing here invents a rule; it mirrors the four assertions those doors make\n// and is wrong the moment they change, which is what the suite is for.\n//\n// ABSENT OR HONEST, NEVER DEAD. Every `false` here carries the sentence that\n// says why and what to do about it, so a control can be left out AND explained.\n// A screen that hid a control with nothing to say is the silent half of the\n// same defect.\n\nimport { atLeast, type PermissionLevel } from \"@ai-matrx/records/field-kinds\";\nimport type { Table } from \"@ai-matrx/records\";\n\n/** The six things a person does to a record or a table, as the screens offer them. */\nexport type Capability = \"read\" | \"comment\" | \"write\" | \"organise\" | \"remove\" | \"share\" | \"structure\";\n\nexport interface WhatYouMayDo {\n /** The word the store answered, or null when it answered nothing. */\n level: PermissionLevel | null;\n /**\n * Whether the store has ANSWERED yet. `false` is a third state and not a\n * refusal: a screen that drew \"you may not\" while the answer was in flight\n * would blink every control off on every reload, which is its own lie.\n */\n known: boolean;\n read: boolean;\n comment: boolean;\n write: boolean;\n /** Duplicate, merge, restore, make a layout the default: the doors that ask `editor`, above content. */\n organise: boolean;\n remove: boolean;\n share: boolean;\n structure: boolean;\n /** Why this person may not do that, in one sentence naming the way in. */\n why: (what: Capability) => string;\n}\n\n/** What each rung of the ladder is called where a person reads it. */\nexport const LEVEL_WORD: Record<PermissionLevel, string> = {\n viewer: \"View access\",\n commenter: \"Comment access\",\n edit_content: \"Edit access\",\n editor: \"Edit access\",\n admin: \"Full access\",\n};\n\n/**\n * WHICH RUNG EACH DOOR ASKS FOR. Read off the doors themselves, in one place,\n * so a screen never re-decides it and the suite has one thing to check.\n */\nconst NEEDS: Record<Capability, PermissionLevel> = {\n read: \"viewer\",\n // custom.io_comment_write\n comment: \"commenter\",\n // custom.record_update / custom.record_write — `edit_content` changes rows and page content;\n // columns, views and settings (structure) stay with admin below, and sharing with admin.\n write: \"edit_content\",\n // custom.view_designate / view_declare / migrate_merge / record_restore — all ask `editor`: more than\n // changing content (`edit_content`), less than changing columns (`admin`).\n organise: \"editor\",\n // custom.record_delete\n remove: \"editor\",\n // custom.share_grant — ONE-LADDER (2026-10-10): Edit may pass View / Comment / Edit on inside the\n // organization (iam.may_grant_as, knobs access.sharing/*). Which levels, and to whom, is the share\n // dialog's own question (iam.my_grantable_levels); the Share button only has to open for Edit.\n share: \"editor\",\n // custom.field_declare / field_update / field_retire / table settings\n structure: \"admin\",\n};\n\n/** The rung a capability asks for — so a short \"Needs Full access\" never re-decides the ladder. */\nexport function levelNeededFor(what: Capability): PermissionLevel {\n return NEEDS[what];\n}\n\nconst NOT_YET =\n \"Checking what you may do here. Nothing is offered until then.\";\n\nconst NOTHING_AT_ALL =\n \"You have not been given this. Ask somebody with Full access on it to share it with you.\";\n\n/** The sentence for one refusal: what the level is, what it would have to be. */\nfunction sentenceFor(what: Capability, level: PermissionLevel | null): string {\n if (level === null) return NOTHING_AT_ALL;\n const need = LEVEL_WORD[NEEDS[what]];\n const have = LEVEL_WORD[level];\n const doing: Record<Capability, string> = {\n read: \"open this\",\n comment: \"leave a comment\",\n write: \"change anything here\",\n organise: \"organize this\",\n remove: \"delete this\",\n share: \"pass this on to somebody else\",\n structure: \"change the columns of this table\",\n };\n return `You have ${have} here, and it takes ${need} to ${doing[what]}. Ask somebody with Full access on it to move you up.`;\n}\n\n/**\n * WHAT ONE LEVEL LETS A PERSON DO. `level` null and `known` true means the\n * store said \"nothing\" — a real answer. `known` false means it has not said.\n */\nexport function whatYouMayDo(level: PermissionLevel | null, known = true): WhatYouMayDo {\n const may = (what: Capability) => known && atLeast(level, NEEDS[what]);\n return {\n level: known ? level : null,\n known,\n read: may(\"read\"),\n comment: may(\"comment\"),\n write: may(\"write\"),\n organise: may(\"organise\"),\n remove: may(\"remove\"),\n share: may(\"share\"),\n structure: may(\"structure\"),\n why: (what) => (known ? sentenceFor(what, level) : NOT_YET),\n };\n}\n\n/** Nothing offered, because nothing is known yet. */\nexport const NOT_ANSWERED_YET: WhatYouMayDo = whatYouMayDo(null, false);\n\n/**\n * REC-27. The nine Tables the platform ships are not administered from a\n * person's screen whatever level they hold on them — so the structure controls\n * are absent for a kernel Table and say why, and everything else follows the\n * level as usual.\n */\nexport const KERNEL_REASON =\n \"This is one of the tables the platform ships, so its columns are not changed from a screen. \" +\n \"Make your own table to change columns.\";\n\nexport function whatYouMayDoWithTable(\n table: Table | null | undefined,\n level: PermissionLevel | null,\n known: boolean,\n): WhatYouMayDo {\n const base = whatYouMayDo(level, known);\n // A LOCKED DATABASE (lane NOTION-SMALL-2): the columns and the table's settings stay as they are until\n // somebody unlocks it. An editing convenience, never a permission — the lock changes what is OFFERED, the\n // store's ladder is untouched and anyone who may edit the table may unlock it.\n if (!table?.is_kernel) return table && tableIsLocked(table) ? lockedStructure(base) : base;\n return {\n ...base,\n structure: false,\n why: (what) => (what === \"structure\" ? KERNEL_REASON : base.why(what)),\n };\n}\n\n/** Is this table locked against column and settings changes? Kept on the table's own metadata. */\nexport function tableIsLocked(table: Pick<Table, \"metadata\"> | null | undefined): boolean {\n return table?.metadata?.[\"locked\"] === true;\n}\n\nexport const DATABASE_LOCKED_REASON = \"This database is locked, so its columns and settings are read-only. Unlock it to change them.\";\n\nfunction lockedStructure(base: WhatYouMayDo): WhatYouMayDo {\n return { ...base, structure: false, why: (what) => (what === \"structure\" ? DATABASE_LOCKED_REASON : base.why(what)) };\n}\n","// src/tableRights.ts — @ai-matrx/records-ui (pure; also served by `@ai-matrx/records-ui/helpers`)\n//\n// What a person may do to one table, as the screens read it. `./host.tsx` (the React context the\n// screens ask) re-exports everything here; a host that builds rights by hand (`tableRightsAt`) at\n// boot reads this file alone and never pulls a screen.\n\nimport type { PermissionLevel } from \"@ai-matrx/records\";\nimport { NOT_ANSWERED_YET, whatYouMayDo, type WhatYouMayDo } from \"./rights\";\n\n/**\n * What a person may do to one table. The four words and the ladder are the\n * store's (`rights.ts`), not ours.\n *\n * `admin`, `comment` and `write` are kept with the names they have always had,\n * because every screen in this package and in the host apps reads them; they\n * are now the store's ANSWER rather than a host's guess.\n */\nexport interface TableRights extends WhatYouMayDo {\n /** SCR-2: holders of `admin` on the table see the \"+\" and the settings panel. */\n admin: boolean;\n /**\n * Why this answer, in one sentence. Kept for callers that show a single\n * reason; `why(what)` is the per-control sentence and is what the screens use.\n */\n reason: string;\n}\n\n/** Internal: the rights record for an answer (`host.tsx` folds the store's answers through it). */\nexport function tableRights(may: WhatYouMayDo, overallReason?: string): TableRights {\n return {\n ...may,\n admin: may.structure,\n reason: overallReason ?? (may.structure ? \"\" : may.why(\"structure\")),\n };\n}\n\n/**\n * Kept so a host that imported it still compiles. It is no longer any screen's\n * default: the store answers this question now, and a package that said \"I\n * assume nothing\" while holding the answer would be hiding controls from the\n * people who hold them.\n */\nexport const NO_RIGHTS: TableRights = tableRights(NOT_ANSWERED_YET);\n\n/**\n * THE ONE WAY TO BUILD A `TableRights` BY HAND — for a host with its own\n * authority, and for a suite that wants to mount one seat's screen. It takes\n * the LEVEL, never six booleans, so nobody can hand a screen a combination the\n * ladder cannot produce (write without read, share without edit).\n */\nexport function tableRightsAt(level: PermissionLevel | null): TableRights {\n return tableRights(whatYouMayDo(level, true));\n}\n","// src/names.ts — @ai-matrx/records-ui\n//\n// WHAT A PERSON READS, NEVER WHAT THE MACHINE STORES.\n//\n// Measured on the real screens (independent verdict, 19 September): a table row\n// read `Saved views · 9 fields · records_ui_view`, a relation cell read a bare\n// `8f2c…` identifier, a header read `stage` because the Field's label was\n// blank, and the type word on a column tooltip read `long_text`. Airtable,\n// Notion and Linear never show a person an internal name; the verdict called\n// this one of the three things a first-time user feels within a minute.\n//\n// So every place this package prints something a person reads goes through one\n// of these three functions. They are deliberately dumb: they choose the best\n// human string that IS AVAILABLE and, when none is, say what the thing is\n// rather than printing the token. No screen in this package formats a name of\n// its own any more.\n\nimport type { Field, ReadRow, RecordDocument, Table } from \"@ai-matrx/records\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\n\n/** The name of one Field, as a header, a form label or a peek's term. */\nexport function fieldName(field: Field): string {\n const label = (field.label ?? \"\").trim();\n // A LABEL THAT IS ONLY A MACHINE KEY is not a name (merged-grid review 2026-09-26): a table made\n // by an import or an agent kept `label: \"job_no\"`, and the header read `job_no`. A key joined by\n // underscores is written the way a person writes it (\"Job no\"). A single lowercase word the\n // owner typed (\"mobile\", \"title\") is their own words and is shown as they wrote it.\n if (label !== \"\" && label === field.key && /^[a-z0-9]+(?:[_.-][a-z0-9]+)+$/.test(label)) return humanizeIdentifier(label);\n if (label !== \"\") return label;\n const name = (field.name ?? \"\").trim();\n if (name !== \"\") return name;\n return humanizeIdentifier(field.key);\n}\n\n/** The name of one Table, as a card, a heading or a breadcrumb. */\nexport function tableName(table: Table): string {\n const name = (table.name ?? \"\").trim();\n if (name !== \"\") return name;\n const singular = (table.label_singular ?? \"\").trim();\n if (singular !== \"\") return singular;\n return humanizeIdentifier(table.slug ?? \"\");\n}\n\n/**\n * The name of one RECORD, for a chip, a card, a relation cell or a peek title.\n *\n * `titleKey` is the Table's own `title_field` when the caller knows the Table —\n * that is the store's answer to \"what makes this record a chip\" (REC-2) — and\n * the conventional keys are tried after it. A record with nothing readable is\n * NOT shown as a truncated uuid: it says it has no name yet, because \"8f2c1b0a\"\n * tells a person nothing and looks like a bug.\n */\nexport function recordName(\n document: RecordDocument | undefined,\n titleKey?: string | null,\n fallback = \"Untitled\",\n): string {\n const data = (document ?? {}) as Record<string, unknown>;\n const keys = [titleKey, \"title\", \"name\", \"label\", \"full_name\", \"subject\", \"summary\"].filter(\n (key): key is string => typeof key === \"string\" && key !== \"\",\n );\n for (const key of keys) {\n const value = data[key];\n // AN ID IS NEVER A NAME, AND THIS FUNCTION USED TO RETURN ONE (TAILS-2, 2026-09-21).\n // A Table's title column may be a RELATION, and a relation's stored value IS the other\n // record's id (FLD-6 / REL-1) — so `recordName` handed every caller a bare uuid for\n // every Table titled that way, which is how the board's unplaced list came to read\n // \"11 records are not in any of these columns — ca5f1ac7-…\". A caller that can resolve\n // the id resolves it (`scalarText` with the label lookup); a caller that cannot is\n // better off reading the next column, and then the fallback, than a hex number.\n if (typeof value === \"string\" && value.trim() !== \"\" && !looksLikeId(value.trim())) {\n return value.trim();\n }\n if (typeof value === \"number\") return String(value);\n }\n return fallback;\n}\n\n\n/**\n * Is this string the store's id for something, rather than words a person wrote?\n *\n * The same question `custom._card_words` asks on the database, with the same regex, so the\n * screen and the store agree about what is a name (TAILS-2, 2026-09-21).\n */\nexport function looksLikeId(value: unknown): boolean {\n return typeof value === \"string\" && isUuidShape(value.trim());\n}\n\n/** The same question for a row the read door returned. */\nexport function rowName(row: ReadRow | undefined, titleKey?: string | null, fallback = \"Untitled\"): string {\n return recordName(row?.document, titleKey, fallback);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// NAMING A RECORD WHOSE TABLE YOU ALREADY HOLD — ONE CALL, NOT A COPY PER SCREEN.\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// 🚨 WHY THESE TWO EXIST (lane RELATION-DISPLAY-2, 2026-09-21).\n//\n// `check:one-reference-builder` shipped with a baseline of SIX, and its own header said the\n// number was not zero because \"moving six surfaces onto the store door is real work\". Three\n// of the six were not asking the store's question at all. `Grid.tsx` names the row a person\n// is looking at for the Talk action; `Peek.tsx` names the record being peeked at;\n// `PortalsPanel.tsx` names the rows of the portal's own client Table; and this repo's\n// `TryEverythingScreen.tsx` does the same in two places. NONE of them is resolving a\n// RELATION — they hold the Table and they hold the document, and there is nothing to ask a\n// door about. What they were each doing by hand was the two-line join between them:\n//\n// recordName(row.document, table.title_field)\n//\n// Written out five times in four files, which is how a Table whose title column is `cname`\n// came to read \"Untitled\" on one screen and correctly on the next. It is the same question\n// as the store's, one rung down the ladder, and the same one answer should serve it — so it\n// lives HERE, in the file the guard exempts BY CONSTRUCTION as the primitive itself, and\n// every screen calls it instead of re-deriving it.\n//\n// WHAT THESE ARE NOT. They are not a second resolver and must never become one. They take a\n// Table a caller ALREADY HAS and a document it ALREADY HAS. The moment a caller is holding\n// an ID and wants words, that is the store's question and the answer is\n// `client.relationWords` / `client.relationWordsMany` — which ask the read-access ladder\n// BEFORE they read a name, apply that column's own display spec, and return the withheld\n// sentence for a record the reader may not open. Nothing in here can do any of that, and\n// nothing in here should try.\n\n/** A Table as far as naming is concerned — its own declared title column (REC-2). */\ntype TitledTable = Pick<Table, \"title_field\"> | null | undefined;\n\n/**\n * THE NAME OF A RECORD WHOSE TABLE YOU ALREADY HOLD.\n *\n * `table` is the Table the record belongs to; its `title_field` is the store's answer to\n * \"what makes this record a chip\" (REC-2) and is tried first, then the conventional keys,\n * then the fallback. A Table that has not loaded yet is `null` and the conventional keys\n * still answer — a name arriving a tick late is better than a screen that shows nothing.\n */\nexport function recordNameIn(\n table: TitledTable,\n document: RecordDocument | undefined,\n fallback = \"Untitled\",\n): string {\n return recordName(document, table?.title_field ?? null, fallback);\n}\n\n/**\n * THE NAME A CHANGE NOTICE USES — the record as it is AFTER the change (merged-grid tails,\n * 2026-09-26). Typing a first name into a row's label column read \"Changed Title on Untitled\":\n * the notice named the row from the document held before the write. The row is called what it is\n * called now; only when the change emptied its name does the notice use the name it had.\n */\nexport function changedRecordName(\n table: TitledTable,\n document: RecordDocument | undefined,\n key: string,\n after: unknown,\n): string {\n const now = recordName({ ...((document ?? {}) as Record<string, unknown>), [key]: after } as RecordDocument, table?.title_field ?? null, \"\");\n return now !== \"\" ? now : recordNameIn(table, document);\n}\n\n/** The same, for a row the read door returned. */\nexport function rowNameIn(table: TitledTable, row: ReadRow | undefined, fallback = \"Untitled\"): string {\n return recordName(row?.document, table?.title_field ?? null, fallback);\n}\n\n/**\n * WHAT A RELATION CHIP SAYS WHEN THE RECORD IT POINTS AT IS NOT YOURS.\n *\n * A relation joins two records in two tables, and holding one end says nothing\n * about the other: a Job shared with you may point at a Client nobody shared.\n * The chip then has three possible answers and only one of them is honest —\n * the target's TITLE is a leak, a bare id is a bug with a hex number in it, and\n * a permanent \"Loading…\" is a lie that never resolves.\n *\n * This is the SAME sentence `platform.relation_withheld_label()` answers on the\n * database, word for word, so a person reads one wording whether the screen or\n * the store worked it out. Changing it changes both (RELATION-DECLARE,\n * 2026-09-20).\n */\nexport const WITHHELD_RECORD_LABEL = \"A record you have not been given access to\";\n/**\n * WHEN THE STORE COULD NOT BE ASKED (a 503, a dropped connection) the name is UNREAD, not\n * withheld: saying \"not given access\" for a failed read lies about the data (W1.1 verifier,\n * 2026-10-02). This is what a reference reads until a later read answers.\n */\nexport const UNREAD_RECORD_LABEL = \"Couldn't load this name\";\n\n/**\n * THE PLURAL A PERSON READS, NEVER A MACHINE'S \"…ss\" (VERIFIER-16 M3 / VERIFIER-17 M3).\n *\n * A table the store or the mover never gave a real plural carries `name + \"s\"` — so a table\n * already named in the plural reads \"Customerss\", \"Status optionss\". That word was made by a\n * machine appending one letter, and it says nothing the name does not; it is never shown.\n * Returns the table's own plural when a person (or the example library) wrote one, and `null`\n * when the only plural on record is that appended letter.\n */\nexport function realPlural(table: { name?: string | null; label_singular?: string | null; label_plural?: string | null }): string | null {\n const plural = (table.label_plural ?? \"\").trim();\n if (plural === \"\") return null;\n for (const base of [table.name, table.label_singular]) {\n const b = (base ?? \"\").trim();\n if (b !== \"\" && plural === `${b}s`) return null;\n }\n return plural;\n}\n\n/**\n * ONE RECORD'S NOUN, IN A SENTENCE (\"Book a 30-minute visit\") — lane HANDOVER, 2026-09-28.\n *\n * Cedar Ridge Physical Therapy's booking page was titled \"Book a 30-minute Visits appointment\":\n * the table's NAME (a plural, a heading) was put where one record's noun goes. The noun is the\n * table's own singular (\"Visit\"), else its name, else the fallback; a Title-case word is written\n * the way a sentence writes it (\"visit\"), an acronym is kept (\"MRI scan\").\n */\nexport function singularNoun(\n table: { name?: string | null; label_singular?: string | null } | null | undefined,\n fallback = \"record\",\n): string {\n const word = (table?.label_singular ?? \"\").trim() || (table?.name ?? \"\").trim() || fallback;\n return word\n .split(/\\s+/)\n .map((w) => (/^[A-Z][a-z'’-]*$/.test(w) ? w.toLowerCase() : w))\n .join(\" \");\n}\n\n/**\n * A plural for a sentence (\"Check in ran on 2 appointments\"): the table's real plural, else the\n * singular with an \"s\" only when that does not double a final \"s\".\n */\nexport function pluralNoun(table: { name?: string | null; label_singular?: string | null; label_plural?: string | null } | null | undefined, fallback = \"record\"): string {\n const real = table ? realPlural(table) : null;\n if (real) return real;\n const singular = (table?.label_singular ?? \"\").trim() || fallback;\n return /s$/i.test(singular) ? singular : `${singular}s`;\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// WHAT A CARD IS TITLED BY (lane UI-FIX-18, VERIFIER-18 H5).\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// MEASURED 2026-09-24 on production: *ZZZ UI-QUICK-1 Rincon-style Jobs* (title column `title`)\n// grouped by Stage titled every kanban card \"false\" or \"true\". The board took the FIRST Field\n// the read door answered that was not the group column — here the *Urgent* checkbox — as the\n// title. A card is named by what names its record: the Table's own `title_field` first (REC-2),\n// then the conventional name keys, then the first words column in declared order. A yes/no\n// column, the column the board is grouped by and the store's own stamps never title a card.\n\nconst CONVENTIONAL_TITLE_KEYS = [\"title\", \"name\", \"label\", \"full_name\", \"subject\", \"summary\"];\n\nfunction canTitle(field: Field, excluded: ReadonlySet<string>): boolean {\n if (excluded.has(field.key)) return false;\n if (field.type === \"boolean\") return false;\n if (field.type === \"formula\" && (field.config ?? {})[\"system\"]) return false;\n return true;\n}\n\n/**\n * THE FIELD A CARD IS TITLED BY — kanban, calendar, gallery and pipeline alike.\n *\n * Order: the Table's `title_field` → a conventional name key (`title`, `name`, …) → the first\n * text column in declared `sort` order → the first other column that can title (never a\n * checkbox, never the group column, never a system stamp). `undefined` when nothing can, and\n * the card falls back to `rowName`, which says \"Untitled\" rather than \"false\".\n */\nexport function cardTitleField(\n fields: readonly Field[],\n titleKey: string | null | undefined,\n exclude: readonly (string | null | undefined)[] = [],\n): Field | undefined {\n const excluded = new Set(exclude.filter((k): k is string => typeof k === \"string\" && k !== \"\"));\n const ordered = [...fields].sort((a, b) => (a.sort ?? 100) - (b.sort ?? 100) || a.key.localeCompare(b.key));\n const byKey = (key: string) => ordered.find((f) => f.key === key && canTitle(f, excluded));\n if (titleKey) {\n const declared = byKey(titleKey);\n if (declared) return declared;\n }\n for (const key of CONVENTIONAL_TITLE_KEYS) {\n const found = byKey(key);\n if (found) return found;\n }\n return (\n ordered.find((f) => f.type === \"text\" && canTitle(f, excluded)) ?? ordered.find((f) => canTitle(f, excluded))\n );\n}\n","import { formatRelativeTime } from \"@ai-matrx/kit/format\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\n// src/whoChanged.ts — @ai-matrx/records-ui · SCR-17, the cell's half\n//\n// \"WHO?\" IS A QUESTION. A SCREEN IS SUPPOSED TO ANSWER IT.\n//\n// 🚨 WHAT A CLINIC SAW (crew B2, 2026-09-21, ten real patients on the live app):\n//\n// \"Every single cell shows a small 'who?' hover badge next to its value instead\n// of a resolved author name, an agent/rule label, or even 'system' — the\n// attribution feature is visibly wired up (it renders on every cell) but never\n// resolves to anything readable.\"\n//\n// They were right that it never resolved, and the reason was that nothing ever\n// asked. The badge opened a panel; it never looked anything up. Meanwhile the\n// store had the answer the whole time: `custom.field_history` on those exact ten\n// patients answers `kind: user, name: admin` on every one of them, and has since\n// they were written.\n//\n// So the badge asks, on the gesture that already reaches it — a hover or a Tab —\n// for the ONE cell being asked about. Nothing is fetched for a page of two\n// hundred cells nobody points at.\n//\n// THE THREE WORDS, AND NEVER A UUID. VAL-8 fixes the vocabulary at `user`,\n// `agent`, `system` and there is no fourth. An agent ALWAYS names the person it\n// acted for (AGT-N-4: it carries exactly that person's authority, so a screen\n// showing the machine without the person would be hiding who is answerable). The\n// system is \"the system\" — a platform word a person can read, not a null. And a\n// person whose name the door did not carry is resolved through the app's ONE\n// organization-scoped roster (the `members` port, FIX-7B's rule: the people of\n// THIS organization and nobody else). If even that cannot name them, the sentence\n// says so in words. It never prints an id: SCR-N-5 forbids showing one to a\n// person, and \"87a6e699…\" answers nobody's question anyway.\n\nimport type { FieldHistoryEntry, HistoryActor, Uuid } from \"@ai-matrx/records\";\n\n// Read the same realm-wide slot set by design-system's setDisplayTimeZone. This\n// helper is also exported by the light /data-source entry, so it cannot import\n// design-system's field-format bundle merely to read the saved zone.\nconst displayZone = globalSlot<{ zone: string | null }>(\"ai-matrx.design-system.display-time-zone\", () => ({ zone: null }));\n\n/** What the roster can tell us about a user id. `null` when it cannot. */\nexport type ResolveName = (userId: Uuid) => string | null;\n\n/** The honest stand-in when nobody and nothing can put a name to the author. */\nexport const SOMEBODY = \"somebody in this organization\";\n\n/** The platform's own word for itself. Never \"null\", never \"system_user\". */\nexport const THE_SYSTEM = \"Matrx\";\n\n/**\n * WHO, in the words a person reads. One place, so the grid cell, the record\n * timeline and the column history cannot drift into three different answers.\n */\nexport function actorWords(actor: HistoryActor, resolve?: ResolveName | undefined): string {\n if (actor.kind === \"system\") return THE_SYSTEM;\n const named = actor.name?.trim() || (actor.user_id && resolve ? resolve(actor.user_id)?.trim() : null) || null;\n if (actor.kind === \"agent\") {\n // An agent without the person it acted for cannot happen at the door — the\n // store refuses that write — but a screen still says something true if it does.\n const on = actor.on_behalf_of;\n const person = on?.name?.trim() || (on?.user_id && resolve ? resolve(on.user_id)?.trim() : null) || SOMEBODY;\n const approver = actor.approved_by\n ? actor.approved_by.name?.trim() || (resolve ? resolve(actor.approved_by.user_id)?.trim() : null) || SOMEBODY\n : null;\n return `${named ?? \"an assistant\"}, for ${person}${approver ? `, approved by ${approver}` : \"\"}`;\n }\n return named ?? SOMEBODY;\n}\n\n/** How long ago, in the words a person uses out loud. */\nexport function whenWords(at: string, now: Date = new Date()): string {\n const then = new Date(at);\n const age = now.getTime() - then.getTime();\n if (!Number.isFinite(age)) return \"at an unknown time\";\n if (age < 30 * 86_400_000) return formatRelativeTime(then, { style: \"intl\", now: now.getTime() });\n return then.toLocaleDateString(undefined, displayZone.zone ? { timeZone: displayZone.zone } : undefined);\n}\n\n/**\n * THE WHOLE ANSWER, as one sentence, ending in what to do to see the rest.\n * `null` is a real state and gets its own sentence: this column has never been\n * changed on this record since the store started keeping versions, which is not\n * the same as \"we could not find out\".\n */\n/**\n * WHAT HAPPENED, IN A PERSON'S WORDS (BREAKER-2 B2-29). The store words four operations and\n * lowercases any other (`RETYPE` → \"retype\"), so the panel read \"retype · admin · part of a bigger\n * change\". Every word the store can send is worded here; an unknown one is still written the way\n * a person writes it, never as a token. A soft delete is an archive, and says so.\n */\nconst OPERATION_WORDS: Record<string, string> = {\n created: \"Created\",\n edited: \"Edited\",\n deleted: \"Archived\",\n archived: \"Archived\",\n restored: \"Restored\",\n retype: \"Column type changed\",\n delete: \"Removed\",\n soft_delete: \"Archived\",\n insert: \"Created\",\n update: \"Edited\",\n restore: \"Restored\",\n};\n\nexport function operationWords(label: string | null | undefined): string {\n const raw = (label ?? \"\").trim();\n if (raw === \"\") return \"Changed\";\n const known = OPERATION_WORDS[raw.toLowerCase()];\n if (known) return known;\n const words = humanizeIdentifier(raw).toLowerCase();\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\nexport function lastChangeSentence(\n fieldLabel: string,\n entry: FieldHistoryEntry | null,\n resolve?: ResolveName | undefined,\n): string {\n if (!entry) {\n return `Nothing is recorded against ${fieldLabel} on this record yet. Press H for the whole history of this column.`;\n }\n const verb = operationWords(entry.operation_label).toLowerCase();\n return `${fieldLabel} — ${verb} by ${actorWords(entry.actor, resolve)}, ${whenWords(entry.occurred_at)}. Press H for the whole history.`;\n}\n\n/**\n * The SHORT form the badge wears once it knows: a name a person recognizes at a\n * glance, in the width of a cell corner. Never a uuid, never an email's domain.\n */\nexport function actorBadge(actor: HistoryActor, resolve?: ResolveName | undefined): string {\n if (actor.kind === \"system\") return THE_SYSTEM;\n const words = actorWords(actor, resolve);\n if (words === SOMEBODY) return \"somebody\";\n const first = words.split(\",\")[0]!.trim();\n const at = first.indexOf(\"@\");\n return at > 0 ? first.slice(0, at) : first;\n}\n","// The withheld value's WORDS, with no React (`@ai-matrx/records-ui/helpers` serves this file alone).\n// The cell that shows them is `./withheld.tsx`, which re-exports these.\nimport type { Field, HiddenFieldNotice } from \"@ai-matrx/records\";\nimport { fieldName } from \"./names\";\n\n/** The word a withheld cell shows in place of a value. Never \"—\", which means empty. */\nexport const WITHHELD_WORD = \"Withheld\";\n\ntype Hidden = Readonly<Record<string, HiddenFieldNotice | undefined>> | null | undefined;\n\n/** The store's notice for this column of this row, when the store withheld it. */\nexport function withheldNoticeOf(hidden: Hidden, key: string): HiddenFieldNotice | null {\n const notice = hidden?.[key];\n return notice && typeof notice === \"object\" ? notice : null;\n}\n\n/**\n * THE SENTENCE, in the store's own words: the notice's `says` when the store wrote one (a\n * worked-out column names what it reads), else the notice's reason, the level it needs and the\n * other way in.\n */\nexport function withheldSentence(field: Pick<Field, \"key\" | \"label\" | \"name\">, notice: HiddenFieldNotice): string {\n const extra = notice as HiddenFieldNotice & { says?: unknown; part?: unknown; who?: unknown };\n if (typeof extra.says === \"string\" && extra.says.trim() !== \"\") return extra.says.trim();\n const name = fieldName(field as Field);\n // A PART'S NOTICE (access-setup PLAN §12.1): \"Hourly rate is in Pay — people with Record admin on this row see it.\"\n if (typeof extra.part === \"string\" && extra.part.trim() !== \"\" && typeof extra.who === \"string\" && extra.who.trim() !== \"\") {\n return `${name} is in ${extra.part.trim()} — ${extra.who.trim()} see it.`;\n }\n const reason = notice.reason ? ` It is ${notice.reason}` : \"\";\n const needs = notice.needs ? `${reason ? \",\" : \" It\"} and reading it needs ${notice.needs}` : \"\";\n const or = notice.or ? `${needs || reason ? \", or\" : \" It needs\"} ${notice.or}` : \"\";\n return `${name} is withheld from you.${reason}${needs}${or}${reason || needs || or ? \".\" : \"\"}`;\n}\n","// src/choiceLooks.ts — @ai-matrx/records-ui · merge tranche 6f (early)\n//\n// A CHOICE WEARS THE COLOR ITS OWNER GAVE IT.\n//\n// The older /data grid let a person paint each choice of a list (\"Completed\" green, \"Scheduled\"\n// blue), and those colors are kept on the Field itself: `display_format.options.choices`, the\n// document `custom.field_update` writes (the /data Sheet's seam writes it the same way, and a\n// column's settings here write it back). The grid used to ignore it and HASH THE WORD into a\n// color, so a column painted green on /data came up amber here, and a color a person set in the\n// settings changed nothing on screen — the silent half of a setting.\n//\n// Pure: no React, no store call. The Field the grid already holds carries everything.\n\nimport { newerKindOf } from \"@ai-matrx/records/field-kinds\";\nimport type { Field } from \"@ai-matrx/records\";\n// The values from the pure `table-style` subpath (no \"use client\", no grid): `@ai-matrx/records-ui/helpers`\n// reaches this file through `fieldTypeLabel`, and the data-table root would drag the whole grid with it.\nimport { CHOICE_CHIP_CLASS, NEUTRAL_CHIP_CLASS, STYLE_COLORS } from \"@ai-matrx/design-system/data-table/table-style\";\nimport type { ChoiceColorLookup, StyleColor } from \"@ai-matrx/design-system/data-table\";\n\n/** One choice's look, as the Field keeps it. */\nexport interface ChoiceLook {\n value: string;\n label?: string;\n color?: StyleColor;\n}\n\n/** The Field's display document, which the store keeps beside its declared keys. */\nexport function displayFormatOf(field: Field): { id: string; options: Record<string, unknown> } | null {\n const raw = (field as unknown as { display_format?: unknown }).display_format;\n if (!raw || typeof raw !== \"object\") return null;\n const id = (raw as { id?: unknown }).id;\n if (typeof id !== \"string\" || id === \"\") return null;\n const options = (raw as { options?: unknown }).options;\n return { id, options: options && typeof options === \"object\" ? (options as Record<string, unknown>) : {} };\n}\n\nfunction isStyleColor(v: unknown): v is StyleColor {\n return typeof v === \"string\" && (STYLE_COLORS as readonly string[]).includes(v);\n}\n\n/** Every choice look the Field keeps, in its own order. A color outside the palette is dropped. */\nexport function choiceLooksOf(field: Field): ChoiceLook[] {\n const display = displayFormatOf(field);\n const choices = display?.options[\"choices\"];\n if (!Array.isArray(choices)) return [];\n const out: ChoiceLook[] = [];\n for (const c of choices) {\n if (!c || typeof c !== \"object\") continue;\n const value = (c as { value?: unknown }).value;\n if (typeof value !== \"string\" || value.trim() === \"\") continue;\n const color = (c as { color?: unknown }).color;\n const label = (c as { label?: unknown }).label;\n out.push({\n value: value.trim(),\n ...(typeof label === \"string\" && label.trim() !== \"\" ? { label: label.trim() } : {}),\n ...(isStyleColor(color) ? { color } : {}),\n });\n }\n return out;\n}\n\n/**\n * ONE WORD, HOWEVER IT WAS WRITTEN. A moved list keeps its words as `completed` / `truck_4` and\n * shows them as `Completed` / `Truck 4`; a color kept against either spelling is the same choice.\n */\nexport function choiceWord(value: unknown): string {\n return String(value ?? \"\")\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/**\n * NOTION'S STATUS COLORS, BY GROUP: To-do gray, In progress blue, Complete green. A status choice\n * the column paints nothing for wears its group's color, so a fresh Status column reads the way\n * Notion's does with nobody picking a color. A choice with a color of its own keeps it\n * (`storedChoiceColor` asks the column first).\n */\nexport const STATUS_GROUP_COLOR = { todo: \"gray\", in_progress: \"blue\", done: \"green\" } as const satisfies Record<string, StyleColor>;\n\n/** The color a status choice's GROUP gives it, or `undefined` when the column is not a Status. */\nexport function statusGroupColor(field: Field, value: unknown): StyleColor | undefined {\n if (newerKindOf(field) !== \"status\" || value === null || value === undefined || value === \"\") return undefined;\n const word = choiceWord(value);\n if (word === \"\") return undefined;\n const groups = ((field.config ?? {}) as Record<string, unknown>)[\"status_groups\"];\n if (groups && typeof groups === \"object\") {\n // the group is kept under the choice's KEY; the cell may hold its WORDS (\"In progress\" ↔ in_progress)\n for (const [key, group] of Object.entries(groups as Record<string, unknown>)) {\n if (choiceWord(key) !== word) continue;\n return group === \"in_progress\" ? STATUS_GROUP_COLOR.in_progress : group === \"done\" ? STATUS_GROUP_COLOR.done : STATUS_GROUP_COLOR.todo;\n }\n }\n return STATUS_GROUP_COLOR.todo;\n}\n\n/** The color this Field keeps for this value, or `undefined` when it keeps none. */\nexport function storedChoiceColor(field: Field, value: unknown): StyleColor | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n const word = choiceWord(value);\n if (word === \"\") return undefined;\n for (const look of choiceLooksOf(field)) {\n if (!look.color) continue;\n if (choiceWord(look.value) === word || (look.label && choiceWord(look.label) === word)) return look.color;\n }\n return statusGroupColor(field, value);\n}\n\n/**\n * THE COLOR-BY LOOKUP, STORED COLORS FIRST. A value whose column keeps a color for it wears\n * that color; any other value still paints, deterministically, through `fallback` — a color-by\n * that silently did nothing would be the screen lying about a setting a person just changed.\n */\nexport function storedChoiceColorLookup(\n fields: readonly Field[],\n fallback: ChoiceColorLookup,\n): ChoiceColorLookup {\n const byKey = new Map(fields.map((f) => [f.key, f] as const));\n return (fieldKey, value) => {\n const field = byKey.get(fieldKey);\n return (field ? storedChoiceColor(field, value) : undefined) ?? fallback(fieldKey, value);\n };\n}\n\n/**\n * THE ORDER A NEW CHOICE IS PAINTED IN (Airtable): each choice added to a list takes the next\n * palette color the list does not wear yet, so a fresh list reads as distinct chips with nobody\n * picking a color. Gray last — it reads as \"no color\".\n */\nexport const NEW_CHOICE_PALETTE: readonly StyleColor[] = [\"blue\", \"green\", \"amber\", \"red\", \"violet\", \"teal\", \"slate\"];\n\n/** The color the next choice of a list takes, given the colors its choices already wear. */\nexport function nextChoiceColor(worn: ReadonlyArray<StyleColor | null | undefined>): StyleColor {\n const taken = new Set(worn.filter((c): c is StyleColor => Boolean(c)));\n const free = NEW_CHOICE_PALETTE.find((c) => !taken.has(c));\n return free ?? NEW_CHOICE_PALETTE[worn.length % NEW_CHOICE_PALETTE.length]!;\n}\n\n/**\n * THE ONE CHIP A CHOICE IS DRAWN AS — the grid cell, the picker's list and its chip, a form's\n * pills: the color the column keeps for the value (by any of the words given — its key, its\n * label), else the neutral chip. One answer, so no surface paints a choice its own way.\n */\nexport function choiceChipLookOf(field: Field, ...words: unknown[]): { className: string; color: StyleColor | null } {\n for (const word of words) {\n const color = storedChoiceColor(field, word);\n if (color) return { className: CHOICE_CHIP_CLASS[color], color };\n }\n return { className: NEUTRAL_CHIP_CLASS, color: null };\n}\n","// src/docs.ts — @ai-matrx/records-ui · SCR-20, SCR-21, SCR-22\n//\n// DOCUMENTS OVER RECORDS. A template is a body whose tokens point at Fields BY\n// ID; a render is written ONCE and frozen with the SHA-256 of its own text; a\n// signature seals that exact version and is immutable once made.\n//\n// Three things this package refuses to re-implement, because the store already\n// does them and doing them twice is how two answers appear:\n// · which tokens a body contains — `custom.doc_tokens`;\n// · which of them this Table cannot answer, and why — `custom.doc_unresolved_tokens`;\n// · whether a signature still holds — `custom.doc_signature_intact`.\n//\n// The token syntax is the store's own: `{{field:<the field's id>}}`. A name\n// would be a token that silently stops resolving the day somebody renames a\n// Field, which is the exact failure REC-17 exists to prevent.\n\nimport type { Field, Uuid } from \"@ai-matrx/records\";\n\n/** The one token form, written the way the store's own pattern reads it. */\nexport function fieldToken(fieldId: Uuid): string {\n return `{{field:${fieldId}}}`;\n}\n\n/** THE DECLARATIVE SPEC an agent writes. One template, whole, in one object. */\nexport interface DocTemplateSpec {\n name: string;\n /** The body, tokens and all. */\n body: string;\n}\n\n/**\n * A template written in terms of Field KEYS — which is how an agent thinks and\n * how a person reads — turned into the store's id-based tokens. The agent writes\n * `{{title}}`; what is stored points at the Field's id, so a rename never\n * silently empties the document.\n *\n * A key this Table does not have is LEFT EXACTLY AS IT IS, so\n * `custom.doc_unresolved_tokens` names it and the screen shows the store's own\n * reason — it is never quietly deleted from the body.\n */\nexport function bodyFromKeys(body: string, fields: Field[]): string {\n const byKey = new Map(fields.map((f) => [f.key, f.id]));\n return body.replace(/\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g, (whole, key: string) => {\n const id = byKey.get(key);\n return id ? fieldToken(id) : whole;\n });\n}\n\n/** The reverse, for a person reading a stored body: ids shown as the Field's label. */\nexport function bodyForReading(body: string, fields: Field[]): string {\n const byId = new Map(fields.map((f) => [f.id, f.label || f.key]));\n return body.replace(/\\{\\{\\s*field:([0-9a-fA-F-]{36})\\s*\\}\\}/g, (whole, id: string) => {\n const label = byId.get(id);\n return label ? `{{${label}}}` : whole;\n });\n}\n\n/** VAL-10: a signature is a Value on a text Field whose format is `signature`. */\nexport function isSignatureField(field: Field): boolean {\n return field.type === \"text\" && (field.format ?? \"\").toLowerCase() === \"signature\";\n}\n","// src/fieldTypes.ts — @ai-matrx/records-ui\n//\n// EVERY KIND OF COLUMN THE STORE TAKES, IN THE WORDS A PERSON USES.\n//\n// The store publishes fourteen parity types and, for each, a sentence about what\n// it is MADE OF — \"REC-31: a File record reached through a relation, target the\n// kernel `File` Table\", \"FLD-9: a declared computation, on read or on write,\n// evaluated by custom.rule_eval\", \"config.via names the relation field,\n// config.pick the Value on the far side\". Those sentences are true and they are\n// for us. The 19 September verdict found them printed at the person choosing a\n// column type, alongside contract row ids, and called it what it is: machine\n// identity where a person is looking.\n//\n// So this file holds the OTHER sentence — what the type is FOR — and the field\n// panel shows that one. The store's own `made_of` stays where it belongs, in\n// `PARITY_MADE_OF`, for an engineer reading the package.\n//\n// The LIST itself is still the store's: `PARITY_FIELD_TYPES` is generated from\n// `custom.parity_field_types()`, and `assertEveryParityTypeIsExplained` (run by\n// the suite) fails the moment the store ships a fourteenth and nobody wrote a\n// sentence for it. A type with no explanation would otherwise appear with a\n// blank line under it, which is the silent version of the same defect. It caught the\n// fourteenth — `checkbox`, 2026-09-21 — exactly as it was written to.\n\nimport { DECLARABLE_FIELD_KINDS, NEWER_FIELD_KINDS, PARITY_FIELD_TYPES, type DeclarableFieldKind, type NewerFieldKind, type ParityFieldType } from \"@ai-matrx/records/field-kinds\";\n\n/** The three behaviors that carry no parity type of their own. */\nexport type PlainFieldType = \"text\" | \"long_text\" | \"number\";\n\n/**\n * THE ONE A PERSON COMING FROM AIRTABLE REACHES FOR FIRST, AND IT WAS NOT HERE.\n *\n * The list above offered `member` (a Person) and `attachment` (a File) — the two\n * relations whose target is a Table the PLATFORM keeps — and nothing at all for\n * \"this job belongs to that customer\". The store has taken it since 2026-09-20\n * (`custom.field_declare` with `type: \"relation\"` and a `relation_target`), the\n * Field type has named it since the same day, and `editorKindFor` has answered\n * `\"relation\"` for one since long before that. Only the menu did not offer it,\n * so the guide's section 3 told a person to pick a kind that did not exist.\n *\n * It is NOT a parity type of its own. `custom.parity_field_types()` ships\n * fourteen (the fourteenth is `checkbox`) and a relation is a BEHAVIOR — the same behavior `member` and\n * `attachment` are made of — so it sits beside the three plain ones as its own\n * word, and `parityTypesWithNoExplanation()` is unaffected by it in both\n * directions: it does not appear there, and it cannot hide a real gap there.\n */\nexport type RelationFieldType = \"relation\";\n\n/**\n * What a person picks in the panel — AND IT IS THE STORE'S OWN LIST, not a union\n * assembled here.\n *\n * 🚨 THE CLASS FIX (FIX-10B-F6, VERIFIER-10). This used to read\n * `ParityFieldType | PlainFieldType | RelationFieldType` — the parity floor plus two words\n * this file knew about — and that union was the whole defect. `custom.doc_sign` accepts\n * exactly one field, a text column whose format is `signature`, and it is granted to\n * `authenticated`; the Documents screen told a person in so many words to go and declare\n * one; and no list any screen could read named it, so the control did not exist and the\n * e-sign half of Documents was unreachable from the product. A kind the store takes and no\n * screen offers is invisible, and nothing failed — which is the only reason it survived.\n *\n * `custom.field_kinds()` is now the ONE registry and `DECLARABLE_FIELD_KINDS` is generated\n * from it, so the next kind the store learns arrives here as a TYPE ERROR in\n * `FIELD_TYPE_CHOICES`'s coverage and as a red `kindsWithNoChoice()` below — never as a\n * silence.\n */\nexport type PickableFieldType = DeclarableFieldKind | SystemFieldKind | \"entity_reference\" | NewerFieldKind | LookFieldKind;\n\n/**\n * A KIND THAT IS A PLAIN COLUMN WEARING A LOOK (grids review 3, lane H item 5). The store keeps a\n * column's \"Shows as\" on the Field (`display_format`, `custom.display_format_ids()` has `rating` and\n * `time`), so a Rating is a whole number shown as stars and a Time is a time of day kept as its\n * 24-hour text — declared through the ordinary door (`{ plain, display_format }`) the same way the\n * \"Shows as\" picker makes one. Offered whenever the store does not yet publish the kind as its own\n * word (`custom.field_kinds()`): a Rating the store publishes goes as `{ type: \"rating\", max }`.\n */\nexport type LookFieldKind = \"time\" | \"color_pair\" | \"measure\" | \"type_style\" | \"shadow\";\n\nexport interface LookKind {\n plain: \"number\" | \"text\";\n look: (args: { ratingMax: number }) => { id: string; options?: Record<string, unknown> };\n}\n\nexport const LOOK_KINDS: Partial<Record<PickableFieldType, LookKind>> = {\n rating: { plain: \"number\", look: ({ ratingMax }) => ({ id: \"rating\", options: { ratingMax } }) },\n time: { plain: \"text\", look: () => ({ id: \"time\" }) },\n // PLUG-IN DESIGN LOOKS (2026-10-17, `looks/designLooks.tsx`): a structured token is JSON text in a text column.\n color_pair: { plain: \"text\", look: () => ({ id: \"color_pair\" }) },\n measure: { plain: \"number\", look: () => ({ id: \"measure\", options: { unit: \"px\" } }) },\n type_style: { plain: \"text\", look: () => ({ id: \"type_style\" }) },\n shadow: { plain: \"text\", look: () => ({ id: \"shadow\" }) },\n};\n\n/** Is this kind declared as a plain column wearing a look (because the store does not publish it)? */\nexport function declaredAsLook(kind: string): boolean {\n return kind in LOOK_KINDS && !storePublishesKind(kind);\n}\n\n/**\n * LANE 10 P4: THE NINE NEWER KINDS (rating, duration, created by, last changed by, status, address,\n * barcode, formatted text, count). Each is listed in `FIELD_TYPE_CATALOGUE` below, so every reader\n * (Settings, the column panel, every layout) names a column of one by its own word; the MENU offers\n * one only once `custom.field_kinds()` publishes it (after the chair's apply and\n * `pnpm records:generate`), so a person is never offered a kind the live store would refuse.\n */\nexport function storePublishesKind(kind: string): boolean {\n return DECLARABLE_FIELD_KINDS.some((row) => (row.kind as string) === kind);\n}\n\n/**\n * LANE SC-R: a column that points at a PLATFORM thing (a note, a web site, an agent). Its menu entry\n * is drawn only once `custom.field_kinds()` publishes `entity_reference` (after the chair's apply\n * and `pnpm records:generate`), so the menu never offers a kind the live store would refuse.\n */\nexport const STORE_PUBLISHES_ENTITY_REFERENCE = DECLARABLE_FIELD_KINDS.some(\n (row) => (row.kind as string) === \"entity_reference\",\n);\n\n/**\n * THE STORE'S OWN STAMPS AS COLUMNS (GRID-PRIMITIVES G5; TABLE-PARITY H2 H3, lane\n * DEFAULT-GRID-PARITY). `custom.field_declare` takes these three WORDS and makes each a formula\n * Field whose expression is the system node (`fx.autonumber`, `fx.created_time`,\n * `fx.modified_time`, `config.system` naming which), so nobody types into them and every reader\n * that serves a worked-out value serves them. `custom.field_kinds()` does not publish them,\n * because each is a formula, not a behavior of its own. So they are named here, sent as their\n * word through the `{ type }` arm, and a new autonumber column numbers the records already in\n * the table through `custom.autonumber_backfill`.\n */\nexport type SystemFieldKind = \"autonumber\" | \"created_time\" | \"modified_time\";\n\nexport const SYSTEM_FIELD_KINDS: readonly SystemFieldKind[] = [\"autonumber\", \"created_time\", \"modified_time\"];\n\nexport function isSystemFieldKind(id: string): id is SystemFieldKind {\n return (SYSTEM_FIELD_KINDS as readonly string[]).includes(id);\n}\n\nexport interface FieldTypeChoice {\n id: PickableFieldType;\n /** The word on the menu. */\n label: string;\n /** One line, under the word, saying what it is FOR. Never what it is made of. */\n explanation: string;\n /** The heading it sits under, so seventeen choices read as four short lists. */\n group: \"Words\" | \"Numbers and dates\" | \"Choices and people\" | \"Worked out\";\n}\n\n/**\n * EVERY KIND THIS PACKAGE CAN NAME AND DRAW, in menu order. The menu (`FIELD_TYPE_CHOICES`) is this\n * list less the kinds the live store does not take yet; every reader names a column from this one.\n */\nexport const FIELD_TYPE_CATALOGUE: FieldTypeChoice[] = [\n { id: \"text\", group: \"Words\", label: \"Text\", explanation: \"A short line of writing — a name, a reference, a title.\" },\n { id: \"long_text\", group: \"Words\", label: \"Long text\", explanation: \"Several lines — a description, notes, an address.\" },\n { id: \"rich_text\", group: \"Words\", label: \"Formatted text\", explanation: \"Notes with bold, lists and links.\" },\n { id: \"email\", group: \"Words\", label: \"Email address\", explanation: \"An email address, checked as you type and ready to write to.\" },\n { id: \"phone\", group: \"Words\", label: \"Phone number\", explanation: \"A phone number, checked as you type.\" },\n { id: \"url\", group: \"Words\", label: \"Link\", explanation: \"A web address that opens in a new tab when you click it.\" },\n { id: \"address\", group: \"Words\", label: \"Address\", explanation: \"A street address in parts, opened in maps.\" },\n { id: \"color_pair\", group: \"Words\", label: \"Color\", explanation: \"A color for light and dark, with a readability check.\" },\n { id: \"type_style\", group: \"Words\", label: \"Type style\", explanation: \"A font, weight and size, shown as a sample.\" },\n { id: \"shadow\", group: \"Words\", label: \"Shadow\", explanation: \"A shadow, shown on a card.\" },\n { id: \"json\", group: \"Words\", label: \"JSON\", explanation: \"Structured data — a list or a set of named values — shown folded.\" },\n { id: \"barcode\", group: \"Words\", label: \"Barcode\", explanation: \"A code a scanner reads, like a wristband or a box.\" },\n { id: \"button\", group: \"Words\", label: \"Button\", explanation: \"A button on each record that opens a link or runs an action.\" },\n\n { id: \"number\", group: \"Numbers and dates\", label: \"Number\", explanation: \"A plain number you can total up and sort by.\" },\n { id: \"currency\", group: \"Numbers and dates\", label: \"Money\", explanation: \"An amount of money, shown with its currency wherever it appears.\" },\n { id: \"percent\", group: \"Numbers and dates\", label: \"Percentage\", explanation: \"A number out of a hundred, kept between 0 and 100.\" },\n { id: \"rating\", group: \"Numbers and dates\", label: \"Rating\", explanation: \"A score in stars, set with one click.\" },\n { id: \"duration\", group: \"Numbers and dates\", label: \"Duration\", explanation: \"A length of time, typed as 45 min or 1:30.\" },\n { id: \"time\", group: \"Numbers and dates\", label: \"Time\", explanation: \"A time of day with no date — a shift start, opening hours.\" },\n { id: \"measure\", group: \"Numbers and dates\", label: \"Size\", explanation: \"A number with a unit: 16 px, 1.5 rem, 200 ms.\" },\n { id: \"datetime\", group: \"Numbers and dates\", label: \"Date\", explanation: \"A day, or a day and a time. Dates are what the calendar view reads.\" },\n\n { id: \"select\", group: \"Choices and people\", label: \"Choice\", explanation: \"One answer from a list you write here. Choices are what the board view groups by.\" },\n { id: \"multi_select\", group: \"Choices and people\", label: \"Several choices\", explanation: \"Any number of answers from a list you write here.\" },\n { id: \"status\", group: \"Choices and people\", label: \"Status\", explanation: \"Choices grouped into To do, In progress and Done.\" },\n { id: \"checkbox\", group: \"Choices and people\", label: \"Yes / no\", explanation: \"A box you tick. Left alone it stays unanswered, which is not the same as a no.\" },\n { id: \"member\", group: \"Choices and people\", label: \"Person\", explanation: \"Somebody in this organization, picked from the people who are in it.\" },\n { id: \"attachment\", group: \"Choices and people\", label: \"File\", explanation: \"A file or a picture kept with the record.\" },\n { id: \"signature\", group: \"Choices and people\", label: \"Signature\", explanation: \"Somebody's sign-off on a document made from this record. Nobody types in it — it fills in when they sign.\" },\n { id: \"relation\", group: \"Choices and people\", label: \"Points at another record\", explanation: \"A link to records in another of your tables — the customer a job is for, the lines on an invoice.\" },\n {\n id: \"entity_reference\",\n group: \"Choices and people\",\n label: \"Points at something else on the platform\",\n explanation: \"A note, a web site, an agent, a workbook — anything you keep here that is not one of your tables.\",\n },\n\n { id: \"lookup\", group: \"Worked out\", label: \"Borrowed value\", explanation: \"A value read from a record this one points at, kept in step with it.\" },\n { id: \"rollup\", group: \"Worked out\", label: \"Total of linked records\", explanation: \"A count or a total worked out from the records this one points at.\" },\n { id: \"count\", group: \"Worked out\", label: \"Count of linked records\", explanation: \"How many records this one points at.\" },\n { id: \"formula\", group: \"Worked out\", label: \"Worked out from other columns\", explanation: \"A value this record works out for itself from its own other columns.\" },\n { id: \"autonumber\", group: \"Worked out\", label: \"Record number\", explanation: \"A number the table gives each record, one after another, never reused. Records already here are numbered in the order they were made.\" },\n { id: \"created_time\", group: \"Worked out\", label: \"Created time\", explanation: \"When each record was made. Nobody types it.\" },\n { id: \"modified_time\", group: \"Worked out\", label: \"Last changed time\", explanation: \"When each record last changed. Nobody types it.\" },\n { id: \"created_by\", group: \"Worked out\", label: \"Created by\", explanation: \"Who made each record. Nobody types it.\" },\n { id: \"modified_by\", group: \"Worked out\", label: \"Last changed by\", explanation: \"Who last changed each record. Nobody types it.\" },\n];\n\n/** The kinds the menu offers only once the live store publishes them. */\nconst GATED_KINDS = new Set<string>([\"entity_reference\", ...NEWER_FIELD_KINDS]);\n\nexport const FIELD_TYPE_CHOICES: FieldTypeChoice[] = FIELD_TYPE_CATALOGUE.filter(\n (c) => !GATED_KINDS.has(c.id) || storePublishesKind(c.id) || c.id in LOOK_KINDS,\n);\n\nexport const FIELD_TYPE_GROUPS: FieldTypeChoice[\"group\"][] = [\n \"Words\",\n \"Numbers and dates\",\n \"Choices and people\",\n \"Worked out\",\n];\n\nconst BY_ID = new Map<string, FieldTypeChoice>(FIELD_TYPE_CATALOGUE.map((c) => [c.id, c]));\n\nexport function fieldTypeChoice(id: string): FieldTypeChoice | undefined {\n return BY_ID.get(id);\n}\n\n/** The three that are a plain behavior rather than one of the fourteen. */\nexport function isPlainFieldType(id: string): id is PlainFieldType {\n return id === \"text\" || id === \"long_text\" || id === \"number\";\n}\n\n/**\n * The one that is a relation a person aims themselves. It is neither plain nor\n * one of the thirteen, so every caller that branched on `isPlainFieldType`\n * alone has to answer this question too — which is why it is a named function\n * and not an inline string comparison at four call sites.\n */\nexport function isRelationFieldType(id: string): id is RelationFieldType {\n return id === \"relation\";\n}\n\n/**\n * One of FLD-11's fourteen, which is what `parity_type` on a declaration means.\n *\n * Read from the store's own generated floor, never from a list here — because a kind that\n * is NOT one of the fourteen (plain text, a person-aimed relation, a signature) has to be\n * declared by its WORD (`type`) and a panel that sent `parity_type` for it would be refused\n * \"There is no field type called …\". That is the shape of the F6 defect: the panel's `save`\n * had exactly two branches, relation and plain, and everything else fell into `parity_type`.\n */\nexport function isParityFieldType(id: string): id is ParityFieldType {\n return PARITY_FIELD_TYPES.some((row) => row.parity_type === id);\n}\n\n/**\n * THE GUARD THIS FILE NEEDS, because the list it explains is generated.\n *\n * Returns the parity types the store ships that nothing here explains. The\n * suite asserts it is empty; a fourteenth type would otherwise reach the menu\n * with a blank line under it and nobody would notice until a person did.\n *\n * `relation` is deliberately NOT one of the thirteen and therefore never\n * appears in this answer: `PARITY_FIELD_TYPES` is the store's own generated\n * list and a behavior that carries no parity type is not in it.\n */\nexport function parityTypesWithNoExplanation(): string[] {\n return PARITY_FIELD_TYPES.map((row) => row.parity_type).filter((type) => !BY_ID.has(type));\n}\n\n/**\n * 🚨 THE GUARD THAT CLOSES THE CLASS (FIX-10B-F6).\n *\n * `parityTypesWithNoExplanation()` above watches the parity FLOOR, and the floor was never\n * the whole list: the store also declares plain text, long text, number, a person-aimed\n * relation and a signature, and for months nothing anywhere compared the panel's menu with\n * THAT. So `signature` — the one field `custom.doc_sign` accepts, on a door granted to\n * every signed-in person, named to the person by the Documents screen itself — was absent\n * from the menu and every check stayed green.\n *\n * This returns the kinds `custom.field_kinds()` publishes that this panel does not offer.\n * The suite asserts it is empty, so a kind the store learns tomorrow either reaches the\n * person or turns a test red the same day. It is the class, not the instance: it would have\n * caught `signature`, and it will catch the twentieth kind nobody has thought of yet.\n */\nexport function kindsWithNoChoice(): string[] {\n return DECLARABLE_FIELD_KINDS.map((row) => row.kind).filter((kind) => !BY_ID.has(kind));\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// THE WORDS ON THE TWO BUTTONS, IN ONE PLACE — because they used to be the SAME\n// WORDS in two places, and that cost somebody their column.\n//\n// 🚨 THE DEFECT (TAILS-5, 2026-09-21, measured while driving the panel headless\n// on Rincon Plumbing's Summerland branch). The Jobs toolbar's control that OPENS\n// the field panel read exactly \"Add field\", and the panel's own SAVE button read\n// exactly \"Add field\" too — `FieldEditor` says \"Save field\" only when EDITING an\n// existing column, so on the create path the two were character-identical. The\n// toolbar control is a TOGGLE: pressing it while the panel is open closes the\n// panel and throws away everything typed into it. So a person who typed a column\n// name, chose a type, picked the target table and its display columns, then\n// looked up at the words they were told to press, could lose all of it — with no\n// sentence, no request sent, and nothing to say it had happened. A walk written\n// by an agent lost the column twice that way and spent a round diagnosing the\n// store before reading the two labels side by side.\n//\n// WHY THEY LIVE HERE AND NOT IN `@ai-matrx/design-system`. The words are RECORDS\n// vocabulary — \"field\", \"column\" — and the design system knows nothing about\n// either; a labels module there would be a domain word in a generic package, and\n// the next person adding a button would not find it. This file is already the\n// one place that owns what a person READS about a column (`FIELD_TYPE_CHOICES`\n// is right above), and both surfaces that draw these buttons are in this\n// package. One module, one import each, and `fieldTypes.test.ts` asserts the two\n// can never be the same string again.\n//\n// THE RULE: the control that OPENS a panel and the control that COMMITS it never\n// read the same words. The opener is an invitation; the committer says what it\n// will make.\n\n/** The toolbar control that OPENS the add-a-column panel. An invitation. */\nexport const ADD_FIELD_OPEN_LABEL = \"Add column\";\n\n/** The panel's own primary, on the CREATE path. It says what pressing it makes. */\nexport const ADD_FIELD_SAVE_LABEL = \"Create column\";\n\n/** The panel's own primary when an existing column is being changed. */\nexport const EDIT_FIELD_SAVE_LABEL = \"Save column\";\n","// src/parity.ts — @ai-matrx/records-ui\n//\n// FLD-11, the parity floor. A Field stores a BEHAVIOR (one of five) plus\n// modifiers, unit and format; a person picked one of THIRTEEN parity types in\n// the UI. This resolves the second from the first, using the same facts the\n// store's own `custom.parity_field_types()` describes — which is generated into\n// `@ai-matrx/records` and imported here, never retyped.\n//\n// Nothing in this file decides policy. It decides which editor to draw.\n\nimport { displayFormatOf } from \"./choiceLooks\";\nimport {\n KERNEL_TABLES,\n PARITY_FIELD_TYPES,\n fieldKindFor,\n newerKindOf,\n isButtonField,\n type FieldKind,\n type KernelTargets,\n type ParityFieldType,\n} from \"@ai-matrx/records/field-kinds\";\nimport type { Field } from \"@ai-matrx/records\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { isSignatureField } from \"./docs\";\nimport { fieldTypeChoice, isSystemFieldKind, type PickableFieldType } from \"./fieldTypes\";\n\n/** The kernel ids come from the store's own kernel rows, never from a literal here. */\nconst kernelId = (name: string): string =>\n KERNEL_TABLES.find((t) => t.name === name)?.id ?? \"\";\nconst KERNEL_FILE_TABLE = kernelId(\"File\");\nconst KERNEL_PERSON_TABLE = kernelId(\"Person\");\n\nexport const PARITY_LABEL: Record<ParityFieldType, string> = {\n attachment: \"Attachment\",\n checkbox: \"Yes / no\",\n currency: \"Currency\",\n datetime: \"Date\",\n email: \"Email\",\n formula: \"Formula\",\n lookup: \"Lookup\",\n member: \"Person\",\n multi_select: \"Multi-select\",\n percent: \"Percent\",\n phone: \"Phone\",\n rollup: \"Rollup\",\n select: \"Select\",\n url: \"Link\",\n};\n\n/** The \"made of\" sentence the store itself publishes, for the field editor's help text. */\nexport const PARITY_MADE_OF: Record<string, string> = Object.fromEntries(\n PARITY_FIELD_TYPES.map((p) => [p.parity_type, p.made_of]),\n);\n\n/**\n * Plain text and plain number are behaviors with no parity type of their own.\n *\n * 🚨 THIS IS NOW AN ALIAS, AND THAT IS THE POINT (TAILS-3, 2026-09-21). The\n * classifier moved into `@ai-matrx/records` as `FieldKind` so that the editor a\n * person types into and the COERCION applied to what they typed are decided by\n * one body. They were decided by two, and the public booking page paid for it:\n * \"Vehicle Year takes a number, and it was given a string\" on every table with\n * a number field.\n */\nexport type EditorKind = FieldKind;\n\n/** The kernel ids come from the store's own kernel rows, never from a literal here. */\nconst KERNEL: KernelTargets = { file: KERNEL_FILE_TABLE, person: KERNEL_PERSON_TABLE };\n\n/**\n * Which editor one Field wants. Reads the Field's own declaration only — the\n * behavior, the modifiers, the format, the relation target and the config —\n * because those are what the store stores, and a screen that guessed from a\n * value would draw a different editor for an empty record.\n *\n * It is `fieldKindFor` with this package's kernel ids bound. Nothing here\n * decides anything the core does not.\n */\nexport function editorKindFor(field: Field): EditorKind {\n return fieldKindFor(field, KERNEL);\n}\n\n/**\n * WHICH KIND A PERSON PICKED, read back off the Field the store keeps — the ONE reader every\n * \"what does this column hold\" answer goes through (the Settings column list, the column panel).\n *\n * `editorKindFor` answers which EDITOR to draw, and for two families that is not the kind a\n * person picked: a Signature is a text Field whose format is `signature` (it draws a line of\n * text), and the store's stamps — Record number, Created time, Last changed time — are formula\n * Fields whose `config.system` names the stamp. Read through the editor classifier alone, the\n * Settings list called a Signature \"Text\" and a Record number \"Worked out from other columns\"\n * (lane 10 W1-A, guard `every-pickable-kind-reads-back-as-itself.test.tsx`).\n *\n * `undefined` when the Field is none of the kinds the menu offers.\n */\nexport function pickableTypeOf(field: Field): PickableFieldType | undefined {\n if (isSignatureField(field)) return \"signature\";\n // NOTION-PROPS-3: a button is text wearing the format `button`.\n if (isButtonField(field)) return \"button\";\n // LANE 10 P4: the nine newer kinds, each a base type wearing a format (`newerKindOf`).\n const newer = newerKindOf(field);\n if (newer) return newer;\n // A RATING OR A TIME made as a plain column wearing its look (`LOOK_KINDS`): named by that kind.\n const look = displayFormatOf(field)?.id;\n if (look === \"rating\" && field.type === \"range\") return \"rating\";\n if (look === \"time\" && field.type === \"text\") return \"time\";\n if ((look === \"color_pair\" || look === \"type_style\" || look === \"shadow\") && field.type === \"text\") return look;\n if (look === \"measure\" && field.type === \"range\") return \"measure\";\n const system = (field.config as Record<string, unknown> | undefined)?.[\"system\"];\n if (field.type === \"formula\" && typeof system === \"string\" && isSystemFieldKind(system)) return system;\n const kind = editorKindFor(field);\n return fieldTypeChoice(kind) ? (kind as PickableFieldType) : undefined;\n}\n\n/**\n * The type word a person sees in a header or a settings row — and it is the\n * SAME word the field panel offers, read from `FIELD_TYPE_CHOICES`, so a column\n * added as \"Money\" is never described anywhere else as \"Currency\".\n */\nexport function fieldTypeLabel(field: Field): string {\n const kind = pickableTypeOf(field) ?? editorKindFor(field);\n const known = fieldTypeChoice(kind)?.label;\n if (known) return field.multi && kind !== \"multi_select\" ? `${known} (many)` : known;\n const plain: Record<string, string> = {\n // `boolean` is the BEHAVIOR word; `checkbox` is the type a person picks. Both are\n // written the way a person writes them, never as a raw token.\n boolean: \"Yes / no\",\n date: \"Date\",\n json: \"Structured data\",\n relation: \"Link to a record\",\n };\n // Never a raw token on a screen: an editor kind this table has not named is\n // still written the way a person writes it.\n return plain[kind] ?? humanizeIdentifier(kind);\n}\n","// src/tablePickerEntries.ts — @ai-matrx/records-ui (pure; also served by `@ai-matrx/records-ui/helpers`)\nimport { momentZoneOptions } from \"@ai-matrx/design-system/field-formats\";\n//\n// THE RULE for which tables a \"choose a table\" control offers (the full reasoning heads\n// `./tablePicking.tsx`, which re-exports everything here and adds the hook and the toggle).\n// No React, no store call: a host's picker data and a server read ask the same answer.\n\n/** The facts a picker needs about one table, whichever list it came from. */\nexport interface PickerTable {\n id: string;\n name: string;\n platform_owned?: boolean | null | undefined;\n /** The Table document's own key for the same fact (`tableList()` spreads the document onto the Table). */\n kept_by_the_app?: boolean | null | undefined;\n /** `custom.table_facts`: which feature keeps it (`choices` for a value set). */\n kept_for?: string | null | undefined;\n /** `custom.data_home_tables`: the store's one word for what it is (`list` for a value set). */\n kind?: string | null | undefined;\n /** The table a value set belongs to (`custom.table_facts.used_in_table_id`). */\n used_in_table_id?: string | null | undefined;\n /** A checklist's steps, a booking page's slots, a workflow's states. */\n work_kind?: unknown;\n slug?: string | null | undefined;\n /** When the table was made — what tells two lists apart once their column is gone. */\n created_at?: string | null | undefined;\n}\n\n/** The slug prefix of the tables this package keeps for its own bookkeeping (saved views, forms …). */\nconst PLATFORM_TABLE_PREFIX = \"records_ui_\";\n\n/** The store's flag (`platform_owned`) or the Table document's own key (`kept_by_the_app`) — either says the app keeps it. */\nfunction keptByPlatform(table: PickerTable): boolean {\n return table.platform_owned === true || table.kept_by_the_app === true;\n}\n\n/** A value set: the List a choice column keeps its choices in. */\nexport function isValueSet(table: PickerTable): boolean {\n if (table.kept_for === \"choices\") return true;\n return table.kept_for == null && table.kind === \"list\" && keptByPlatform(table);\n}\n\n/** Anything the app keeps for itself rather than a table a person keeps. */\nexport function isKeptTable(table: PickerTable): boolean {\n return (\n keptByPlatform(table) ||\n isValueSet(table) ||\n Boolean(table.work_kind) ||\n (table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX)\n );\n}\n\nexport interface TablePickerEntry<T extends PickerTable> {\n table: T;\n id: string;\n /** Unique among the entries returned. */\n label: string;\n /** A value set (shown only with \"Show lists\", or because it is the chosen one). */\n isList: boolean;\n}\n\nexport interface TablePickerEntries<T extends PickerTable> {\n entries: TablePickerEntry<T>[];\n /** How many value sets \"Show lists\" would add — 0 means the control is not worth drawing. */\n listCount: number;\n}\n\nconst CHOICES_SUFFIX = / choices$/i;\n\n/**\n * THE ONE RULE. Tables first (by name), then — with `showLists` — the value sets, each named\n * \"<column> — <owning table>\". Any names still equal get \" (2)\", \" (3)\" so no two entries match.\n */\nexport function tablePickerEntries<T extends PickerTable>(\n tables: readonly T[],\n options: { showLists?: boolean; keep?: string | null | undefined } = {},\n): TablePickerEntries<T> {\n const byId = new Map(tables.map((t) => [t.id, t]));\n const lists = tables.filter(isValueSet);\n const listLabel = (t: T): string => {\n const column = t.name.replace(CHOICES_SUFFIX, \"\");\n // A LIST WHOSE COLUMN IS GONE: `custom.table_facts` names the list itself (or nothing) as where\n // it is used. Said so, and told apart by the day it was made — never by a counter.\n if (!t.used_in_table_id || t.used_in_table_id === t.id) {\n const made = madeOn(t.created_at);\n return made ? `${column} — no column · ${made}` : `${column} — no column`;\n }\n const owner = byId.get(t.used_in_table_id);\n // Owned by a table this person cannot see: its own name, as the store gave it.\n if (!owner) return t.name;\n return `${column} — ${owner.name}`;\n };\n const plain = tables\n .filter((t) => !isKeptTable(t) || (t.id === options.keep && !isValueSet(t)))\n .map((t) => ({ table: t, id: t.id, label: t.name, isList: false }))\n .sort((a, b) => a.label.localeCompare(b.label));\n const shownLists = lists\n .filter((t) => options.showLists || t.id === options.keep)\n .map((t) => ({ table: t, id: t.id, label: listLabel(t), isList: true }))\n .sort((a, b) => a.label.localeCompare(b.label));\n const entries = [...plain, ...shownLists];\n const seen = new Map<string, number>();\n for (const entry of entries) {\n const key = entry.label.toLowerCase();\n const n = (seen.get(key) ?? 0) + 1;\n seen.set(key, n);\n if (n > 1) entry.label = `${entry.label} (${n})`;\n }\n return { entries, listCount: lists.length };\n}\n\n/** \"Sep 3, 2026\" in the reader's own locale, or null when the store gave no date. */\nfunction madeOn(stamp: string | null | undefined): string | null {\n if (!stamp) return null;\n const at = new Date(stamp);\n if (Number.isNaN(at.getTime())) return null;\n return new Intl.DateTimeFormat(undefined, { month: \"short\", day: \"numeric\", year: \"numeric\", ...momentZoneOptions(at) }).format(at);\n}\n","/**\n * The Gantt mode of a timeline view, by Field key. `mode` turns the left task list on; `critical` paints the longest\n * chain; `progress` is a percent/number column; `milestone` a yes/no column; `baselineStart` / `baselineEnd` the two\n * date columns \"Save baseline\" writes; `dependency` the link column that dependencies are written to.\n */\nexport interface GanttLook {\n mode?: boolean;\n critical?: boolean;\n progress?: string;\n milestone?: string;\n baselineStart?: string;\n baselineEnd?: string;\n dependency?: string;\n}\n\n/** Read a stored Gantt look; unknown keys and wrong shapes are dropped. */\nexport function parseGanttLook(raw: unknown): GanttLook | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const v = raw as Record<string, unknown>;\n const out: GanttLook = {};\n if (v[\"mode\"] === true) out.mode = true;\n if (v[\"critical\"] === true) out.critical = true;\n for (const k of [\"progress\", \"milestone\", \"baselineStart\", \"baselineEnd\", \"dependency\"] as const) {\n const x = v[k];\n if (typeof x === \"string\" && x !== \"\") out[k] = x;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * HOW A TABLE LOOKS — colors, formats and the frozen column.\n *\n * THE SPLIT, AND WHY IT IS THIS ONE. A Field declares WHAT it holds: a\n * currency, a percent, a date, a person. A VIEW declares HOW that reads and\n * what it is worth looking at: two decimal places or none, tint the row when\n * Status is Blocked, keep Name in place while the rest scrolls. Airtable draws\n * the line in exactly this place, and it has to be here: two people read one\n * table two different ways, and neither reading is a fact about the records.\n *\n * So nothing in this module is a new column on a Field and nothing here needed\n * a migration. A presentation lives on the saved-view record (`views.ts`), which\n * is an ordinary record of an ordinary Table — which means an agent sets it\n * through the same `records` tool it uses for everything else, and it travels\n * with the table the way every other record does.\n *\n * A FIELD STILL GETS ITS MONEY RIGHT WITH NO CONFIGURATION. `formatForField`\n * reads the Field's OWN declaration — a `currency` parity type with unit `$`, a\n * `percent`, a `datetime` with `config.kind` — and returns the format that\n * follows from it. The view's `formats` map only OVERRIDES that. A table nobody\n * has ever styled still shows `$1,250.50` and `45%`.\n */\n\n// The style parser from its own client-free subpath (lane SSR-ROWS): `@ai-matrx/records-ui/first-page`\n// runs in a host's SERVER component, and every export of the \"use client\" `data-table` entry is a\n// client reference there — calling `parseTableStyle` through it threw on the server.\nimport { COLOR_ROTATION, parseTableStyle, tableStyleIsEmpty } from \"@ai-matrx/design-system/data-table/table-style\";\nimport type {\n ChoiceColorLookup,\n GroupAggregateKind,\n GroupAggregateSpec,\n GroupOrder,\n StyleColor,\n TableStyle,\n} from \"@ai-matrx/design-system/data-table\";\nimport { getFieldFormat, type FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\nimport type { ColorRule } from \"@ai-matrx/design-system/data-table\";\nimport { newerKindOf, ratingMaxOf } from \"@ai-matrx/records/field-kinds\";\nimport type { Field, TableDecorations } from \"@ai-matrx/records\";\n\nimport { editorKindFor } from \"./parity\";\nimport { dateFormatFor } from \"./dates\";\n\n/**\n * SECTIONS BY A FIELD — the view's own grouping.\n *\n * `field` is a Field KEY, exactly like `frozen` and the keys of `formats`,\n * because a view is written against the Table's declaration and never against\n * whatever id a screen happened to build its columns with.\n *\n * `aggregates` is keyed by Field key too, and `collapsed` holds the data\n * table's own group keys (`s:Blocked`, `n:3`, `empty`), which is what the\n * primitive emits and the only thing that survives a value rendering the same\n * text as another.\n *\n * NOTHING HERE IS EVER CALLED `valueOf`, `toString` or `hasOwnProperty`: every\n * object in JavaScript already has all three, so an optional field by one of\n * those names is NEVER absent and a `config.valueOf ? … : …` check silently\n * reads `Object.prototype`. It cost the primitive a whole grouping once.\n */\nexport type GridGrouping = {\n /** The Field key whose value makes the sections. */\n field: string;\n /** Per-Field-key subtotal on every section header. */\n aggregates?: Record<string, GroupAggregateSpec>;\n /** Section order. The primitive's default is `value-asc`; blanks sort last. */\n order?: GroupOrder;\n /** The sections this view keeps shut, by the primitive's own group key. */\n collapsed?: string[];\n /** The grouped column stays drawn as a column (Airtable). Absent = shown; `false` = the person stepped it aside. */\n showColumn?: boolean;\n /**\n * SUB-GROUPS (lane S1-PRIME VIEW-KEYS; ui-bench LISTS \"sub-grouping\"): up to two more levels\n * inside each section, by Field key. At most three levels in all — the store refuses a fourth\n * (`custom.view_declare`). A layout that draws one level ignores the rest; it never drops them,\n * because this list is parsed and written back whole with the rest of the look.\n */\n then?: GridSubGroup[];\n /**\n * DRILL (lane DRILL-TABLE-PRIMITIVE): the Dimension pivoted across the top — a Field key, or\n * `<key>:<grain>` for a date cut into periods.\n */\n across?: string;\n /** DRILL: the period `field` is cut into when it is a date (`month`); the store keeps `field` a Field key. */\n grain?: string;\n /** The Measures shown (\"what to display\"), by the store's own keys (`count`, `sum_quantity`). */\n show?: string[];\n /** The drill trail, in order: each crumb a Dimension reference and the value it narrowed to. */\n trail?: GridDrillStep[];\n};\n\n/** One crumb of a saved drill trail. `value: null` is \"no value\". */\nexport type GridDrillStep = { dim: string; value: string | null };\n\n/** One sub-group level: a Field key and its section order. */\nexport type GridSubGroup = { field: string; order?: GroupOrder; grain?: string };\n\n/** Everything a view says about how its table LOOKS. */\nexport type GridPresentation = {\n /** Color-by-a-column, rules and manual highlights. */\n style?: TableStyle;\n /** Per-column format overrides, by the Field's key. */\n formats?: Record<string, FieldFormatConfig>;\n /**\n * The columns that stay in place while the table scrolls sideways, by Field\n * key. Only the LEADING run of the view's column order can actually freeze —\n * the data table decides that, and declines rather than pinning a column at a\n * guessed offset.\n */\n frozen?: string[];\n /** Collapsible sections by one Field, with subtotals on each header. */\n grouping?: GridGrouping;\n /**\n * The width a person dragged a column to, by Field key. SPARSE on purpose —\n * a view saved before widths existed carries none and still parses, and a\n * column nobody resized is left to the table's own measurement.\n */\n widths?: Record<string, number>;\n /** The body row height this view remembers, in px. */\n rowHeight?: number;\n /**\n * Field keys hidden from this view — the SAME hidden-column list the grid's\n * own column picker holds, now given a place on the view so it survives a\n * reload and a layout switch reads the identical set gallery and grid agree\n * on, rather than a second \"fields shown\" list nobody kept in sync.\n */\n hiddenFields?: string[];\n /**\n * THE FIELDS A CARD LEAVES OFF (board, list, gallery, calendar, timeline), by Field key — the\n * card's own choice, kept apart from `hiddenFields` so a board's \"Card fields\" never hides the\n * grid's columns when the view switches layout (v7 TABLE-EXPERIENCE, walk 2026-10-05). An empty\n * list is a choice (every field shown); absent means the card never chose.\n */\n cardHidden?: string[];\n /**\n * THE ORDER A PERSON DRAGGED THE COLUMNS INTO, by Field key (merge tranche 6a). Sparse like\n * `widths`: a key it does not name keeps its Field's own place after the named ones, and a key\n * whose Field is gone is skipped — a column order can never hide or invent a column.\n */\n columnOrder?: string[];\n /**\n * The gallery's card size, remembered the same way the grid remembers its\n * row height — a per-view look, not a global default.\n */\n gallerySize?: \"small\" | \"medium\" | \"large\";\n /**\n * THE BOARD'S OWN LOOK (lane BOARD-SWIMLANES, Notion's board options). All kept on the view, all\n * read only by the kanban layout. Absent means the board's default: columns wear their choice's\n * color, each heading shows its count, empty columns and lanes are drawn, cards are medium with\n * no preview.\n * boardSize card size: sets the column width, the preview's height and, small, drops the card's extras\n * boardPreview the FILE field drawn as a cover at the top of each card (absent = no preview)\n * boardHideEmpty leave out a column or a lane that holds no card\n * boardColorColumns false = neutral headings, no accent bar on the cards\n * boardCounts false = no count beside the heading\n * boardLanesShut the swimlanes kept shut to a strip, by the lane's name\n */\n boardSize?: \"small\" | \"medium\" | \"large\";\n boardPreview?: string;\n boardHideEmpty?: boolean;\n boardColorColumns?: boolean;\n boardCounts?: boolean;\n boardLanesShut?: string[];\n /**\n * A CHART VIEW'S MENU (PIVOT-VIEW): `chartLabels` draws each mark's value on it (the chart menu's \"Data labels\"\n * switch); `chartLegend: false` leaves the legend off. Read only by the chart layout.\n */\n chartLabels?: boolean;\n chartLegend?: boolean;\n /**\n * A LOCKED VIEW (lane NOTION-SMALL-2): its layout, filters, sorts and settings are not saved over until\n * somebody unlocks it. An editing convenience against an accidental change, never a permission.\n */\n locked?: boolean;\n /**\n * THIS VIEW'S OWN LAYOUT CHOICES, over the organization's `custom/grid_layout` knob (lane\n * DEFAULT-GRID-PARITY, TABLE-PARITY D1 D5 D6). Absent means \"whatever the organization\n * says\"; present is the view's word. `freezeFirst: false` is an explicit NO over an\n * organization that freezes the first column — an empty `frozen` cannot say that.\n */\n wrap?: boolean;\n /** AIRTABLE'S \"WRAP FIELD HEADERS\": column titles take a second line instead of being cut. Absent = one line. */\n headerWrap?: boolean;\n /** NOTION'S \"WRAP COLUMN\" (N5): the columns that wrap their text when the view as a whole does not. */\n wrapColumns?: string[];\n fit?: \"auto\" | \"fit\" | \"scroll\";\n freezeFirst?: boolean;\n /**\n * THE SUMMARY BAR (TABLE-PARITY F1): Field key → the store measure shown under that column\n * (`count`, `sum`, `avg`, `min`, `max`, `median`, `filled`, `empty`, `unique`), worked out\n * by `custom.record_aggregate` over the whole table.\n */\n summaries?: Record<string, string>;\n /** THE TIMELINE'S GANTT MODE (kept as `presentation.gantt`): see `GanttLook`. */\n gantt?: GanttLook;\n /**\n * WHERE THE FOOTER SITS (lane TABLE-PAGE-CHROME, owner 2026-09-25) — the row count and the\n * pages: `sticky`, pinned to the bottom of the screen while the rows scroll (the older grid's\n * way, and the default when a view says nothing), or `inline`, right after the last row with\n * the page scrolling. Read by the Grid and a host's Sheet.\n */\n footer?: FooterPlacement;\n};\n\n/** Where a grid's footer sits. */\nexport type FooterPlacement = \"sticky\" | \"inline\";\n\n/** What a view that says nothing gets — the older grid's pinned footer. */\nexport const DEFAULT_FOOTER: FooterPlacement = \"sticky\";\n\n/** Where THIS view's footer sits, said or defaulted. */\nexport function footerOf(p: GridPresentation | null | undefined): FooterPlacement {\n return p?.footer ?? DEFAULT_FOOTER;\n}\n\nexport const EMPTY_PRESENTATION: GridPresentation = {};\n\n/** A frozen column needs a known width, or the table declines to freeze at all. */\nexport const FROZEN_COLUMN_WIDTH = 200;\n\n/**\n * WHAT A ROW HEIGHT IS ALLOWED TO BE. Below the floor the text is clipped and\n * no editor fits; above the ceiling one record fills the screen. A view asking\n * for anything outside it is DROPPED rather than obeyed, because a saved look\n * must not be able to make a table unreadable — and the Fields' own heights\n * still draw, which is the tolerant half.\n */\nexport const MIN_ROW_HEIGHT = 24;\nexport const MAX_ROW_HEIGHT = 240;\n\n/**\n * The aggregate kinds and orders the primitive actually implements. Listed here\n * because they are the tolerant parser's allow-list and a view is hostile input:\n * `satisfies` ties them to the primitive's own union, so a kind it renames stops\n * this file compiling instead of quietly parsing into a subtotal nobody draws.\n */\nconst AGGREGATE_KINDS = [\n \"count\",\n \"sum\",\n \"average\",\n \"min\",\n \"max\",\n \"empty\",\n \"filled\",\n \"unique\",\n \"checked\",\n \"unchecked\",\n \"percentFilled\",\n] as const satisfies readonly GroupAggregateKind[];\n\nconst GROUP_ORDERS = [\n \"value-asc\",\n \"value-desc\",\n \"count-desc\",\n \"first-seen\",\n] as const satisfies readonly GroupOrder[];\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * Read a presentation out of whatever the view record holds — an object, or the\n * JSON string a text field stores.\n *\n * Tolerant in exactly the way `parseTableStyle` is: an unreadable half is\n * dropped and the rest still applies, because a table must keep drawing when\n * one piece of its styling goes out of date.\n */\nexport function parseGridPresentation(raw: unknown): GridPresentation {\n let value = raw;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed === \"\") return {};\n try {\n value = JSON.parse(trimmed);\n } catch {\n return {};\n }\n }\n if (!isRecord(value)) return {};\n\n const out: GridPresentation = {};\n\n const style = parseTableStyle(value[\"style\"]);\n if (!tableStyleIsEmpty(style)) out.style = style;\n\n if (isRecord(value[\"formats\"])) {\n const formats: Record<string, FieldFormatConfig> = {};\n for (const [key, cfg] of Object.entries(value[\"formats\"])) {\n if (!isRecord(cfg)) continue;\n const id = cfg[\"id\"];\n if (typeof id !== \"string\") continue;\n const options = cfg[\"options\"];\n formats[key] = isRecord(options)\n ? {\n id: id as FieldFormatConfig[\"id\"],\n options: options as NonNullable<FieldFormatConfig[\"options\"]>,\n }\n : { id: id as FieldFormatConfig[\"id\"] };\n }\n if (Object.keys(formats).length > 0) out.formats = formats;\n }\n\n if (Array.isArray(value[\"frozen\"])) {\n const frozen = value[\"frozen\"].filter((k): k is string => typeof k === \"string\");\n if (frozen.length > 0) out.frozen = frozen;\n }\n\n const grouping = parseGrouping(value[\"grouping\"]);\n if (grouping) out.grouping = grouping;\n\n if (isRecord(value[\"widths\"])) {\n const widths: Record<string, number> = {};\n for (const [key, raw] of Object.entries(value[\"widths\"])) {\n // A width that is not a usable number is one column's loss, never the\n // view's: the rest of the widths still apply and that column is measured.\n if (typeof raw !== \"number\" || !Number.isFinite(raw) || raw <= 0) continue;\n widths[key] = Math.round(raw);\n }\n if (Object.keys(widths).length > 0) out.widths = widths;\n }\n\n const rowHeight = value[\"rowHeight\"];\n if (\n typeof rowHeight === \"number\" &&\n Number.isFinite(rowHeight) &&\n rowHeight >= MIN_ROW_HEIGHT &&\n rowHeight <= MAX_ROW_HEIGHT\n ) {\n out.rowHeight = Math.round(rowHeight);\n }\n\n if (Array.isArray(value[\"hiddenFields\"])) {\n const hiddenFields = value[\"hiddenFields\"].filter((k): k is string => typeof k === \"string\");\n if (hiddenFields.length > 0) out.hiddenFields = hiddenFields;\n }\n if (Array.isArray(value[\"cardHidden\"])) {\n out.cardHidden = value[\"cardHidden\"].filter((k): k is string => typeof k === \"string\");\n }\n\n if (Array.isArray(value[\"columnOrder\"])) {\n const columnOrder = value[\"columnOrder\"].filter((k): k is string => typeof k === \"string\");\n if (columnOrder.length > 0) out.columnOrder = columnOrder;\n }\n\n const gallerySize = value[\"gallerySize\"];\n if (gallerySize === \"small\" || gallerySize === \"medium\" || gallerySize === \"large\") {\n out.gallerySize = gallerySize;\n }\n\n const boardSize = value[\"boardSize\"];\n if (boardSize === \"small\" || boardSize === \"medium\" || boardSize === \"large\") out.boardSize = boardSize;\n if (typeof value[\"boardPreview\"] === \"string\" && value[\"boardPreview\"] !== \"\") out.boardPreview = value[\"boardPreview\"];\n if (typeof value[\"boardHideEmpty\"] === \"boolean\") out.boardHideEmpty = value[\"boardHideEmpty\"];\n if (typeof value[\"boardColorColumns\"] === \"boolean\") out.boardColorColumns = value[\"boardColorColumns\"];\n if (typeof value[\"boardCounts\"] === \"boolean\") out.boardCounts = value[\"boardCounts\"];\n if (typeof value[\"chartLabels\"] === \"boolean\") out.chartLabels = value[\"chartLabels\"];\n if (typeof value[\"chartLegend\"] === \"boolean\") out.chartLegend = value[\"chartLegend\"];\n if (value[\"locked\"] === true) out.locked = true;\n if (Array.isArray(value[\"boardLanesShut\"])) {\n const shut = value[\"boardLanesShut\"].filter((k): k is string => typeof k === \"string\");\n if (shut.length > 0) out.boardLanesShut = shut;\n }\n\n if (typeof value[\"wrap\"] === \"boolean\") out.wrap = value[\"wrap\"];\n if (typeof value[\"headerWrap\"] === \"boolean\") out.headerWrap = value[\"headerWrap\"];\n if (Array.isArray(value[\"wrapColumns\"])) {\n const wrapColumns = value[\"wrapColumns\"].filter((k): k is string => typeof k === \"string\");\n if (wrapColumns.length > 0) out.wrapColumns = wrapColumns;\n }\n const fit = value[\"fit\"];\n if (fit === \"auto\" || fit === \"fit\" || fit === \"scroll\") out.fit = fit;\n if (typeof value[\"freezeFirst\"] === \"boolean\") out.freezeFirst = value[\"freezeFirst\"];\n const footer = value[\"footer\"];\n if (footer === \"sticky\" || footer === \"inline\") out.footer = footer;\n {\n const gantt = parseGanttLook(value[\"gantt\"]);\n if (gantt) out.gantt = gantt;\n }\n if (isRecord(value[\"summaries\"])) {\n const summaries: Record<string, string> = {};\n for (const [key, op] of Object.entries(value[\"summaries\"])) {\n // A measure name is judged by the store when it is asked; a non-string is nobody's.\n if (typeof op === \"string\" && op.trim() !== \"\") summaries[key] = op;\n }\n if (Object.keys(summaries).length > 0) out.summaries = summaries;\n }\n\n return out;\n}\n\n/**\n * A grouping, or nothing. A grouping with no Field to group BY is not a partial\n * grouping — it is no grouping at all, so it is dropped whole; an unreadable\n * subtotal or a section order this primitive does not have costs only itself.\n */\nfunction parseGrouping(raw: unknown): GridGrouping | undefined {\n if (!isRecord(raw)) return undefined;\n const field = raw[\"field\"];\n if (typeof field !== \"string\" || field.trim() === \"\") return undefined;\n\n const out: GridGrouping = { field };\n\n if (isRecord(raw[\"aggregates\"])) {\n const aggregates: Record<string, GroupAggregateSpec> = {};\n for (const [key, spec] of Object.entries(raw[\"aggregates\"])) {\n if (!isRecord(spec)) continue;\n const kind = spec[\"kind\"];\n if (typeof kind !== \"string\") continue;\n if (!(AGGREGATE_KINDS as readonly string[]).includes(kind)) continue;\n const label = spec[\"label\"];\n aggregates[key] =\n typeof label === \"string\"\n ? { kind: kind as GroupAggregateKind, label }\n : { kind: kind as GroupAggregateKind };\n }\n if (Object.keys(aggregates).length > 0) out.aggregates = aggregates;\n }\n\n const order = raw[\"order\"];\n if (typeof order === \"string\" && (GROUP_ORDERS as readonly string[]).includes(order)) {\n out.order = order as GroupOrder;\n }\n\n if (Array.isArray(raw[\"collapsed\"])) {\n const collapsed = raw[\"collapsed\"].filter((k): k is string => typeof k === \"string\");\n if (collapsed.length > 0) out.collapsed = collapsed;\n }\n\n if (typeof raw[\"showColumn\"] === \"boolean\") out.showColumn = raw[\"showColumn\"];\n\n if (Array.isArray(raw[\"then\"])) {\n const then: GridSubGroup[] = [];\n for (const level of raw[\"then\"]) {\n if (!isRecord(level)) continue;\n const sub = level[\"field\"];\n if (typeof sub !== \"string\" || sub.trim() === \"\") continue;\n const subOrder = level[\"order\"];\n const subGrain = level[\"grain\"];\n then.push({\n field: sub,\n ...(typeof subOrder === \"string\" && (GROUP_ORDERS as readonly string[]).includes(subOrder)\n ? { order: subOrder as GroupOrder }\n : {}),\n ...(typeof subGrain === \"string\" && subGrain !== \"\" ? { grain: subGrain } : {}),\n });\n }\n if (then.length > 0) out.then = then.slice(0, 2);\n }\n\n const grain = raw[\"grain\"];\n if (typeof grain === \"string\" && grain !== \"\") out.grain = grain;\n const across = raw[\"across\"];\n if (typeof across === \"string\" && across.trim() !== \"\") out.across = across;\n if (Array.isArray(raw[\"show\"])) {\n const show = raw[\"show\"].filter((k): k is string => typeof k === \"string\" && k !== \"\");\n if (show.length > 0) out.show = show;\n }\n if (Array.isArray(raw[\"trail\"])) {\n const trail: GridDrillStep[] = [];\n for (const step of raw[\"trail\"]) {\n if (!isRecord(step) || typeof step[\"dim\"] !== \"string\" || step[\"dim\"] === \"\") continue;\n const value = step[\"value\"];\n if (value !== null && typeof value !== \"string\") continue;\n trail.push({ dim: step[\"dim\"], value });\n }\n if (trail.length > 0) out.trail = trail;\n }\n\n return out;\n}\n\n/** True when nothing here would change how anything looks. */\nexport function presentationIsEmpty(p: GridPresentation): boolean {\n return (\n (p.style === undefined || tableStyleIsEmpty(p.style)) &&\n Object.keys(p.formats ?? {}).length === 0 &&\n (p.frozen?.length ?? 0) === 0 &&\n p.grouping === undefined &&\n Object.keys(p.widths ?? {}).length === 0 &&\n p.rowHeight === undefined &&\n (p.hiddenFields?.length ?? 0) === 0 &&\n p.cardHidden === undefined &&\n (p.columnOrder?.length ?? 0) === 0 &&\n p.gallerySize === undefined &&\n p.boardSize === undefined &&\n p.boardPreview === undefined &&\n p.boardHideEmpty === undefined &&\n p.boardColorColumns === undefined &&\n p.boardCounts === undefined &&\n (p.boardLanesShut?.length ?? 0) === 0 &&\n p.chartLabels === undefined &&\n p.chartLegend === undefined &&\n p.locked === undefined &&\n p.wrap === undefined &&\n p.headerWrap === undefined &&\n p.fit === undefined &&\n p.freezeFirst === undefined &&\n p.footer === undefined &&\n Object.keys(p.summaries ?? {}).length === 0 &&\n p.gantt === undefined\n );\n}\n\n/** The string a view record stores. Empty string for \"this view styles nothing\". */\nexport function presentationDocument(p: GridPresentation): string {\n return presentationIsEmpty(p) ? \"\" : JSON.stringify(p);\n}\n\n/** Kinds whose value is a control the record renderer draws, never a formatter's string. */\nconst DRAWN_KINDS = new Set([\"select\", \"multi_select\", \"relation\", \"member\", \"person\", \"attachment\", \"file\", \"entity_reference\", \"checkbox\", \"boolean\", \"signature\", \"json\"]);\n\n/**\n * The display format a column's settings chose for it, when it is one the platform registry\n * knows and the column is not one the record renderer draws itself. `undefined` otherwise.\n */\nexport function shownAsOf(field: Field): FieldFormatConfig | undefined {\n if (DRAWN_KINDS.has(String(editorKindFor(field)))) return undefined;\n const raw = (field as unknown as { display_format?: unknown }).display_format;\n if (!raw || typeof raw !== \"object\") return undefined;\n const id = (raw as { id?: unknown }).id;\n // `formula` is the column's KIND, never a look: a worked-out column shows as its result format.\n if (typeof id !== \"string\" || id === \"formula\" || !getFieldFormat(id)) return undefined;\n const options = (raw as { options?: unknown }).options;\n return options && typeof options === \"object\" && Object.keys(options).length > 0\n ? ({ id, options } as FieldFormatConfig)\n : ({ id } as FieldFormatConfig);\n}\n\n/**\n * The format a Field's OWN declaration implies, before any view says anything.\n *\n * Returns `undefined` for a Field whose value the record renderer already draws\n * better than a formatter could — a relation chip, a person, an attachment, a\n * choice — because handing those to a text formatter would REPLACE a working\n * control with a string.\n */\n/**\n * A COLUMN THAT HOLDS YEARS (\"Founded\", \"Year\", \"Year built\", \"Established\", \"Model year\"…).\n * A year is a number that is never grouped: \"Founded 2,008\" read as a quantity (lane RECORD-PAGE-UI,\n * 2026-10-15). Known by its name; a value is printed as a year only when it is also a whole number\n * from 1000 to 2999 (`isYearValue`).\n */\nconst YEAR_NAMES = /(^|[\\s_-])(year|founded|established|incorporated|vintage)([\\s_-]|$)/i;\nexport function isYearField(field: Pick<Field, \"key\" | \"label\">): boolean {\n return YEAR_NAMES.test(String(field.label ?? \"\")) || YEAR_NAMES.test(field.key);\n}\nexport function isYearValue(value: unknown): boolean {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1000 && value <= 2999;\n}\n/** A number format with its grouping off for a year column, unless the column chose grouping itself. */\nfunction ungroupedForYears(field: Field, format: FieldFormatConfig): FieldFormatConfig {\n if (format.id !== \"number\" || !isYearField(field)) return format;\n const options = (format.options ?? {}) as Record<string, unknown>;\n if (options[\"useGrouping\"] !== undefined) return format;\n return { ...format, options: { ...options, useGrouping: false } };\n}\n\nexport function formatForField(field: Field): FieldFormatConfig | undefined {\n // \"SHOWS AS\" — THE FORMAT THE COLUMN'S OWN SETTINGS CHOSE (merge tranche 6a/6e). The column\n // keeps it on the Field (`display_format`, written by `custom.field_update`), so the grid, the\n // record panel and the export read one answer. A column the record renderer draws better than\n // a formatter (a choice, a link, a person, a file) keeps its own drawing.\n const shownAs = shownAsOf(field);\n // A RATING'S TOP STAR IS ITS MAX RULE (lane 10 P4), so changing the rule changes the stars.\n if (newerKindOf(field) === \"rating\" && (!shownAs || shownAs.id === \"rating\")) {\n return { id: \"rating\", options: { ...(shownAs?.options ?? {}), ratingMax: ratingMaxOf(field) } };\n }\n if (shownAs) return ungroupedForYears(field, shownAs);\n // THE STORE'S OWN STAMPS (Created time, Last changed time) are instants and print like\n // every other date-and-time cell — `dates.ts` answers, the same helper every card reads.\n const stamp = dateFormatFor(field);\n if (stamp && editorKindFor(field) !== \"datetime\") return stamp;\n switch (editorKindFor(field)) {\n case \"currency\":\n return {\n id: \"currency\",\n options: { currency: currencyCodeFor(field.unit) },\n };\n case \"percent\":\n return { id: \"percent\" };\n case \"datetime\":\n // The COLUMN's declaration: a `kind: \"date\"` column is a date column, anything else can\n // hold a moment. Each VALUE is still printed in its own shape (`RecordValue` →\n // `dates.dateFormatFor(field, value)`), so a bare date in a datetime column reads as a date.\n return String(field.config?.[\"kind\"] ?? \"\") === \"date\" ? { id: \"date\" } : { id: \"datetime\" };\n case \"email\":\n return { id: \"email\" };\n case \"url\":\n return { id: \"url\" };\n case \"phone\":\n return { id: \"phone\" };\n case \"number\":\n return ungroupedForYears(field, { id: \"number\" });\n default:\n return undefined;\n }\n}\n\n/**\n * THE FORMAT ONE CELL OF A COLUMN IS DRAWN IN — the grid's cell and the gallery's card alike\n * (guard G4 \"one format\", lane VIEWS-AND-FIELDS W1-B): the view's own format for the column when\n * it set one, else the Field's own (`formatForField`). One function, so no layout formats money\n * (or a date, or a percent) its own way.\n */\nexport function cellFormatFor(field: Field, viewFormat?: FieldFormatConfig | undefined): FieldFormatConfig | undefined {\n return viewFormat ?? formatForField(field);\n}\n\n/**\n * The store lets a person type the SYMBOL they think in (`$`, `€`), and\n * `Intl.NumberFormat` wants the ISO code. The symbols people actually enter are\n * mapped; anything else is passed straight through, because a real ISO code is\n * the other thing that lands in this field, and an unknown code still renders\n * (`1,234.00 XYZ`) rather than blanking — THE FALLBACK LAW.\n */\nconst SYMBOL_TO_CODE: Record<string, string> = {\n $: \"USD\",\n \"£\": \"GBP\",\n \"€\": \"EUR\",\n \"¥\": \"JPY\",\n \"₹\": \"INR\",\n \"₽\": \"RUB\",\n \"₩\": \"KRW\",\n \"R$\": \"BRL\",\n \"C$\": \"CAD\",\n \"A$\": \"AUD\",\n};\n\nexport function currencyCodeFor(unit: string | null | undefined): string {\n const raw = (unit ?? \"\").trim();\n if (raw === \"\") return \"USD\";\n return SYMBOL_TO_CODE[raw] ?? raw.toUpperCase();\n}\n\n/**\n * The color a value paints with when a view colors BY a column.\n *\n * NOTHING FAILS SILENTLY, so this never returns \"no color\" for a value that\n * exists. The store keeps a list column's choices as records of another Table,\n * and this grid has not read that Table's option colors, so the color is\n * derived from the value's own text: the same word always gets the same color,\n * different words get different ones, and `true` is green the way every\n * checklist reads. When those option colors do land, this is the ONE function\n * that changes and every screen follows.\n */\nexport const colorFromTheValue: ChoiceColorLookup = (_fieldKey, value) => {\n if (value === true) return \"green\";\n if (value === false || value === null || value === undefined) return undefined;\n const text = String(value).trim().toLowerCase();\n if (text === \"\") return undefined;\n let hash = 0;\n for (let i = 0; i < text.length; i += 1) {\n hash = (hash * 31 + text.charCodeAt(i)) >>> 0;\n }\n return COLOR_ROTATION[hash % COLOR_ROTATION.length] as StyleColor;\n};\n\n/**\n * G1's TABLE-LEVEL COLORS (`custom.table_decorations` / `client.tableDecorations`),\n * TRANSLATED INTO A `TableStyle` — the same document a saved view's own `presentation.style`\n * is, so one resolver (`resolveTableStyle`, below) can treat \"the table's colors\" and \"this\n * view's colors\" as two layers of the SAME thing instead of two unrelated systems.\n *\n * THE TRANSLATION IS NECESSARY AND IT IS THE ONLY ONE. G1 addresses a Field by its ID\n * (REC-17 — a column renamed keeps its color), because it is the STORE's own door; a\n * `TableStyle` addresses a Field by its KEY, because it reads straight off `row.document`,\n * which is keyed by Field key. A rule or a color-by whose Field has been deleted (its id no\n * longer resolves to a key) is dropped rather than crashing the whole style — a defect in\n * one rule costs that rule, never the read.\n */\nexport function styleFromDecorations(\n decorations: TableDecorations | null | undefined,\n fields: readonly Field[],\n): TableStyle {\n if (!decorations) return { version: 1 };\n const keyOf = (id: string) => fields.find((f) => f.id === id)?.key;\n const style: TableStyle = { version: 1 };\n\n if (decorations.color_by?.field) {\n const field = keyOf(decorations.color_by.field);\n if (field) style.colorBy = { field, target: decorations.color_by.target };\n }\n\n if (Array.isArray(decorations.rules) && decorations.rules.length > 0) {\n const rules: ColorRule[] = [];\n decorations.rules.forEach((rule, index) => {\n const field = keyOf(rule.field);\n if (!field) return;\n rules.push({\n id: rule.id ?? `decoration:${index}`,\n field,\n op: rule.op,\n color: rule.color,\n target: rule.target,\n ...(rule.value === undefined || rule.value === null ? {} : { value: String(rule.value) }),\n });\n });\n if (rules.length > 0) style.rules = rules;\n }\n\n if (decorations.rows && Object.keys(decorations.rows).length > 0) {\n style.rows = { ...decorations.rows };\n }\n\n const columns: Record<string, StyleColor> = {};\n for (const [id, color] of Object.entries(decorations.columns ?? {})) {\n const key = keyOf(id);\n if (key) columns[key] = color;\n }\n if (Object.keys(columns).length > 0) style.columns = columns;\n\n const cells: Record<string, Record<string, StyleColor>> = {};\n for (const [rowId, byField] of Object.entries(decorations.cells ?? {})) {\n for (const [id, color] of Object.entries(byField ?? {})) {\n const key = keyOf(id);\n if (!key) continue;\n (cells[rowId] ??= {})[key] = color;\n }\n }\n if (Object.keys(cells).length > 0) style.cells = cells;\n\n return style;\n}\n\n/**\n * THE ONE PRESENTATION RESOLVER every colored surface in this package reads —\n * `Grid`, and (via `Card`) the kanban board, the calendar and the gallery.\n *\n * THE CLASS THIS CLOSES (lane UI-QUICK-1, TABLE-PARITY review, 2026-09-24). Threading\n * `view.presentation.style` into `Card` closed the instance the CALENDAR-GALLERY bench\n * found — a VIEW that had its own color-by looked right everywhere — but it left the\n * class open: a table whose colors are the ORGANIZATION's decorations (G1's\n * `custom.table_decorations` — \"color rows by Account Type\", \"MAXED and NEAR rules\" on\n * Arman's own Coding Accounts table) and whose views never set a `presentation.style` of\n * their own drew NOTHING, on the grid exactly as much as on every other layout, because\n * nothing in this package had ever read G1's door at all.\n *\n * TWO LAYERS, ONE DOCUMENT. The table's decorations are the base coat — what every view\n * of this table shows until a view says otherwise. A view's OWN `presentation.style` is\n * an override, piece by piece: a view that only ever set manual row highlights still\n * inherits the table's color-by and rules for everything it never touched, and a view\n * that fully redecorated (its own `colorBy` AND its own `rules`) is not haunted by a\n * table rule it meant to replace. Per-piece, never all-or-nothing, because a view is a\n * LOOK on top of the table, not a wholesale substitute for it.\n */\nexport function resolveTableStyle(\n decorations: TableDecorations | null | undefined,\n fields: readonly Field[],\n viewStyle: TableStyle | undefined,\n): TableStyle {\n const base = styleFromDecorations(decorations, fields);\n if (!viewStyle) return base;\n const colorBy = viewStyle.colorBy ?? base.colorBy;\n const rules = viewStyle.rules ?? base.rules;\n const rows = viewStyle.rows ?? base.rows;\n const columns = viewStyle.columns ?? base.columns;\n const cells = viewStyle.cells ?? base.cells;\n return {\n version: 1,\n ...(colorBy !== undefined ? { colorBy } : {}),\n ...(rules !== undefined ? { rules } : {}),\n ...(rows !== undefined ? { rows } : {}),\n ...(columns !== undefined ? { columns } : {}),\n ...(cells !== undefined ? { cells } : {}),\n };\n}\n","// src/pages.ts — @ai-matrx/records-ui\n//\n// A PAGE BUILT FROM TABLES (v6 lane 11, wave D; DASHBOARDS-AND-PAGES-MODEL §0). A Page is NOT a new\n// record type: it is a dashboard record (`custom.record`, `data_class = 'dashboard'`) whose\n// `presentation.kind` is `\"page\"`. `custom.dashboard_declare` stores `presentation` exactly as given\n// (read on the clone, 2026-10-03), so no new store door is needed:\n//\n// · chart blocks stay in `blocks` — judged by `dashboard_block_normalize`, answered by `dashboard_run`;\n// · every other block lives in `presentation.page_blocks`, each with a stable `id`;\n// · `presentation.page_blocks` is ALSO the page's reading order: a chart appears there as\n// `{ kind: \"chart\", id }`, where `id` is the chart's own block id in `blocks`.\n//\n// Every data block reads through the existing client doors under the viewer's own principal\n// (list / read / form / action), so a column the store hides from a viewer never reaches a block.\n// Champion: Airtable Interfaces — list, record detail, buttons and filters as elements on one page.\n\nimport type { DashboardSummary, RecordFilter, RuleExpression, StoreFilter, Uuid } from \"@ai-matrx/records\";\nimport { isRuleFilter } from \"@ai-matrx/records/views\";\n\n/** Every kind of block a page holds. `chart` points at a block in the dashboard's own `blocks`. */\nexport const PAGE_BLOCK_KINDS = [\n \"list\",\n \"layout\",\n \"review\",\n \"record\",\n \"number\",\n \"button\",\n \"form\",\n \"filter\",\n \"chart\",\n \"heading\",\n \"text\",\n \"image\",\n \"embed\",\n \"applet\",\n] as const;\nexport type PageBlockKind = (typeof PAGE_BLOCK_KINDS)[number];\n\n/** What \"Add block\" reads for each kind. */\nexport const PAGE_BLOCK_LABEL: Record<PageBlockKind, string> = {\n list: \"List\",\n layout: \"Layout\",\n review: \"Record review\",\n record: \"Record panel\",\n number: \"Number\",\n button: \"Button\",\n form: \"Form\",\n filter: \"Filter\",\n chart: \"Chart\",\n heading: \"Heading\",\n text: \"Text\",\n image: \"Image\",\n embed: \"Embed\",\n applet: \"Applet\",\n};\n\n/**\n * AT-INTERFACE — the table layouts a page element draws, each through the ONE renderer of that layout\n * (`ViewSwitcher`), never a page copy of a board or a calendar.\n */\nexport const ELEMENT_LAYOUTS = [\"grid\", \"gallery\", \"kanban\", \"calendar\", \"timeline\", \"map\", \"orgchart\"] as const;\nexport type ElementLayout = (typeof ELEMENT_LAYOUTS)[number];\nexport const ELEMENT_LAYOUT_LABEL: Record<ElementLayout, string> = {\n grid: \"Grid\",\n gallery: \"Gallery\",\n kanban: \"Kanban\",\n calendar: \"Calendar\",\n timeline: \"Timeline\",\n map: \"Map\",\n orgchart: \"Org chart\",\n};\n\n/** What \"Add element\" offers, in Airtable's order: data views first, then numbers, actions and layout pieces. */\nexport type AddChoice = PageBlockKind | `layout:${ElementLayout}`;\nexport const ADD_CHOICES: readonly { value: AddChoice; label: string }[] = [\n { value: \"list\", label: \"List\" },\n ...ELEMENT_LAYOUTS.map((l) => ({ value: `layout:${l}` as AddChoice, label: ELEMENT_LAYOUT_LABEL[l] })),\n { value: \"review\", label: \"Record review\" },\n { value: \"record\", label: \"Record panel\" },\n { value: \"number\", label: \"Number\" },\n { value: \"chart\", label: \"Chart\" },\n { value: \"button\", label: \"Button\" },\n { value: \"form\", label: \"Form\" },\n { value: \"filter\", label: \"Filter\" },\n { value: \"heading\", label: \"Heading\" },\n { value: \"text\", label: \"Text\" },\n { value: \"image\", label: \"Image\" },\n { value: \"embed\", label: \"Embed\" },\n { value: \"applet\", label: \"Applet\" },\n];\n\n/** A titled group of fields on a record detail (Airtable's field groups). */\nexport interface FieldGroup {\n title: string;\n fields: string[];\n}\n\n/**\n * Who sees which rows. `me_field` names a person / email / relation column (Airtable's \"current user\"\n * filter): a viewer OUTSIDE the organization always sees only the rows that point at her (the store applies\n * it, `custom.interface_rows`); `me_only` applies the same rule to members too.\n */\ninterface ScopedRows {\n table_id: Uuid;\n view_id?: Uuid | null;\n filter?: RecordFilter;\n columns?: string[];\n me_field?: string | null;\n me_only?: boolean;\n}\n\ninterface PageBlockBase {\n /** Stable across saves, moves and resizes. */\n id: string;\n /** Width in twelfths from 640 px up (`dashboardLayout.ts`); full width on a phone. */\n span?: number;\n title?: string;\n}\n\nexport interface ListPageBlock extends PageBlockBase {\n kind: \"list\";\n /** \"Current user\": only the viewer's rows, always (see `ScopedRows`). */\n me_only?: boolean;\n table_id: Uuid;\n /** A saved view of the table: its filter and sort shape the list. */\n view_id?: Uuid | null;\n /** The block's own question, the store's flat filter (field key → value). */\n filter?: RecordFilter;\n /** The columns shown, by field key; left out, the first few the table declares. */\n columns?: string[];\n /** A person column. Offers \"Assigned to me\": the viewer's own Person record against it. */\n me_field?: string | null;\n /** Whether \"Assigned to me\" starts on. */\n me_default?: boolean;\n limit?: number;\n}\n\nexport interface RecordPageBlock extends PageBlockBase {\n kind: \"record\";\n /** The list block whose selected row this panel shows. */\n source: string;\n /** Shown as titled groups instead of the whole record. */\n field_groups?: FieldGroup[];\n}\n\n/** A table drawn as one layout on the page. */\nexport interface LayoutPageBlock extends PageBlockBase, ScopedRows {\n kind: \"layout\";\n layout: ElementLayout;\n group_field?: string | null;\n date_field?: string | null;\n end_field?: string | null;\n image_field?: string | null;\n /** Map: the address or latitude column, and the longitude column when it is a latitude. */\n map_field?: string | null;\n map_lng_field?: string | null;\n /** Org chart: the link column to this table that says who a record reports to. */\n parent_field?: string | null;\n}\n\n/** Record review: the records on one side, the chosen one beside it, with next and previous. */\nexport interface ReviewPageBlock extends PageBlockBase, ScopedRows {\n kind: \"review\";\n field_groups?: FieldGroup[];\n}\n\n/** One number: how many records answer the element's question. */\nexport interface NumberPageBlock extends PageBlockBase, ScopedRows {\n kind: \"number\";\n}\n\nexport interface ImagePageBlock extends PageBlockBase {\n kind: \"image\";\n url: string;\n alt?: string;\n}\n\nexport interface EmbedPageBlock extends PageBlockBase {\n kind: \"embed\";\n url: string;\n}\n\nexport interface ButtonPageBlock extends PageBlockBase {\n kind: \"button\";\n /** The list block whose selected row the action runs on. */\n source: string;\n table_id: Uuid;\n /** An existing row action of that table (`custom.row_actions`). */\n action_id: Uuid;\n}\n\nexport interface FormPageBlock extends PageBlockBase {\n kind: \"form\";\n table_id: Uuid;\n form_id: Uuid;\n}\n\nexport interface FilterPageBlock extends PageBlockBase {\n kind: \"filter\";\n table_id: Uuid;\n /** A choice (or yes/no) column of that table. */\n field: string;\n /** The list blocks it narrows. Empty = every list on the page over the same table. */\n targets?: string[];\n}\n\nexport interface ChartPageBlock extends PageBlockBase {\n kind: \"chart\";\n}\n\nexport interface HeadingPageBlock extends PageBlockBase {\n kind: \"heading\";\n text: string;\n}\n\nexport interface TextPageBlock extends PageBlockBase {\n kind: \"text\";\n text: string;\n}\n\n/**\n * AN APPLET ON THE PAGE (v7 APPS-ON-DATA item 3 — Arman's endgame, 2026-10-02: one custom start page\n * per person, built on the applets system, nested applets). The host draws it (`RecordsUiHost.applets`);\n * this package only keeps which one, so a page can mix a person's own data with platform features.\n */\nexport interface AppletPageBlock extends PageBlockBase {\n kind: \"applet\";\n /** The applet (agent app) id; empty until chosen. */\n app_id: string;\n}\n\nexport type PageBlock =\n | ListPageBlock\n | LayoutPageBlock\n | ReviewPageBlock\n | NumberPageBlock\n | ImagePageBlock\n | EmbedPageBlock\n | RecordPageBlock\n | ButtonPageBlock\n | FormPageBlock\n | FilterPageBlock\n | ChartPageBlock\n | HeadingPageBlock\n | TextPageBlock\n | AppletPageBlock;\n\n/** The `presentation.kind` that makes a dashboard record a Page. */\nexport const PAGE_KIND = \"page\";\n\n/** Is this dashboard row a Page? Every row with no kind is a dashboard (the store's default). */\nexport function isPage(row: Pick<DashboardSummary, \"presentation\"> | { presentation?: unknown }): boolean {\n const p = row.presentation as Record<string, unknown> | null | undefined;\n return !!p && typeof p === \"object\" && p[\"kind\"] === PAGE_KIND;\n}\n\nfunction isBlock(value: unknown): value is PageBlock {\n if (!value || typeof value !== \"object\") return false;\n const b = value as Record<string, unknown>;\n return typeof b[\"id\"] === \"string\" && typeof b[\"kind\"] === \"string\" && (PAGE_BLOCK_KINDS as readonly string[]).includes(b[\"kind\"] as string);\n}\n\n/**\n * The page's blocks in reading order, read strictly out of `presentation`. A chart the store holds\n * in `blocks` but the order does not name is appended (it was added by an agent or the old canvas),\n * and a `chart` entry whose block is gone is dropped — the page never draws a block it cannot answer.\n */\nexport function pageBlocksOf(presentation: Record<string, unknown> | null | undefined, chartIds: readonly string[]): PageBlock[] {\n const raw = presentation?.[\"page_blocks\"];\n const listed = (Array.isArray(raw) ? raw : []).filter(isBlock);\n const charts = new Set(chartIds);\n const kept = listed.filter((b) => b.kind !== \"chart\" || charts.has(b.id));\n const named = new Set(kept.filter((b) => b.kind === \"chart\").map((b) => b.id));\n return [...kept, ...chartIds.filter((id) => !named.has(id)).map((id): ChartPageBlock => ({ id, kind: \"chart\" }))];\n}\n\n/** The presentation a page is saved with: its kind and its blocks, everything else it held kept. */\nexport function pagePresentation(presentation: Record<string, unknown> | null | undefined, blocks: readonly PageBlock[]): Record<string, unknown> {\n return { ...(presentation ?? {}), kind: PAGE_KIND, page_blocks: blocks };\n}\n\n/** A fresh block id. */\nexport function newBlockId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * THE STARTER PAGE on one table, the way Airtable's record-review layout starts: the table's records\n * on the left, the chosen one on the right. One press makes a page that already works.\n */\nexport function starterPageBlocks(tableId: Uuid): PageBlock[] {\n const list = newBlockId();\n return [\n { id: list, kind: \"list\", table_id: tableId, span: 6 },\n { id: newBlockId(), kind: \"record\", source: list, span: 6 },\n ];\n}\n\n/** The list blocks a filter block narrows: those it names, or every list over its table. */\nexport function filterTargets(filter: FilterPageBlock, blocks: readonly PageBlock[]): string[] {\n if (filter.targets && filter.targets.length > 0) return filter.targets;\n return blocks.filter((b): b is ListPageBlock => b.kind === \"list\" && b.table_id === filter.table_id).map((b) => b.id);\n}\n\n/**\n * ONE QUESTION FOR A LIST BLOCK, in the store's own filter shapes. `base` is the view's question —\n * its `where` Rule or its flat `filters` — and `extra` the page's own (the block's filter, the\n * filter blocks, \"Assigned to me\"), all equalities by key. Both flat: one merged map (the page's\n * value wins). The view asks a Rule: the extras join it under `and`, by field id, which is the only\n * way the Rule shape names a column (REC-17). An extra whose key has no id is left out and named.\n */\nexport function combineFilter(\n base: StoreFilter | null | undefined,\n extra: RecordFilter,\n fieldIdOf: (key: string) => string | undefined,\n): { filter: StoreFilter | null; dropped: string[] } {\n const extraKeys = Object.keys(extra);\n if (!base || (!isRuleFilter(base) && Object.keys(base).length === 0)) {\n return { filter: extraKeys.length > 0 ? { ...extra } : null, dropped: [] };\n }\n if (!isRuleFilter(base)) return { filter: { ...(base as RecordFilter), ...extra }, dropped: [] };\n const dropped: string[] = [];\n let rule: RuleExpression = base;\n for (const key of extraKeys) {\n const id = fieldIdOf(key);\n if (!id) {\n dropped.push(key);\n continue;\n }\n const value = extra[key];\n const leaf: RuleExpression =\n value === null\n ? { op: \"not\", args: [{ op: \"present\", args: [{ field: id }] }] }\n : { op: \"eq\", args: [{ field: id }, { const: value }] };\n rule = { op: \"and\", args: [rule, leaf] };\n }\n return { filter: rule, dropped };\n}\n\n/** The kinds of element that read rows of a table (and so may be read through the interface door). */\nexport const ROW_ELEMENT_KINDS: ReadonlySet<PageBlockKind> = new Set([\"list\", \"layout\", \"review\", \"number\"]);\n\n/**\n * A NEW ELEMENT of one kind, on the page's first table. A chart also returns its spec (charts live in the\n * dashboard's own `blocks`). `ChartSpec` is passed in by the caller so this module stays free of chart code.\n */\nexport function newElement(\n choice: AddChoice,\n blocks: readonly PageBlock[],\n subject: Uuid,\n): PageBlock {\n const firstList = blocks.find((b): b is ListPageBlock => b.kind === \"list\");\n const firstTable = blocks.find((b): b is ListPageBlock | LayoutPageBlock | ReviewPageBlock =>\n b.kind === \"list\" || b.kind === \"layout\" || b.kind === \"review\",\n );\n const table = (firstTable?.table_id ?? subject) as Uuid;\n const id = newBlockId();\n if (choice.startsWith(\"layout:\")) {\n return { id, kind: \"layout\", layout: choice.slice(7) as ElementLayout, table_id: table, span: 12 };\n }\n switch (choice as PageBlockKind) {\n case \"list\":\n return { id, kind: \"list\", table_id: table, span: 6 };\n case \"review\":\n return { id, kind: \"review\", table_id: table, span: 12 };\n case \"record\":\n return { id, kind: \"record\", source: firstList?.id ?? \"\", span: 6 };\n case \"number\":\n return { id, kind: \"number\", table_id: table, span: 3, title: \"Records\" };\n case \"button\":\n return { id, kind: \"button\", source: firstList?.id ?? \"\", table_id: table, action_id: \"\" as Uuid, span: 4 };\n case \"form\":\n return { id, kind: \"form\", table_id: table, form_id: \"\" as Uuid, span: 6 };\n case \"filter\":\n return { id, kind: \"filter\", table_id: table, field: \"\", span: 4 };\n case \"heading\":\n return { id, kind: \"heading\", text: \"Heading\", span: 12 };\n case \"applet\":\n return { id, kind: \"applet\", app_id: \"\", span: 12 };\n case \"image\":\n return { id, kind: \"image\", url: \"\", span: 6 };\n case \"embed\":\n return { id, kind: \"embed\", url: \"\", span: 12 };\n case \"chart\":\n return { id, kind: \"chart\", span: 6 };\n case \"text\":\n default:\n return { id, kind: \"text\", text: \"\", span: 12 };\n }\n}\n","// src/interfaces.ts — @ai-matrx/records-ui · AT-INTERFACE\n//\n// AN INTERFACE IS A NAMED SET OF PAGES (Airtable's Interface Designer), built on the Page model, never beside\n// it. Like a Page it is a dashboard record (`custom.record`, data_class `dashboard`); its `presentation.kind`\n// is `\"interface\"` and its pages live INSIDE it, so one record is one thing to share, archive and restore:\n//\n// presentation = {\n// kind: \"interface\", icon, color,\n// draft: { pages: InterfacePage[] } ← what builders edit\n// published: { pages: InterfacePage[], version, at, by } | null ← what everybody else sees\n// versions: InterfaceVersion[] ← every publish, newest first (restore)\n// }\n//\n// Each page holds the SAME `PageBlock`s a Page holds (one canvas, `PageCanvas`), plus its own chart specs.\n// The record's `blocks` (what `custom.dashboard_run` answers) is every chart the draft or the published\n// version uses, so a builder previews a draft chart while viewers keep the published one. A published chart is\n// never edited in place: the draft gets a copy under a new id (`withDraftChart`).\n//\n// A person the interface is shared with reads it through `custom.interface_read` / `custom.interface_rows`\n// — only the published pages, only what each element exposes.\n\nimport type { DashboardSummary, Uuid } from \"@ai-matrx/records\";\nimport type { ChartSpec } from \"./charts\";\nimport { newBlockId, type PageBlock } from \"./pages\";\n\nexport const INTERFACE_KIND = \"interface\";\n\n/** How many published versions an interface keeps to restore from. */\nexport const INTERFACE_VERSIONS_KEPT = 20;\n\nexport interface InterfacePage {\n id: string;\n name: string;\n /** A lucide icon name. */\n icon?: string;\n blocks: PageBlock[];\n charts: ChartSpec[];\n}\n\nexport interface InterfacePublished {\n pages: InterfacePage[];\n version: number;\n at: string;\n by?: string | null;\n}\n\nexport interface InterfaceVersion extends InterfacePublished {}\n\nexport interface InterfaceShape {\n icon: string;\n color: string;\n draft: { pages: InterfacePage[] };\n published: InterfacePublished | null;\n versions: InterfaceVersion[];\n}\n\n/** The interface colors, by token name (`INTERFACE_COLOR_CLASS` paints them). */\nexport const INTERFACE_COLORS = [\"blue\", \"green\", \"amber\", \"rose\", \"violet\", \"slate\"] as const;\nexport const INTERFACE_ICONS = [\"layout-dashboard\", \"kanban\", \"calendar\", \"users\", \"briefcase\", \"megaphone\", \"clipboard-check\", \"star\"] as const;\n\nexport function isInterface(row: Pick<DashboardSummary, \"presentation\"> | { presentation?: unknown }): boolean {\n const p = row.presentation as Record<string, unknown> | null | undefined;\n return !!p && typeof p === \"object\" && p[\"kind\"] === INTERFACE_KIND;\n}\n\nfunction pagesOf(value: unknown): InterfacePage[] {\n if (!Array.isArray(value)) return [];\n return value\n .filter((p): p is Record<string, unknown> => !!p && typeof p === \"object\" && typeof (p as Record<string, unknown>)[\"id\"] === \"string\")\n .map((p) => ({\n id: p[\"id\"] as string,\n name: typeof p[\"name\"] === \"string\" && p[\"name\"] ? (p[\"name\"] as string) : \"Page\",\n ...(typeof p[\"icon\"] === \"string\" ? { icon: p[\"icon\"] as string } : {}),\n blocks: Array.isArray(p[\"blocks\"]) ? (p[\"blocks\"] as PageBlock[]) : [],\n charts: Array.isArray(p[\"charts\"]) ? (p[\"charts\"] as ChartSpec[]) : [],\n }));\n}\n\nfunction publishedOf(value: unknown): InterfacePublished | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n return {\n pages: pagesOf(v[\"pages\"]),\n version: typeof v[\"version\"] === \"number\" ? v[\"version\"] : 1,\n at: typeof v[\"at\"] === \"string\" ? v[\"at\"] : \"\",\n by: typeof v[\"by\"] === \"string\" ? v[\"by\"] : null,\n };\n}\n\n/** The interface read strictly out of a presentation. A viewer's copy has no draft: she sees the published pages. */\nexport function interfaceOf(presentation: Record<string, unknown> | null | undefined): InterfaceShape {\n const p = presentation ?? {};\n const published = publishedOf(p[\"published\"]);\n const draftRaw = p[\"draft\"] as Record<string, unknown> | undefined;\n const draftPages = draftRaw && typeof draftRaw === \"object\" ? pagesOf(draftRaw[\"pages\"]) : (published?.pages ?? []);\n return {\n icon: typeof p[\"icon\"] === \"string\" ? (p[\"icon\"] as string) : \"layout-dashboard\",\n color: typeof p[\"color\"] === \"string\" ? (p[\"color\"] as string) : \"blue\",\n draft: { pages: draftPages },\n published,\n versions: Array.isArray(p[\"versions\"]) ? (p[\"versions\"] as unknown[]).map(publishedOf).filter((v): v is InterfaceVersion => !!v) : [],\n };\n}\n\n/** The presentation an interface is saved with. */\nexport function interfacePresentation(shape: InterfaceShape): Record<string, unknown> {\n return {\n kind: INTERFACE_KIND,\n icon: shape.icon,\n color: shape.color,\n draft: shape.draft,\n published: shape.published,\n versions: shape.versions,\n };\n}\n\n/** Every chart the draft or the published version uses, once: what the record's `blocks` holds. */\nexport function interfaceCharts(shape: InterfaceShape): ChartSpec[] {\n const out: ChartSpec[] = [];\n const seen = new Set<string>();\n for (const page of [...shape.draft.pages, ...(shape.published?.pages ?? [])]) {\n for (const chart of page.charts) {\n if (!chart.id || seen.has(chart.id)) continue;\n seen.add(chart.id);\n out.push(chart);\n }\n }\n return out;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/** Does the draft differ from what viewers see? (Never published counts as a change once there is a page.) */\nexport function hasUnpublishedChanges(shape: InterfaceShape): boolean {\n if (!shape.published) return shape.draft.pages.length > 0;\n return !same(shape.draft.pages, shape.published.pages);\n}\n\n/** PUBLISH: the draft becomes what viewers see, and a version is kept to restore. */\nexport function publish(shape: InterfaceShape, at: string, by: string | null): InterfaceShape {\n const version = Math.max(shape.published?.version ?? 0, ...shape.versions.map((v) => v.version), 0) + 1;\n const published: InterfacePublished = { pages: shape.draft.pages, version, at, by };\n return { ...shape, published, versions: [published, ...shape.versions].slice(0, INTERFACE_VERSIONS_KEPT) };\n}\n\n/** CLEAR UNPUBLISHED CHANGES: the draft goes back to what viewers see. */\nexport function clearUnpublished(shape: InterfaceShape): InterfaceShape {\n if (!shape.published) return shape;\n return { ...shape, draft: { pages: shape.published.pages } };\n}\n\n/** RESTORE a version INTO THE DRAFT (Airtable's way): the builder looks, then publishes. */\nexport function restoreInterfaceVersion(shape: InterfaceShape, version: number): InterfaceShape {\n const found = shape.versions.find((v) => v.version === version);\n return found ? { ...shape, draft: { pages: found.pages } } : shape;\n}\n\n/** Replace one draft page. */\nexport function withDraftPage(shape: InterfaceShape, page: InterfacePage): InterfaceShape {\n return { ...shape, draft: { pages: shape.draft.pages.map((p) => (p.id === page.id ? page : p)) } };\n}\n\n/**\n * A CHART EDITED IN THE DRAFT. A chart the published version also shows, with different settings, is copied\n * under a new id so viewers keep theirs until Publish; the page's block order follows the new id.\n */\nexport function withDraftChart(shape: InterfaceShape, page: InterfacePage, chart: ChartSpec): InterfacePage {\n const published = (shape.published?.pages ?? []).flatMap((p) => p.charts).find((c) => c.id === chart.id);\n if (!published || same(published, chart)) {\n return { ...page, charts: page.charts.map((c) => (c.id === chart.id ? chart : c)) };\n }\n const id = newBlockId();\n return {\n ...page,\n charts: page.charts.map((c) => (c.id === chart.id ? { ...chart, id } : c)),\n blocks: page.blocks.map((b) => (b.kind === \"chart\" && b.id === chart.id ? { ...b, id } : b)),\n };\n}\n\n/** A new page, empty or with one starter element. */\nexport function newInterfacePage(name: string, blocks: PageBlock[] = [], charts: ChartSpec[] = []): InterfacePage {\n return { id: newBlockId(), name, blocks, charts };\n}\n\n/** A fresh interface on one table: an Overview page with that table's records, nothing published yet. */\nexport function newInterfaceShape(tableId: Uuid): InterfaceShape {\n const list = newBlockId();\n return {\n icon: \"layout-dashboard\",\n color: \"blue\",\n draft: {\n pages: [\n newInterfacePage(\"Overview\", [\n { id: list, kind: \"list\", table_id: tableId, span: 6 },\n { id: newBlockId(), kind: \"record\", source: list, span: 6 },\n ]),\n ],\n },\n published: null,\n versions: [],\n };\n}\n\n/** The page a viewer is on: by id, else the first one. */\nexport function pageById(pages: readonly InterfacePage[], id: string | null | undefined): InterfacePage | null {\n return pages.find((p) => p.id === id) ?? pages[0] ?? null;\n}\n","// src/tableLanes.ts — @ai-matrx/records-ui · which lane of the tables home one Table sits in, with no React\n//\n// Pure, so `/helpers` carries `laneFor` and a host's table switcher sorts tables before it loads any\n// screen (records-ui front door, 2026-10-16). `TablesHome.tsx` re-exports it. Why the platform's own\n// tables get a lane of their own: the comment above `LANE_EMPTY` in `TablesHome.tsx`.\n\nimport type { Table } from \"@ai-matrx/records\";\n\nexport type TableLane = \"mine\" | \"organization\" | \"system\" | \"community\" | \"app\";\n\n/** The slug prefix of the tables this package keeps for itself (saved views, comments). */\nexport const PLATFORM_TABLE_PREFIX = \"records_ui_\";\n\n/**\n * WHETHER THE STORE ITSELF KEEPS THIS TABLE FOR THE APP — a choice list made per\n * choice field, for one. The Table record's document carries `kept_by_the_app:\n * true`, and `tableList()` spreads the whole document onto the Table; the\n * `Table` interface does not declare it yet, so it is read through this one\n * narrow cast.\n *\n * 🚨 MEASURED ON RINCON PLUMBING CO (VERIFIER-15): 13 \"Crew choices\" and 14\n * \"Status choices\" tables sat under My organization here, beside Jobs and\n * Invoices, while the organization hub above them already counted them as the\n * app's. Two lists on one page disagreed about the same 27 tables. They go to\n * the app's lane, with the saved views.\n */\nexport function platformOwned(table: Table): boolean {\n // `platform_owned` is the store's answer (the facts door); `kept_by_the_app` is the stored document key.\n const t = table as unknown as { platform_owned?: unknown; kept_by_the_app?: unknown };\n return t.platform_owned === true || t.kept_by_the_app === true;\n}\n\n/** Which lane one Table belongs to, from the record's own columns. */\nexport function laneFor(table: Table): TableLane {\n if (table.is_kernel) return \"system\";\n if ((table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX) || platformOwned(table)) return \"app\";\n if (publishedToWeb(table)) return \"community\";\n if (shownToOnlyMe(table)) return \"mine\";\n return \"organization\";\n}\n\n/** Published to the web — the store's own column, else its old lane word. */\nexport function publishedToWeb(table: Table): boolean {\n if (typeof table.published_to_web === \"boolean\") return table.published_to_web;\n return table.visibility === \"public\" || table.visibility === \"link\";\n}\n\n/** Shown to \"Only me\" — the store's own column, else its old lane word. */\nexport function shownToOnlyMe(table: Table): boolean {\n if (table.shown_to !== undefined) return table.shown_to === \"only_me\";\n return table.visibility === \"personal\";\n}\n","// src/bodyField.ts — @ai-matrx/records-ui · which column a record page writes its body in, with no React\n//\n// Pure, so `/helpers` carries it (records-ui front door, 2026-10-16). `RecordBody.tsx` re-exports it.\n\nimport type { Field } from \"@ai-matrx/records\";\nimport { newerKindOf } from \"@ai-matrx/records/field-kinds\";\n\n/** The names a page's body goes by (Notion's page content), in a person's words. */\nconst BODY_NAMES = /^(notes?|page|body|content|page content|details|description)$/i;\n\n/**\n * The column a record page writes its body in: the formatted-text column NAMED like a page's body\n * (\"Notes\", \"Page content\"…), else the table's first formatted-text column. A \"Caption\" before a\n * \"Notes\" stays a field (walk 2026-10-05: the body took the Caption).\n */\nexport function bodyFieldOf(fields: readonly Field[]): Field | undefined {\n const rich = fields.filter((field) => newerKindOf(field) === \"rich_text\");\n return rich.find((field) => BODY_NAMES.test((field.label ?? field.key).trim()) || BODY_NAMES.test(field.key.replace(/_/g, \" \"))) ?? rich[0];\n}\n","// src/viewKeys.ts — @ai-matrx/records-ui · lane S1-PRIME VIEW-KEYS\n//\n// THE VIEW-KEY REGISTRY MOVED TO `@ai-matrx/records/views` (step 10, 2026-10-08): the declared keys, the one\n// reader and the one writer are headless there. What stays here is this package's LOOK: the grid\n// presentation (colors, formats, frozen columns — `presentation.ts`, built on design-system) bound as the\n// view's presentation codec. Every name this file exported is unchanged.\n\nimport * as base from \"@ai-matrx/records/views\";\nimport { parseGridPresentation, presentationDocument, presentationIsEmpty, type GridPresentation } from \"./presentation\";\n\nexport {\n STORE_KEEPS_SWIPE,\n STORE_KEEPS_TIMELINE,\n STORE_KEPT_LAYOUTS,\n VIEW_KEYS,\n storeKeepsLayout,\n viewKeysFor,\n viewSettingsFor,\n type ViewKeyDeclaration,\n type ViewKeyLayout,\n type ViewKeyWriter,\n type ViewSortKey,\n} from \"@ai-matrx/records/views\";\n\n/** This package's look, as the view's presentation codec. */\nexport const gridPresentationCodec: base.ViewPresentationCodec<GridPresentation> = {\n parse: parseGridPresentation,\n isEmpty: presentationIsEmpty,\n toDocument: (presentation) => JSON.parse(presentationDocument(presentation)) as Record<string, unknown>,\n};\n\n/** EVERY DECLARED KEY OF A VIEW, TYPED, with this package's grid look. */\nexport type ViewSettings = base.ViewSettings<GridPresentation>;\nexport type ViewSettingsPatch = base.ViewSettingsPatch<GridPresentation>;\n\n/** Every view and look door with this package's grid look bound — bindings of records' one definition. */\nexport const boundViews = base.bindViewCodec<GridPresentation>(gridPresentationCodec);\n\n/** THE READER (a stored `definition` and the row's flat `filters` in, every declared key out) and THE WRITER'S SHAPE. */\nexport const { viewSettings, viewSettingsPatch } = boundViews;\n","// src/viewLook.ts — @ai-matrx/records-ui · lane VIEW-STATE-PERSONAL (VERIFIER-23 item 1, 2026-09-25)\n//\n// A LOOK AT A VIEW IS YOURS UNTIL YOU SAVE IT.\n//\n// On production the owner of a maintenance-requests table grouped its board by Status, and the\n// tenant liaison's board came up grouped by Status the next time she opened it: every pick was\n// written onto the shared view. Airtable and Notion keep the two apart — how you are looking at a\n// shared view (its grouping, its date field, its sort, its filter, hidden columns, widths, the\n// layout) is YOUR look, it persists for you, and the view changes only when you press \"Save to\n// view\" (Notion's \"Save for everyone\"), save it as a new view, or \"Reset to view\".\n//\n// The store keeps one look per (person, view) through `custom.view_look_set` / `view_look_read`\n// (viewer on the table, never written onto the view row). This file is the look's shape on this\n// side: the keys a look may hold, how it reads back, how it lays over the view, and what \"Save to\n// view\" sends.\n\nimport * as base from \"@ai-matrx/records/views\";\n\nimport type { GridPresentation } from \"./presentation\";\nimport { boundViews } from \"./viewKeys\";\n\n// The look's logic moved to `@ai-matrx/records/views` (step 10, 2026-10-08); this package binds its grid look.\nexport { applyLook, lookDiffers, lookPart, saveToViewPlan } from \"@ai-matrx/records/views\";\n\n/** What a look may hold, with this package's grid look. */\nexport type ViewLook = base.ViewLook<GridPresentation>;\n\nexport const { lookDocument, lookFromDocument, readLooks, keepLook } = boundViews;\n\n/** The words of the look bar. One sentence, then the doors. */\nexport const LOOK_WORDS = {\n /** The reason, for a tooltip or a screen reader — never a line on the page (interface-text). */\n yours: \"You changed how this view looks. Only you see it.\",\n /** The visible label for the same fact. */\n yoursLabel: \"Only you see this\",\n saveToView: \"Save to view\",\n saveAsNew: \"Save as new view\",\n reset: \"Reset to view\",\n /** The one button your look's doors fold into when the toolbar row has no room for three. */\n folded: \"Your look\",\n newName: \"Name for the new view\",\n} as const;\n\n/**\n * WHAT \"RESET VIEW\" KEEPS (member walk, 2026-10-10). Reset puts back the saved view's QUESTION — search,\n * sort, filter and grouping — and keeps how the person has laid the columns out: their order, widths,\n * frozen columns, hidden columns, row height and layout (Notion's \"Reset\" on unsaved view changes\n * reverts the filters and sorts and leaves the property layout alone; Airtable's per-person column\n * arrangement likewise survives clearing a filter). `null` when nothing of the look is left to keep.\n */\nconst QUESTION_KEYS = [\"sorts\", \"where\", \"groupField\", \"swimlaneField\"] as const;\nexport function lookAfterReset(look: ViewLook | null | undefined): ViewLook | null {\n if (!look) return null;\n const kept: Record<string, unknown> = { ...look };\n for (const key of QUESTION_KEYS) delete kept[key];\n // Grouping lives on the look's presentation (the Group control writes `presentation.grouping`): Reset clears it too.\n const presentation = kept[\"presentation\"];\n if (presentation && typeof presentation === \"object\") {\n const { grouping: _grouping, ...layout } = presentation as Record<string, unknown>;\n if (Object.keys(layout).length > 0) kept[\"presentation\"] = layout;\n else delete kept[\"presentation\"];\n }\n for (const key of Object.keys(kept)) if (kept[key] === undefined) delete kept[key];\n return Object.keys(kept).length > 0 ? (kept as ViewLook) : null;\n}\n","// src/views.ts — @ai-matrx/records-ui · SCR-6, SCR-7, SCR-N-6\n//\n// SAVED VIEWS MOVED TO `@ai-matrx/records/views` (step 10, 2026-10-08): the spec, the layouts, the page-view\n// words and the doors that keep a view (`declareView`, `saveViewPatch`, `designateView`) are headless there.\n// This file binds this package's grid look (`gridPresentationCodec`, viewKeys.ts) so every name it exported\n// keeps its signature: `SavedViewSpec.presentation` is a `GridPresentation` here.\n\nimport * as base from \"@ai-matrx/records/views\";\nimport type { GridPresentation } from \"./presentation\";\nimport { boundViews } from \"./viewKeys\";\n\nexport {\n STORE_KEEPS_TIMELINE,\n STORE_KEPT_LAYOUTS,\n storeKeepsLayout,\n VIEW_LAYOUTS,\n LAYOUT_LABEL,\n wordsList,\n VIEW_NEEDS,\n freeColumnName,\n viewOrderOf,\n defaultViewOf,\n LAYOUT_FIELD_KIND,\n PAGE_VIEWS,\n PAGE_VIEW_LABEL,\n pageViewFromParam,\n unknownViewLine,\n makeDefaultLabel,\n designateView,\n viewPatchFor,\n groupViewsBySection,\n planViewDrop,\n sectionDropId,\n type ViewDropWrite,\n sectionNames,\n sectionNameOk,\n reassignSection,\n type ViewSection,\n type ViewLayout,\n type ViewNeedKind,\n type ViewNeed,\n type ViewSort,\n type ViewOrder,\n type PageView,\n} from \"@ai-matrx/records/views\";\n\n/** THE DECLARATIVE SPEC, with this package's grid look. */\nexport type SavedViewSpec = base.SavedViewSpec<GridPresentation>;\n/** A saved view as it comes back out of the store, with its row's own id. */\nexport type SavedView = base.SavedView<GridPresentation>;\n\n/** The view's doors with this package's grid look bound — bindings of records' one definition. */\nexport const { viewDocument, viewFromRow, declareView, saveViewPatch, viewPatchDocument } = boundViews;\n","// src/viewAddressParams.ts — @ai-matrx/records-ui · the view in the address bar, as words, with no React\n//\n// Pure, so `/helpers` carries it and a host route reads and writes the address before it loads any\n// screen (records-ui front door, 2026-10-16). `viewAddress.ts` re-exports all of it beside its context.\n\n/** The words this feature owns in an address. A host must not use them for anything else. */\nexport const VIEW_ADDRESS_KEYS = [\"sort\", \"cf\", \"q\", \"hide\", \"page\"] as const;\n\nexport type ViewAddressSort = { field: string; direction: \"asc\" | \"desc\" };\n\n/** What the address says about a look. Absent keys say nothing. */\nexport type ViewAddressState = {\n sort?: ViewAddressSort | null;\n /** The grid's column filters, in the grid's own shape (field key → its filter value). */\n filters?: Record<string, unknown>;\n search?: string;\n /** Field keys hidden on this look. */\n hidden?: string[];\n /** 1-based page; 1 is never written. */\n page?: number;\n};\n\nexport function isViewAddressEmpty(state: ViewAddressState | null | undefined): boolean {\n if (!state) return true;\n return (\n !state.sort &&\n Object.keys(state.filters ?? {}).length === 0 &&\n !(state.search ?? \"\").trim() &&\n (state.hidden?.length ?? 0) === 0 &&\n !(state.page && state.page > 1)\n );\n}\n\n/** The state as flat address words. Empty parts are left out, so a plain view has a plain address. */\nexport function viewAddressToParams(state: ViewAddressState | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!state) return out;\n if (state.sort) out[\"sort\"] = `${state.sort.field}:${state.sort.direction}`;\n const filters = Object.fromEntries(Object.entries(state.filters ?? {}).filter(([, v]) => v !== undefined && v !== null));\n if (Object.keys(filters).length > 0) out[\"cf\"] = JSON.stringify(filters);\n if ((state.search ?? \"\").trim()) out[\"q\"] = (state.search ?? \"\").trim();\n if (state.hidden && state.hidden.length > 0) out[\"hide\"] = JSON.stringify(state.hidden);\n if (state.page && state.page > 1) out[\"page\"] = String(Math.floor(state.page));\n return out;\n}\n\n/** The address words back into a state; null when the address says nothing (or only nonsense). */\nexport function viewAddressFromParams(get: (key: string) => string | null | undefined): ViewAddressState | null {\n const out: ViewAddressState = {};\n const sort = get(\"sort\");\n if (sort) {\n const at = sort.lastIndexOf(\":\");\n const field = at > 0 ? sort.slice(0, at) : \"\";\n const dir = at > 0 ? sort.slice(at + 1) : \"\";\n if (field && (dir === \"asc\" || dir === \"desc\")) out.sort = { field, direction: dir };\n }\n const cf = get(\"cf\");\n if (cf) {\n try {\n const parsed: unknown = JSON.parse(cf);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) out.filters = parsed as Record<string, unknown>;\n } catch {\n /* a broken filter word says nothing */\n }\n }\n const q = get(\"q\");\n if (q && q.trim()) out.search = q.trim();\n const hide = get(\"hide\");\n if (hide) {\n try {\n const parsed: unknown = JSON.parse(hide);\n if (Array.isArray(parsed)) {\n const keys = parsed.filter((k): k is string => typeof k === \"string\");\n if (keys.length > 0) out.hidden = keys;\n }\n } catch {\n /* ditto */\n }\n }\n const page = Number(get(\"page\"));\n if (Number.isInteger(page) && page > 1) out.page = page;\n return isViewAddressEmpty(out) ? null : out;\n}\n\n/** Two states that say the same thing — so a report that changes nothing is never sent. */\nexport function sameViewAddress(a: ViewAddressState | null | undefined, b: ViewAddressState | null | undefined): boolean {\n return JSON.stringify(viewAddressToParams(a)) === JSON.stringify(viewAddressToParams(b));\n}\n","// src/calendarFeed.ts — @ai-matrx/records-ui · CAL-FEED-UI\n//\n// THE PRIVATE CALENDAR LINK, as the screens see it. The doors (create / rotate / revoke / list) are\n// the host's: they live in the `users` schema, not in the records store, so the host binds them as\n// ONE port (`RecordsUiHost.calendarFeed`). A host without the port has no link to give, so the menu\n// entry is absent, never dead. The token is shown ONCE — only its first characters are ever listed.\n\nimport type { ObjectAction } from \"./objectActions\";\n\n/** What a door answers when it mints or changes a link. The token is the only time it is seen. */\nexport interface CalendarFeedMade {\n id: string;\n token: string;\n expires_at: string | null;\n}\n\n/** One line of the person's list. Never a token — `token_prefix` is its first characters. */\nexport interface CalendarFeedRow {\n id: string;\n title: string;\n organization_id: string;\n table_id: string;\n view_id: string | null;\n token_prefix: string;\n time_zone: string;\n created_at: string;\n expires_at: string | null;\n last_read_at: string | null;\n read_count: number;\n expired: boolean;\n}\n\nexport interface CalendarFeedPort {\n create(args: {\n organizationId: string;\n tableId: string;\n viewId: string;\n title: string;\n timeZone: string;\n }): Promise<CalendarFeedMade>;\n rotate(id: string): Promise<CalendarFeedMade>;\n revoke(id: string): Promise<void>;\n list(): Promise<CalendarFeedRow[]>;\n /** The https address a calendar app reads for this token (the host's route). */\n urlFor(token: string): string;\n}\n\n/** webcal:// is the same address, asking the calendar app to subscribe. */\nexport function webcalUrl(httpsUrl: string): string {\n return httpsUrl.replace(/^https?:\\/\\//i, \"webcal://\");\n}\n\n/** Google Calendar's \"add by URL\": the webcal address, encoded whole into `cid`. */\nexport function googleCalendarUrl(httpsUrl: string): string {\n return `https://calendar.google.com/calendar/r?cid=${encodeURIComponent(webcalUrl(httpsUrl))}`;\n}\n\nexport const SUBSCRIBE_ACTION_ID = \"subscribe-calendar\";\n\n/** \"Subscribe in your calendar…\" in the table's one action list. */\nexport function subscribeCalendarAction(args: {\n disabledReason?: string | undefined;\n run: () => void | Promise<void>;\n}): ObjectAction {\n return {\n id: SUBSCRIBE_ACTION_ID,\n label: \"Subscribe in your calendar…\",\n icon: \"calendar-clock\",\n group: \"share\",\n ...(args.disabledReason ? { disabledReason: args.disabledReason } : {}),\n run: args.run,\n };\n}\n","// src/enumLabels.ts — @ai-matrx/records-ui\n//\n// ONE LABEL MAP PER ENUM. NOTHING ELSE IN THIS PACKAGE OWNS A COPY.\n//\n// Lane FRONT-DOOR's finding (2026-09-21): about twenty sites in this package\n// turned an enum VALUE the store already canonicalizes into a person-facing\n// word, each one on its own — worst example, `ChecklistRunner.tsx` called the\n// work-due state \"finished\" **\"Done\"** while `ActionInbox.tsx`, reading the\n// SAME `WorkDueState` off the SAME `custom.work_inbox`/`checklist_run` doors,\n// called it **\"Finished\"**. A person moving between a table's checklist tab\n// and her inbox saw two different words for one fact about her own work.\n//\n// So every enum this package draws a label for is named ONCE, here, keyed by\n// its canonical values — imported from `@ai-matrx/records` wherever the store\n// exports a named type/const for it, and named locally (with the reason) where\n// it does not. A panel imports the map; it never writes its own.\n//\n// THE GUARD: `enumLabels.test.tsx` renders every converted panel's label\n// function over the FULL canonical value list of its enum (pulled from\n// `@ai-matrx/records`, not retyped) and fails the moment a value has no entry\n// or a caller falls through to the raw token. See that file for RED/GREEN.\n\nimport type {\n ChecklistRequirementKind,\n ContextPolicy,\n FieldSensitivity,\n StageRuleOnFail,\n SubscriptionCadence,\n WorkDueState,\n WorkInboxKind,\n WorkApprovalState,\n} from \"@ai-matrx/records\";\n\n/**\n * An array literal checked, AT COMPILE TIME, to name every member of `T` and no\n * extra one. `WorkDueState`, `WorkInboxKind`, `ChecklistRequirementKind` and\n * `SubscriptionCadence` are typed unions in `@ai-matrx/records` with no\n * runtime array exported alongside them — so this is how the four `*_VALUES`\n * lists below stay tied to the PACKAGE'S OWN TYPE instead of drifting from it\n * by hand: add a sixth `WorkDueState` in `@ai-matrx/records` and `tsc` refuses\n * this file until the array is updated to name it too. The census test below\n * imports these arrays rather than the store's raw union so it is exercising\n * the same list this file's label maps are keyed against.\n */\nfunction exhaustiveValuesOf<T extends string>() {\n return function <const U extends readonly T[]>(values: [T] extends [U[number]] ? U : never): U {\n return values as U;\n };\n}\n\n// ── work due state — WorkDueState (packages/records/src/work.ts) ───────────\n//\n// Shared by a checklist step (`checklist_run().due_state`) and a work-inbox\n// row (`work_inbox().due_state`, `work_list().due_state`) — ONE enum, drawn in\n// both a checklist runner and an approvals inbox. This is the pair the finding\n// named: \"finished\" read \"Done\" in one and \"Finished\" in the other. **\"Done\"\n// wins** — it is the word a non-technical business owner actually says out\n// loud about a piece of work (\"is that job done yet?\"), it is one syllable\n// shorter than the other four words in this set are used to being read\n// alongside (\"Overdue\", \"Today\", \"Scheduled\", \"No date\"), and \"Finished\" reads\n// more like a formal status report than a plain answer to \"is it done\".\nexport const WORK_DUE_STATES = exhaustiveValuesOf<WorkDueState>()([\n \"overdue\",\n \"due_today\",\n \"scheduled\",\n \"undated\",\n \"finished\",\n]);\nexport const DUE_STATE_LABEL: Record<WorkDueState, string> = {\n overdue: \"Overdue\",\n due_today: \"Today\",\n scheduled: \"Scheduled\",\n undated: \"No date\",\n finished: \"Done\",\n};\n\n// ── work inbox kind — WorkInboxKind (packages/records/src/work.ts) ─────────\nexport const WORK_INBOX_KINDS = exhaustiveValuesOf<WorkInboxKind>()([\"assignment\", \"approval\", \"proposal\"]);\n// UI-FIX-19 (VERIFIER-19 #6): a kind is a NOUN. \"Approve\" in the row's bordered kind badge read as\n// a live Approve control on every withdrawn and decided item; only a control may be a verb.\nexport const WORK_INBOX_KIND_LABEL: Record<WorkInboxKind, string> = {\n assignment: \"Assigned\",\n approval: \"Approval\",\n proposal: \"Agent proposal\",\n};\n/** The heading an inbox grouped by kind reads (lane S5-PRIME) — plural, the way Linear groups. */\nexport const WORK_INBOX_KIND_GROUP_LABEL: Record<WorkInboxKind, string> = {\n approval: \"Approvals\",\n proposal: \"Agent proposals\",\n assignment: \"Assigned to you\",\n};\n\n// ── approval state — WorkApprovalState (packages/records/src/work.ts) ──────\n// Lane S5-PRIME: a closed item says what happened to it. `withdrawn` is the store's own close —\n// the thing it would change was archived — never a person's decision.\nexport const WORK_APPROVAL_STATES = exhaustiveValuesOf<WorkApprovalState>()([\"pending\", \"approved\", \"declined\", \"withdrawn\"]);\nexport const WORK_APPROVAL_STATE_LABEL: Record<WorkApprovalState, string> = {\n pending: \"Waiting\",\n approved: \"Approved\",\n declined: \"Declined\",\n withdrawn: \"Withdrawn\",\n};\n\n// ── checklist requirement kind — ChecklistRequirementKind (checklist.ts) ───\nexport const CHECKLIST_REQUIREMENT_KINDS = exhaustiveValuesOf<ChecklistRequirementKind>()([\n \"none\",\n \"note\",\n \"answer\",\n \"record_field\",\n \"form\",\n \"document\",\n]);\nexport const CHECKLIST_REQUIREMENT_LABEL: Record<ChecklistRequirementKind, string> = {\n none: \"\",\n note: \"Say what you did\",\n answer: \"Fill this in\",\n record_field: \"This has to be filled in on the record\",\n form: \"This step is a form\",\n document: \"This step is a document\",\n};\n\n// ── field sensitivity — FieldSensitivity (vocabulary.ts, FLD-12/AGT-7) ─────\n// THE WORDS MATCH THE STORE'S OWN RULE (knob `custom/field_sensitivity_levels`, read live 2026-10-21):\n// internal reads at Viewer, confidential and restricted at ADMIN (Arman, 2026-10-20: a Confidential column is hidden\n// below admin unless someone is granted it; lane CONFIDENTIAL-DEFAULT moved confidential from Editor). Every member\n// starts as an Editor (`custom/member_default_level`), so both words hide a column from members; a share of the\n// column itself opens it. Organizations may override the knob; the column-access screen reads it live.\n// Guard: `a-sensitivity-word-says-who-it-hides-from.test.tsx` reads these against the store's knob.\nexport const FIELD_SENSITIVITY_LABEL: Record<FieldSensitivity, string> = {\n public: \"Anyone who can open the record\",\n internal: \"People in this organization\",\n confidential: \"Administrators and anyone granted it\",\n restricted: \"Administrators only\",\n};\n\n// ── context policy — ContextPolicy (vocabulary.ts, FLD-12) ─────────────────\n// Whether an agent may see a Field's values at all — not `Delivery` (how much\n// of a merge field's value reaches a turn), a different vocabulary entirely.\nexport const CONTEXT_POLICY_LABEL: Record<ContextPolicy, string> = {\n include: \"Yes, an assistant can read it\",\n summarize: \"Only a summary of it\",\n on_request: \"Only on request\",\n exclude: \"No, keep it away from assistants\",\n};\n\n// ── stage-rule on_fail — StageRuleOnFail (pipeline.ts) ──────────────────────\nexport const STAGE_RULE_ON_FAIL_LABEL: Record<StageRuleOnFail, string> = {\n refuse: \"Turn it away\",\n require_approval: \"Ask for approval\",\n};\n\n// ── subscription cadence — SubscriptionCadence (subscription.ts) ───────────\n//\n// `DigestScheduler.tsx` carries its own copy of this enum's words as a\n// grammatical FRAGMENT dropped into a sentence (\"arrives the moment something\n// arrives\") rather than a standalone label (\"hourly summary\") — a different\n// job for the same four values. That file is owned by another lane right now\n// (lane preamble's do-not-touch list) so it is left exactly as it is; this map\n// is the standalone-label form used by every OTHER site that names a cadence.\nexport const SUBSCRIPTION_CADENCES = exhaustiveValuesOf<SubscriptionCadence>()([\"instant\", \"hourly\", \"daily\", \"weekly\"]);\nexport const SUBSCRIPTION_CADENCE_LABEL: Record<SubscriptionCadence, string> = {\n instant: \"as it happens\",\n hourly: \"hourly summary\",\n daily: \"daily summary\",\n weekly: \"weekly summary\",\n};\n\n// ── subscription channel — no named export in @ai-matrx/records ───────────\n//\n// `Subscription.channel` is typed inline as `\"in_app\" | \"email\" | \"sms\"`\n// (subscription.ts) with no exported const array, so the value list below IS\n// the canonical list — the same three literals the store's type carries.\nexport const SUBSCRIPTION_CHANNEL_VALUES = [\"in_app\", \"email\", \"sms\"] as const;\nexport type SubscriptionChannel = (typeof SUBSCRIPTION_CHANNEL_VALUES)[number];\n// `NotifyRuleEditor.tsx` used to say plain \"by email\" / \"by text\" with no\n// caveat; `SubscriptionsPanel.tsx` (and the untouched `DigestScheduler.tsx`)\n// say \"only if an address/number is on the account\". **The caveat wins** — a\n// person choosing email delivery needs to know up front that it silently does\n// nothing without an address on file, the way Linear and Notion surface a\n// precondition next to the control rather than failing quietly later.\nexport const SUBSCRIPTION_CHANNEL_LABEL: Record<SubscriptionChannel, string> = {\n in_app: \"in the app\",\n email: \"by email — only if an address is on the account\",\n sms: \"by text — only if a number is on the account\",\n};\n\n// ── rollup aggregate operation — NewFieldDeclaration[\"agg\"] (field.ts) ─────\n//\n// `field.ts` types this inline (`agg?: \"sum\" | \"count\" | \"min\" | \"max\" |\n// \"avg\"`) with no exported const array, so — same as the channel above — the\n// list below IS the canonical list.\nexport const ROLLUP_AGG_VALUES = [\n \"count\", \"sum\", \"avg\", \"min\", \"max\",\n // AIRTABLE PARITY (lane AT-FORMULA): the aggregates that read the linked values as they are.\n \"countall\", \"counta\", \"and\", \"or\", \"xor\", \"arrayjoin\", \"concatenate\", \"arrayunique\", \"arraycompact\",\n] as const;\nexport type RollupAgg = (typeof ROLLUP_AGG_VALUES)[number];\nexport const ROLLUP_AGG_LABEL: Record<RollupAgg, string> = {\n count: \"How many there are\",\n sum: \"The total of\",\n avg: \"The average of\",\n min: \"The smallest\",\n max: \"The largest\",\n countall: \"How many values, empty ones too\",\n counta: \"How many values are filled in\",\n and: \"Yes when every value is yes\",\n or: \"Yes when any value is yes\",\n xor: \"Yes when an odd number are yes\",\n arrayjoin: \"All the values, joined with commas\",\n concatenate: \"All the values, run together\",\n arrayunique: \"Each different value once\",\n arraycompact: \"The values that are filled in\",\n};\n\n// ── formula operation — the FormulaOperations menu (FieldEditor.tsx) ───────\n//\n// No `@ai-matrx/records` type names this set at all; it is this package's own\n// menu of what a two-column formula field can do, so this file is its one\n// canonical home.\nexport const FORMULA_OP_VALUES = [\"concat\", \"add\", \"sub\", \"mul\", \"div\"] as const;\nexport type FormulaOp = (typeof FORMULA_OP_VALUES)[number];\nexport const FORMULA_OP_LABEL: Record<FormulaOp, string> = {\n concat: \"Join them together\",\n add: \"Add them up\",\n sub: \"Take the second from the first\",\n mul: \"Multiply them\",\n div: \"Divide the first by the second\",\n};\n/** Whether this operation reads naturally as \"X and Y and Z…\" over more than two columns. */\nexport const FORMULA_OP_JOINS: Record<FormulaOp, boolean> = {\n concat: true,\n add: true,\n sub: false,\n mul: true,\n div: false,\n};\n\n// ── field validation-rule kind — FieldRule[\"kind\"] (field.ts) ──────────────\n//\n// `field.ts` types this inline with no exported const array; canonical here.\nexport const FIELD_RULE_KIND_VALUES = [\"min\", \"max\", \"length\", \"pattern\", \"equals_field\", \"differs_from_field\"] as const;\nexport type FieldRuleKindValue = (typeof FIELD_RULE_KIND_VALUES)[number];\nexport const FIELD_RULE_KIND_LABEL: Record<FieldRuleKindValue, string> = {\n min: \"At least\",\n max: \"At most\",\n length: \"Number of characters\",\n pattern: \"Looks like\",\n equals_field: \"Same as the column\",\n differs_from_field: \"Different from the column\",\n};\n\n// ── proposed-change act — `ProposedChange[\"act\"]` (ProposalRow.tsx, package-local) ──\n//\n// This type is not in `@ai-matrx/records` (`ProposalRow.tsx` declares it\n// itself, for an agent's field/table proposal), so it is canonical here.\nexport const PROPOSED_CHANGE_ACT_VALUES = [\"add\", \"update\", \"remove\"] as const;\nexport type ProposedChangeAct = (typeof PROPOSED_CHANGE_ACT_VALUES)[number];\nexport const PROPOSED_CHANGE_ACT_LABEL: Record<ProposedChangeAct, string> = {\n add: \"Add\",\n update: \"Update\",\n remove: \"Remove\",\n};\n\n// ── booking-page state — `FormSummary[\"state\"]` / `BookingSummary` (rule.ts) ──\n//\n// `rule.ts` types this inline (`\"draft\" | \"open\" | \"closed\" | \"full\"`) with no\n// exported const array; canonical here.\nexport const BOOKING_PAGE_STATE_VALUES = [\"draft\", \"open\", \"closed\", \"full\"] as const;\nexport type BookingPageState = (typeof BOOKING_PAGE_STATE_VALUES)[number];\nexport const BOOKING_PAGE_STATE_LABEL: Record<BookingPageState, string> = {\n draft: \"Not open yet — nobody can book until you open it.\",\n open: \"Open. Anyone with the link can book a time.\",\n closed: \"Closed. The link still works and says you are not taking bookings.\",\n full: \"Every time you offered is taken.\",\n};\n\n// ── value-envelope absence word — `ValueEnvelope.absent` (record.ts) ───────\n//\n// Kept for completeness of the census: `values.tsx` mapped each absence word\n// to itself (`\"none\" → \"none\"`), which is a passthrough with a safe fallback\n// rather than a wording decision, so there is no conflict to resolve — this is\n// still its one home so a future word change happens in one place.\nexport const ABSENCE_WORD_VALUES = [\"never asked\", \"none\", \"refused\", \"conflicting\"] as const;\nexport type AbsenceWord = (typeof ABSENCE_WORD_VALUES)[number];\nexport const ABSENCE_WORD_LABEL: Record<AbsenceWord, string> = {\n \"never asked\": \"never asked\",\n none: \"none\",\n refused: \"refused\",\n conflicting: \"conflicting\",\n};\n","// src/standardFieldChoices.ts — @ai-matrx/records-ui · what a field of a standard table can be, with no React\n//\n// Pure, so `/helpers` carries `CUSTOM_FIELD_ADDABLE_TYPES` and a host settings page lists the\n// addable types before it loads any screen (records-ui front door, 2026-10-16). `FieldEditor.tsx`\n// and `CustomFieldsSection.tsx` re-export these.\n\nimport { DECLARABLE_FIELD_KINDS } from \"@ai-matrx/records/field-kinds\";\nimport { FIELD_TYPE_CHOICES, isSystemFieldKind, type FieldTypeChoice } from \"./fieldTypes\";\n\n/**\n * WHAT A FIELD OF A STANDARD TABLE CAN BE — every kind that HOLDS a value there (lane 7 W1, fix\n * round 1). The store's own kind registry (`custom.field_kinds()`, generated into\n * `DECLARABLE_FIELD_KINDS`) says what each kind is made of; a kind whose behavior is `formula` —\n * Borrowed value, Total, Count, Worked out, and the stamps (Record number, Created / Last changed\n * time), which are formula words — is worked out by `custom.rule_eval` over a custom record, and a\n * standard row is never worked out. Measured on the clone 2026-10-02 (a CRM company; every kind\n * declared, a realistic value written through `custom.entity_row_write`, read back through\n * `custom.entity_record_read`): every other kind came back holding its value; every formula kind\n * came back null. So a record page offers exactly the kinds that hold a value, read from the\n * store's registry — one source, no hand list. A kind the registry does not publish is not offered.\n */\nconst STORE_BEHAVIOUR = new Map<string, string>(DECLARABLE_FIELD_KINDS.map((row) => [row.kind as string, row.behavior as string]));\n\n/** True when a field of this kind holds a value on a standard table's row. */\nexport function holdsAValueOnAStandardTable(kind: string): boolean {\n if (isSystemFieldKind(kind)) return false;\n const behaviour = STORE_BEHAVIOUR.get(kind);\n return behaviour !== undefined && behaviour !== \"formula\";\n}\n\n/** What a record page's Add field offers: `fieldTypes.ts`'s choices, less what cannot hold a value there. */\nexport const STANDARD_TABLE_FIELD_CHOICES: FieldTypeChoice[] = FIELD_TYPE_CHOICES.filter((c) =>\n holdsAValueOnAStandardTable(c.id),\n);\n\n\n/**\n * WHAT A PERSON CAN ADD FROM A RECORD PAGE: EVERYTHING A TABLE'S COLUMN CAN BE.\n *\n * 🚨 G3 — ONE PALETTE (lane 7 STANDARD-TABLES, wave 1). This used to be a hand-kept list of\n * eleven types (`ADDABLE_TYPE_IDS`) \"that need nothing more than a name\", so a CRM contact could\n * not get a Choice, a Yes / no or a link to another record, and none of the column's governance —\n * while `custom.entity_field_declare` resolves its spec through the very `custom._field_document_for`\n * a custom table's column goes through. A standard table and a custom table are one primitive, so\n * the record page opens the table's own `FieldEditor` and offers `fieldTypes.ts`'s pickable set\n * less the kinds that cannot hold a value on a standard row (`STANDARD_TABLE_FIELD_CHOICES`, read\n * from the store's kind registry). `a-record-page-adds-a-field-with-the-tables-own-palette.test.tsx`\n * fails the moment this list and that set differ.\n */\nexport const ADDABLE_TYPES = STANDARD_TABLE_FIELD_CHOICES.map((choice) => ({\n value: choice.id as string,\n label: choice.label,\n}));\n","// src/plainWords.ts — @ai-matrx/records-ui\n//\n// THE ONE FORMATTER EVERY REFUSAL PASSES THROUGH.\n//\n// WHAT A PERSON READ (independent verdict, sixth pass, 19-20 September):\n//\n// \"You do not have access to this table, so custom.applicable_fields has\n// nothing to show you.\"\n// \"config.via names a relation Field of this same table, by its key… The\n// store's code for this was 23514.\"\n//\n// The verdict's third measured gap against Airtable, Notion and Linear was\n// exactly this: \"The machinery still shows through… two column types answer\n// with a contract row id and a SQL error number. Airtable, Notion and Linear\n// never show a person an internal name.\"\n//\n// WHY FILTERING THE HINT WAS NOT ENOUGH. The previous pass filtered the store's\n// HINT — the half written for whoever fixes the caller — and printed the\n// MESSAGE verbatim, because the store writes good messages. Most of them are\n// good. But the store's access refusals are built by `format()` from the DOOR'S\n// OWN NAME (`assert_client_may_change`: \"…so % may not write to it\", with the\n// door name substituted in), so the machine identity is IN the sentence a\n// person reads and no amount of hint-filtering reaches it.\n//\n// SO: ONE function, here, and every screen in this package renders what it\n// returns and nothing else. It does three things and refuses to do a fourth:\n//\n// 1. It KEEPS the store's own words wherever they are a person's words. The\n// store writes the best sentences in this feature (\"Being a member of the\n// organization is not by itself permission to rewrite somebody else's\n// row\") and this package does not rewrite them.\n// 2. It DROPS the clause that carries machine identity, by SHAPE — a\n// schema-qualified object, a document path, a contract row id, a SQLSTATE,\n// a uuid, a bare snake_case token. Dropped, never deleted: it joins the\n// SQLSTATE on the notice for whoever has to debug it.\n// 3. It ADDS a REMEDY — the sentence that says what to do now — keyed off the\n// store's own refusal code, because a refusal with nothing to do about it\n// is a dead end with an explanation.\n//\n// 4. It does NOT invent a diagnosis. When every clause of a message is\n// machine identity there is nothing honest left to say about the specifics,\n// so it says what happened in general terms and offers the remedy. Making\n// something up would be worse than the identifier it replaced.\n//\n// The guard for all of this is `demo/plain-words.test.tsx` plus the sweep in\n// `demo/honest.test.tsx`, which reads the RENDERED text of the real screens and\n// fails on any of the shapes below. A formatter nobody is forced through is a\n// formatter somebody bypasses next week.\n\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n/**\n * MACHINE IDENTITY, BY SHAPE — never by a list of the sentences we happen to\n * have seen, because the next refusal is one nobody has read yet.\n *\n * `FLD-11:` / `REC-29:` / `AGT-7:` a contract row id\n * `custom.field_declare` a schema-qualified database object\n * `config.via` / `data.fields` a path inside a stored document\n * `retention_days` a document key, snake_case\n * `8f2c1b0a-…` a uuid\n * `23514` / `PT409` a SQLSTATE\n * `STORE-TAILS-3:` / `UI-FIX-19:` a build lane's tag (UI-FIX-19)\n */\nexport const MACHINE_IDENTITY: RegExp[] = [\n /\\b[A-Z]{2,4}-\\d{1,3}\\b/,\n // A build lane's tag: capital words joined by hyphens, then a colon (\"STORE-TAILS-3:\",\n // \"MOVE-AND-OUTSIDER:\"). A person never reads which lane wrote a sentence.\n /\\b[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+:/,\n /\\b(?:custom|platform|iam|history|public|auth|campaign_watch)\\.[a-z_]+/,\n /\\b(?:config|data|document|spec|patch)\\.[a-z_]+/,\n /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/i,\n /\\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\\b/,\n // Five characters of digits and capitals, at least one a digit — so `23514`\n // and `PT409` match and an emphatic `NEVER` does not.\n /\\b(?=[0-9A-Z]{5}\\b)(?=[0-9A-Z]*\\d)[0-9A-Z]{5}\\b/,\n];\n\n/** Whether any shape above appears in this text. */\nexport function isMachineIdentity(text: string): boolean {\n return MACHINE_IDENTITY.some((shape) => shape.test(text));\n}\n\n/**\n * Every fragment of `text` that a person should never have been shown. Used by\n * the suite to say WHAT it found rather than only that it found something.\n */\nexport function machineIdentityIn(text: string): string[] {\n const found: string[] = [];\n for (const shape of MACHINE_IDENTITY) {\n const all = new RegExp(shape.source, shape.flags.includes(\"g\") ? shape.flags : `${shape.flags}g`);\n for (const hit of text.matchAll(all)) if (hit[0]) found.push(hit[0]);\n }\n return [...new Set(found)];\n}\n\n/** What the notice is called. The store's code, in the words of what went wrong. */\nconst TITLE: Record<string, string> = {\n stale_write: \"Someone else wrote first\",\n door: \"You do not have access to this\",\n door_absent: \"That is not built yet\",\n refused_by_rule: \"That value was not accepted\",\n invalid_argument: \"That was not accepted\",\n not_found: \"Not there any more\",\n missing_reference: \"That points at something that is not there\",\n already_exists: \"That already exists\",\n not_supported: \"That cannot be done here\",\n store_limit: \"This has got as big as it can\",\n // 🚨 NOT \"THE SWITCH IS OFF\" (lane 7 W1 fix round 1). PGRST202 / PGRST205 land here, and the\n // commonest cause is a door this screen asks for that the database it talks to does not serve\n // YET — a release in flight. Telling the person her organization has its store switched off was\n // false (the switch is answered by its own door, `platform.unified_data_store_on`). Honest:\n // nothing happened, and it is ours, and it passes.\n store_not_served: \"This isn't available right now\",\n unreachable: \"We could not reach your data\",\n needs_approval: \"This is waiting on someone's approval\",\n stale_read: \"Your view of this is a moment behind\",\n timed_out: \"That took too long to answer\",\n internal: \"Something went wrong at our end\",\n};\n\n/**\n * WHAT TO DO NOW. One sentence per refusal code, and it is the whole reason\n * this file exists rather than a regular expression in `Refusal.tsx`: a\n * sentence that names what went wrong and nothing to do about it is a dead end.\n */\nconst REMEDY: Record<string, string> = {\n stale_write:\n \"Look at what they wrote. Keep theirs, or try again and yours goes on top.\",\n door:\n \"Ask somebody who administers this to share it with you at the level you need.\",\n door_absent:\n \"There is nothing to do here yet. It is on our list, not yours.\",\n refused_by_rule: \"Change the value so it passes, then try again.\",\n invalid_argument: \"Change what you entered, then try again.\",\n not_found:\n \"It may have been deleted. Go back to the list and open it again from there.\",\n missing_reference: \"Pick something that is still there.\",\n already_exists: \"Use a different name.\",\n not_supported: \"There is another way to do this — ask, and we will point you at it.\",\n store_limit: \"Split it up, or ask us to raise the ceiling for your organization.\",\n store_not_served: \"Nothing was changed. Try again in a few minutes.\",\n // 🚨 NOTHING WAS WRITTEN AND NOTHING WAS REFUSED (lane TAILS-6). The call\n // never arrived, so \"try again\" is the honest instruction rather than a\n // consolation — and saying nothing changed is the half a person actually\n // worries about.\n unreachable:\n \"Nothing was changed. Check your connection and open this again.\",\n needs_approval:\n \"Nothing was changed yet. The people who can approve it have been asked.\",\n stale_read: \"Open this again in a moment and it will be up to date.\",\n // 🚨 ONE REMEDY THAT IS TRUE OF EVERY DOOR (lane CHAIR-STORE-PERF, 2026-10-03). The store cancels the\n // WHOLE statement at its clock, so a timed-out door wrote nothing — a create, a column add and a page\n // read alike. \"Try a smaller page\" was written for the page read and was printed to a person adding\n // one row to a three-row table (clone walk, 2026-10-03; the clock was a lock another lane's\n // rehearsal held, not the row). A door whose page can shrink says so in its own hint, which wins here.\n // ONE SENTENCE, NOT TWO (lane TIMEOUT-ONE-SENTENCE, 2026-10-19): the shared timed-out sentence (\"That took too long.\n // Nothing was lost; try again.\") already says what happened and what to do, so the table adds NO second remedy\n // (\"Nothing was changed\" was also wrong on a read). Empty = the notice prints no remedy line and the one-line\n // form is the sentence alone. A door's own hint still wins.\n timed_out: \"\",\n internal:\n \"Nothing you did caused this. Try again, and tell us if it keeps happening.\",\n};\n\n/**\n * 🚨 A HINT THIS PACKAGE OR ITS CLIENT WROTE IS NOT A PERSON'S REMEDY.\n *\n * `refusalForAPerson` prefers the DOOR's own hint over the table above, because\n * the door that refused knows more about the way out than a code does. That is\n * right — but it assumed every hint came from the store. It did not: until\n * `@ai-matrx/records` 0.47.0 the client appended its OWN note to `hint` when it\n * met a SQLSTATE it did not know, and the machine-identity filter let it\n * through whenever the code was not exactly five characters (an empty code from\n * a dropped connection, or an HTTP status like `404`). So the Checklists tab of\n * a plumbing company's jobs table told its owner:\n *\n * @ai-matrx/records did not recognize SQLSTATE from checklistTemplates\n *\n * The client no longer writes there. This is the guard on the other side, by\n * SHAPE and not by that one sentence: a hint that talks about a package, a\n * SQLSTATE, or a `camelCaseDoor` is engineer text wherever it came from, and it\n * joins the engineer's line instead of a person's screen.\n */\nexport const ENGINEER_TEXT: RegExp[] = [\n /@ai-matrx\\//,\n /\\bSQLSTATE\\b/i,\n /\\bPostgREST\\b/i,\n /\\bIndexedDB\\b/i,\n // `<RecordsUiProvider>` — a component, on a screen.\n /<\\/?[A-Z][A-Za-z0-9]*\\s*\\/?>/,\n // `savedViews`, `openRecords`, `onReask` — an identifier, however it is\n // quoted. English does not write camelCase; code does.\n /\\b[a-z][a-z0-9]*[A-Z][A-Za-z0-9]*\\b/,\n // A backticked token is a thing you type into an editor, not a thing you do.\n /`[A-Za-z_][A-Za-z0-9_.]*`/,\n // \"bind X on Y\", \"pass X\", \"import X\" — an instruction to whoever maintains\n // the app, arriving on the screen of somebody who cannot act on it.\n /\\bbind\\s+[`'\"A-Za-z]/i,\n];\n\n/**\n * THE ONE GUARD ON A DOOR'S HINT. True when the hint is developer text and must never be\n * printed at a person: engineer shapes (package, SQLSTATE, component, camelCase, backticked\n * token), a code fence, stack-like lines, or a block too long to be one remedy (over 600).\n * Machine clauses INSIDE an otherwise plain hint are cut by `plainSentence`, not by this.\n */\nexport function isDeveloperHint(hint: string): boolean {\n const text = hint.trim();\n if (text === \"\") return false;\n if (text.includes(\"```\")) return true;\n if (/\\n\\s+at\\s+\\S+/.test(text)) return true;\n if (text.length > 600) return true;\n return isEngineerText(text);\n}\n\n/** The hint a person may read: cleaned to people's sentences, or null. The one place that decides. */\nexport function peopleHint(hint: string | null | undefined): string | null {\n const said = (hint ?? \"\").trim();\n if (said === \"\" || isDeveloperHint(said)) return null;\n return plainSentence(said).kept;\n}\n\n/** Whether this sentence was written for whoever maintains the code. */\nexport function isEngineerText(text: string): boolean {\n return ENGINEER_TEXT.some((shape) => shape.test(text));\n}\n\n/** The one shape every screen in this package renders a refusal from. */\nexport interface PlainRefusal {\n /** The heading. Never the store's code. */\n title: string;\n /**\n * What happened, in the store's own words where they are a person's words\n * and in ours where they are not. Never empty.\n */\n sentence: string;\n /** What to do now. Never empty. */\n remedy: string;\n /**\n * TRUE when `sentence` is the store's own words (UI-FIX-19): a notice is then HEADED by that\n * sentence, never by the generic `title` over it.\n */\n storeSaid: boolean;\n /**\n * Everything a person should not read, kept for whoever has to debug it: the\n * SQLSTATE, the hint written for a caller, and any clause dropped above.\n * Kept on the notice's `data-for-engineers` attribute only (UI-FIX-19): never a\n * tooltip, never text a screen can copy or read aloud; never deleted.\n */\n forEngineers: string;\n}\n\n/**\n * A sentence with its machine clauses taken out — or null when nothing honest\n * is left. Clauses are split on the joins the store's own `format()` templates\n * use (\"…, so custom.x may not write to it\", \"… — FLD-11: …\").\n */\nfunction withoutMachineClauses(sentence: string): { kept: string | null; dropped: string[] } {\n const dropped: string[] = [];\n // 🚨 A PARENTHETICAL ID IS EXCISED, NOT A REASON TO BIN THE SENTENCE AROUND IT\n // (lane LIMITS-FIX-UI, 2026-09-21). The store's own way out for a colleague who\n // is not in the organization — \"Invite them to the organization, share with\n // their organization instead (VIS-23), or, if they are a client rather than a\n // colleague, put them in a portal\" — was thrown away WHOLE because of those\n // eight characters, so a plumbing company trying to show one customer her own\n // jobs was told nothing at all about what to do instead. A contract id in\n // brackets is a footnote: lift it out and the sentence around it is a person's\n // sentence. It is still kept for the engineer, below.\n const footnotes: string[] = [];\n const withoutFootnotes = sentence.replace(/\\s*\\((?:see\\s+)?[A-Z]{2,5}-[A-Z0-9-]{1,8}\\)/g, (hit) => {\n footnotes.push(hit.trim());\n return \"\";\n });\n dropped.push(...footnotes);\n const clauses = withoutFootnotes\n .split(/(?:,\\s+so\\s+|\\s+—\\s+|\\s+--\\s+|\\s*\\|\\s*)/)\n .map((clause) => clause.trim())\n .filter((clause) => clause !== \"\");\n const kept = clauses.filter((clause) => {\n if (!isMachineIdentity(clause)) return true;\n dropped.push(clause);\n return false;\n });\n if (kept.length === 0) return { kept: null, dropped };\n // 🚨 A CLEANER THAT DROPPED NOTHING CHANGES NOTHING (same lane, same day).\n //\n // The split above is on the joins the store's `format()` templates use, and\n // \", so \" is one of them — which is also how ordinary English joins two\n // clauses. So \"That person is not in this organization, so they cannot be\n // given access to this table yet.\" came back out as \"That person is not in\n // this organization. they cannot be given access to this table yet.\" — a\n // sentence nobody wrote, with a lower-case word after a full stop, shown to\n // every person every time. Nothing was dropped from it; there was nothing to\n // clean. When that is true the sentence is returned exactly as the store wrote\n // it, and this function's re-joining only ever runs on a sentence it actually\n // took something out of.\n if (dropped.length === 0) return { kept: sentence.trim(), dropped };\n let joined = kept.join(\". \").replace(/\\.\\.+/g, \".\").trim();\n if (!/[.!?]$/.test(joined)) joined = `${joined}.`;\n return { kept: joined, dropped };\n}\n\n/**\n * THE PEOPLE-FACING SENTENCE OF A STORE MESSAGE, AND NOTHING AFTER IT (lane\n * RECORDS-UI-REFUSAL-TEXT, 2026-10-01). A refusal's message is one plain sentence,\n * then ` — ` and developer detail, or a second sentence written for whoever fixes the\n * caller. A person reads the first sentence only; the rest rides `forEngineers`.\n */\nfunction peopleSentence(message: string): { kept: string | null; dropped: string[] } {\n const [lead = \"\", ...tail] = message.split(/\\s+—\\s+|\\s+--\\s+/);\n // A full stop after an abbreviation or an initial (\"Ask Dr. Whitfield\", \"e.g. a quote\") is not an end.\n const sentences = lead.trim().split(/(?<=(?<!\\b(?:Dr|Mr|Mrs|Ms|St|vs|No|e\\.g|i\\.e|etc|[A-Z]))[.!?])\\s+/);\n const first = sentences[0] ?? \"\";\n const rest = [...sentences.slice(1), ...tail].map((part) => part.trim()).filter((part) => part !== \"\");\n const cleaned = plainSentence(first);\n return { kept: cleaned.kept, dropped: [...cleaned.dropped, ...rest] };\n}\n\n/**\n * THE ONE SENTENCE A PERSON READS FOR A REFUSAL — the store's first sentence, or the\n * title when nothing of it is a person's words. Never the hint, details, code or\n * SQLSTATE. Every place that needs a refusal as a string (a toast, a cell, a banner)\n * calls this and nothing else; `check:records-ui-refusal-text` fails on a raw\n * `error.message` / `error.hint` render anywhere else.\n */\nexport function refusalSentence(error: Pick<RecordsError, \"message\"> & Partial<RecordsError>): string {\n return refusalForAPerson(error as RecordsError).sentence;\n}\n\n// A BUILD LABEL OPENING A SENTENCE (lane CLOSE-LINK, CD-LINK-07): the acceptance test or the lane/rule tag the store was\n// built against — \"Test 3 (Reparent):\", \"REC-21:\", \"T5 / VAL-4:\", \"CLOSE-LINK:\". A person never reads it, and it is\n// never a reason to drop the remedy after it (which is what the machine-identity filter did to the whole sentence).\nconst BUILD_LABEL = String.raw`(?:Test \\d+ \\([^)]{1,40}\\)|[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+|[A-Z]{1,5}\\d+[a-z]?)`;\nconst LEADING_BUILD_LABEL = new RegExp(String.raw`^${BUILD_LABEL}(?:\\s*\\/\\s*${BUILD_LABEL})*:\\s+`);\n\n/** The sentence with any build label lifted off its start, the label kept for engineers. */\nfunction withoutBuildLabel(sentence: string): { label: string | null; rest: string } {\n const hit = LEADING_BUILD_LABEL.exec(sentence);\n if (!hit) return { label: null, rest: sentence };\n const rest = sentence.slice(hit[0].length).trim();\n return { label: hit[0].trim(), rest: rest.charAt(0).toUpperCase() + rest.slice(1) };\n}\n\n/** Every sentence of a message, cleaned; the ones that cannot be cleaned are dropped. */\nfunction plainSentence(message: string): { kept: string | null; dropped: string[] } {\n const dropped: string[] = [];\n const kept: string[] = [];\n for (const raw of message.split(/(?<=[.!?])\\s+/)) {\n const labelled = withoutBuildLabel(raw.trim());\n if (labelled.label) dropped.push(labelled.label);\n const sentence = labelled.rest;\n if (sentence === \"\") continue;\n const cleaned = withoutMachineClauses(sentence);\n dropped.push(...cleaned.dropped);\n if (cleaned.kept) kept.push(cleaned.kept);\n }\n return { kept: kept.length === 0 ? null : kept.join(\" \"), dropped };\n}\n\n/** A remedy is a sentence, not the one word left after a build label was lifted off (\"FLD-1: text.\" keeps \"Text.\"). */\nfunction readsAsASentence(text: string | null): boolean {\n return (text ?? \"\").trim().split(/\\s+/).filter(Boolean).length >= 2;\n}\n\n/** The example a pattern refusal carries in its detail, when it carries one. */\nfunction exampleOf(error: RecordsError): string | null {\n const detail = (error as { detail?: unknown }).detail;\n if (!detail || typeof detail !== \"object\") return null;\n const example = (detail as { example?: unknown }).example;\n return typeof example === \"string\" && example.trim() !== \"\" ? example.trim() : null;\n}\n\n/** What a statement timeout says of itself, in place of the database's own words. */\n// ONE SENTENCE EVERYWHERE: the same words as design-system's `TIMED_OUT_SENTENCE` (what every screen prints through\n// `refusalSaid`) and records' `TIMED_OUT_MESSAGE`. This file is the light helpers door, so it cannot import either\n// (design-system's root is heavy); `a-timeout-reads-as-the-platforms-sentence.test.tsx` fails if the three drift.\nconst TIMED_OUT_SAID = \"That took too long. Nothing was lost; try again.\";\n\n/**\n * THE FORMATTER. Every refusal a screen in this package shows goes through\n * here, and nothing in this package renders `error.message` directly.\n */\nexport function refusalForAPerson(error: RecordsError): PlainRefusal {\n const code = error.code ?? \"internal\";\n // A STATEMENT TIMEOUT is the database's words, never a person's (AT-SNAPJOB-2, 2026-10-19: a base rename showed\n // \"canceling statement due to statement timeout\"). Whatever way it arrived (the package's `timed_out`, SQLSTATE\n // 57014, or only Postgres' sentence on an error with no code) it reads as the timed-out refusal: its title and\n // remedy below, and a sentence of our own in place of the database's.\n const timedOut =\n code === \"timed_out\" ||\n (error as { sqlstate?: string }).sqlstate === \"57014\" ||\n /canceling statement due to statement timeout/i.test(String(error.message ?? \"\"));\n // A refusal THIS package wrote (`refusals.ts` marks it `ours`) is whole people-facing prose, a\n // count then a reason; only a door's message is cut after its first sentence.\n const ours = (error as { ours?: unknown }).ours === true;\n const hint = plainSentence(String(error.hint ?? \"\"));\n const message = ours ? plainSentence(String(error.message ?? \"\")) : peopleSentence(String(error.message ?? \"\"));\n\n const title = timedOut ? TITLE[\"timed_out\"]! : (TITLE[code] ?? \"That was refused\");\n\n // 🚨 ONE REMEDY, AND IT IS THE DOOR'S OWN WHEN THE DOOR HAS ONE (lane\n // LIMITS-FIX-UI, 2026-09-21).\n //\n // The table below is a FALLBACK, not an answer. `custom.share_grant` refuses a\n // colleague who is not in the organization with its own three ways forward —\n // *\"Invite them to the organization, share with their organization instead, or,\n // if they are a client rather than a colleague, put them in a portal\"* — and\n // this formatter used to print that AND then \"Change the value so it passes,\n // then try again\", which is not a thing anybody can do about a membership. Two\n // remedies, one of them wrong, is worse than one: a person follows the last\n // sentence they read. The door that refused knows more about the way out than\n // a table keyed on a code does, so its hint wins whenever it survived the\n // machine-identity filter, and the table answers when it did not.\n // 🚨 THE DOOR'S HINT IS THE REMEDY WHEN IT READS AS A PERSON'S SENTENCE (chair ruling,\n // 2026-10-01, restoring the 2026-09-21 one-remedy ruling). A hint that is developer text (a\n // SQL state, a snake_case name, a uuid, a code fence, a stack, a package or component name)\n // is never printed: it rides `forEngineers` and the code's table sentence is the remedy.\n const hintIsForEngineers = isDeveloperHint(String(error.hint ?? \"\"));\n // STORE-RULE-GAPS: a pattern that carries an example hands it over as DATA\n // (`detail.example`), because an example is the person's own shape of value.\n const example = exampleOf(error);\n const remedy =\n (example ? `Enter it like ${example}.` : null) ??\n (hintIsForEngineers || !readsAsASentence(hint.kept) ? null : hint.kept) ??\n (timedOut ? REMEDY[\"timed_out\"] : REMEDY[code]) ??\n REMEDY[\"internal\"]!;\n\n // The store's own sentence for what happened. Its hint is the REMEDY above\n // rather than more of this, so the two halves never say the same thing twice.\n // A STORE MESSAGE IS NEVER ENGINEER TEXT; a stand-in written by a client can\n // be, and a person must not read it. It still reaches the engineer's line.\n const messageIsForEngineers = isEngineerText(String(error.message ?? \"\"));\n const said = timedOut ? TIMED_OUT_SAID : (messageIsForEngineers ? \"\" : (message.kept ?? \"\")).trim();\n\n const forEngineers = [\n error.sqlstate ? `SQLSTATE ${error.sqlstate}.` : null,\n // The client's own note about a class it did not recognize, or a call that\n // never reached the store. It is rendered out of sight, never as a sentence.\n error.diagnostic ? error.diagnostic : null,\n messageIsForEngineers || timedOut ? `Message: ${error.message}` : null,\n error.hint && (hintIsForEngineers || hint.kept !== error.hint) ? `Hint: ${error.hint}` : null,\n message.dropped.length > 0 || hint.dropped.length > 0\n ? `Dropped from the person's view: ${[...message.dropped, ...hint.dropped].join(\" | \")}`\n : null,\n ]\n .filter(Boolean)\n .join(\" \");\n\n return {\n title,\n // Nothing invented. When every clause was machine identity the title says\n // what happened and the remedy says what to do; a made-up diagnosis would\n // be worse than the identifier it replaced.\n sentence: said === \"\" ? `${title}.` : said,\n remedy,\n storeSaid: said !== \"\",\n forEngineers,\n };\n}\n\n/**\n * The same answer as one line, for a cell or a field where a block would break\n * the layout. Still one sentence and one remedy — never the sentence alone,\n * because half of this formatter's job is the thing to do next.\n */\nexport function refusalLineForAPerson(error: RecordsError): string {\n const plain = refusalForAPerson(error);\n // TWO SENTENCES, NOT ONE RUN-ON (VERIFIER-15/16): the store's rule message has no\n // full stop (\"Pressure (psi) has to be at least 0\"), and joining it to the remedy\n // read \"…at least 0 Send this column somewhere else\". A line ends its sentence.\n const sentence = plain.sentence.trim();\n const ended = sentence === \"\" || /[.!?…:]$/.test(sentence) ? sentence : `${sentence}.`;\n return `${ended} ${plain.remedy}`.trim();\n}\n\n/** The store refused because the request was missing something (22023 / invalid_argument): a decision, never text to print. */\nexport function refusalIsMissingInput(error: Partial<RecordsError>): boolean {\n return error.sqlstate === \"22023\" || error.code === \"invalid_argument\";\n}\n\n/**\n * A STORED SENTENCE WITHOUT ITS INTERNAL CODES (lane F2, D11). The store's older sentences — a kept-aside\n * reason, a migration note — end with the spec codes they were written against (\"(FLD-4 / T12)\",\n * \"(VAL-1)\"). Those codes are for the people who wrote the store; the store no longer writes them, and the\n * ones already saved come off here, wherever a person reads them.\n */\nexport function withoutInternalCodes(text: string): string {\n return text\n .replace(/\\s*\\((?:[A-Z]{2,}-\\d+[A-Za-z]?|T\\d+)(?:\\s*\\/\\s*(?:[A-Z]{2,}-\\d+[A-Za-z]?|T\\d+))*\\)/g, \"\")\n .replace(/\\s+([.,;])/g, \"$1\")\n .trim();\n}\n","// src/codeDependsRefusal.ts — @ai-matrx/records-ui · the \"an app's code depends on this table\" refusal, read\n//\n// Pure, so `/helpers` carries it and a host's archive action reads the refusal before it loads the\n// deliberate-archive dialog (records-ui front door, 2026-10-16). `ArchiveDeliberately.tsx` re-exports it.\n\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n/** What a \"the app's code depends on this table\" refusal names, or null for any other refusal. */\nexport function codeDependsRefusal(error: RecordsError | null | undefined): { slug: string; declaredIn: string | null } | null {\n if (!error) return null;\n const d = error.detail as Record<string, unknown> | undefined;\n if (!d || d[\"code_depends\"] !== true || typeof d[\"slug\"] !== \"string\") return null;\n const where = d[\"declared_in\"];\n const declaredIn = Array.isArray(where) ? where.map(String).join(\", \") : typeof where === \"string\" ? where : null;\n return { slug: d[\"slug\"], declaredIn };\n}\n","// src/announceTableArchived.ts — @ai-matrx/records-ui · the reversible action, for a table\n//\n// A TABLE ARCHIVED IS ANNOUNCED ONE WAY, WHEREVER IT WAS ARCHIVED FROM — the settings panel, the\n// table action list's Archive, any later surface. The package says what happened and how to undo\n// it; the host's `notify.reversible` (`@ai-matrx/kit/reversible`) decides how loud to be for this\n// person and answers ⌘Z.\n//\n// UNDO BRINGS THE WHOLE TABLE BACK. `custom.table_archive` writes every pass of one archive into ONE\n// archive event (STORE-TAILS-3), and `custom.table_restore` restores exactly that event — the table\n// and its columns first, then every record, then its forms, saved views and dashboards — in passes\n// (`client.tableRestoreWhole` loops them; one call timed out on a big table, TABLE-ACTIONS 2026-10-03).\n\nimport type { RecordsError, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport type { RecordsUiHost } from \"./host\";\nimport { refusalSentence } from \"./plainWords\";\n\nexport interface AnnounceTableArchived {\n notify: RecordsUiHost[\"notify\"];\n client: Pick<RecordsClient, \"tableRestoreWhole\">;\n tableId: Uuid;\n /** The table's name as the store gave it. */\n name: string;\n /** Called once the table is back, so the surface can show it again. */\n onRestored?: (() => void) | undefined;\n}\n\n/** Thrown by the undo when the store refuses it; its message is the store's one sentence. */\nexport class TableRestoreRefused extends Error {\n readonly refusal: RecordsError;\n readonly sentence: string;\n constructor(refusal: RecordsError) {\n const sentence = refusalSentence(refusal);\n super(sentence);\n this.name = \"TableRestoreRefused\";\n this.refusal = refusal;\n this.sentence = sentence;\n }\n}\n\nexport function announceTableArchived({ notify, client, tableId, name, onRestored }: AnnounceTableArchived): void {\n const undo = async () => {\n const back = await client.tableRestoreWhole({ table_id: tableId });\n if (!back.ok) throw new TableRestoreRefused(back.error);\n onRestored?.();\n };\n if (notify?.reversible) {\n notify.reversible({ verb: \"archive\", noun: \"table\", subject: name, undo });\n return;\n }\n // A host without the announcer: the sentence and one Undo, as before.\n notify?.success(\"Table archived\", {\n label: \"Undo\",\n run: () => {\n void undo().then(\n () => notify?.success(\"Restored\", undefined, { description: `“${name}”` }),\n // The store's refusal is already a person's sentence; anything else never prints raw.\n (thrown: unknown) =>\n notify?.error(\"Not restored\", { description: thrown instanceof TableRestoreRefused ? thrown.sentence : `“${name}”` }),\n );\n },\n }, { description: `“${name}”` });\n}\n","// src/skeletonLayout.ts — @ai-matrx/records-ui · the skeleton's layout words, with no React\n//\n// Pure, so `/helpers` carries `skeletonLayoutFor` and a host can choose a loading frame before it\n// loads any screen (records-ui front door, 2026-10-16). `RecordsSkeleton.tsx` re-exports all of it.\n\n/** Every place a records surface shows while its first read is out. */\nexport type RecordsSkeletonLayout =\n | \"grid\"\n | \"kanban\"\n | \"gallery\"\n | \"list\"\n | \"calendar\"\n | \"timeline\"\n | \"map\"\n | \"orgchart\"\n | \"pivot\"\n | \"swipe\"\n | \"form\"\n | \"record\"\n | \"chart\"\n | \"home\";\n\nexport const RECORDS_SKELETON_LAYOUTS: readonly RecordsSkeletonLayout[] = [\n \"grid\",\n \"kanban\",\n \"gallery\",\n \"list\",\n \"calendar\",\n \"timeline\",\n \"map\",\n \"orgchart\",\n \"pivot\",\n \"swipe\",\n \"form\",\n \"record\",\n \"chart\",\n \"home\",\n];\n\n/** A layout word the address or a view carries, as the skeleton that stands for it. */\nexport function skeletonLayoutFor(layout: string | null | undefined): RecordsSkeletonLayout {\n if (layout === \"board\" || layout === \"pipeline\") return \"kanban\";\n return (RECORDS_SKELETON_LAYOUTS as readonly string[]).includes(layout ?? \"\")\n ? (layout as RecordsSkeletonLayout)\n : \"grid\";\n}\n\n/**\n * THE GEOMETRY OF AN EMBEDDED GRID, MEASURED ON A LIVE SPACES PAGE (lane SKELETON-HEIGHT, 2026-10-17).\n * A loading frame that is not the loaded frame moves everything under it when the rows land. The\n * embedded grid is: a 12px wrap (the body's 4px padding twice plus its 4px gap), the data table's 36px\n * header, one 37px row per record, and the footer line (44.5px: the add-row line) when there is a row.\n * Pure numbers, so a host can size a frame before it loads any screen.\n */\nexport const EMBEDDED_ROW_PX = 37;\nexport const EMBEDDED_HEADER_PX = 36;\nexport const EMBEDDED_FOOTER_PX = 44.5;\nexport const EMBEDDED_WRAP_PX = 12;\n/** An embedded table reads this many rows at a time (the same number as `EMBEDDED_PAGE_SIZE`, firstPage.ts; a test holds them equal). */\nexport const SKELETON_EMBEDDED_PAGE_ROWS = 50;\n/** A full page's grid reads this many rows at a time (the page's own `pageSize`). */\nexport const SKELETON_PAGE_ROWS = 100;\n\n/**\n * THE ROWS A LOADING FRAME DRAWS WHEN THE SERVER KNOWS HOW MANY THE PERSON SEES: min(rows, page size).\n * `rowsVisible` is the count the store gave (`custom.where_id_opens` / the table bundle: the caller's own\n * visible rows, capped), `pageSize` the rows the surface reads first. Null/undefined/invalid = not known.\n */\nexport function skeletonRowsFor(rowsVisible: number | null | undefined, pageSize: number): number | null {\n if (typeof rowsVisible !== \"number\" || !Number.isFinite(rowsVisible) || rowsVisible < 0) return null;\n return Math.min(Math.floor(rowsVisible), pageSize);\n}\n\n/** The height (px) of an embedded grid's body with `rows` rows drawn: the loaded body's own height. */\nexport function embeddedGridBodyPx(rows: number): number {\n return EMBEDDED_WRAP_PX + EMBEDDED_HEADER_PX + EMBEDDED_ROW_PX * rows + (rows > 0 ? EMBEDDED_FOOTER_PX : 0);\n}\n\n/**\n * THE CARDS EACH BOARD COLUMN DRAWS WHEN THE SERVER KNOWS THEM (lane SKELETON-HEIGHT-2): the store's\n * per-group counts (`opening_view.groups`), each min(cards, page size). Null = not known (empty or invalid),\n * so the board skeleton keeps its stand-in columns. A column with no card still draws (its header).\n */\nexport function skeletonColumnsFor(groups: readonly number[] | null | undefined, pageSize: number): number[] | null {\n if (!Array.isArray(groups) || groups.length === 0) return null;\n const out: number[] = [];\n for (const g of groups) {\n if (typeof g !== \"number\" || !Number.isFinite(g) || g < 0) return null;\n out.push(Math.min(Math.floor(g), pageSize));\n }\n return out;\n}\n","// src/gridAgentContext.ts — @ai-matrx/records-ui · merge tranche 6l (inventory H1 / H2)\n//\n// WHAT AN AGENT BESIDE THE GRID IS TOLD.\n//\n// The older /data grid published a live scope for the `matrx-user/data-tables` surface: the table,\n// its columns with their formats and choices, the row label, the row actions, the current cell and\n// row, the selected block as TSV, the ticked rows, the rows on screen and the search. An agent in\n// the side chat read it and could write ONE confirmed cell. The merged grid tells the host the same\n// facts through `RecordsUiHost.onGridContext`, in the store's own shapes (`Field`, the masked\n// document), and the host builds its surface scope from it — this package ships no chat.\n//\n// Pure: `gridContextSnapshot` assembles, `gridContextKey` says whether anything changed, so the\n// host is told once per change and never on an unrelated render.\n\nimport type { Field, ReadRow, RecordDocument, RowAction, Table, Uuid } from \"@ai-matrx/records\";\n\nimport { recordNameIn, tableName } from \"./names\";\nimport { toDelimited } from \"@ai-matrx/kit/delimited\";\n\n/** One record as the grid shows it: its id, its name (the row label) and its masked document. */\nexport interface GridContextRecord {\n id: Uuid;\n title: string;\n document: RecordDocument;\n}\n\nexport interface GridContextSnapshot {\n tableId: Uuid;\n tableName: string;\n /** The table's own description (`metadata.description`), when it has one. */\n tableDescription: string | null;\n /** The Field key that names each record (`title_field`), or null. */\n titleField: string | null;\n /** The columns in the order the grid draws them (hidden columns left out). */\n fields: Field[];\n /** The table's row actions as the store lists them (update and agent). */\n rowActions: RowAction[];\n /** May this person change records here at all. */\n canWrite: boolean;\n /** The cell the cursor is on: its record, its Field key and the value drawn in it. */\n currentCell: { rowId: Uuid; key: string; value: unknown } | null;\n /** The record the cursor is on (or whose editor is open). */\n currentRow: GridContextRecord | null;\n /** A block of more than one cell: Excel/Sheets TSV with a header line of Field keys. */\n selectedRange: { tsv: string; cellCount: number; rowIds: Uuid[]; keys: string[] } | null;\n /** The rows ticked with the row boxes. */\n selectedRows: GridContextRecord[];\n /** The page of records on screen, in screen order. */\n visibleRows: GridContextRecord[];\n /** How many records match the search and filters, when the store said. */\n total: number | null;\n search: string;\n}\n\n/** Where the cursor is, as the data table tells it (`spreadsheet.onSelectionChange`). */\nexport interface GridCursor {\n active: { rowId: string; columnId: string };\n rowIds: string[];\n columnIds: string[];\n cellCount: number;\n tsv: string;\n}\n\nfunction recordOf(table: Table | null, row: ReadRow): GridContextRecord {\n const document = (row.document ?? {}) as RecordDocument;\n return { id: row.id, title: recordNameIn(table, document as Record<string, unknown>), document };\n}\n\nexport function gridContextSnapshot(args: {\n tableId: Uuid;\n table: Table | null;\n fields: readonly Field[];\n /** The Field keys on screen, in order. */\n shownKeys: readonly string[];\n rows: readonly ReadRow[];\n rowActions: readonly RowAction[];\n canWrite: boolean;\n cursor: GridCursor | null;\n /** The cell whose editor is open, which wins over the cursor. */\n editing: { rowId: Uuid; key: string; draft: unknown } | null;\n selectedIds: readonly string[];\n total: number | null;\n search: string;\n}): GridContextSnapshot {\n const { table, rows } = args;\n const byKey = new Map(args.fields.map((f) => [f.key, f] as const));\n const fields = args.shownKeys.map((k) => byKey.get(k)).filter((f): f is Field => f !== undefined);\n const byId = new Map(rows.map((r) => [r.id as string, r] as const));\n\n let currentCell: GridContextSnapshot[\"currentCell\"] = null;\n if (args.editing) {\n currentCell = { rowId: args.editing.rowId, key: args.editing.key, value: args.editing.draft ?? null };\n } else if (args.cursor && byId.has(args.cursor.active.rowId) && byKey.has(args.cursor.active.columnId)) {\n const row = byId.get(args.cursor.active.rowId)!;\n const key = args.cursor.active.columnId;\n currentCell = { rowId: row.id, key, value: ((row.document ?? {}) as Record<string, unknown>)[key] ?? null };\n }\n const currentRowSource = currentCell ? byId.get(currentCell.rowId) : undefined;\n\n let selectedRange: GridContextSnapshot[\"selectedRange\"] = null;\n if (args.cursor && args.cursor.cellCount > 1) {\n const keys = args.cursor.columnIds.filter((k) => byKey.has(k));\n selectedRange = {\n tsv: `${toDelimited([keys], { format: \"tsv\", spreadsheetSafe: false })}\\n${args.cursor.tsv}`,\n cellCount: args.cursor.cellCount,\n rowIds: args.cursor.rowIds.filter((id) => byId.has(id)) as Uuid[],\n keys,\n };\n }\n\n const description = table?.metadata?.[\"description\"];\n return {\n tableId: args.tableId,\n tableName: table ? tableName(table) : \"\",\n tableDescription: typeof description === \"string\" && description.trim() ? description : null,\n titleField: table?.title_field ?? null,\n fields,\n rowActions: [...args.rowActions],\n canWrite: args.canWrite,\n currentCell,\n currentRow: currentRowSource ? recordOf(table, currentRowSource) : null,\n selectedRange,\n selectedRows: args.selectedIds\n .map((id) => byId.get(id))\n .filter((r): r is ReadRow => r !== undefined)\n .map((r) => recordOf(table, r)),\n visibleRows: rows.map((r) => recordOf(table, r)),\n total: args.total,\n search: args.search,\n };\n}\n\n/** A snapshot's identity: two snapshots with the same key say the same thing. */\nexport function gridContextKey(snapshot: GridContextSnapshot): string {\n return JSON.stringify([\n snapshot.tableId,\n snapshot.tableName,\n snapshot.tableDescription,\n snapshot.titleField,\n snapshot.fields.map((f) => [f.id, f.key, f.version ?? null]),\n snapshot.rowActions.map((a) => [a.id, a.name]),\n snapshot.canWrite,\n snapshot.currentCell,\n snapshot.selectedRange,\n snapshot.selectedRows.map((r) => r.id),\n snapshot.visibleRows.map((r) => [r.id, r.document]),\n snapshot.total,\n snapshot.search,\n ]);\n}\n","// src/objectActions.ts — @ai-matrx/records-ui\n//\n// THE ONE ACTION LIST FOR A RECORD-STORE TABLE (lane TABLE-ACTIONS, v6 lane 1).\n//\n// Every menu a person meets on a table — the header ⋯, a row ⋯ on the Data\n// home, right-click, a card, the phone sheet, later ⌘K — is drawn from the\n// array `tableActions()` returns. Before this there were three hand-made lists\n// (`TABLE_MENU` in TablePage, `dataHomeRowActions` in matrx-frontend, the\n// Sheet's own v3 sections) and they drifted: no Archive, no Copy link, no\n// Duplicate, Rename and Share only as hand JSX beside the list.\n//\n// THE SHAPE IS COPIED, NOT INVENTED. It is the in-house registry pattern of\n// `features/agents/browse/agentActionRegistry.tsx` and `conversationActionRegistry.tsx`\n// in matrx-frontend: a context of HOST HANDLERS in, one ordered list out, every\n// renderer reading the same list. The one difference is deliberate: those two\n// build matrx-frontend's `ItemMenuConfig` directly, which this package cannot\n// import, so the list here is renderer-neutral (`ObjectAction[]`) and each\n// renderer has a pure adapter (`toDropdownEntries` / `toStripAndRows` here;\n// `toItemMenuConfig` and `toExtraSections` in matrx-frontend\n// `features/unified-data/actions/`).\n//\n// TWO INVARIANTS, each with a guard (`one-table-action-list-*.test.tsx`,\n// `rights-never-change-the-table-menus-shape.test.tsx`):\n// G1 — every renderer draws the same ids — none hidden, none added, disabled ones\n// drawn disabled with their reason — for every seat and with handlers missing.\n// G2 — rights change only `disabledReason`, never which ids appear, their order,\n// their verb or their rank (Airtable hides items from members; we beat it).\n// A missing host handler is the same: the action stays, disabled, with its reason.\n//\n// THE ORDER (handoff §4, the same everywhere):\n// Open · Open in new tab · Copy link | Rename · Duplicate · Move to… · Favorite |\n// Share… · Export… · Import… | Add column · Settings · History · Make … the default |\n// Built on it ▸ (Forms, Bookings, Checklists, Notifications, Portals, Inbox,\n// Dashboards, Archived records) | Archive table (last, destructive).\n// \"Add column\" and \"Make … the default\" are the header ⋯'s own entries before the\n// registry (TABLE_MENU and the designate item); they sit with Settings.\n//\n// VERB AND RANK — for the icon-strip menu. An action with a `verb` is one of the\n// platform's standard verbs (a strip icon); every other action has a `rank`, its\n// place among the feature rows. Neither changes the list's order: `toStripAndRows`\n// is a renderer that splits the same list, and G1 holds it to the same ids.\n//\n// No JSX here: this file is the `./object-actions` subpath, light enough for a\n// list row's menu to import without pulling every screen of the package.\n\nimport type { Table } from \"@ai-matrx/records\";\nimport { formatTapShortcut } from \"@ai-matrx/design-system/tap-shortcut\";\nimport { ADD_FIELD_OPEN_LABEL } from \"./fieldTypes\";\nimport { LEVEL_WORD, levelNeededFor, type Capability, type WhatYouMayDo } from \"./rights\";\n\n/**\n * A Lucide icon NAME, kebab-case — the same currency `Table.icon` already uses.\n * Closed on purpose: each renderer maps every member to its own glyph, and a\n * new member fails that renderer's typecheck until it is mapped.\n */\nexport type ObjectActionIcon =\n | \"folder-open\"\n | \"external-link\"\n | \"link\"\n | \"pencil\"\n | \"copy\"\n | \"folder-input\"\n | \"star\"\n | \"star-off\"\n | \"share-2\"\n | \"download\"\n | \"upload\"\n | \"columns-3\"\n | \"settings\"\n | \"history\"\n | \"blocks\"\n | \"file-text\"\n | \"calendar-clock\"\n | \"list-checks\"\n | \"bell\"\n | \"door-open\"\n | \"inbox\"\n | \"layout-dashboard\"\n | \"archive-restore\"\n | \"archive\"\n | \"link-2\"\n | \"layout-grid\"\n | \"git-merge\"\n | \"split\"\n | \"arrow-up-from-line\"\n | \"corner-down-right\"\n | \"lock\"\n | \"lock-open\"\n | \"eraser\"\n | \"printer\";\n\n/** The groups, in their one order. Separators fall out of group boundaries. */\nexport type ObjectActionGroup = \"open\" | \"organize\" | \"share\" | \"manage\" | \"built-on\" | \"danger\";\n\n/**\n * THE STANDARD VERBS every object's menu shares — what the icon strip draws. One\n * per meaning; an object maps its action onto the verb, never a second \"share\".\n */\nexport type StandardVerbId =\n | \"open\"\n | \"open-new-tab\"\n | \"copy-link\"\n | \"rename\"\n | \"duplicate\"\n | \"move\"\n | \"favorite\"\n | \"share\"\n | \"export\"\n | \"import\"\n | \"settings\"\n | \"history\"\n | \"archive\";\n\nexport const STANDARD_VERBS: readonly StandardVerbId[] = [\n \"open\",\n \"open-new-tab\",\n \"copy-link\",\n \"rename\",\n \"duplicate\",\n \"move\",\n \"favorite\",\n \"share\",\n \"export\",\n \"import\",\n \"settings\",\n \"history\",\n \"archive\",\n];\n\nexport interface ObjectActionGroupDef {\n id: ObjectActionGroup;\n /** Present only on a group that renders as a submenu. */\n label?: string;\n icon?: ObjectActionIcon;\n /** Rendered as ONE submenu entry holding the group's actions. */\n submenu: boolean;\n}\n\nexport const OBJECT_ACTION_GROUPS: readonly ObjectActionGroupDef[] = [\n { id: \"open\", submenu: false },\n { id: \"organize\", submenu: false },\n { id: \"share\", submenu: false },\n { id: \"manage\", submenu: false },\n { id: \"built-on\", label: \"Built on it\", icon: \"blocks\", submenu: true },\n { id: \"danger\", submenu: false },\n];\n\nconst GROUP_IDS = new Set<string>(OBJECT_ACTION_GROUPS.map((g) => g.id));\n\n/** One thing a person can do to an object, for any renderer. */\nexport interface ObjectAction {\n /** Stable within the object's list. React key, test handle, future ⌘K id. */\n id: string;\n label: string;\n icon: ObjectActionIcon;\n group: ObjectActionGroup;\n /** The standard verb this action IS (a strip icon). Absent = a feature row. */\n verb?: StandardVerbId;\n /** A feature row's place among the rows, 1 first. Ignored when `verb` is set. */\n rank?: number;\n /** Display-only hint (\"⌘D\"). */\n shortcut?: string;\n destructive?: boolean;\n /** Present = shown disabled with this line (≤ 60 chars). Absent = enabled. */\n disabledReason?: string;\n /** Called only when enabled. The host owns the side effect and its feedback. */\n run: () => void | Promise<void>;\n}\n\n/** What the list needs to know about the table. A full `Table` satisfies it. */\nexport type TableActionSubject = Pick<Table, \"id\" | \"name\"> & Partial<Pick<Table, \"is_kernel\">>;\n\n/** The places built on a table, in their one order. */\nexport type BuiltOnDestination =\n | \"forms\"\n | \"bookings\"\n | \"checklists\"\n | \"notifications\"\n | \"portals\"\n | \"inbox\"\n | \"dashboards\"\n | \"archived\";\n\ntype Handler = (table: TableActionSubject) => void | Promise<void>;\n\n/**\n * THE SIDE EFFECTS THIS PACKAGE CANNOT OWN. Every handler is optional: one the\n * host leaves out keeps its action in the list, disabled, saying so.\n */\nexport interface TableActionHost {\n /** Origin for Copy link and Open in new tab. Default `https://www.aimatrx.com`. */\n origin?: string;\n open?: Handler;\n /** Receives the table's link (`<origin>/data/<id>`). */\n openInNewTab?: (url: string, table: TableActionSubject) => void;\n /** Receives the table's link. Runs inside the click (clipboard needs the gesture). */\n copyText?: (text: string, table: TableActionSubject) => void | Promise<void>;\n rename?: Handler;\n duplicate?: Handler;\n move?: Handler;\n /** Current favorite state; flips the Favorite label. Unknown = \"Add to favorites\". */\n isFavorite?: boolean;\n toggleFavorite?: Handler;\n share?: Handler;\n export?: Handler;\n import?: Handler;\n addColumn?: Handler;\n settings?: Handler;\n history?: Handler;\n /** Make the layout on screen the table's default. Leave out when it already is. */\n makeDefault?: Handler;\n /** The layout on screen, for \"Make Kanban the default\". */\n layoutLabel?: string;\n /** The \"Built on it\" destinations, one handler for all eight. */\n openBuiltOn?: (destination: BuiltOnDestination, table: TableActionSubject) => void;\n archive?: Handler;\n /**\n * Why an action whose handler is left out is unavailable here, by action id\n * (≤ 60 chars) — e.g. `make-default: \"Already the default\"`. Unnamed ids say\n * \"Not available here\". Never used when rights already refuse.\n */\n unavailableReasons?: Readonly<Record<string, string>>;\n /**\n * ANOTHER LANE'S ENTRIES (\"Link a record…\", a hub tile's verbs, a feature's own\n * row such as \"When a row changes, run an agent…\"). Return the same ids whatever\n * `rights` say — express rights as `disabledReason`. Each entry lands at the END\n * of its named group, in the order returned. Refused, loudly: the `danger` group\n * (Archive is always last), a group that does not exist, and an id already in\n * the list.\n */\n extend?: (table: TableActionSubject, rights: WhatYouMayDo) => readonly ObjectAction[];\n}\n\nexport interface TableActionsInput {\n table: TableActionSubject;\n rights: WhatYouMayDo;\n host: TableActionHost;\n}\n\nexport const DEFAULT_ACTION_ORIGIN = \"https://www.aimatrx.com\";\n\n/** The one link to a table: `<origin>/data/<tableId>`. */\nexport function tableLink(tableId: string, origin: string = DEFAULT_ACTION_ORIGIN): string {\n return `${origin.replace(/\\/+$/, \"\")}/data/${encodeURIComponent(tableId)}`;\n}\n\n/** The designate entry's words, matching `makeDefaultLabel` in views.ts. */\nfunction makeDefaultWords(layoutLabel: string | undefined): string {\n return layoutLabel ? `Make ${layoutLabel} the default` : \"Make this the default\";\n}\n\n// Reasons — one line, ≤ 60 characters, said on the action itself.\nexport const ACTION_NOT_HERE_REASON = \"Not available here\";\nexport const ACTION_CHECKING_ACCESS_REASON = \"Checking your access…\";\nexport const ACTION_NO_ACCESS_REASON = \"You don't have access\";\nexport const ACTION_PLATFORM_TABLE_REASON = \"Platform tables can't be changed here\";\n\n/** Why `rights` refuse `what`, in one short line — or null when they allow it. */\nexport function rightsReason(\n rights: WhatYouMayDo,\n what: Capability,\n table?: TableActionSubject,\n): string | null {\n if (!rights.known) return ACTION_CHECKING_ACCESS_REASON;\n if (what === \"structure\" && table?.is_kernel) return ACTION_PLATFORM_TABLE_REASON;\n if (rights[what]) return null;\n if (rights.level === null) return ACTION_NO_ACCESS_REASON;\n return `Needs ${LEVEL_WORD[levelNeededFor(what)]}`;\n}\n\n// Feature rows' ranks: what the strip menu shows as its first rows. Lower is first.\nconst BUILT_ON: ReadonlyArray<{ destination: BuiltOnDestination; label: string; icon: ObjectActionIcon; rank: number }> = [\n { destination: \"forms\", label: \"Forms\", icon: \"file-text\", rank: 2 },\n { destination: \"bookings\", label: \"Bookings\", icon: \"calendar-clock\", rank: 6 },\n { destination: \"checklists\", label: \"Checklists\", icon: \"list-checks\", rank: 7 },\n { destination: \"notifications\", label: \"Notifications\", icon: \"bell\", rank: 8 },\n { destination: \"portals\", label: \"Portals\", icon: \"door-open\", rank: 9 },\n { destination: \"inbox\", label: \"Inbox\", icon: \"inbox\", rank: 10 },\n { destination: \"dashboards\", label: \"Dashboards\", icon: \"layout-dashboard\", rank: 3 },\n { destination: \"archived\", label: \"Archived records\", icon: \"archive-restore\", rank: 5 },\n];\n\nconst NOOP = () => {};\n\n/**\n * THE TABLE'S KEYBOARD CHORDS (lane TABLE-ACTIONS wave 4, item 17): ⌥⇧ + one key, the same on\n * every surface that runs the list. Chosen because nothing else owns them: ⌘D is the browser's\n * bookmark, ⌘S save, ⌘P print, ⌘K the command bar, ⌘⇧K the menu's palette, ⌘Z undo — and the\n * app binds no ⌥⇧ chord. A chord is never taken while the person types in a field\n * (`objectActionForKey`). `code` is the KeyboardEvent.code, so ⌥ on a Mac (which changes\n * `key` to a symbol) still matches.\n */\nexport const TABLE_ACTION_CHORDS: Readonly<Record<string, { code: string; chord: string }>> = {\n \"copy-link\": { code: \"KeyL\", chord: \"alt+shift+l\" },\n rename: { code: \"KeyR\", chord: \"alt+shift+r\" },\n duplicate: { code: \"KeyD\", chord: \"alt+shift+d\" },\n move: { code: \"KeyM\", chord: \"alt+shift+m\" },\n favorite: { code: \"KeyF\", chord: \"alt+shift+f\" },\n share: { code: \"KeyS\", chord: \"alt+shift+s\" },\n export: { code: \"KeyE\", chord: \"alt+shift+e\" },\n import: { code: \"KeyI\", chord: \"alt+shift+i\" },\n settings: { code: \"Comma\", chord: \"alt+shift+,\" },\n history: { code: \"KeyH\", chord: \"alt+shift+h\" },\n archive: { code: \"Backspace\", chord: \"alt+shift+backspace\" },\n};\n\n/**\n * The chords with their LABEL in this platform's words — \"⌥⇧S\" on a Mac, \"Alt+Shift+S\" on Windows\n * and Linux — through the design system's one shortcut formatter (`formatTapShortcut`, the tap\n * button's tooltip), so a menu entry and the ⌘K bar read alike everywhere.\n */\nexport const TABLE_ACTION_KEYS: Readonly<Record<string, { code: string; label: string }>> = Object.fromEntries(\n Object.entries(TABLE_ACTION_CHORDS).map(([id, { code, chord }]) => [id, { code, label: formatTapShortcut(chord) }]),\n);\n\n/** The fields of a keyboard event a chord reads (a DOM KeyboardEvent satisfies it). */\nexport interface ChordEvent {\n code: string;\n altKey: boolean;\n shiftKey: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n target?: EventTarget | null;\n}\n\nfunction typingIn(target: EventTarget | null | undefined): boolean {\n const el = target as { tagName?: string; isContentEditable?: boolean } | null | undefined;\n if (!el || typeof el.tagName !== \"string\") return false;\n return el.isContentEditable === true || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName);\n}\n\n/**\n * The action a key press asks for, or null: ⌥⇧ + its key, no ⌘/Ctrl, never inside a field. A\n * disabled action is still RETURNED (the caller says its reason instead of doing nothing).\n */\nexport function objectActionForKey(actions: readonly ObjectAction[], event: ChordEvent): ObjectAction | null {\n if (!event.altKey || !event.shiftKey || event.metaKey || event.ctrlKey) return null;\n if (typingIn(event.target)) return null;\n const id = Object.keys(TABLE_ACTION_KEYS).find((k) => TABLE_ACTION_KEYS[k]!.code === event.code);\n return id ? (actions.find((a) => a.id === id) ?? null) : null;\n}\n\n/**\n * One action, from its needs: the capability it asks for and the host handler\n * that performs it. Rights speak first; a missing handler second.\n */\nfunction action(\n base: Omit<ObjectAction, \"run\" | \"disabledReason\">,\n needs: Capability,\n input: TableActionsInput,\n perform: (() => void | Promise<void>) | undefined,\n): ObjectAction {\n const chord = TABLE_ACTION_KEYS[base.id];\n if (chord && base.shortcut === undefined) base = { ...base, shortcut: chord.label };\n const refused = rightsReason(input.rights, needs, input.table);\n if (refused !== null) return { ...base, disabledReason: refused, run: NOOP };\n if (perform === undefined) {\n return { ...base, disabledReason: input.host.unavailableReasons?.[base.id] ?? ACTION_NOT_HERE_REASON, run: NOOP };\n }\n return { ...base, run: perform };\n}\n\nfunction bind(handler: Handler | undefined, table: TableActionSubject): (() => void | Promise<void>) | undefined {\n return handler ? () => handler(table) : undefined;\n}\n\n/**\n * THE TABLE'S ACTIONS, in the one order. Same ids, same order, same verbs and\n * ranks, for every seat and every host — only `disabledReason` varies.\n */\nexport function tableActions(input: TableActionsInput): ObjectAction[] {\n const { table, host } = input;\n const url = tableLink(table.id, host.origin);\n const favorite = host.isFavorite === true;\n const openInNewTab = host.openInNewTab;\n const copyText = host.copyText;\n const openBuiltOn = host.openBuiltOn;\n\n const built: ObjectAction[] = [\n action({ id: \"open\", label: \"Open\", icon: \"folder-open\", group: \"open\", verb: \"open\" }, \"read\", input, bind(host.open, table)),\n action(\n { id: \"open-new-tab\", label: \"Open in new tab\", icon: \"external-link\", group: \"open\", verb: \"open-new-tab\" },\n \"read\",\n input,\n openInNewTab ? () => openInNewTab(url, table) : undefined,\n ),\n action(\n { id: \"copy-link\", label: \"Copy link\", icon: \"link\", group: \"open\", verb: \"copy-link\" },\n \"read\",\n input,\n copyText ? () => copyText(url, table) : undefined,\n ),\n action({ id: \"rename\", label: \"Rename…\", icon: \"pencil\", group: \"organize\", verb: \"rename\" }, \"structure\", input, bind(host.rename, table)),\n action({ id: \"duplicate\", label: \"Duplicate\", icon: \"copy\", group: \"organize\", verb: \"duplicate\" }, \"read\", input, bind(host.duplicate, table)),\n action({ id: \"move\", label: \"Move to…\", icon: \"folder-input\", group: \"organize\", verb: \"move\" }, \"structure\", input, bind(host.move, table)),\n action(\n {\n id: \"favorite\",\n label: favorite ? \"Remove from favorites\" : \"Add to favorites\",\n icon: favorite ? \"star-off\" : \"star\",\n group: \"organize\",\n verb: \"favorite\",\n },\n \"read\",\n input,\n bind(host.toggleFavorite, table),\n ),\n action({ id: \"share\", label: \"Share…\", icon: \"share-2\", group: \"share\", verb: \"share\" }, \"share\", input, bind(host.share, table)),\n action({ id: \"export\", label: \"Export…\", icon: \"download\", group: \"share\", verb: \"export\" }, \"read\", input, bind(host.export, table)),\n action({ id: \"import\", label: \"Import…\", icon: \"upload\", group: \"share\", verb: \"import\" }, \"structure\", input, bind(host.import, table)),\n action({ id: \"add-column\", label: ADD_FIELD_OPEN_LABEL, icon: \"columns-3\", group: \"manage\", rank: 1 }, \"structure\", input, bind(host.addColumn, table)),\n action({ id: \"settings\", label: \"Settings\", icon: \"settings\", group: \"manage\", verb: \"settings\" }, \"structure\", input, bind(host.settings, table)),\n action({ id: \"history\", label: \"History\", icon: \"history\", group: \"manage\", verb: \"history\" }, \"read\", input, bind(host.history, table)),\n // custom.view_designate asks editor on the table — `canDesignate` in TablePage.\n action(\n { id: \"make-default\", label: makeDefaultWords(host.layoutLabel), icon: \"layout-grid\", group: \"manage\", rank: 4 },\n \"organise\",\n input,\n bind(host.makeDefault, table),\n ),\n ...BUILT_ON.map(({ destination, label, icon, rank }) =>\n action(\n { id: `built-on.${destination}`, label, icon, group: \"built-on\", rank },\n \"read\",\n input,\n openBuiltOn ? () => openBuiltOn(destination, table) : undefined,\n ),\n ),\n action(\n { id: \"archive\", label: \"Archive table\", icon: \"archive\", group: \"danger\", destructive: true, verb: \"archive\" },\n \"structure\",\n input,\n bind(host.archive, table),\n ),\n ];\n\n return withExtensions(built, host.extend ? host.extend(table, input.rights) : []);\n}\n\n/**\n * Another lane's entries, placed deterministically: each at the end of its\n * group, in the order given. Loud on every mistake that would break the\n * invariants — a `danger` entry (Archive must stay last), a group that does not\n * exist (it would be dropped by every renderer) and a duplicate id.\n */\nexport function withExtensions(base: readonly ObjectAction[], extra: readonly ObjectAction[]): ObjectAction[] {\n if (extra.length === 0) return [...base];\n const seen = new Set(base.map((a) => a.id));\n for (const entry of extra) {\n if (entry.group === \"danger\") {\n throw new Error(`Object action \"${entry.id}\": the danger group is closed to extensions.`);\n }\n if (!GROUP_IDS.has(entry.group)) {\n throw new Error(`Object action \"${entry.id}\": \"${String(entry.group)}\" is not a group.`);\n }\n if (seen.has(entry.id)) {\n throw new Error(`Object action \"${entry.id}\" is already in the list.`);\n }\n seen.add(entry.id);\n }\n const out: ObjectAction[] = [];\n for (const group of OBJECT_ACTION_GROUPS) {\n out.push(...base.filter((a) => a.group === group.id), ...extra.filter((a) => a.group === group.id));\n }\n return out;\n}\n\n/** A run of actions that renders together: a plain section, or one submenu. */\nexport interface ObjectActionSection {\n group: ObjectActionGroupDef;\n actions: ObjectAction[];\n}\n\n/**\n * THE ONE GROUPING every adapter uses: the list cut at group boundaries, in\n * group order, empty groups dropped, the order inside a group kept.\n */\nexport function groupObjectActions(actions: readonly ObjectAction[]): ObjectActionSection[] {\n const sections: ObjectActionSection[] = [];\n for (const group of OBJECT_ACTION_GROUPS) {\n const inGroup = actions.filter((a) => a.group === group.id);\n if (inGroup.length > 0) sections.push({ group, actions: inGroup });\n }\n return sections;\n}\n\n/** The header ⋯ dropdown's entries — records-ui's own renderer reads these. */\nexport type ObjectActionDropdownEntry =\n | { kind: \"separator\"; id: string }\n | { kind: \"item\"; action: ObjectAction }\n | { kind: \"submenu\"; id: string; label: string; icon: ObjectActionIcon | undefined; actions: ObjectAction[] };\n\nexport function toDropdownEntries(actions: readonly ObjectAction[]): ObjectActionDropdownEntry[] {\n const entries: ObjectActionDropdownEntry[] = [];\n groupObjectActions(actions).forEach(({ group, actions: inGroup }, index) => {\n if (index > 0) entries.push({ kind: \"separator\", id: `separator:${group.id}` });\n if (group.submenu) {\n entries.push({ kind: \"submenu\", id: group.id, label: group.label ?? group.id, icon: group.icon, actions: inGroup });\n } else {\n for (const a of inGroup) entries.push({ kind: \"item\", action: a });\n }\n });\n return entries;\n}\n\n/** The actions a dropdown draws, in order — what G1 compares. */\nexport function dropdownActions(entries: readonly ObjectActionDropdownEntry[]): ObjectAction[] {\n return entries.flatMap((e) => (e.kind === \"item\" ? [e.action] : e.kind === \"submenu\" ? e.actions : []));\n}\n\n/** The action ids a dropdown draws, in order. */\nexport function dropdownActionIds(entries: readonly ObjectActionDropdownEntry[]): string[] {\n return dropdownActions(entries).map((a) => a.id);\n}\n\n/** The icon-strip menu: standard verbs as icons, then the first feature rows, then the rest. */\nexport interface StripAndRows {\n /** Every action with a `verb`, in the list's order. */\n strip: ObjectAction[];\n /** The first `rowCount` feature actions by rank (ties keep list order). */\n rows: ObjectAction[];\n /** The remaining feature actions, behind \"More … options\", same ordering. */\n more: ObjectAction[];\n}\n\nexport const STRIP_FEATURE_ROWS = 4;\n\n/**\n * THE STRIP RENDERER'S SPLIT of the same list. Nothing is added or dropped: every\n * id lands in exactly one of strip / rows / more (G1). Unranked feature actions\n * (an extension that gave none) follow every ranked one.\n */\nexport function toStripAndRows(actions: readonly ObjectAction[], rowCount: number = STRIP_FEATURE_ROWS): StripAndRows {\n const strip = actions.filter((a) => a.verb !== undefined);\n const features = actions\n .map((a, index) => ({ a, index }))\n .filter(({ a }) => a.verb === undefined)\n .sort((x, y) => (x.a.rank ?? Infinity) - (y.a.rank ?? Infinity) || x.index - y.index)\n .map(({ a }) => a);\n return { strip, rows: features.slice(0, rowCount), more: features.slice(rowCount) };\n}\n","// src/recordActions.ts — @ai-matrx/records-ui\n//\n// THE ONE ACTION LIST FOR A RECORD (lane TABLE-ACTIONS, v6 lane 1, item 14).\n//\n// Every menu a person meets on ONE RECORD — a Gallery card's ⋯ and right-click, a Kanban card's,\n// a Pipeline card's, the grid row's — is drawn from the array `recordActions()` returns. It is\n// built exactly the way `tableActions()` is (`objectActions.ts`): host handlers in, one ordered\n// `ObjectAction[]` out, every renderer reading the same list through the same adapters\n// (`toDropdownEntries`, `ObjectActionMenuItems`, `RecordActionMenu`).\n//\n// The same two invariants hold, with their guard (`one-record-action-list-*.test.tsx`):\n// G1 — every renderer draws the same ids, none hidden, none added.\n// G2 — rights change only `disabledReason`, never which ids appear or their order.\n//\n// THE ORDER: Open · Open in new tab · Copy link | Duplicate · Merge with… · Split… · Extract parent… · Move to another table… · Link a record… | Print with layout… | History |\n// Archive record (last, red).\n\nimport type { Uuid } from \"@ai-matrx/records\";\nimport {\n ACTION_NOT_HERE_REASON,\n DEFAULT_ACTION_ORIGIN,\n rightsReason,\n withExtensions,\n type ObjectAction,\n} from \"./objectActions\";\nimport type { Capability, WhatYouMayDo } from \"./rights\";\n\n/** What the list needs to know about the record. */\nexport interface RecordActionSubject {\n id: Uuid;\n tableId: Uuid;\n /** The record's name as every card reads it (`recordNameIn` / `cardWords`). */\n name: string;\n}\n\ntype RecordHandler = (record: RecordActionSubject) => void | Promise<void>;\n\n/** THE SIDE EFFECTS THIS LIST CANNOT OWN. A handler left out keeps its action, disabled. */\nexport interface RecordActionHost {\n /** Origin for Copy link and Open in new tab. Default `https://www.aimatrx.com`. */\n origin?: string;\n /**\n * The record's own page (the host's `hrefForRecord`), absolute or root-relative. When given, Copy\n * link and Open in new tab carry it instead of the table page with `?record=`.\n */\n href?: string;\n open?: RecordHandler;\n openInNewTab?: (url: string, record: RecordActionSubject) => void;\n /** Runs inside the click (the clipboard needs the gesture). */\n copyText?: (text: string, record: RecordActionSubject) => void | Promise<void>;\n duplicate?: RecordHandler;\n /** Merge another record of the same table into this one (`MergeRecordDialog`). */\n merge?: RecordHandler;\n /** Move some of this record's values to a new record of the same table (`SplitRecordDialog`). */\n split?: RecordHandler;\n /** Copy some values up into a new record of a parent table and put this one under it (`ExtractParentDialog`). */\n extractParent?: RecordHandler;\n /** Put this record under another record you pick (`MoveUnderDialog`, `custom.record_reparent`, test 3). */\n moveUnder?: RecordHandler;\n /** Move this record to another table of its organization, keeping its id (`MoveRecordDialog`, test 9). */\n moveToTable?: RecordHandler;\n /** Open the host's one record picker pointed at this record (`RecordsUiHost.linkRecord`). */\n link?: RecordHandler;\n /** Open the print-with-layout dialog for this record (`PrintWithLayoutDialog`). */\n printLayout?: RecordHandler;\n history?: RecordHandler;\n archive?: RecordHandler;\n /** Why an action whose handler is left out is unavailable here, by id (≤ 60 chars). */\n unavailableReasons?: Readonly<Record<string, string>>;\n /** Another lane's record entries; same rules as `TableActionHost.extend`. */\n extend?: (record: RecordActionSubject, rights: WhatYouMayDo) => readonly ObjectAction[];\n}\n\nexport interface RecordActionsInput {\n record: RecordActionSubject;\n /** The person's rights on the record (its row level), or on the table when that is all there is. */\n rights: WhatYouMayDo;\n host: RecordActionHost;\n}\n\n/** The one link to a record: the table page with the record open, `<origin>/data/<table>?record=<id>`. */\nexport function recordLink(tableId: string, recordId: string, origin: string = DEFAULT_ACTION_ORIGIN): string {\n return `${origin.replace(/\\/+$/, \"\")}/data/${encodeURIComponent(tableId)}?record=${encodeURIComponent(recordId)}`;\n}\n\nconst NOOP = () => {};\n\nfunction action(\n base: Omit<ObjectAction, \"run\" | \"disabledReason\">,\n needs: Capability,\n input: RecordActionsInput,\n perform: (() => void | Promise<void>) | undefined,\n): ObjectAction {\n const refused = rightsReason(input.rights, needs);\n if (refused !== null) return { ...base, disabledReason: refused, run: NOOP };\n if (perform === undefined) {\n return { ...base, disabledReason: input.host.unavailableReasons?.[base.id] ?? ACTION_NOT_HERE_REASON, run: NOOP };\n }\n return { ...base, run: perform };\n}\n\nfunction bind(handler: RecordHandler | undefined, record: RecordActionSubject) {\n return handler ? () => handler(record) : undefined;\n}\n\n/**\n * THE RECORD'S ACTIONS, in the one order. Same ids, same order, same verbs for every seat and every\n * host — only `disabledReason` varies.\n */\nexport function recordActions(input: RecordActionsInput): ObjectAction[] {\n const { record, host } = input;\n const origin = (host.origin ?? DEFAULT_ACTION_ORIGIN).replace(/\\/+$/, \"\");\n const url = host.href ? (/^https?:/.test(host.href) ? host.href : `${origin}${host.href}`) : recordLink(record.tableId, record.id, host.origin);\n const openInNewTab = host.openInNewTab;\n const copyText = host.copyText;\n const built: ObjectAction[] = [\n action({ id: \"open\", label: \"Open\", icon: \"folder-open\", group: \"open\", verb: \"open\" }, \"read\", input, bind(host.open, record)),\n action(\n { id: \"open-new-tab\", label: \"Open in new tab\", icon: \"external-link\", group: \"open\", verb: \"open-new-tab\" },\n \"read\",\n input,\n openInNewTab ? () => openInNewTab(url, record) : undefined,\n ),\n action(\n { id: \"copy-link\", label: \"Copy link\", icon: \"link\", group: \"open\", verb: \"copy-link\" },\n \"read\",\n input,\n copyText ? () => copyText(url, record) : undefined,\n ),\n action({ id: \"duplicate\", label: \"Duplicate\", icon: \"copy\", group: \"organize\", verb: \"duplicate\" }, \"organise\", input, bind(host.duplicate, record)),\n action(\n { id: \"merge\", label: \"Merge with…\", icon: \"git-merge\", group: \"organize\" },\n \"organise\",\n input,\n bind(host.merge, record),\n ),\n action({ id: \"split\", label: \"Split…\", icon: \"split\", group: \"organize\" }, \"organise\", input, bind(host.split, record)),\n action(\n { id: \"extract-parent\", label: \"Extract parent…\", icon: \"arrow-up-from-line\", group: \"organize\" },\n \"organise\",\n input,\n bind(host.extractParent, record),\n ),\n // Moving a record under another changes who it inherits access from — Full (admin) on the record, the store's level for record_reparent.\n action({ id: \"move-under\", label: \"Move under…\", icon: \"corner-down-right\", group: \"organize\" }, \"structure\", input, bind(host.moveUnder, record)),\n // Moving a record changes what table it is — Full (admin) on the record, the store's own level for the verb.\n action({ id: \"move-to-table\", label: \"Move to another table…\", icon: \"folder-input\", group: \"organize\" }, \"structure\", input, bind(host.moveToTable, record)),\n // A link is an edge beside the record, never a change to it: reading the record is enough.\n action({ id: \"link-record\", label: \"Link a record…\", icon: \"link-2\", group: \"organize\" }, \"read\", input, bind(host.link, record)),\n // Printing is reading, never a change: whoever can read the record can print it through a layout.\n action({ id: \"print-layout\", label: \"Print with layout…\", icon: \"file-text\", group: \"organize\" }, \"read\", input, bind(host.printLayout, record)),\n action({ id: \"history\", label: \"History\", icon: \"history\", group: \"manage\", verb: \"history\" }, \"read\", input, bind(host.history, record)),\n action(\n { id: \"archive\", label: \"Archive record\", icon: \"archive\", group: \"danger\", destructive: true, verb: \"archive\" },\n \"remove\",\n input,\n bind(host.archive, record),\n ),\n ];\n return withExtensions(built, host.extend ? host.extend(record, input.rights) : []);\n}\n"]}
|