@ai-matrx/records-ui 0.116.76 → 0.116.78

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SaveToTable.tsx","../src/unfinishedTable.ts","../src/ImportWizard.tsx","../src/importRuleCheck.ts","../src/pasteValues.ts","../src/importKinds.ts","../src/importCombine.ts","../src/importRefusals.ts","../src/TablesHome.tsx","../src/NewTableStart.tsx","../src/newTableColumns.ts","../src/importFileRead.ts","../src/BookingSlots.tsx","../src/BookingBuilder.tsx","../src/bookingMessages.ts","../src/publicQuestions.ts","../src/TimeZoneInput.tsx","../src/BuildOrAsk.tsx","../src/BuiltOnArchive.tsx","../src/ObjectActionMenuItems.tsx","../src/objectActionIcons.tsx","../src/WhereItLives.tsx","../src/tableLanes.ts","../src/writeOnTheWinningVersion.ts"],"sourcesContent":["\"use client\";\n\n// src/SaveToTable.tsx — @ai-matrx/records-ui · lane SAVE-AS-TABLE-EVERYWHERE\n//\n// SAVE WHAT YOU ARE LOOKING AT AS A TABLE — THE ONE SCREEN. Arman, 2026-09-29: anywhere\n// information appears in a shape the system understands (a markdown table, a list or a few bullet\n// points, key:value lines, a CSV/TSV paste, a kind value, an agent's answer, a note, a transcript\n// section, a form result) the SAME action exists — save it as a new table, or add its rows to a\n// table you already have with the columns matched. Every menu in every host opens THIS screen; no\n// surface builds its own.\n//\n// WHAT IT DOES AND WHOSE DOORS IT USES.\n// · The rows are read by `readTableShapes` (the one shape reader) — a list offers its splits.\n// · A NEW table: the person sees every column's label and proposed type (`guessColumn`) and\n// changes any of it; \"Make the table\" is `declareTable` (the one birth — the store takes the\n// declared types and mints nothing a person sees), then the rows go through the store's import\n// doors (`importBegin` / `importRows` / `importFinish`) exactly as a file's do, with the rows'\n// sha-256 as the run's identity, so saving the same answer twice writes nothing and says so.\n// · AN EXISTING table: `ImportWizard` with these rows as its source — the store's plan matches\n// the columns by name, offers the ones the table lacks, asks about choice words it does not\n// know (the enum ask), and reports what landed.\n// There is no write here that the file import, the grid's paste or the agent's `import_propose`\n// does not also make.\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useRecordsClient, useMyLevels, useTables, type Uuid } from \"@ai-matrx/records/react\";\nimport type { RecordsError } from \"@ai-matrx/records\";\nimport {\n Button,\n Checkbox,\n ConfirmDialog,\n Input,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { addFields, declareTable, tokenFor, type NewFieldSpec } from \"./createTable\";\nimport { choiceWordsOwed, findUnfinishedTable } from \"./unfinishedTable\";\nimport { ImportWizard } from \"./ImportWizard\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { refusal as refusalOf, refusalFromThrown } from \"./refusals\";\nimport { fieldTypeChoice } from \"./fieldTypes\";\nimport { laneFor } from \"./TablesHome\";\nimport {\n guessColumn,\n readTableShapes,\n shapeOfGrid,\n shapeOfValue,\n type ColumnGuess,\n type GuessedFieldType,\n type TableShape,\n} from \"./tableShape\";\nimport { tablePickerEntries } from \"./tablePicking\";\nimport { changeRecordsAt, readTableVersionNow } from \"./recordVersions\";\nimport { updateOnTheWinningVersion } from \"./writeOnTheWinningVersion\";\n\n/** What the person is saving. Exactly one of `text`, `value` or `grid` carries the rows. */\nexport interface SaveToTableSource {\n /** Markdown, a CSV or TSV paste, a note, an answer — every shape in it is offered. */\n text?: string | undefined;\n /** A kind value or JSON rows. */\n value?: unknown;\n /** Rows a host already holds (a rendered table's headers and cells). */\n grid?: { headers: string[]; rows: string[][]; /** What the rows came out of (\"table\", \"sheet\"); the offered line says \"from a <it>\". Default \"table\". */ from?: string | undefined } | undefined;\n /** What it came from, in words — the name a new table is offered, and the import's source name. */\n title?: string | null | undefined;\n}\n\nexport interface SaveToTableProps {\n source: SaveToTableSource;\n /** When the text holds several shapes, the one to open on (the one the person right-clicked). */\n shapeIndex?: number | undefined;\n /** Open a table (after it was made, or rows were added). Absent: no \"Open\" button is drawn. */\n onOpenTable?: ((tableId: Uuid) => void) | undefined;\n /** The rows landed — `new` when this screen made the table. */\n onSaved?: ((tableId: Uuid, how: \"new\" | \"existing\") => void) | undefined;\n /** The person is finished (the report's Done). */\n onClose?: (() => void) | undefined;\n /**\n * \"Turn into a table\" — ONE click: make the new table at once with the proposed name and column\n * types (no form first), then show the result with Open. The screen stays the full one for a\n * person who wants to change it next time; this only presses \"Make the table\" for them.\n */\n makeAtOnce?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** The types a NEW table's column is offered here — the ones a text value can honestly be. */\nexport const SAVE_TO_TABLE_TYPES: readonly GuessedFieldType[] = [\n \"text\",\n \"long_text\",\n \"number\",\n \"currency\",\n \"percent\",\n \"datetime\",\n \"checkbox\",\n \"select\",\n \"email\",\n \"url\",\n \"phone\",\n];\n\ninterface ColumnDraft {\n header: string;\n label: string;\n guess: ColumnGuess;\n /** A choice column's words as the person edits them, comma separated. */\n options: string;\n /** Kept in the new table (the JSON dialog's \"Use\" box, adopted 2026-09-29). */\n use: boolean;\n}\n\n/** The shapes a source holds, top to bottom. */\nexport function shapesOfSource(source: SaveToTableSource): TableShape[] {\n if (source.grid) {\n const s = shapeOfGrid(source.grid.headers, source.grid.rows, source.title ?? null, source.grid.from);\n return s ? [s] : [];\n }\n if (source.value !== undefined) {\n const s = shapeOfValue(source.value, source.title ?? null);\n return s ? [s] : [];\n }\n return readTableShapes(source.text ?? \"\");\n}\n\nfunction draftsFor(headers: string[], rows: Array<Record<string, string>>): ColumnDraft[] {\n return headers.map((header) => {\n const guess = guessColumn(rows.map((r) => r[header] ?? \"\"));\n return { header, label: header, guess, options: (guess.options ?? []).join(\", \"), use: true };\n });\n}\n\n/** Unique keys from labels: the store's own token rule, a second \"notes\" becomes `notes_2`. */\nfunction keysFor(labels: string[]): string[] {\n const used = new Set<string>();\n return labels.map((label, i) => {\n const base = tokenFor(label) === \"table\" && !/table/i.test(label) ? `column_${i + 1}` : tokenFor(label);\n let key = base;\n let n = 2;\n while (used.has(key)) key = `${base}_${n++}`;\n used.add(key);\n return key;\n });\n}\n\n/** A name no table of yours already has: \"Home exercises\" → \"Home exercises 2\". */\nfunction freeName(name: string, taken: readonly string[]): string {\n const lower = new Set(taken.map((t) => t.trim().toLowerCase()));\n const base = name.trim() || \"Saved table\";\n if (!lower.has(base.toLowerCase())) return base;\n for (let n = 2; n < 100; n += 1) if (!lower.has(`${base} ${n}`.toLowerCase())) return `${base} ${n}`;\n return `${base} ${Date.now()}`;\n}\n\nasync function sha256Text(text: string): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction typeWord(t: GuessedFieldType): string {\n return fieldTypeChoice(t)?.label ?? t;\n}\n\nexport function SaveToTable({ source, shapeIndex = 0, onOpenTable, onSaved, onClose, makeAtOnce = false, className }: SaveToTableProps) {\n const client = useRecordsClient();\n const shapes = useMemo(() => shapesOfSource(source), [source]);\n const [which, setWhich] = useState(() => Math.min(Math.max(0, shapeIndex), Math.max(0, shapes.length - 1)));\n const shape = shapes[which] ?? null;\n const [split, setSplit] = useState<string>(\"\");\n const reading = shape?.splits.find((s) => s.delimiter === split) ?? null;\n const headers = reading?.headers ?? shape?.headers ?? [];\n const rows = reading?.rows ?? shape?.rows ?? [];\n\n const [target, setTarget] = useState<\"new\" | \"existing\">(\"new\");\n const tables = useTables();\n // Tables a person keeps (`tablePicking.ts`) — never a platform table or one the app keeps.\n const own = tablePickerEntries(tables.data ?? [])\n .entries.map((e) => e.table)\n .filter((t) => laneFor(t) !== \"system\");\n const levels = useMyLevels(own.map((t) => t.id));\n const writable = own\n .filter((t) => {\n const level = levels.data?.[t.id];\n return level === \"edit_content\" || level === \"editor\" || level === \"admin\";\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n const [tableId, setTableId] = useState<string>(\"\");\n\n const proposedName = shape?.name ?? source.title ?? \"Saved table\";\n const [name, setName] = useState<string | null>(null);\n // ADOPTED FROM THE DIALOGS THIS SCREEN REPLACED (2026-09-29): a new table's description (the\n // \"Save as data\" dialog and the JSON dialog both had one), and — for rows added to a table the\n // person has — \"replace what it holds\", done as an archive the person confirms first.\n const [description, setDescription] = useState(\"\");\n const [replaceAsked, setReplaceAsked] = useState(false);\n const [replacing, setReplacing] = useState(false);\n const [replaced, setReplaced] = useState<{ tableId: string; count: number } | null>(null);\n const [drafts, setDrafts] = useState<ColumnDraft[] | null>(null);\n const columns = drafts ?? draftsFor(headers, rows);\n const [problem, setProblem] = useState<RecordsError | null>(null);\n const [phase, setPhase] = useState<\"ready\" | \"making\" | \"writing\" | \"done\">(\"ready\");\n const [made, setMade] = useState<{ tableId: Uuid; sentence: string } | null>(null);\n\n const sourceName = source.title?.trim() || shape?.name || \"the rows above\";\n // makeAtOnce: press \"Make the table\" once, as soon as the person's tables are known (so the new\n // name never collides with one they have).\n const makeRef = useRef<(() => Promise<void>) | null>(null);\n const madeAtOnce = useRef(false);\n const tablesKnown = tables.data !== undefined;\n useEffect(() => {\n if (!makeAtOnce || madeAtOnce.current || !shape || !tablesKnown || !makeRef.current) return;\n madeAtOnce.current = true;\n void makeRef.current();\n }, [makeAtOnce, shape, tablesKnown]);\n const sourceText = useMemo(() => JSON.stringify({ headers, rows }), [headers, rows]);\n // ONE object per reading, so the wizard plans these rows once — a fresh object every render would\n // be a fresh source every render.\n const wizardSource = useMemo(\n () => ({ name: sourceName, parsed: { headers, rows }, text: sourceText }),\n [sourceName, headers, rows, sourceText],\n );\n\n if (!shape) {\n return (\n <div className={cn(\"flex flex-col gap-2 text-sm\", className)} data-save-to-table=\"\">\n <p className=\"text-muted-foreground\">\n Nothing here reads as rows — a table, a list, lines of “Name: value”, CSV or pasted spreadsheet cells can be\n saved as a table.\n </p>\n </div>\n );\n }\n\n const chooseShape = (i: number) => {\n setWhich(i);\n setSplit(\"\");\n setDrafts(null);\n setName(null);\n };\n\n const make = async () => {\n setProblem(null);\n const kept = columns.filter((c) => c.use);\n if (kept.length === 0) {\n setProblem(refusalOf(\"invalid_argument\", \"Every column is left out.\", \"Keep at least one column, then make the table.\"));\n return;\n }\n const labels = kept.map((c) => c.label.trim() || c.header);\n if (new Set(labels.map((l) => l.toLowerCase())).size !== labels.length) {\n setProblem(refusalOf(\"invalid_argument\", \"Two columns have the same name.\", \"Rename one of them, then make the table.\"));\n return;\n }\n const keys = keysFor(labels);\n const fields: NewFieldSpec[] = kept.map((c, i) => {\n const options = c.options.split(\",\").map((o) => o.trim()).filter(Boolean);\n return {\n key: keys[i]!,\n label: labels[i]!,\n type: c.guess.type,\n sort: (i + 1) * 10,\n ...(c.guess.type === \"select\" ? { options } : {}),\n ...(c.guess.type === \"currency\" && c.guess.unit ? { unit: c.guess.unit } : {}),\n ...(c.guess.type === \"datetime\" && c.guess.kind ? { kind: c.guess.kind } : {}),\n };\n });\n setPhase(\"making\");\n try {\n // AN EARLIER TRY THAT WAS CUT OFF (the page closed mid-make) IS FINISHED, NEVER DUPLICATED:\n // same name, made in the last day, no rows, no column this save lacks (`unfinishedTable.ts`).\n const earlier = await findUnfinishedTable(client, name ?? proposedName, fields.map((f) => f.key), rows.length);\n let tableName: string;\n let newId: Uuid;\n if (earlier) {\n tableName = (name ?? proposedName).trim();\n newId = earlier.tableId;\n const lacking = fields.filter((f) => !earlier.haveKeys.has(f.key));\n const added = await addFields(client, newId, lacking);\n if (!added.ok) {\n setProblem(added.error);\n setPhase(\"ready\");\n return;\n }\n // The earlier try's choice columns hold the words of ITS rows: top them up with this save's.\n const present = await client.fields({ table_id: newId });\n if (present.ok) {\n for (const owed of choiceWordsOwed(present.data, fields)) {\n const topped = await client.fieldUpdate({ field_id: owed.fieldId, patch: { options_add: owed.words } });\n if (!topped.ok) {\n setProblem(topped.error);\n setPhase(\"ready\");\n return;\n }\n }\n }\n } else {\n tableName = freeName(name ?? proposedName, (tables.data ?? []).map((t) => t.name));\n const born = await declareTable(client, { name: tableName, fields });\n if (!born.ok) {\n setProblem(born.error);\n setPhase(\"ready\");\n return;\n }\n newId = born.data;\n }\n if (description.trim()) {\n // The table's own description, written the way its settings write it; a refusal is said\n // beside the result and never undoes the table.\n // The table was just made here: its version is the one it was made at, read once.\n const described = await updateOnTheWinningVersion(\n client,\n newId,\n { description: description.trim() },\n await readTableVersionNow(client, newId),\n { description: null },\n );\n if (!described.ok) setProblem(described.error);\n }\n if (rows.length === 0) {\n setMade({ tableId: newId, sentence: `“${tableName}” was made with ${kept.length} column${kept.length === 1 ? \"\" : \"s\"} and no rows yet.` });\n setPhase(\"done\");\n onSaved?.(newId, \"new\");\n return;\n }\n setPhase(\"writing\");\n const mapping: Record<string, string> = {};\n kept.forEach((c, i) => {\n mapping[c.header] = keys[i]!;\n });\n const opened = await client.importBegin({\n table_id: newId,\n format: \"csv\",\n source_name: sourceName,\n source_columns: kept.map((c) => c.header),\n file_hash: await sha256Text(sourceText),\n file_bytes: sourceText.length,\n policy: { on_duplicate: \"skip\", unmapped: \"ignore\" },\n });\n if (!opened.ok) {\n setProblem(opened.error);\n setMade({ tableId: newId, sentence: `“${tableName}” was made, and its rows were not written.` });\n setPhase(\"done\");\n return;\n }\n // A column the person left out is not sent at all — not even for the store to ignore.\n const sent = rows.map((r) => Object.fromEntries(kept.map((c) => [c.header, r[c.header] ?? \"\"])));\n let take = opened.data.rows_per_call ?? 250;\n let at = 0;\n while (at < sent.length) {\n const batch = sent.slice(at, at + take);\n const answered = await client.importRows({ import_id: opened.data.import_id, rows: batch, mapping });\n if (!answered.ok) {\n setProblem(answered.error);\n break;\n }\n at += batch.length;\n if (answered.data.rows_per_call) take = answered.data.rows_per_call;\n }\n const finished = await client.importFinish({ import_id: opened.data.import_id, unmapped: \"ignore\" });\n const sentence = finished.ok\n ? `“${tableName}” was made with ${kept.length} column${kept.length === 1 ? \"\" : \"s\"}. ${finished.data.message}`\n : `“${tableName}” was made.`;\n if (!finished.ok) setProblem(finished.error);\n setMade({ tableId: newId, sentence });\n setPhase(\"done\");\n onSaved?.(newId, \"new\");\n } catch (thrown) {\n setProblem(refusalFromThrown(thrown, \"The table could not be made.\", \"Try again in a moment.\", \"internal\"));\n setPhase(\"ready\");\n }\n };\n\n makeRef.current = make;\n const busy = phase === \"making\" || phase === \"writing\";\n\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-3 text-sm\", className)} data-save-to-table=\"\">\n {/* WHAT WAS READ — and, when the text holds several shapes, which one. */}\n <div className=\"flex flex-wrap items-center gap-2\">\n {shapes.length > 1 ? (\n <Select value={String(which)} onValueChange={(v) => chooseShape(Number(v))} disabled={busy || phase === \"done\"}>\n <SelectTrigger size=\"sm\" aria-label=\"Which of these to save\" className=\"min-w-[16rem]\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {shapes.map((s, i) => (\n <SelectItem key={i} value={String(i)}>\n {s.name ? `${s.name} — ` : \"\"}\n {s.said}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <span className=\"text-muted-foreground\" data-save-to-table-said=\"\">\n {shape.name ? `${shape.name} — ` : \"\"}\n {shape.said}\n </span>\n )}\n {shape.splits.length > 0 ? (\n <Select\n value={split || \"__one__\"}\n onValueChange={(v) => {\n setSplit(v === \"__one__\" ? \"\" : v);\n setDrafts(null);\n }}\n disabled={busy || phase === \"done\"}\n >\n <SelectTrigger size=\"sm\" aria-label=\"How to read the list\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__one__\">One column</SelectItem>\n {shape.splits.map((s) => (\n <SelectItem key={s.delimiter} value={s.delimiter}>\n {s.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : null}\n </div>\n\n {/* THE ROWS, AS THEY WILL LAND — the first few, under the names they will have. */}\n <div className=\"max-h-48 overflow-auto rounded border\">\n <table className=\"w-full border-collapse text-xs\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n {columns.map((c) => (\n <th key={c.header} className=\"border-b px-2 py-1 text-left font-medium\">\n {c.label || c.header}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {rows.slice(0, 8).map((r, i) => (\n <tr key={i} className=\"border-b last:border-0\">\n {columns.map((c) => (\n <td key={c.header} className=\"max-w-[16rem] truncate px-2 py-1 align-top\">\n {r[c.header] ?? \"\"}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n {rows.length > 8 ? <p className=\"-mt-2 text-xs text-muted-foreground\">and {rows.length - 8} more</p> : null}\n\n {phase === \"done\" && made ? (\n <div className=\"flex flex-col gap-2\" data-save-to-table-done=\"\">\n <p>{made.sentence}</p>\n {problem ? <RefusalNotice error={problem} /> : null}\n <div className=\"flex gap-2\">\n {onOpenTable ? (\n <Button size=\"sm\" onClick={() => onOpenTable(made.tableId)}>\n Open the table\n </Button>\n ) : null}\n {onClose ? (\n <Button size=\"sm\" variant=\"outline\" onClick={onClose}>\n Done\n </Button>\n ) : null}\n </div>\n </div>\n ) : (\n <>\n {/* WHERE THE ROWS GO. */}\n <div className=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label=\"Where to save these rows\">\n <Button\n size=\"sm\"\n variant={target === \"new\" ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={target === \"new\"}\n disabled={busy}\n onClick={() => setTarget(\"new\")}\n >\n A new table\n </Button>\n <Button\n size=\"sm\"\n variant={target === \"existing\" ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={target === \"existing\"}\n disabled={busy}\n onClick={() => setTarget(\"existing\")}\n >\n Add to a table\n </Button>\n </div>\n\n {target === \"new\" ? (\n <div className=\"flex flex-col gap-2\" data-save-to-table-new=\"\">\n <label className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium\">Table name</span>\n <Input\n value={name ?? proposedName}\n onChange={(e) => setName(e.target.value)}\n disabled={busy}\n aria-label=\"Table name\"\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium\">Description (optional)</span>\n <Input\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n disabled={busy}\n aria-label=\"Table description\"\n placeholder=\"What these rows are for\"\n />\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium\">Columns</span>\n {columns.map((c, i) => (\n <div\n key={c.header}\n className=\"grid grid-cols-[auto_minmax(8rem,1fr)_minmax(9rem,12rem)] items-center gap-2\"\n data-save-to-table-column={c.header}\n >\n <Checkbox\n checked={c.use}\n disabled={busy}\n aria-label={`Keep the column ${c.label || c.header}`}\n onCheckedChange={(v) => setDrafts(columns.map((d, j) => (j === i ? { ...d, use: v === true } : d)))}\n />\n <Input\n value={c.label}\n aria-label={`Name of the column ${c.header}`}\n disabled={busy || !c.use}\n onChange={(e) =>\n setDrafts(columns.map((d, j) => (j === i ? { ...d, label: e.target.value } : d)))\n }\n />\n <Select\n value={c.guess.type}\n disabled={busy || !c.use}\n onValueChange={(v) =>\n setDrafts(\n columns.map((d, j) => {\n if (j !== i) return d;\n const type = v as GuessedFieldType;\n const again = guessColumn(rows.map((r) => r[d.header] ?? \"\"));\n const words = type === \"select\" && !d.options ? (again.options ?? Array.from(new Set(rows.map((r) => (r[d.header] ?? \"\").trim()).filter(Boolean)))).join(\", \") : d.options;\n return { ...d, guess: { ...d.guess, type }, options: words };\n }),\n )\n }\n >\n <SelectTrigger size=\"sm\" aria-label={`What the column ${c.label || c.header} holds`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {SAVE_TO_TABLE_TYPES.map((t) => (\n <SelectItem key={t} value={t}>\n {typeWord(t)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {c.guess.type === \"select\" && c.use ? (\n <Input\n className=\"col-span-2 col-start-2\"\n value={c.options}\n aria-label={`The choices of ${c.label || c.header}`}\n disabled={busy}\n onChange={(e) =>\n setDrafts(columns.map((d, j) => (j === i ? { ...d, options: e.target.value } : d)))\n }\n />\n ) : null}\n </div>\n ))}\n </div>\n {problem ? <RefusalNotice error={problem} /> : null}\n <div className=\"flex items-center gap-2\">\n <Button size=\"sm\" disabled={busy} onClick={() => void make()}>\n {phase === \"making\"\n ? \"Making the table…\"\n : phase === \"writing\"\n ? \"Writing the rows…\"\n : rows.length === 0\n ? \"Make the table with these columns\"\n : `Make the table with ${rows.length} row${rows.length === 1 ? \"\" : \"s\"}`}\n </Button>\n <span className=\"text-xs text-muted-foreground\">Nothing is made until you press it.</span>\n </div>\n </div>\n ) : (\n <div className=\"flex flex-col gap-2\" data-save-to-table-existing=\"\">\n {tables.loading || levels.loading ? (\n <p className=\"text-muted-foreground\">Reading your tables…</p>\n ) : tables.error ? (\n <RefusalNotice error={tables.error} />\n ) : writable.length === 0 ? (\n <p className=\"text-muted-foreground\">\n There is no table in this organization you can add rows to. Make a new one instead.\n </p>\n ) : (\n <Select value={tableId} onValueChange={setTableId} disabled={busy}>\n <SelectTrigger size=\"sm\" aria-label=\"Which table to add the rows to\" className=\"min-w-[16rem]\">\n <SelectValue placeholder=\"Choose a table\" />\n </SelectTrigger>\n <SelectContent>\n {writable.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {t.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n {tableId ? (\n <div className=\"flex flex-col gap-1\" data-save-to-table-replace=\"\">\n {replaced?.tableId === tableId ? (\n <p className=\"text-xs text-muted-foreground\">\n {replaced.count === 0\n ? \"The table held no rows, so nothing was archived.\"\n : `${replaced.count} row${replaced.count === 1 ? \"\" : \"s\"} it held moved to the archive, where ${replaced.count === 1 ? \"it\" : \"they\"} can be restored. The rows below go in their place.`}\n </p>\n ) : (\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={replaceAsked}\n disabled={busy || replacing}\n onCheckedChange={(v) => setReplaceAsked(v === true)}\n aria-label=\"Replace what this table holds\"\n />\n Replace what this table holds (its current rows move to the archive first)\n </label>\n )}\n </div>\n ) : null}\n <ConfirmDialog\n open={replaceAsked && Boolean(tableId) && replaced?.tableId !== tableId}\n onOpenChange={(open) => {\n if (!open && !replacing) setReplaceAsked(false);\n }}\n variant=\"destructive\"\n title={`Move every row of “${writable.find((t) => t.id === tableId)?.name ?? \"this table\"}” to the archive?`}\n description=\"Restorable from Archived items\"\n confirmLabel={replacing ? \"Archiving…\" : \"Archive them\"}\n cancelLabel=\"Keep them\"\n busy={replacing}\n onConfirm={async () => {\n setReplacing(true);\n setProblem(null);\n const ids: Uuid[] = [];\n for (let offset = 0; ; offset += 500) {\n const page = await client.listPage({ table_id: tableId as Uuid, limit: 500, offset });\n if (!page.ok) {\n setProblem(page.error);\n setReplacing(false);\n return;\n }\n ids.push(...page.data.rows.map((r) => r.id as Uuid));\n if (page.data.rows.length + (page.data.locked ?? 0) < 500) break;\n }\n for (let at = 0; at < ids.length; at += 200) {\n const archived = await changeRecordsAt(client, {\n table_id: tableId as Uuid,\n changes: ids.slice(at, at + 200).map((record_id) => ({ op: \"archive\" as const, record_id })),\n });\n if (!archived.ok) {\n setProblem(archived.error);\n setReplacing(false);\n setReplaced({ tableId, count: at });\n return;\n }\n }\n setReplaced({ tableId, count: ids.length });\n setReplacing(false);\n setReplaceAsked(false);\n }}\n />\n {problem && target === \"existing\" ? <RefusalNotice error={problem} /> : null}\n {tableId ? (\n <ImportWizard\n key={`${tableId}:${which}:${split}`}\n tableId={tableId as Uuid}\n source={wizardSource}\n onWrote={() => onSaved?.(tableId as Uuid, \"existing\")}\n onDone={() => (onOpenTable ? onOpenTable(tableId as Uuid) : onClose?.())}\n />\n ) : null}\n </div>\n )}\n </>\n )}\n </div>\n );\n}\n","// src/unfinishedTable.ts — @ai-matrx/records-ui\n//\n// A NEW TABLE IS FOUR ACTS, AND THE PAGE CAN GO AWAY BETWEEN ANY TWO OF THEM.\n//\n// \"Make the table\" declares the table, declares each column, then sends the rows. A person who\n// closes the tab, reloads, or leaves while that runs (1-4 s on a real connection) leaves a table\n// with no rows — and the retry used to see the name taken and make \"… 2\" beside it, so every\n// interrupted try left a husk and the next one a twin.\n//\n// The store has no transaction a client can hold across those calls, so the half-made table is\n// recognized instead of prevented: a table with the very name being asked for, made by this person in the last day,\n// holding no rows (or only some of this save's rows, within minutes), whose columns are all among the ones about to be written, IS the earlier try. The\n// retry finishes it — adds the columns it lacks, sends the rows — and never makes a twin. A table\n// that has more rows than this save carries, or any column this save does not carry, is somebody's table and is left alone.\n\nimport type { Table, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\n\n/** How long a half-made table with NO rows stays \"the earlier try\". */\nexport const UNFINISHED_WINDOW_MS = 24 * 60 * 60 * 1000;\n/**\n * How long a table that holds SOME of this save's rows (never more than the save carries) stays \"the\n * earlier try\": the page can go away after the rows are sent and before the host links them, so the\n * retry finds the table full. Sending the same rows again is safe (the import skips duplicates).\n */\nexport const FILLED_WINDOW_MS = 15 * 60 * 1000;\n\nexport interface UnfinishedTable {\n tableId: Uuid;\n /** The column keys it already has. */\n haveKeys: ReadonlySet<string>;\n}\n\nexport async function findUnfinishedTable(\n client: Pick<RecordsClient, \"tableList\" | \"tableRowCounts\" | \"recordHeaders\" | \"fields\">,\n wantedName: string,\n wantedKeys: readonly string[],\n /** How many rows this save carries. */\n wantedRows: number,\n now: number = Date.now(),\n): Promise<UnfinishedTable | null> {\n const name = wantedName.trim().toLowerCase();\n if (!name) return null;\n const listed = await client.tableList();\n if (!listed.ok) return null;\n const named = listed.data.filter((t: Table) => !t.is_kernel && t.name.trim().toLowerCase() === name);\n if (named.length === 0) return null;\n // A Table's own birth time and maker are not in the list the read door answers; the header door has them.\n const headers = await client.recordHeaders({ ids: named.map((t) => t.id) });\n if (!headers.ok) return null;\n const madeAt = new Map<string, number>();\n for (const h of headers.data) {\n const at = Date.parse(h.created_at);\n if (h.mine && h.deleted_at === null && Number.isFinite(at) && now - at <= UNFINISHED_WINDOW_MS) madeAt.set(h.id, at);\n }\n const candidates = named.filter((t) => madeAt.has(t.id));\n if (candidates.length === 0) return null;\n const counted = await client.tableRowCounts({ table_ids: candidates.map((t) => t.id) });\n if (!counted.ok) return null;\n const rowsOf = new Map(counted.data.map((c) => [c.table_id as string, c.visible_rows]));\n const wanted = new Set(wantedKeys);\n // Newest first: the latest try is the one being retried.\n const ordered = [...candidates].sort((a, b) => (madeAt.get(b.id) ?? 0) - (madeAt.get(a.id) ?? 0));\n for (const t of ordered) {\n const rows = rowsOf.get(t.id) ?? 0;\n if (rows > 0 && (rows > wantedRows || now - (madeAt.get(t.id) ?? 0) > FILLED_WINDOW_MS)) continue;\n const read = await client.fields({ table_id: t.id });\n if (!read.ok) continue;\n const have = new Set(read.data.map((f) => f.key));\n if ([...have].every((k) => wanted.has(k))) return { tableId: t.id, haveKeys: have };\n }\n return null;\n}\n\n/**\n * A retry that FINISHES an earlier try also owes it this save's choice words. The earlier try made each\n * choice column with the words of ITS rows; a retry (or a different answer saved under the same name\n * within the day) carries other words, and a choice column refuses a word it does not have — every row\n * of the save came back \"refused\" with the table sitting empty. `options_add` is idempotent (a live\n * same-words choice adds nothing), so every choice column this save carries and the table already has is\n * topped up with this save's words, never narrowed.\n */\nexport function choiceWordsOwed(\n existing: ReadonlyArray<{ id: string; key: string }>,\n wanted: ReadonlyArray<{ key: string; type: string; options?: readonly string[] }>,\n): Array<{ fieldId: string; words: string[] }> {\n const idOf = new Map(existing.map((f) => [f.key, f.id]));\n const owed: Array<{ fieldId: string; words: string[] }> = [];\n for (const f of wanted) {\n const fieldId = idOf.get(f.key);\n const words = [...new Set((f.options ?? []).map((w) => w.trim()).filter(Boolean))];\n if (f.type === \"select\" && fieldId && words.length > 0) owed.push({ fieldId, words });\n }\n return owed;\n}\n","\"use client\";\n\n// src/ImportWizard.tsx — @ai-matrx/records-ui · SCR-10, SCR-N-7\n//\n// DROP A FILE, SEE WHAT THE STORE MAKES OF IT, FIX WHAT IT GOT WRONG, RUN IT,\n// AND CLICK THROUGH TO THE ROWS THAT DID NOT LAND.\n//\n// WHAT CHANGED, AND WHY IT HAD TO. Until lane IMPORT this screen parsed the file\n// and then called `recordWrite` once per row — one HTTP round trip each. At the\n// five thousand rows a real spreadsheet holds that is five thousand round trips\n// and about half an hour of a person watching a progress bar; there was no\n// duplicate check, so importing a corrected file made a second copy of\n// everything; nothing recorded that a value came from a file; and a refusal\n// carried a row NUMBER into a file this screen no longer had, so \"row 3,184 was\n// refused\" was information nobody could act on.\n//\n// Now the bytes are parsed here (Postgres cannot unzip a workbook) and\n// EVERYTHING after the parse is the store's: `importPlan` says what each column\n// is, `importBegin` gives the run the file's sha-256 as its identity so a\n// re-import doubles nothing, `importRows` writes a BATCH through the one write\n// door and answers one outcome per row, and `importFinish` sends the columns\n// this table does not have to the ONE approvals inbox. This screen holds no\n// import logic of its own — if it did, a file imported from here and the same\n// file imported by the agent would land differently.\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useFields, useRecordsClient, useTable, type Field, type Uuid } from \"@ai-matrx/records/react\";\nimport {\n importCsv,\n importXlsx,\n type ImportColumnPlan,\n type ImportOutcome,\n type ImportPlan,\n type ImportProposal,\n type ImportRun,\n type ParsedImport,\n} from \"@ai-matrx/records/core\";\nimport {\n Badge,\n Button,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n Separator,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { relationNameIndexOf, relationNameKey, relationNamesIn, splitListCell, type RecordsError, type RelationNameIndex } from \"@ai-matrx/records\";\nimport { RefusalLine, RefusalNotice } from \"./Refusal\";\nimport { refusal as refusalOf, refusalFromThrown } from \"./refusals\";\nimport { checkImportRules, refusedCellsOf, type ImportRefusedCell } from \"./importRuleCheck\";\nimport { useTableRights } from \"./host\";\nimport { FilePicker } from \"./FilePicker\";\nimport { fieldName } from \"./names\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { fieldTypeLabel } from \"./parity\";\nimport { fieldTypeChoice } from \"./fieldTypes\";\nimport { editorKindFor } from \"./parity\";\nimport { choiceOptionsOf, valueFromPastedText, type ChoiceOptions } from \"./pasteValues\";\nimport { useChoiceNudge } from \"./choiceNudge\";\nimport { IMPORT_KINDS, datesOfColumn, declarationFor, exactDuplicateRows, importKindOfPlan, looksLike, looksLikeDates, type ImportKind } from \"./importKinds\";\nimport { PickOne } from \"./PickOne\";\nimport { combineRows, sameRecordLikely, titleRepeats } from \"./importCombine\";\nimport { groupReasons, offerDownload, refusedFileName, refusedRowsCsv } from \"./importRefusals\";\n\n/**\n * IMPORT-2: THE ONLY BATCH SIZE THIS SCREEN KNOWS, AND IT IS A FALLBACK.\n *\n * Until 2026-09-22 this screen sent 250 rows a call because 250 was written\n * here. MEASURED on the main database that day with a real 1,000-row dispatch\n * file: 250 rows cost 3.6–4.0 s on a quiet database and 8.2 s — SQLSTATE 57014,\n * PostgREST's ~8 s ceiling, the whole call rolled back — on a loaded one. A\n * batch size is not this screen's to choose: it depends on how many columns the\n * table has, what the guards on them cost, and what the database is busy with.\n *\n * So the STORE says it. `importBegin` answers `rows_per_call` for the first\n * call, and every `importRows` answers the `rows_per_call` it measured on\n * itself for the next one. This constant is used only if a store older than\n * IMPORT-2 answers neither.\n */\nconst BATCH = 250;\n/**\n * How many values of a column the store judges its kind by (VISION-REACH G4). It was the first 40\n * rows, so twelve last names in forty rows read as \"a few repeating words\" and became a choice\n * list; the whole file (up to this many rows) is what a column's kind is read from now.\n */\nconst SAMPLES = 2000;\n\n/** How many new columns one \"add the columns\" call declares (VISION-REACH G6). */\nconst COLUMNS_PER_CALL = 3;\n\n/**\n * What a row does with a name its relation column cannot link. `merge` (VISION-REACH lane 5): the\n * records of one name in the other table are combined into one, through the store's own merge door,\n * so the row links instead of being refused — the way out of \"2 records called Cox family\" when the\n * duplicates are the other table's problem, not this file's.\n */\ntype UnlinkedChoice = \"create\" | \"empty\" | \"skip\" | \"merge\";\n\n/**\n * FIX-11B F9: THE NARROWEST A \"GOES TO\" CONTROL MAY EVER BE, IN PIXELS.\n *\n * VERIFIER-11 measured all seven of them at **10 px** in a 416 px right rail at\n * 1600x1000 — slivers on the one screen where the whole import is decided, so\n * the person could not read what ANY column was mapped to. A `<table>` with\n * `table-fixed` and a `<colgroup>` was supposed to hold them open and did not:\n * a table's fixed layout is only a HINT once its container is narrower than the\n * declared widths, and a bare `<select>` has no intrinsic width to defend\n * itself with. So the row is a GRID whose \"Goes to\" track is `minmax(14rem, …)`\n * — a floor a container cannot argue with — and the control is the design\n * system's `Select`, which is a button and carries its own minimum.\n *\n * `check:import-mapping-is-readable` measures the real control in a real\n * browser against this number and goes red below it.\n */\nexport const GOES_TO_MIN_PX = 224; // 14rem\n\n/**\n * Radix's Select has no empty value — an empty string is how it says \"nothing is\n * chosen\" — so \"leave this column out\" is a real, named choice with a token of\n * its own rather than an absence the control cannot represent.\n */\nconst ABSENT = \"__absent__\";\n/** \"Leave this column out\" on its own (VISION-REACH G4) — never sent, never offered as a column. */\nconst LEAVE = \"__leave__\";\n/**\n * THE NAME COLUMN'S WORDS, FROM A COLUMN THAT ALSO KEEPS ITS OWN COLUMN (VISION-REACH lane 5). A\n * pledge list has no name of its own; a person names each pledge by its family — and \"Family\" must\n * ALSO link to Families. One header cannot go two places in the mapping, so the rows carry the words\n * a second time under this key, mapped to the title column. Never shown, never offered as a column.\n */\nexport const TITLE_COPY = \"__name__\";\n\n/** A relation column this import is about to make, as the Field the relation ask reads. */\nfunction planRelationField(c: ImportColumnPlan): Field {\n return {\n id: `plan:${c.field_key}`,\n key: c.field_key,\n label: c.label || c.header,\n name: null,\n type: \"relation\",\n multi: false,\n dated: false,\n rules: [],\n config: {},\n required: false,\n default: null,\n sort: null,\n relation_target: c.relation_target ?? null,\n relation_max: null,\n on_target_delete: null,\n } as unknown as Field;\n}\n\n/**\n * FIX-11B F2: THE COLUMN A RECORD IS NAMED BY, GUESSED THE WAY A PERSON WOULD.\n *\n * An import that creates its own columns used to leave the table's title column\n * empty, so all 312 records it wrote read `—` in the first column of the grid —\n * every one of them nameless, in a store whose own rule is that a record without\n * a title cannot be a chip (REC-2). Nothing was broken; nobody had been ASKED.\n * So the wizard asks, and opens on the answer a person would have given: a\n * header that says it is the name, else the first column the file's own plan\n * typed as text.\n */\nfunction obviousTitleColumn(\n columns: ImportColumnPlan[],\n rows: ReadonlyArray<Record<string, string>> = [],\n /** The table's name column's label and the table's own names (VISION-REACH G4). */\n names: { title?: string | null; table?: string | null; singular?: string | null } = {},\n): string | null {\n // VISION-REACH G4: THE COLUMN THAT SAYS WHAT THIS TABLE NAMES. The dry run's physicians table\n // opened on \"Patient name\" because the header ended in \"name\". A header spelled like the name\n // column wins; else the header sharing the most words with the name column and the table\n // (\"Referring physician\" for Referring physicians / Physician name), \"name\" and \"id\" not counting.\n const words = (t: string | null | undefined) =>\n new Set(\n (t ?? \"\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .map((w) => w.replace(/s$/, \"\"))\n .filter((w) => w.length > 1 && w !== \"name\" && w !== \"id\"),\n );\n const flat = (t: string) => t.toLowerCase().replace(/[^a-z0-9]+/g, \" \").trim();\n // VISION-REACH lane 5 (persona P03): A NAME IS WORDS THAT TELL ROWS APART. \"Date received\" — mostly\n // blank, dates where filled — became every pledge's name because it was the only text column left.\n // A column whose values are mostly numbers or read as dates is never a name, whatever the plan\n // typed it; and a column of words that points at another table (Family) may be one — the wizard\n // then keeps the link too (TITLE_COPY).\n const valuesOf = (c: ImportColumnPlan) => rows.map((r) => String(r[c.header] ?? \"\").trim()).filter(Boolean);\n // \"Sep 20\", \"20 Sep\", \"9/20\", \"2026-09-20\": a day written any common way, with or without a year.\n const MONTH = \"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\\\\.?\";\n const dateish = new RegExp(`^(?:${MONTH}\\\\s+\\\\d{1,2}(?:,?\\\\s*\\\\d{2,4})?|\\\\d{1,2}\\\\s+${MONTH}(?:\\\\s+\\\\d{2,4})?|\\\\d{1,4}[/.-]\\\\d{1,2}(?:[/.-]\\\\d{1,4})?)$`, \"i\");\n const worded = (c: ImportColumnPlan) => {\n const v = valuesOf(c);\n // Empty, or blank on most rows (a \"Date received\" that unpaid pledges leave empty), is no name.\n if (v.length === 0 || (rows.length > 0 && v.length / rows.length < 0.5)) return false;\n const numeric = v.filter((x) => /^[\\d\\s.,:$%-]+$/.test(x)).length;\n if (numeric / v.length > 0.4) return false;\n const dates = v.filter((x) => dateish.test(x)).length;\n if (dates / v.length > 0.4) return false;\n return !looksLikeDates(rows, c.header);\n };\n const wordy = columns.filter((c) => (c.type === \"text\" || c.type === \"long_text\" || c.type === \"select\" || c.type === \"relation\") && worded(c));\n const texty = wordy.filter((c) => c.type === \"text\" || c.type === \"long_text\");\n if (names.title) {\n const exact = columns.find((c) => flat(c.header) === flat(names.title!));\n if (exact) return exact.header;\n }\n const wanted = new Set([...words(names.title), ...words(names.table), ...words(names.singular)]);\n if (wanted.size > 0) {\n let best: { header: string; score: number } | null = null;\n for (const c of wordy) {\n const overlap = [...words(c.header)].filter((w) => wanted.has(w)).length;\n if (overlap === 0) continue;\n const distinct = new Set(valuesOf(c).map((v) => v.toLowerCase())).size;\n const score = overlap * 100000 + distinct;\n if (!best || score > best.score) best = { header: c.header, score };\n }\n if (best) return best.header;\n }\n // Else the first column of words whose every value is different — what a name does.\n for (const c of texty) {\n const values = valuesOf(c);\n if (new Set(values.map((v) => v.toLowerCase())).size === values.length) return c.header;\n }\n const says = /^(title|name|record|customer|client|company|job|item|subject|label|description|room|patient|product|task|project)\\b|(\\bname|\\btitle)$/i;\n const named = wordy.find((c) => says.test(c.header.trim()));\n if (named) return named.header;\n // VERIFIER-30 #2: \"the first text column\" named every record of a rooms paste after its FLOOR\n // (\"1\", \"1\", \"Lower\"). A name is words and it tells rows apart: the column of words whose values\n // are most often different from each other, first column breaking ties.\n let best: { header: string; score: number } | null = null;\n for (const c of texty) {\n const score = new Set(valuesOf(c).map((v) => v.toLowerCase())).size;\n if (!best || score > best.score) best = { header: c.header, score };\n }\n if (best && best.score > 0) return best.header;\n // No column of plain words: a column of words that points at another table names the rows\n // (\"Cox family\" on every pledge), and the wizard keeps its link as well.\n const pointing = wordy[0];\n if (pointing) return pointing.header;\n // Nothing in this file is a name. The panel asks rather than naming records by a date or a number.\n return null;\n}\n\n/**\n * ROWS THAT ARE NOT A FILE (lane SAVE-AS-TABLE-EVERYWHERE, 2026-09-29): a table in a chat answer,\n * a list in a note, a CSV paste, a kind value — already read into headers and rows by\n * `readTableShapes`. The wizard plans, maps, asks and writes them exactly as it does a file's rows,\n * through the same doors, so \"add these rows to that table\" has ONE importer whatever it came from.\n */\nexport interface ImportSource {\n /** What the rows came from, in words (\"Home exercises after knee surgery\"). */\n name: string;\n parsed: ParsedImport;\n /** The text the rows were read from; its sha-256 is the run's identity, so the same rows twice write nothing. */\n text: string;\n}\n\nexport interface ImportWizardProps {\n tableId: Uuid;\n /** Rows to import instead of a file. When present the file control is not offered. */\n source?: ImportSource | undefined;\n /**\n * FIX-12 F2: THE PERSON SAYS WHEN THEY ARE FINISHED WITH AN IMPORT — NOT THE\n * LAST ROW.\n *\n * This used to fire the moment `io_import_finish` answered, and every host\n * wires it to close the rail. So the screen that finally knew the truth — the\n * ledger sentence, the refusal list, the columns that went to the inbox — was\n * unmounted in the same tick it became true. VERIFIER-12 watched a 40-row file\n * land 28 and refuse 12 and saw NOTHING at all: the whole run fitted inside\n * one call, so the report existed for less than a paint. A long file only\n * looked better because the person had time to read the PROGRESS; its report\n * was destroyed just as fast.\n *\n * It is now the \"Done\" button on the report, and nothing else calls it.\n */\n onDone?: ((written: number) => void) | undefined;\n /**\n * FIX-12 F2: the rows landed. Fired when the run finishes, for a host that\n * needs to refresh behind the panel — never for closing it.\n */\n onWrote?: ((written: number) => void) | undefined;\n /**\n * A BRAND-NEW TABLE HAS NOTHING TO REVIEW (2026-10-11). \"Next: columns\" in the New table window\n * made the table and stopped at this screen; a person who read the button as \"make my table\" was\n * left with an empty table holding only Title. With `autoRun` the import runs by itself the moment\n * the plan is ready and the Import button would be pressable, and the report is what is shown.\n */\n autoRun?: boolean | undefined;\n className?: string | undefined;\n}\n\ntype Phase = \"waiting\" | \"reading\" | \"planning\" | \"ready\" | \"linking\" | \"declaring\" | \"writing\" | \"done\";\n\n/** VISION-REACH G4: kinds whose values a text-like column would hold as mere words. */\nconst TYPED_VALUES = new Set([\"datetime\", \"number\", \"currency\", \"percent\", \"checkbox\"]);\nfunction valuesLookTyped(type: string): boolean {\n return TYPED_VALUES.has(type);\n}\n/** Whether a column of `target` kind takes values the store read as `values`. */\nfunction kindTakes(target: string, values: string): boolean {\n if (target === values) return true;\n const numeric = [\"number\", \"currency\", \"percent\"];\n return numeric.includes(target) && numeric.includes(values);\n}\n\n/** \"line 4\", \"lines 4, 9, 12\", \"lines 4, 9 and 6 more\" — where a name sits in the file. */\nfunction linesWord(lines: number[], word: (row: number) => string): string {\n const shown = lines.slice(0, 3).map(word).join(\", \");\n return lines.length > 3 ? `${shown} +${lines.length - 3}` : shown;\n}\n\n/**\n * The file's identity. Web Crypto is in every browser this app supports and in\n * Node 18+; where it genuinely is not, the import still runs and SAYS that it\n * cannot recognize this file again — never a fabricated hash, which would make\n * two different files look like the same one and silently skip the second.\n */\nasync function sha256(bytes: ArrayBuffer | Uint8Array): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * ONE WORD PER TYPE, EVERYWHERE. `FIELD_TYPE_CHOICES` is the list the \"Add\n * field\" panel offers and the settings row reads back; the wizard reads the\n * same one, so a column called \"Money\" here is called \"Money\" there. A store\n * word this list has no sentence for shows as itself rather than as nothing —\n * `parityTypesWithNoExplanation()` fails the suite the moment that happens.\n */\nfunction typeWord(t: string): string {\n // 🚨 NEVER THE STORE'S OWN TOKEN (VERIFIER-15 M5, VERIFIER-16 M8). A column this\n // table already has arrives with the FIELD's type, and the store's word for a\n // number is `range` — which this printed at a person as \"range\". A matched\n // column is named from its Field (`fieldTypeLabel`, below); this is the word for\n // everything else, and a token it has no sentence for is written out, not shown raw.\n if (t === \"range\") return fieldTypeChoice(\"number\")?.label ?? \"Number\";\n return fieldTypeChoice(t)?.label ?? (t === \"relation\" ? \"Points at another table\" : humanizeIdentifier(t));\n}\n\n/**\n * THE LINE A PERSON SEES IN THEIR SPREADSHEET (VERIFIER-16 M8).\n *\n * The store numbers a file's rows from 1 across the whole run, and so does\n * `checkImportRules` — the first ROW UNDER THE HEADER is 1. The file a person has\n * open puts its column names on line 1, so that row is on line 2. Every place this\n * wizard says \"line\" goes through here, so the refused `-3` on line 3 of the file\n * is called line 3 and never line 2.\n */\nexport function lineInYourFile(dataRow: number): number {\n return dataRow + 1;\n}\n\n/**\n * B4-03 (2026-09-30): the footer says where EVERY column goes. \"1 of 4 columns go into this table\"\n * read as \"three are dropped\" to an Editor whose three went to the approvals inbox — and they were\n * dropped, until the store kept their values with the waiting column. Now it says so.\n */\nexport function columnsSentence(mapped: number, total: number, unmapped: \"propose\" | \"create\" | \"ignore\"): string {\n const rest = total - mapped;\n if (rest <= 0) return `${mapped} of ${total} columns go into this table`;\n if (unmapped === \"create\") return `${total} of ${total} columns go into this table · ${rest} new`;\n if (unmapped === \"ignore\") return `${mapped} of ${total} columns go into this table · ${rest} left out`;\n return `${mapped} of ${total} go in now · ${rest} wait for approval with their values`;\n}\n\n/** THE REPORT NAMES COLUMNS IN THE ORDER THE FILE HAD THEM (walk 2026-10-17: the store answers in the order\n * it made them — typed ones first — so \"Email, Phone, Supplier…\" read differently from the paste). */\nexport function inFileOrder<T extends { column: string }>(added: T[], headers: string[]): T[] {\n const at = (c: T) => {\n const i = headers.indexOf(c.column);\n return i < 0 ? headers.length : i;\n };\n return added.map((c, i) => ({ c, i })).sort((a, b) => at(a.c) - at(b.c) || a.i - b.i).map((x) => x.c);\n}\n\nexport function ImportWizard({ tableId, source, onDone, onWrote, autoRun, className }: ImportWizardProps) {\n const client = useRecordsClient();\n const table = useTable(tableId);\n const fields = useFields(tableId);\n const rights = useTableRights(table.data);\n\n const [phase, setPhase] = useState<Phase>(\"waiting\");\n // 🚨 A REFUSAL, NEVER ITS RAW MESSAGE (lane REFUSAL-SWEEP, 2026-09-23). Six\n // of these setters handed the store's `error.message` straight to a red\n // paragraph, past the machine-identity filter every other screen goes through.\n const [problem, setProblem] = useState<RecordsError | null>(null);\n const [parsed, setParsed] = useState<ParsedImport | null>(null);\n const [rows, setRows] = useState<Array<Record<string, string>>>([]);\n const [plan, setPlan] = useState<ImportPlan | null>(null);\n const [mapping, setMapping] = useState<Record<string, string>>({});\n const [dedupeKey, setDedupeKey] = useState<string>(\"\");\n /** VISION-REACH G4: the file's columns a person left out by name. Stripped before anything is sent. */\n const [leftOut, setLeftOut] = useState<Set<string>>(() => new Set());\n /** VISION-REACH lane 5: the header whose words name each record while it also keeps its own column. */\n const [titleFrom, setTitleFrom] = useState<string | null>(null);\n /** Rows with the same name become one record (`combine`) or stay several (`each`); null = the panel's default. */\n const [combine, setCombine] = useState<\"combine\" | \"each\" | null>(null);\n /** The person chose what makes a row the same row; the panel's default stops moving it. */\n const [dedupeChosen, setDedupeChosen] = useState(false);\n /** VISION-REACH G1: each mapped relation column's target, indexed by the names the file carries. */\n const [relationIndex, setRelationIndex] = useState<Map<string, RelationNameIndex>>(() => new Map());\n const [relationProblem, setRelationProblem] = useState<RecordsError | null>(null);\n /** What the rows naming an unlinkable record do, per relation column. */\n const [unlinkedChoice, setUnlinkedChoice] = useState<Record<string, { unmatched: UnlinkedChoice; ambiguous: UnlinkedChoice }>>({});\n const [onDuplicate, setOnDuplicate] = useState<\"skip\" | \"update\">(\"skip\");\n /** VISION-REACH G14: what a NEW column is made as, when the person chose it. */\n const [kindChoice, setKindChoice] = useState<Record<string, ImportKind>>({});\n /** VISION-REACH G14: what a date column's unreadable cells do, per header. */\n const [dateMiss, setDateMiss] = useState<Record<string, \"empty\" | \"skip\">>({});\n /** VISION-REACH G14: rows repeating an earlier row exactly are skipped unless the person says not. */\n const [skipRepeats, setSkipRepeats] = useState(true);\n /** The file row (1-based) each sent row came from, so a refusal names the person's own line. */\n const [sentLines, setSentLines] = useState<number[] | null>(null);\n const [repeatsSkipped, setRepeatsSkipped] = useState(0);\n const [unmapped, setUnmapped] = useState<\"propose\" | \"create\" | \"ignore\">(\"propose\");\n // VERIFIER-30 #2: someone who manages this table ADDS the columns it lacks — sending them to the\n // approvals inbox \"for approval\" by the very person importing read as data loss (three rows landed\n // with a Title and nothing else). The inbox stays the default, and the only choice, for everyone\n // else; a person who picks another answer keeps it.\n const [unmappedChosen, setUnmappedChosen] = useState(false);\n useEffect(() => {\n if (rights.admin && !unmappedChosen) setUnmapped(\"create\");\n }, [rights.admin, unmappedChosen]);\n const [fileName, setFileName] = useState<string>(\"\");\n const [fileHash, setFileHash] = useState<string | null>(null);\n const [fileBytes, setFileBytes] = useState<number | null>(null);\n const [format, setFormat] = useState<\"csv\" | \"xlsx\">(\"csv\");\n const [outcomes, setOutcomes] = useState<ImportOutcome[]>([]);\n const [progress, setProgress] = useState<number>(0);\n const [summary, setSummary] = useState<string | null>(null);\n const [proposals, setProposals] = useState<ImportProposal[]>([]);\n const [alreadyRan, setAlreadyRan] = useState<string | null>(null);\n /** IMPORT-2: what the \"add the columns\" step made, shown as its own line. */\n const [columnsAdded, setColumnsAdded] = useState<ImportProposal[] | null>(null);\n const [show, setShow] = useState<\"refused\" | \"duplicate\" | \"all\">(\"all\");\n /**\n * FIX-11B F2: THE STORE'S OWN COUNT OF THIS RUN, NOT THIS SCREEN'S TALLY.\n *\n * VERIFIER-11 watched a 400-row file land 312 records and refuse 88 while the\n * only sentence on screen read \"196 landed · 0 already here · 54 refused\" — a\n * report about ONE batch of 250, for a run of 400. The number came from\n * counting the `outcomes` array this screen happened to be holding, and an\n * outcomes array is a SAMPLE: the door caps what it hands back, and a batch it\n * could not answer for at all contributes nothing to it. A tally of a sample\n * can never be the truth about a run.\n *\n * Every `io_import_rows` answer carries what the STORE wrote in that call —\n * `rows_seen`, `rows_written`, `rows_duplicate`, `rows_refused` — and\n * `io_import_finish` carries the run's final totals off the ledger. This is\n * the sum of the former while the run goes, replaced by the latter when it\n * ends. The screen prints THIS, and never a count of its own array.\n */\n const [ledger, setLedger] = useState<{\n seen: number;\n written: number;\n duplicate: number;\n refused: number;\n final: boolean;\n } | null>(null);\n\n /**\n * FIX-12 F2: THE RUNS THIS TABLE ALREADY HAD — SO A REFUSAL CAN BE FOUND\n * AFTERWARDS, WHICH IS THE OTHER HALF OF THE SAME DEFECT.\n *\n * The store has always kept them: `custom.io_import` holds up to 500 refused\n * rows per run, each with the store's sentence and the whole source row, and\n * `custom.io_import_report` / `custom.io_imports` hand them back. No screen in\n * this package had ever asked. So a person who blinked at the wrong moment —\n * or whose file was small enough to finish between two paints — had no way\n * back to the twelve rows that did not land, and re-opening Import mentioned\n * neither the run nor the refusals. These two calls are that way back.\n */\n const [runs, setRuns] = useState<ImportRun[] | null>(null);\n const [openRun, setOpenRun] = useState<string | null>(null);\n const [runRows, setRunRows] = useState<{\n import_id: string;\n rows: Array<Record<string, unknown>>;\n kept: number;\n total: number;\n note: string | null;\n } | null>(null);\n const [runProblem, setRunProblem] = useState<RecordsError | null>(null);\n const [runsProblem, setRunsProblem] = useState<RecordsError | null>(null);\n\n const loadRuns = useCallback(async () => {\n const answered = await client.imports({ table_id: tableId, limit: 10 });\n // Nothing fails silently: the list of earlier runs that could not be read\n // says so, instead of the section simply never appearing.\n if (answered.ok) {\n setRuns(answered.data);\n setRunsProblem(null);\n } else setRunsProblem(answered.error);\n }, [client, tableId]);\n\n useEffect(() => {\n void loadRuns();\n }, [loadRuns]);\n\n const openRefusals = useCallback(\n async (importId: string) => {\n setRunProblem(null);\n if (openRun === importId) {\n setOpenRun(null);\n setRunRows(null);\n return;\n }\n setOpenRun(importId);\n setRunRows(null);\n const answered = await client.importReport({\n import_id: importId as Uuid,\n state: \"refused\",\n limit: 200,\n });\n if (!answered.ok) {\n setRunProblem(answered.error);\n return;\n }\n setRunRows({\n import_id: answered.data.import_id,\n rows: answered.data.rows,\n kept: answered.data.kept,\n total: answered.data.total,\n note: answered.data.note,\n });\n },\n [client, openRun],\n );\n\n const declared = useMemo(() => fields.data ?? [], [fields.data]);\n\n // ── THE NAME COLUMN, AND ROWS THAT SHARE A NAME (VISION-REACH lane 5, 2026-10-03) ─────────\n // Everything below that reads the file's rows reads `effectiveRows`: the rows as they will be\n // written. When the name column repeats and the repeating rows look like one record (persona\n // P03's families file: one row per student, two or three per family), they are combined — one\n // record per name, every other column keeping every value it held — unless the person says each\n // row is its own record. The choice is shown before the write, never made behind their back.\n const titleKey = table.data?.title_field ?? null;\n const titleHeader: string | null =\n titleFrom ?? (titleKey ? (Object.entries(mapping).find(([h, key]) => key === titleKey && h !== TITLE_COPY)?.[0] ?? null) : null);\n // A row that repeats an earlier row EXACTLY is the G14 \"skip repeated rows\" question, not this\n // one: the name repeats here when rows share a name and differ elsewhere (two students, one family).\n const distinctRows = useMemo(() => {\n const headers = (plan?.columns ?? []).map((c) => c.header).filter((h) => !leftOut.has(h));\n const exact = new Set(exactDuplicateRows(rows, headers).map((r) => r.row));\n return exact.size === 0 ? rows : rows.filter((_, i) => !exact.has(i));\n }, [rows, plan, leftOut]);\n const titleStats = useMemo(() => (titleHeader ? titleRepeats(distinctRows, titleHeader) : null), [distinctRows, titleHeader]);\n const titleRepeating = Boolean(titleStats && titleStats.filled > 0 && titleStats.distinct < titleStats.filled);\n // An amount, a date or a yes/no never says \"these rows are the same record\" — it describes the row.\n const notIdentity = useMemo(() => {\n const out = new Set<string>();\n for (const c of plan?.columns ?? []) {\n const k = importKindOfPlan(c.type);\n if (k === \"currency\" || k === \"date\" || k === \"checkbox\" || looksLikeDates(distinctRows, c.header)) out.add(c.header);\n }\n return out;\n }, [plan, distinctRows]);\n const combineDefault: \"combine\" | \"each\" = useMemo(\n () => (titleRepeating && titleHeader && sameRecordLikely(distinctRows, titleHeader, notIdentity) ? \"combine\" : \"each\"),\n [distinctRows, titleHeader, titleRepeating, notIdentity],\n );\n const combining = titleRepeating && (combine ?? combineDefault) === \"combine\";\n const combined = useMemo(() => (combining && titleHeader ? combineRows(rows, titleHeader) : null), [combining, rows, titleHeader]);\n const effectiveRows = combined?.rows ?? rows;\n // One record per name means the name is what makes a row the same row — so a corrected file\n // imported again brings those records up to date instead of doubling them.\n useEffect(() => {\n if (dedupeChosen) return;\n setDedupeKey(combining && titleKey ? titleKey : \"\");\n }, [combining, titleKey, dedupeChosen]);\n\n /**\n * EVERYTHING AFTER THE PARSE, for a file and for rows that were never a file: the store says\n * what each column is (`importPlan`), and the wizard opens on the name column a person would\n * have picked.\n */\n const planFrom = useCallback(\n async (result: ParsedImport, meta: { name: string; bytes: number | null; hash: string | null; format: \"csv\" | \"xlsx\" }) => {\n setFormat(meta.format);\n setFileName(meta.name);\n setFileBytes(meta.bytes);\n setFileHash(meta.hash);\n setParsed(result);\n setRows(result.rows);\n setLeftOut(new Set());\n setTitleFrom(null);\n setCombine(null);\n setDedupeChosen(false);\n setRelationIndex(new Map());\n setUnlinkedChoice({});\n setKindChoice({});\n setDateMiss({});\n setSkipRepeats(true);\n setSentLines(null);\n setRepeatsSkipped(0);\n\n // EVERY header, mapped or not — the store decides what each one is, and\n // it knows things this screen cannot (the roster, the other tables).\n setPhase(\"planning\");\n const columns = result.headers.map((header) => ({\n header,\n samples: result.rows\n .slice(0, SAMPLES)\n .map((r) => r[header])\n .filter((v): v is string => typeof v === \"string\" && v.trim() !== \"\"),\n }));\n const answered = await client.importPlan({ table_id: tableId, columns });\n if (!answered.ok) {\n setProblem(answered.error);\n setPhase(\"waiting\");\n return;\n }\n setPlan(answered.data);\n const next: Record<string, string> = {};\n for (const column of answered.data.columns) {\n if (column.matched) next[column.header] = column.field_key;\n }\n\n // FIX-11B F2: THE NAME COLUMN IS CHOSEN HERE, NOT LEFT EMPTY.\n // If the store already matched a header onto this Table's title column,\n // that is the answer and nothing is guessed. Otherwise the wizard opens\n // on the column a person would have picked and says so on screen — it is\n // a choice shown, never a choice made behind their back.\n const titleKey = table.data?.title_field ?? null;\n // BREAKER-3 B3-09: the guess never takes a header the store already placed (its \"Exercise\"\n // went to Exercise, then the guess moved it onto `id`), and never names records by a column\n // that is not words — a number, a record number or a time is not a name.\n const titleField = titleKey ? answered.data.fields.find((f) => f.key === titleKey) : undefined;\n const titleTakesWords = !titleField || !/^(range|number|integer|currency|percent|autonumber|created_time|modified_time|boolean|checkbox|date|datetime)$/i.test(String(titleField.type ?? \"\"));\n if (titleKey && titleTakesWords && !Object.values(next).includes(titleKey)) {\n const unplaced = answered.data.columns.filter((c) => !(c.header in next));\n const guess = obviousTitleColumn(unplaced, result.rows, {\n title: titleField?.label ?? null,\n table: table.data?.name ?? null,\n singular: (table.data as { label_singular?: string | null } | null | undefined)?.label_singular ?? null,\n });\n if (guess) {\n const guessed = answered.data.columns.find((c) => c.header === guess);\n // A column of names that points at another table names the records AND keeps its link.\n if (guessed?.type === \"relation\" && guessed.relation_target) {\n next[TITLE_COPY] = titleKey;\n setTitleFrom(guess);\n } else next[guess] = titleKey;\n }\n }\n setMapping(next);\n setPhase(\"ready\");\n },\n [client, tableId, table.data],\n );\n\n const reset = useCallback(() => {\n setPhase(\"reading\");\n setProblem(null);\n setOutcomes([]);\n setSummary(null);\n setProposals([]);\n setAlreadyRan(null);\n setProgress(0);\n setLedger(null);\n }, []);\n\n const take = useCallback(\n async (file: File) => {\n reset();\n try {\n const xlsx = file.name.toLowerCase().endsWith(\".xlsx\");\n const bytes = await file.arrayBuffer();\n // THE PARSE IS A PARSE. It is not given the Fields and cannot decide a\n // mapping: every heading and every value comes through, and the STORE\n // decides what each column is. See `ParsedImport`.\n const result = xlsx ? await importXlsx(bytes) : importCsv(new TextDecoder().decode(bytes));\n await planFrom(result, { name: file.name, bytes: file.size, hash: await sha256(bytes), format: xlsx ? \"xlsx\" : \"csv\" });\n } catch (thrown) {\n setProblem(\n refusalFromThrown(\n thrown,\n \"That file could not be read, so nothing was imported.\",\n \"Save it again as CSV or Excel and pick it again.\",\n \"invalid_argument\",\n ),\n );\n setPhase(\"waiting\");\n }\n },\n [planFrom, reset],\n );\n\n // ROWS THAT ARE NOT A FILE: planned the moment the table's fields are known, once per source.\n const [tookSource, setTookSource] = useState<ImportSource | null>(null);\n useEffect(() => {\n if (!source || tookSource === source || !fields.data || !table.data) return;\n setTookSource(source);\n reset();\n const bytes = new TextEncoder().encode(source.text);\n void sha256(bytes).then((hash) =>\n planFrom(source.parsed, { name: source.name, bytes: bytes.byteLength, hash, format: \"csv\" }),\n );\n }, [source, tookSource, fields.data, table.data, planFrom, reset]);\n\n // ── THE ENUM ASK (lane SAVE-AS-TABLE-EVERYWHERE, 2026-09-29) ─────────────\n // A word going into a choice column that names none of its choices is refused by the store, row\n // by row (`custom._resolve_choice_words`). The grid's paste has always asked first; an import did\n // not, so \"Discharge\" in a pasted list landed as a refused row the person met only in the report.\n // The words are listed BEFORE the write, per column, with the one explicit act — add them — that\n // the grid's paste offers, and the organization's own choice setting decides whether it is asked\n // (`ask`), done as the import runs (`always_add`), or not offered (`never_add`).\n const nudge = useChoiceNudge();\n // BREAKER-3 B3-09: rows from a chat answer or a note are not \"your file\". With a source the\n // wizard counts them as the rows they are (\"Row 2\"), never as lines of a file that does not exist.\n const inYourRows = source ? \"in the rows you are saving\" : \"in your file\";\n const lineWord = (dataRow: number) => (source ? `Row ${dataRow}` : `Line ${lineInYourFile(dataRow)}`);\n const [choiceIndex, setChoiceIndex] = useState<Map<string, ChoiceOptions>>(() => new Map());\n const [addingWords, setAddingWords] = useState<string | null>(null);\n const isChoice = (f: Field) => {\n const kind = String(editorKindFor(f));\n return kind === \"select\" || kind === \"multi_select\";\n };\n const mappedChoiceFields = declared.filter((f) => isChoice(f) && Object.values(mapping).includes(f.key));\n const choiceKeysToRead = mappedChoiceFields.filter((f) => !choiceIndex.has(f.key)).map((f) => f.key).join(\",\");\n const readChoices = useCallback(\n async (wanted: Field[]) => {\n const read = await Promise.all(\n wanted.map(async (f) => {\n const got = await client.fieldOptions({ field_id: f.id });\n return got.ok ? ([f.key, choiceOptionsOf(got.data ?? [])] as const) : null;\n }),\n );\n setChoiceIndex((held) => {\n const next = new Map(held);\n for (const entry of read) if (entry) next.set(entry[0], entry[1]);\n return next;\n });\n },\n [client],\n );\n useEffect(() => {\n if (!choiceKeysToRead) return;\n void readChoices(mappedChoiceFields.filter((f) => choiceKeysToRead.split(\",\").includes(f.key)));\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the fields still unread\n }, [choiceKeysToRead, readChoices]);\n const newChoiceWords = useMemo(() => {\n const out: Array<{ field: Field; header: string; words: string[] }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = declared.find((f) => f.key === key);\n if (!field || !isChoice(field)) continue;\n const options = choiceIndex.get(key);\n if (!options) continue;\n const words: string[] = [];\n for (const row of effectiveRows) {\n const raw = row[header];\n if (typeof raw !== \"string\" || raw.trim() === \"\") continue;\n const read = valueFromPastedText(field, raw, options);\n if (\"unmatched\" in read && read.unmatched) {\n for (const w of read.unmatched) if (!words.some((x) => x.toLowerCase() === w.toLowerCase())) words.push(w);\n }\n }\n if (words.length > 0) out.push({ field, header, words });\n }\n return out;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- isChoice is pure\n }, [mapping, declared, choiceIndex, effectiveRows]);\n const addChoiceWords = useCallback(\n async (field: Field, words: string[]): Promise<boolean> => {\n setAddingWords(field.key);\n const existing = choiceIndex.get(field.key)?.labels ?? [];\n const written = await client.fieldUpdate({ field_id: field.id, patch: { options: [...existing, ...words] } });\n setAddingWords(null);\n if (!written.ok) {\n setProblem(written.error);\n return false;\n }\n await readChoices([field]);\n return true;\n },\n [client, choiceIndex, readChoices],\n );\n\n // ── THE RELATION ASK (VISION-REACH G1, 2026-10-02) ─────────────────────────\n // A file names the record a row points at. The store is asked ONCE per relation column which\n // records those names name (`relationNamesMatch` — the same matcher its write doors use), and\n // every name that matches nothing, or two records, is listed here with its lines and a choice\n // BEFORE anything is written: add it to the other table, leave the link empty, or skip the row\n // (the store then refuses that row by name and keeps it in the report). Never a guessed link.\n const mappedRelations = useMemo(() => {\n const out: Array<{ header: string; field: Field }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = declared.find((f) => f.key === key);\n if (field && editorKindFor(field) === \"relation\" && field.relation_target) out.push({ header, field });\n }\n // VISION-REACH lane 5: a relation column this import is about to MAKE (\"Create and import\" —\n // the plan typed it as pointing at another table and the columns are added) meets the same ask\n // as one the table already has. Persona P03 never saw the ask: the column did not exist yet,\n // so every ambiguous name was met only as a refusal afterwards.\n if (unmapped === \"create\" && rights.admin) {\n for (const c of plan?.columns ?? []) {\n if (leftOut.has(c.header) || c.header in mapping || c.type !== \"relation\" || !c.relation_target) continue;\n out.push({ header: c.header, field: planRelationField(c) });\n }\n }\n return out;\n }, [mapping, declared, plan, leftOut, unmapped, rights.admin]);\n const relationSignature = mappedRelations.map((r) => `${r.header}>${r.field.key}`).join(\"|\");\n const readRelationNames = useCallback(\n async (wanted: Array<{ header: string; field: Field }>): Promise<Map<string, RelationNameIndex> | null> => {\n const next = new Map<string, RelationNameIndex>();\n for (const { header, field } of wanted) {\n const names = effectiveRows.flatMap((r) => relationNamesIn(field, String(r[header] ?? \"\")));\n const got = await client.relationNamesMatch({ table_id: field.relation_target as Uuid, names });\n if (!got.ok) {\n setRelationProblem(got.error);\n return null;\n }\n next.set(field.key, relationNameIndexOf(got.data));\n }\n setRelationProblem(null);\n setRelationIndex(next);\n return next;\n },\n [client, effectiveRows],\n );\n useEffect(() => {\n if (mappedRelations.length === 0) {\n setRelationIndex(new Map());\n return;\n }\n void readRelationNames(mappedRelations);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on which columns are relations\n }, [relationSignature, readRelationNames]);\n\n const relationAsks = useMemo(() => {\n return mappedRelations.flatMap(({ header, field }) => {\n const index = relationIndex.get(field.key);\n if (!index) return [];\n const unmatched = new Map<string, number[]>();\n const ambiguous = new Map<string, { count: number; lines: number[] }>();\n let linked = 0;\n let named = 0;\n effectiveRows.forEach((row, i) => {\n const names = relationNamesIn(field, String(row[header] ?? \"\"));\n if (String(row[header] ?? \"\").trim() === \"\") return;\n named += 1;\n let ok = true;\n for (const name of names) {\n const hits = index.byName.get(relationNameKey(name)) ?? [];\n if (hits.length === 1) continue;\n ok = false;\n if (hits.length === 0) unmatched.set(name, [...(unmatched.get(name) ?? []), i + 1]);\n else ambiguous.set(name, { count: hits.length, lines: [...(ambiguous.get(name)?.lines ?? []), i + 1] });\n }\n if (ok) linked += 1;\n });\n return [{ header, field, index, linked, named, unmatched: [...unmatched.entries()], ambiguous: [...ambiguous.entries()] }];\n });\n }, [mappedRelations, relationIndex, effectiveRows]);\n const choiceFor = (key: string) => unlinkedChoice[key] ?? { unmatched: \"skip\" as UnlinkedChoice, ambiguous: \"skip\" as UnlinkedChoice };\n\n // ── WHAT A NEW COLUMN HOLDS, AND THE DATES (VISION-REACH G14, 2026-10-02) ─────────────────────\n // A new column is made as the kind the person picks (Text, Date, Number, Money, Checkbox), opened\n // on the store's plan — except a column the plan read as words whose cells mostly read as dates,\n // which opens on Date. Every date column, new or already here, is read by the ONE date reader\n // (`readTypedDate`) before it is sent, so \"Mar 31, 2026\", \"8.4.2026\" and \"2026-05-16\" in one\n // column all land as days; a cell that is not a date is listed with its line and a choice.\n const makesColumns = unmapped === \"create\" && rights.admin;\n const guessedKind = useMemo(() => {\n const out: Record<string, ImportKind | null> = {};\n for (const c of plan?.columns ?? []) {\n const k = importKindOfPlan(c.type);\n out[c.header] = (k === \"text\" || c.type === \"select\") && looksLikeDates(effectiveRows, c.header) ? \"date\" : k;\n // Words whose cells are emails, phone numbers or web addresses open on that kind.\n if (out[c.header] === \"text\") out[c.header] = looksLike(effectiveRows, c.header) ?? \"text\";\n // A column that now holds \"K; 3\" because two rows were combined is a list of words, kept as\n // text — never a dropdown whose one choice is \"K; 3\", and never refused.\n if (combined?.multiValued.has(c.header) && (k === null || c.type === \"select\")) out[c.header] = \"text\";\n }\n return out;\n }, [plan, effectiveRows, combined]);\n const kindOf = (header: string): ImportKind | null => kindChoice[header] ?? guessedKind[header] ?? null;\n const newColumns = (plan?.columns ?? []).filter((c) => !leftOut.has(c.header) && !(c.header in mapping));\n const dateAsks = useMemo(() => {\n const out: Array<{ header: string; label: string; withTime: boolean; dates: ReturnType<typeof datesOfColumn> }> = [];\n for (const c of plan?.columns ?? []) {\n if (leftOut.has(c.header)) continue;\n const key = mapping[c.header];\n if (key) {\n const f = declared.find((d) => d.key === key);\n if (!f || String(editorKindFor(f)) !== \"datetime\") continue;\n const withTime = String(f.config?.[\"kind\"] ?? \"date\") === \"datetime\";\n out.push({ header: c.header, label: fieldName(f), withTime, dates: datesOfColumn(effectiveRows, c.header, { withTime }) });\n } else if (makesColumns && (kindChoice[c.header] ?? guessedKind[c.header]) === \"date\") {\n out.push({ header: c.header, label: c.header, withTime: false, dates: datesOfColumn(effectiveRows, c.header) });\n }\n }\n return out;\n }, [plan, leftOut, mapping, declared, effectiveRows, makesColumns, kindChoice, guessedKind]);\n /** Rows that repeat an earlier row exactly over the columns that are sent. */\n const repeats = useMemo(\n () => exactDuplicateRows(effectiveRows, (plan?.columns ?? []).map((c) => c.header).filter((h) => !leftOut.has(h))),\n [effectiveRows, plan, leftOut],\n );\n\n const [goAheadAnyway, setGoAheadAnyway] = useState(false);\n // The cells the rules refuse, kept aside (blanked in what is sent, listed with their reason in the\n // report) when the person says to import the rest anyway — so one refused cell costs the row nothing else.\n const refusedCells = useMemo(\n () => (goAheadAnyway ? refusedCellsOf(declared, effectiveRows, mapping, choiceIndex, relationIndex) : []),\n [goAheadAnyway, declared, effectiveRows, mapping, choiceIndex, relationIndex],\n );\n const [keptAside, setKeptAside] = useState<ImportRefusedCell[]>([]);\n\n /**\n * THE ROWS AS THEY ARE SENT: the left-out columns stripped, and every relation cell turned into\n * the record ids the person saw it link to — so what the panel showed is what is written. A name\n * the person chose to skip stays as written, and the store refuses that row in its own words.\n */\n const rowsToSend = useCallback(\n (index: Map<string, RelationNameIndex>): { rows: Array<Record<string, string>>; lines: number[] } => {\n const repeated = new Set(skipRepeats ? repeats.map((r) => r.row) : []);\n const lines: number[] = [];\n const sent: Array<Record<string, string>> = [];\n effectiveRows.forEach((row, at) => {\n if (repeated.has(at)) return;\n const out: Record<string, string> = {};\n for (const [header, value] of Object.entries(row)) if (!leftOut.has(header)) out[header] = value;\n for (const c of refusedCells) if (c.line === at + 1 && c.header in out) out[c.header] = \"\";\n // The name column's words, carried a second time when they come from a column that keeps\n // its own column (a relation): the record is named by them AND linked through them.\n if (titleFrom) out[TITLE_COPY] = String(row[titleFrom] ?? \"\").trim();\n for (const { header, field } of mappedRelations) {\n const named = index.get(field.key);\n const text = String(row[header] ?? \"\").trim();\n if (!named || text === \"\") continue;\n const parts = field.multi ? splitListCell(text) : [text];\n const ids: string[] = [];\n let skip = false;\n for (const part of parts) {\n const hits = relationNamesIn(field, part).length === 0 ? null : (named.byName.get(relationNameKey(part)) ?? []);\n if (hits === null) ids.push(part); // an id: the store decides it is there\n else if (hits.length === 1) ids.push(hits[0]!.id);\n else if ((hits.length === 0 ? choiceFor(field.key).unmatched : choiceFor(field.key).ambiguous) !== \"empty\") skip = true;\n }\n if (!skip) out[header] = ids.join(\"; \");\n }\n // G14: a date cell goes as the day it reads as; one that is not a date goes empty, or as\n // written when the person chose to skip those rows (the store then refuses it by name).\n for (const ask of dateAsks) {\n const raw = String(row[ask.header] ?? \"\").trim();\n if (raw === \"\") continue;\n const day = ask.dates.read.get(at);\n if (day !== undefined) out[ask.header] = day;\n else if ((dateMiss[ask.header] ?? \"empty\") === \"empty\") out[ask.header] = \"\";\n }\n sent.push(out);\n // A combined row names the FIRST line it was made from; a refusal then points at a line a\n // person can find, and the combined lines are listed with the combine notice.\n lines.push(combined?.lines[at]?.[0] ?? at + 1);\n });\n return { rows: sent, lines };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- choiceFor reads unlinkedChoice\n [effectiveRows, combined, titleFrom, leftOut, mappedRelations, unlinkedChoice, dateAsks, dateMiss, repeats, skipRepeats, refusedCells],\n );\n\n const run = useCallback(async () => {\n if (!plan) return;\n setProblem(null);\n // The organization adds new choices without asking: they are added now, before a row is sent.\n if (nudge === \"always_add\" && rights.admin) {\n for (const ask of newChoiceWords) {\n if (!(await addChoiceWords(ask.field, ask.words))) return;\n }\n }\n setOutcomes([]);\n setColumnsAdded(null);\n setProgress(0);\n setLedger(null);\n\n // ── VISION-REACH lane 5: THE DUPLICATES THE PERSON CHOSE TO COMBINE, BEFORE ANY ROW. ──\n // \"2 records called Cox family\" in Families: the first keeps its id, every other one is merged\n // into it through the store's own merge door (values kept as alternates, links moved, the loser\n // archived and aliased), and the names are read again so every row links to the one record.\n let index = relationIndex;\n const toMerge = relationAsks.filter((ask) => choiceFor(ask.field.key).ambiguous === \"merge\" && ask.ambiguous.length > 0);\n if (toMerge.length > 0) {\n setPhase(\"linking\");\n for (const ask of toMerge) {\n for (const [name] of ask.ambiguous) {\n const hits = ask.index.byName.get(relationNameKey(name)) ?? [];\n const winner = hits[0];\n if (!winner) continue;\n for (const loser of hits.slice(1)) {\n const merged = await client.migrateMerge({\n winner_id: winner.id as Uuid,\n loser_id: loser.id as Uuid,\n note: `Combined while importing ${fileName || \"rows\"}: both were called \"${name}\".`,\n });\n if (!merged.ok) {\n setProblem(merged.error);\n setPhase(\"ready\");\n return;\n }\n }\n }\n }\n const reread = await readRelationNames(mappedRelations);\n if (!reread) {\n setPhase(\"ready\");\n return;\n }\n index = reread;\n }\n\n // ── VISION-REACH G1: THE RECORDS THE PERSON CHOSE TO ADD, BEFORE ANY ROW. ──\n const toMake = relationAsks.filter((ask) => choiceFor(ask.field.key).unmatched === \"create\" && ask.unmatched.length > 0);\n if (toMake.length > 0) {\n setPhase(\"linking\");\n for (const ask of toMake) {\n const title = ask.index.titleField;\n if (!title) continue;\n const made = await client.recordWriteMany({\n table_id: ask.field.relation_target as Uuid,\n rows: ask.unmatched.map(([name]) => ({ [title]: name })),\n });\n if (!made.ok) {\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n }\n const reread = await readRelationNames(mappedRelations);\n if (!reread) {\n setPhase(\"ready\");\n return;\n }\n index = reread;\n }\n const { rows: sendRows, lines: sendLines } = rowsToSend(index);\n setKeptAside(refusedCells.map(({ header, line, raw, why }) => ({ header, line, raw, why })));\n setSentLines(sendLines);\n setRepeatsSkipped(effectiveRows.length - sendRows.length);\n\n // ── IMPORT-2: THE COLUMNS FIRST, AS THEIR OWN STEP. ────────────────────\n // \"Columns this table does not have are added straight away\" used to happen\n // inside the first writing call — eight `field_declare` calls on top of 250\n // record writes, which is what pushed that call over the client ceiling —\n // and it happened AFTER `importBegin`, so a person could not name one of the\n // new columns as the file's duplicate key. It is a step of its own now: the\n // person sees \"8 columns added\", and only then do the rows go.\n let sendMapping: Record<string, string> = mapping;\n // VISION-REACH G14: A NEW COLUMN THE PERSON (OR THE DATE READING) MADE A DIFFERENT KIND is\n // declared as that kind through the one field door, under the key the plan gave it; the rest of\n // the new columns are left to the store's column step below, exactly as before.\n if (makesColumns) {\n const typed = newColumns.filter((c) => {\n const k = kindOf(c.header);\n return k !== null && k !== importKindOfPlan(c.type);\n });\n if (typed.length > 0) setPhase(\"declaring\");\n for (const c of typed) {\n const made = await client.fieldDeclare({\n table_id: tableId,\n spec: { label: c.label || c.header, key: c.field_key, ...declarationFor(kindOf(c.header)!) },\n });\n if (!made.ok) {\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n sendMapping = { ...sendMapping, [c.header]: c.field_key };\n setMapping(sendMapping);\n }\n }\n if (unmapped === \"create\" && rights.admin) {\n setPhase(\"declaring\");\n // VISION-REACH G6: A FEW COLUMNS A CALL. Twelve columns in one call took the dry run past the\n // database's ceiling (each new column is its own Field record, its own guards and its own\n // change notice — measured ~0.1–0.3 s apiece on the clone) and the screen said nothing. Three\n // a call stays far inside it, and a retry picks up where it stopped: a column already added\n // is matched by its header, never added twice.\n const fresh = (plan?.columns ?? [])\n .map((c) => c.header)\n .filter((h) => !leftOut.has(h) && !(h in sendMapping));\n const added: ImportProposal[] = [];\n for (let at = 0; at < fresh.length; at += COLUMNS_PER_CALL) {\n const group = fresh.slice(at, at + COLUMNS_PER_CALL);\n // The column step reads the rows AS THE FILE SPELLS THEM: a relation is recognized by the\n // names matching the other table's name column, so the ids the rows will be sent with\n // would read as text here and the column would be made as text.\n const made = await client.importDeclareColumns({\n table_id: tableId,\n rows: effectiveRows.map((r) => Object.fromEntries(group.map((h) => [h, r[h] ?? \"\"]))),\n mapping: sendMapping,\n });\n if (!made.ok) {\n setColumnsAdded(added.length > 0 ? added : null);\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n added.push(...made.data.columns_added);\n // A header the store matched to a column it already had is a mapping, and\n // the rows must be sent with it or they would go nowhere.\n // VERIFIER-30 #2: THE MAPPING THE STORE ANSWERED IS THE ONE THE ROWS GO WITH. It used to be\n // set into state only, and the loop below then sent the mapping this render closed over —\n // without the columns just added — so every added column's values went nowhere.\n if (made.data.mapping) {\n sendMapping = { ...sendMapping, ...made.data.mapping };\n setMapping(sendMapping);\n }\n }\n setColumnsAdded(added);\n }\n if (makesColumns && plan) {\n // THE FILE'S COLUMN ORDER (walk 2026-10-10: Item, Supplier, Phone, Email, Website, Qty, Status came out\n // Title, Email, Phone, Supplier, Qty, Status, Website — the columns made as another kind went first).\n // The columns just made are put in the order the file had them, the first one still the title.\n const wantedKeys = plan.columns.map((c) => c.header).filter((h) => !leftOut.has(h)).map((h) => sendMapping[h]).filter((k): k is string => Boolean(k));\n const now = await client.fields({ table_id: tableId });\n if (now.ok) {\n const order = new Map(wantedKeys.map((k, i) => [k, i]));\n const current = now.data.filter((f) => order.has(f.key)).sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)).map((f) => f.key);\n const inFileOrder = current.every((k, i) => k === wantedKeys.filter((w) => current.includes(w))[i]);\n if (!inFileOrder) {\n const slots = now.data.filter((f) => order.has(f.key)).map((f) => f.sort ?? 0).sort((a, b) => a - b);\n const byKey = new Map(now.data.map((f) => [f.key, f]));\n const present = wantedKeys.filter((k) => byKey.has(k));\n for (let i = 0; i < present.length; i += 1) {\n const f = byKey.get(present[i]!)!;\n const to = slots[i] ?? (i + 1) * 10;\n if ((f.sort ?? 0) !== to) await client.fieldUpdate({ field_id: f.id as Uuid, patch: { sort: to } });\n }\n }\n }\n }\n\n setPhase(\"writing\");\n const opened = await client.importBegin({\n table_id: tableId,\n format,\n source_name: fileName,\n source_columns: plan.columns.map((c) => c.header).filter((h) => !leftOut.has(h)),\n file_hash: fileHash,\n file_bytes: fileBytes,\n dedupe_key: dedupeKey || null,\n policy: { on_duplicate: onDuplicate, unmapped },\n });\n if (!opened.ok) {\n setProblem(opened.error);\n setPhase(\"ready\");\n return;\n }\n // THE SAME FILE TWICE. The store refuses to run it again and says when it\n // ran and what landed — this screen shows exactly that and writes nothing.\n if (opened.data.already) {\n setAlreadyRan(opened.data.message);\n setSummary(opened.data.message);\n setPhase(\"done\");\n return;\n }\n\n const importId = opened.data.import_id;\n const collected: ImportOutcome[] = [];\n const told = { seen: 0, written: 0, duplicate: 0, refused: 0 };\n // IMPORT-2: the store sizes the call. It opens with a number of its own and\n // every answer carries the one it measured on itself, so a busy afternoon\n // makes the batches smaller instead of making the call fail.\n let take = opened.data.rows_per_call ?? BATCH;\n let at = 0;\n while (at < sendRows.length) {\n const batch = sendRows.slice(at, at + take);\n const answered = await client.importRows({ import_id: importId, rows: batch, mapping: sendMapping });\n if (!answered.ok) {\n setProblem(answered.error);\n setOutcomes([...collected]);\n // The run STOPPED here. What the ledger says is what really landed\n // before it stopped, and the sentence beside it says the rest of the\n // file was never offered — never a total that reads like a finished run.\n setLedger({ ...told, final: false });\n setPhase(\"ready\");\n return;\n }\n collected.push(...answered.data.outcomes);\n setOutcomes([...collected]);\n // FIX-11B F2: the store's own numbers for THIS call, added to the run's.\n // `outcomes` is a sample; these four are what the ledger was moved by.\n told.seen += answered.data.rows_seen;\n told.written += answered.data.rows_written;\n told.duplicate += answered.data.rows_duplicate;\n told.refused += answered.data.rows_refused;\n setLedger({ ...told, final: false });\n at += batch.length;\n setProgress(Math.min(at, sendRows.length));\n if (answered.data.rows_per_call) take = answered.data.rows_per_call;\n }\n\n const finished = await client.importFinish({ import_id: importId, unmapped });\n if (!finished.ok) {\n setProblem(finished.error);\n setPhase(\"done\");\n return;\n }\n setSummary(finished.data.message);\n setProposals(finished.data.proposals);\n // FIX-11B F2: the run's FINAL totals, off the store's ledger, replace the\n // running sum. If the two ever disagree the ledger is right — it counted the\n // writes, this screen counted answers about them.\n setLedger({\n seen: finished.data.rows_seen,\n written: finished.data.rows_written,\n duplicate: finished.data.rows_duplicate,\n refused: finished.data.rows_refused,\n final: true,\n });\n setPhase(\"done\");\n // FIX-12 F2: the host is TOLD the rows landed, and the panel STAYS. Closing\n // it is the person's act, on the report, once they have read it.\n onWrote?.(finished.data.rows_written);\n void loadRuns();\n // eslint-disable-next-line react-hooks/exhaustive-deps -- choiceFor and kindOf read state\n }, [newColumns, makesColumns, kindChoice, guessedKind, addChoiceWords, client, dedupeKey, effectiveRows, fileBytes, fileHash, fileName, format, leftOut, loadRuns, mappedRelations, mapping, newChoiceWords, nudge, onDuplicate, onWrote, plan, readRelationNames, refusedCells, relationAsks, relationIndex, rights.admin, rowsToSend, tableId, unmapped, unlinkedChoice]);\n\n const counts = useMemo(() => {\n let landed = 0;\n let duplicate = 0;\n let refused = 0;\n for (const o of outcomes) {\n if (o.outcome === \"landed\") landed += 1;\n else if (o.outcome === \"duplicate\") duplicate += 1;\n else refused += 1;\n }\n return { landed, duplicate, refused };\n }, [outcomes]);\n\n const interesting = useMemo(\n () => outcomes.filter((o) => (show === \"all\" ? o.outcome !== \"landed\" : o.outcome === show)),\n [outcomes, show],\n );\n\n const mappedCount = Object.keys(mapping).filter((h) => h !== TITLE_COPY).length;\n\n /**\n * FIX-11B F2: THE RUN'S TRUE NUMBERS, AND WHO SAID THEM.\n *\n * `ledger` is the store's. `counts` is this screen's tally of the outcome\n * entries it was handed. They are shown as ONE sentence built from the ledger,\n * and when the screen holds fewer entries than the run refused, it says that\n * out loud instead of letting a short list read as the whole story.\n */\n const titleMappedTo = titleHeader;\n /**\n * REC-2: a Table that declares a title column may not be imported without one — when that column\n * takes WORDS. A table named by a number, a record number or a time (BREAKER-3 B3-09: `id`) gets\n * no \"what each record is called\" question and is never held for one.\n */\n const titleDeclared = titleKey ? declared.find((f) => f.key === titleKey) : undefined;\n const titleTakesWords = !titleDeclared || !/^(range|number|integer|currency|percent|autonumber|created_time|modified_time|boolean|checkbox|date|datetime)$/i.test(String(editorKindFor(titleDeclared)));\n const titleMissing = Boolean(titleKey) && titleTakesWords && titleMappedTo === null;\n const titleFieldLabel: string =\n (titleKey ? plan?.fields.find((f) => f.key === titleKey)?.label : null) ||\n (titleKey ? declared.find((f) => f.key === titleKey)?.label : null) ||\n \"the name column\";\n const busy = phase === \"reading\" || phase === \"planning\" || phase === \"linking\" || phase === \"declaring\" || phase === \"writing\";\n\n // THE COLUMN RULES, ASKED BEFORE THE WRITE (lane REFUSAL-SWEEP). Per mapped\n // column: how many of the file's rows its declared rules would refuse, in the\n // store's own words — so the person fixes the mapping or the file first, or\n // says in so many words that the rest should go ahead.\n const ruleVerdicts = useMemo(\n () => checkImportRules(declared, effectiveRows, mapping, choiceIndex, relationIndex),\n [declared, effectiveRows, mapping, choiceIndex, relationIndex],\n );\n const ruleVerdictOf = useMemo(() => new Map(ruleVerdicts.map((v) => [v.header, v])), [ruleVerdicts]);\n const refusedByRules = ruleVerdicts.reduce((n, v) => n + v.refused, 0);\n // AT-DBFIX 2: the go-ahead is forgotten when the VERDICTS change, never when the same verdicts are\n // merely worked out again (a fields read that lands a new array of the same columns re-ran this\n // effect and unchecked the box under the person's finger, leaving \"Import 9 rows\" disabled).\n const verdictKey = ruleVerdicts.map((v) => `${v.header}:${v.refused}/${v.judged}`).join(\"|\");\n useEffect(() => setGoAheadAnyway(false), [verdictKey]);\n\n // `autoRun`: press Import once, for the person, when it is pressable.\n const [autoRan, setAutoRan] = useState(false);\n useEffect(() => {\n if (!autoRun || autoRan || !source || phase !== \"ready\" || !plan) return;\n if (busy || !rights.write || rows.length === 0 || titleMissing || ruleVerdicts.length > 0) return;\n setAutoRan(true);\n void run();\n }, [autoRun, autoRan, source, phase, plan, busy, rights.write, rows.length, titleMissing, ruleVerdicts, run]);\n\n /**\n * 🚨 AFTER A WRITE, THE WIZARD IS A REPORT — NEVER THE SAME IMPORT AGAIN\n * (VERIFIER-16 H1). A run landed 2 rows and the panel then showed, at once, the\n * result line, the pre-write notice \"…Nothing has been written yet\" (now false),\n * and a live \"Import 3 rows\" that would have written the file a second time. So\n * once this file has been offered to the store — finished, stopped part-way, or\n * turned away as a file already imported — every step that belongs BEFORE a write\n * (what each record is called, the mapping, the options, the rule notice and the\n * Import button) is gone, and what stays is what landed and what was refused.\n * Another run means choosing a file again, which starts the wizard afresh.\n */\n const afterWrite =\n !busy && (phase === \"done\" || alreadyRan !== null || (ledger !== null && ledger.seen > 0));\n\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-2 text-xs\", className)}>\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium\">Import</span>\n <span className=\"text-muted-foreground\">{table.data?.name}</span>\n {/* A file cannot be mapped before the store has said which Fields apply,\n and the rights that decide whether a column may be ADDED are read\n from the Table — so the chooser waits for both answers rather than\n showing an admin a mapping with their own choices missing. */}\n {fields.data && table.data ? null : (\n <span className=\"ml-auto text-muted-foreground\">\n {fields.data ? \"Reading this table…\" : \"Reading this table's fields…\"}\n </span>\n )}\n </div>\n\n {/* 🚨 THE ONE FILE CONTROL, NOT THE BROWSER'S (FIX-10C F10, 2026-09-22).\n This was the browser's own bare file input — `[Choose File] No file chosen`\n in the browser's own font, with nothing said about what a good file\n looks like and no way to back out. Airtable and Notion both explain\n this moment. `FilePicker` is the design-system-built control, shared\n by every screen in this package that takes a file. */}\n {source && !afterWrite ? (\n <p className=\"text-muted-foreground\" data-import-source=\"\">\n From {source.name} — {source.parsed.rows.length} row{source.parsed.rows.length === 1 ? \"\" : \"s\"}. Nothing is written until you press Import.\n </p>\n ) : null}\n {fields.data && table.data && !source ? (\n <FilePicker\n label=\"Choose a file\"\n inputLabel=\"Choose a file to import\"\n accept=\".csv,.xlsx\"\n disabled={busy}\n chosenName={fileName || null}\n hint={\n <>\n A spreadsheet or CSV whose FIRST ROW is the column names — Job Number, Customer,\n Scheduled Date — and one row per record under it. Every column is shown back to you\n with what this table made of it, and nothing is written until you press Import.\n </>\n }\n onFile={(file) => void take(file)}\n {...(fileName\n ? {\n onClear: () => {\n setPlan(null);\n setParsed(null);\n setFileName(\"\");\n setProblem(null);\n setPhase(\"waiting\");\n },\n }\n : {})}\n />\n ) : null}\n\n {problem && !(plan && parsed && !afterWrite) ? <RefusalNotice error={problem} /> : null}\n {phase === \"reading\" ? <p className=\"text-muted-foreground\">Reading the file…</p> : null}\n {phase === \"planning\" ? <p className=\"text-muted-foreground\">Working out what each column is…</p> : null}\n\n {plan && parsed && afterWrite ? (\n <p className=\"text-muted-foreground\" data-import-after-write=\"\">\n {source\n ? `These rows have been sent to this table${ledger && !ledger.final ? \", but the run stopped part-way.\" : \". What landed and what was refused is below.\"}`\n : fileName\n ? `${fileName} has been sent to this table`\n : \"This file has been sent to this table\"}\n {source\n ? null\n : ledger && !ledger.final\n ? \", but the run stopped part-way. Importing it again would write the rows that already landed a second time, so fix the file (or keep only the rows below the ones that landed) and choose it again.\"\n : \". What landed and what was refused is below. To import another file, choose it above.\"}\n </p>\n ) : null}\n\n {plan && parsed && !afterWrite ? (\n <>\n {/* ── FIX-11B F2: WHAT EACH RECORD WILL BE CALLED ────────────────\n An import that made its own columns used to leave this Table's\n title column empty, and 312 records landed with `—` in the first\n column of the grid — every one of them nameless. Nothing was\n broken; nobody had been ASKED. So it is asked here, first, opened\n on the column a person would have picked, and the run is REFUSED\n while it is unanswered (a Table that declares no title column\n never sees this block at all). */}\n {titleKey && titleTakesWords ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded border bg-muted/40 px-2 py-1.5\">\n <span className=\"font-medium\">What each record is called</span>\n <Select\n value={titleMappedTo ?? \"\"}\n disabled={busy}\n onValueChange={(chosen) => {\n const planned = plan.columns.find((c) => c.header === chosen);\n const keepsLink = Boolean(planned && planned.type === \"relation\" && planned.relation_target && !(chosen in mapping));\n setMapping((m) => {\n const next = { ...m };\n for (const [header, key] of Object.entries(next)) {\n if (key === titleKey) delete next[header];\n }\n if (chosen) next[keepsLink ? TITLE_COPY : chosen] = titleKey;\n return next;\n });\n setTitleFrom(keepsLink ? chosen : null);\n setCombine(null);\n if (chosen) setLeftOut((held) => (held.has(chosen) ? new Set([...held].filter((h) => h !== chosen)) : held));\n }}\n >\n <SelectTrigger\n size=\"sm\"\n aria-label=\"Which column each record is named by\"\n className=\"min-w-[14rem]\"\n >\n <SelectValue placeholder=\"— choose the column —\" />\n </SelectTrigger>\n <SelectContent>\n {plan.columns.map((c) => (\n <SelectItem key={c.header} value={c.header}>\n {c.header}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <span className=\"text-muted-foreground\">\n {titleMappedTo\n ? titleFrom\n ? `names each record in ${titleFieldLabel} and still links to the other table.`\n : `goes into ${titleFieldLabel}, so every record this file makes has a name you can read in the grid and on a chip.`\n : `Nothing goes into ${titleFieldLabel} yet, so every record this file makes would land with no name at all. Pick the column that says what each row IS.`}\n </span>\n </div>\n ) : null}\n\n {/* THE MAPPING, COLUMN BY COLUMN, WITH THE TYPE AND WHY. Nothing is\n hidden and nothing is only a badge: every column says what the\n store made of it, in a sentence, and every one can be changed. */}\n {/* 🚨 IT FITS, OR IT SCROLLS — IT NEVER CLIPS (FIX-11B F9, 2026-09-22).\n FIX-10C declared these widths on a `<table className=\"table-fixed\">`\n with a `<colgroup>`; VERIFIER-11 then measured every \"Goes to\"\n control at **10 px** in a 416 px rail at 1600x1000. A table's fixed\n layout is a HINT the moment the container is narrower than the\n declared widths, and a bare `<select>` has no intrinsic width of its\n own to defend — so the four columns collapsed and the header row\n drew \"Goes to\" on top of \"Column in the file\".\n This is a GRID. `minmax(14rem, …)` is a floor no container can argue\n with, the whole row declares the width it needs and the rail scrolls\n it, and the control is the design system's `Select` — a button that\n carries its own minimum. `check:import-mapping-is-readable` measures\n the real control in a real browser and goes red below\n GOES_TO_MIN_PX. */}\n {/* 🚨 IT FITS THE RAIL, SO NOTHING IS OUT OF SIGHT (VERIFIER-15 M5,\n VERIFIER-16 M8). The mapping was a four-column row 52rem wide inside a\n 26rem rail, so \"Kind\", \"First values\" and the per-column refusal sat\n past the rail's right edge and were only seen by scrolling a table\n sideways. Each column of the file is now ONE BLOCK that reads top to\n bottom — its name, where it goes, what it is, what would be refused,\n its first values — the way Airtable's and Notion's import panels list\n fields. The \"Goes to\" control keeps its 14rem floor\n (`check:import-mapping-is-readable`). */}\n <div className=\"flex w-full min-w-0 flex-col rounded border\" data-import-mapping=\"\">\n {plan.columns.map((column: ImportColumnPlan) => {\n const to = mapping[column.header] ?? \"\";\n const absent =\n unmapped === \"ignore\" ? \"— leave it out —\" : unmapped === \"create\" ? \"— add it as a new column —\" : \"— offer it as a new column —\";\n // WHAT IT IS = WHERE IT GOES NOW (VERIFIER-30 #4). The store's plan describes a column it\n // did NOT match by what its values look like (\"Points at another record … a record in\n // 'Visit type choices'\"); once the person — or the name-column guess — sends it into one\n // of this table's columns, it becomes that column's value, so the chip and the sentence\n // are that column's, never the plan's guess about an unplaced column.\n const planField = column.field_id ? declared.find((f) => f.id === column.field_id) : undefined;\n const placedField = to ? declared.find((f) => f.key === to) : undefined;\n const matchedField = placedField ?? planField;\n const whyNow =\n placedField && placedField.id !== column.field_id\n ? `Goes into ${fieldName(placedField)}, which holds ${fieldTypeLabel(placedField).toLowerCase()} values.`\n : column.why;\n return (\n <div\n key={column.header}\n data-import-column={column.header}\n className=\"flex min-w-0 flex-col gap-1 border-t px-2 py-1.5 first:border-t-0\"\n >\n <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"min-w-[8rem] flex-1 break-words font-medium\">{column.header}</span>\n <span className=\"text-muted-foreground\">goes to</span>\n <Select\n value={leftOut.has(column.header) ? LEAVE : to || ABSENT}\n disabled={busy}\n onValueChange={(chosen) => {\n setMapping((m) => {\n const next = { ...m };\n if (chosen === ABSENT || chosen === LEAVE) delete next[column.header];\n else next[column.header] = chosen;\n return next;\n });\n setLeftOut((held) => {\n const next = new Set(held);\n if (chosen === LEAVE) next.add(column.header);\n else next.delete(column.header);\n return next;\n });\n }}\n >\n <SelectTrigger\n size=\"sm\"\n aria-label={`Where ${column.header} goes`}\n data-goes-to={column.header}\n className=\"min-w-[14rem] flex-1\"\n >\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {/* ABSENT IS NOT DROPPED. Leaving a column unmapped is a\n real choice and it says what then happens to it. */}\n <SelectItem value={ABSENT}>{absent}</SelectItem>\n {/* VISION-REACH G4: one column left out on its own, whatever the rest do. */}\n {unmapped !== \"ignore\" ? <SelectItem value={LEAVE}>— leave it out —</SelectItem> : null}\n {plan.fields.map((f) => (\n <SelectItem key={f.field_id} value={f.key}>\n {f.label || f.key}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"min-w-0\">\n {/* VISION-REACH G14: a column this import ADDS is made as the kind chosen here. */}\n {makesColumns && !to && !leftOut.has(column.header) ? (\n <PickOne\n label={`What ${column.header} holds`}\n attrs={{ \"data-import-kind\": column.header }}\n className=\"h-6 text-[11px]\"\n value={kindOf(column.header) ?? \"\"}\n disabled={busy}\n onChange={(picked) => {\n const chosen = picked as ImportKind | \"\";\n setKindChoice((held) => {\n const next = { ...held };\n if (chosen === \"\") delete next[column.header];\n else next[column.header] = chosen;\n return next;\n });\n }}\n options={[\n ...(importKindOfPlan(column.type) === null ? [{ value: \"\", label: typeWord(column.type) }] : []),\n ...IMPORT_KINDS.map((k) => ({ value: k.kind, label: k.label })),\n ]}\n />\n ) : (\n <Badge\n variant={column.matched ? \"secondary\" : \"outline\"}\n className=\"text-[11px] font-normal\"\n data-import-kind={column.header}\n >\n {matchedField ? fieldTypeLabel(matchedField) : typeWord(column.type)}\n </Badge>\n )}\n {column.unit ? <span className=\"ml-1 opacity-60\">{column.unit}</span> : null}\n <p className=\"mt-0.5 break-words text-muted-foreground\">\n {makesColumns && !to && kindOf(column.header) === \"date\" && importKindOfPlan(column.type) !== \"date\"\n ? \"Most of these values read as dates.\"\n : whyNow}\n </p>\n {column.ambiguous ? (\n <p className=\"text-destructive\">Check a date you know before you run this.</p>\n ) : null}\n {column.collides_with ? (\n <p className=\"text-destructive\">Two columns in this file would make the same column.</p>\n ) : null}\n {/* VISION-REACH G4: a column sent somewhere its values do not look like. */}\n {placedField && placedField.id !== column.field_id && valuesLookTyped(column.type) &&\n !kindTakes(String(editorKindFor(placedField)), column.type) ? (\n <p className=\"text-amber-600 dark:text-amber-400\" data-import-kind-mismatch={column.header}>\n These look like {typeWord(column.type).toLowerCase()} values — check where this goes.\n </p>\n ) : null}\n {ruleVerdictOf.get(column.header) ? (\n (() => {\n const v = ruleVerdictOf.get(column.header)!;\n return (\n <div data-import-rule-refusal={column.header} className=\"mt-1\">\n <RefusalLine\n error={refusalOf(\n \"refused_by_rule\",\n `${v.refused} of ${v.judged} row${v.judged === 1 ? \"\" : \"s\"} would be refused by ${fieldName(v.field)}'s rules. ${v.firstWhy}`,\n `Send this column somewhere else, fix those rows ${inYourRows}, or import the rest and they are listed afterwards.`,\n )}\n />\n {/* The file's own text, verbatim — the screen's content,\n never filtered, so \"WO-4473\" is not eaten as an id. */}\n <p className=\"text-muted-foreground\" data-import-rule-sample=\"\">\n {lineWord(v.firstLine)} {inYourRows}: {v.firstRaw}\n </p>\n </div>\n );\n })()\n ) : null}\n </div>\n {(column.samples ?? []).length > 0 ? (\n <p className=\"break-words text-muted-foreground\">\n First values: {(column.samples ?? []).slice(0, 3).map(String).join(\" · \")}\n </p>\n ) : null}\n </div>\n );\n })}\n </div>\n\n <Separator />\n\n {/* VISION-REACH lane 5: THE NAME COLUMN REPEATS, SAID BEFORE THE WRITE. Persona P03's\n families file carried one row per student; 173 rows made 173 \"families\" and 33 of\n them twice. The count is shown, the default is the panel's reading of the rows\n (combine when some other column pins the rows to one record), and either answer is\n one click. */}\n {titleRepeating && titleHeader && titleStats ? (\n <div\n className=\"flex flex-wrap items-center gap-2 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n data-import-combine={combining ? \"combine\" : \"each\"}\n >\n <span>\n {titleHeader} repeats: {titleStats.distinct} names on {titleStats.filled} rows.\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Rows with the same {titleHeader}</span>\n <PickOne\n label={`What rows with the same ${titleHeader} become`}\n value={combine ?? combineDefault}\n disabled={busy}\n onChange={(picked) => setCombine(picked as \"combine\" | \"each\")}\n options={[\n { value: \"combine\", label: \"are one record; other columns keep every value\" },\n { value: \"each\", label: \"are separate records\" },\n ]}\n />\n </label>\n {combined && combined.multiValued.size > 0 ? (\n <span className=\"text-muted-foreground\" data-import-combine-lists=\"\">\n Lists in {[...combined.multiValued].join(\", \")}\n </span>\n ) : null}\n </div>\n ) : null}\n\n <div className=\"flex flex-wrap items-center gap-3\">\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Same row means the same</span>\n <PickOne\n label=\"What makes a row the same row\"\n value={dedupeKey}\n disabled={busy}\n onChange={(picked) => {\n setDedupeChosen(true);\n setDedupeKey(picked);\n }}\n options={[{ value: \"\", label: \"— nothing; write every row —\" }, ...declared.map((f) => ({ value: f.key, label: fieldName(f) }))]}\n />\n </label>\n {dedupeKey ? (\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">and when it is already here</span>\n <PickOne\n label=\"What happens to a row that is already here\"\n value={onDuplicate}\n disabled={busy}\n onChange={(picked) => setOnDuplicate(picked as \"skip\" | \"update\")}\n options={[\n { value: \"skip\", label: \"leave it alone\" },\n { value: \"update\", label: \"bring it up to date\" },\n ]}\n />\n </label>\n ) : null}\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Columns this table does not have</span>\n <PickOne\n label=\"What happens to a column this table does not have\"\n value={unmapped}\n disabled={busy}\n onChange={(picked) => {\n setUnmappedChosen(true);\n setUnmapped(picked as \"propose\" | \"create\" | \"ignore\");\n }}\n options={[\n { value: \"propose\", label: \"go to the approvals inbox\" },\n // SCR-N-7: adding a column outright is gated by the SAME right as the grid's \"+\",\n // and it is ABSENT rather than disabled for anybody else — a dead control that\n // explains nothing is the thing this platform forbids. The default choice above\n // does the same job for them, so nobody is stuck.\n ...(rights.admin ? [{ value: \"create\", label: \"are added straight away\" }] : []),\n { value: \"ignore\", label: \"are left out\" },\n ]}\n />\n </label>\n </div>\n\n {repeats.length > 0 ? (\n <label className=\"flex items-center gap-1.5\" data-import-repeats=\"\">\n <input type=\"checkbox\" checked={skipRepeats} disabled={busy} onChange={(e) => setSkipRepeats(e.target.checked)} />\n Skip {repeats.length} repeated row{repeats.length === 1 ? \"\" : \"s\"} ({linesWord(repeats.map((r) => r.row + 1), lineWord)})\n </label>\n ) : null}\n\n {newChoiceWords.map((ask) => {\n const words = ask.words.map((w) => `“${w}”`).join(\", \");\n const column = fieldName(ask.field);\n const canAdd = rights.admin && nudge !== \"never_add\";\n return (\n <div\n key={ask.field.key}\n className=\"flex flex-wrap items-center gap-2 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n data-import-new-choices={ask.field.key}\n >\n <span>\n {ask.words.length === 1 ? `${words} is not one of ${column}'s choices.` : `${words} are not among ${column}'s choices.`}{\" \"}\n {nudge === \"always_add\" && rights.admin\n ? `Your organization adds new choices without asking, so ${ask.words.length === 1 ? \"it is\" : \"they are\"} added when you import.`\n : canAdd\n ? `Add ${ask.words.length === 1 ? \"it\" : \"them\"}, or the rows that use ${ask.words.length === 1 ? \"it\" : \"them\"} are refused.`\n : `The rows that use ${ask.words.length === 1 ? \"it\" : \"them\"} are refused${rights.admin ? \" (your organization does not add new choices from an import)\" : \" — only someone who manages this table can add choices\"}.`}\n </span>\n {canAdd && nudge !== \"always_add\" ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={busy || addingWords !== null}\n onClick={() => void addChoiceWords(ask.field, ask.words)}\n >\n {addingWords === ask.field.key ? \"Adding…\" : `Add to ${column}`}\n </Button>\n ) : null}\n </div>\n );\n })}\n\n {relationProblem ? <RefusalNotice error={relationProblem} /> : null}\n {relationAsks.map((ask) => {\n const column = fieldName(ask.field);\n const table = ask.index.tableName;\n const choice = choiceFor(ask.field.key);\n const setChoice = (patch: Partial<{ unmatched: UnlinkedChoice; ambiguous: UnlinkedChoice }>) =>\n setUnlinkedChoice((held) => ({ ...held, [ask.field.key]: { ...choice, ...patch } }));\n const clean = ask.unmatched.length === 0 && ask.ambiguous.length === 0;\n return (\n <div\n key={ask.field.key}\n data-import-relation={ask.field.key}\n className={cn(\n \"flex flex-col gap-1 rounded border px-2 py-1.5\",\n clean ? \"bg-muted/40\" : \"border-amber-500/40 bg-amber-500/5\",\n )}\n >\n <span data-import-relation-linked=\"\">\n {column}: {ask.linked} of {ask.named} rows link to {table} by name\n </span>\n {ask.unmatched.length > 0 ? (\n <div className=\"flex flex-col gap-1\" data-import-relation-unmatched=\"\">\n <span>\n Not in {table}:{\" \"}\n {ask.unmatched\n .slice(0, 6)\n .map(([name, lines]) => `“${name}” (${linesWord(lines, lineWord)})`)\n .join(\", \")}\n {ask.unmatched.length > 6 ? ` +${ask.unmatched.length - 6}` : \"\"}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those rows</span>\n <PickOne\n label={`What rows naming a record not in ${table} do`}\n value={choice.unmatched}\n disabled={busy}\n onChange={(picked) => setChoice({ unmatched: picked as UnlinkedChoice })}\n options={[\n ...(ask.index.titleField ? [{ value: \"create\", label: `add the names to ${table}` }] : []),\n { value: \"empty\", label: \"import with no link\" },\n { value: \"skip\", label: \"are skipped\" },\n ]}\n />\n </label>\n </div>\n ) : null}\n {ask.ambiguous.length > 0 ? (\n <div className=\"flex flex-col gap-1\" data-import-relation-ambiguous=\"\">\n <span>\n More than one record in {table}:{\" \"}\n {ask.ambiguous\n .slice(0, 6)\n .map(([name, seen]) => `“${name}” ×${seen.count} (${linesWord(seen.lines, lineWord)})`)\n .join(\", \")}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those rows</span>\n <PickOne\n label={`What rows naming more than one record in ${table} do`}\n value={choice.ambiguous}\n disabled={busy}\n onChange={(picked) => setChoice({ ambiguous: picked as UnlinkedChoice })}\n options={[\n { value: \"merge\", label: `combine the duplicates in ${table}` },\n { value: \"empty\", label: \"import with no link\" },\n { value: \"skip\", label: \"are skipped\" },\n ]}\n />\n </label>\n </div>\n ) : null}\n </div>\n );\n })}\n\n {dateAsks\n .filter((ask) => ask.dates.unreadable.length > 0)\n .map((ask) => {\n const miss = ask.dates.unreadable;\n const byWord = new Map<string, number[]>();\n for (const m of miss) byWord.set(m.raw, [...(byWord.get(m.raw) ?? []), m.row + 1]);\n return (\n <div\n key={ask.header}\n data-import-dates={ask.header}\n className=\"flex flex-col gap-1 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n >\n <span>\n {ask.label}: {miss.length} {miss.length === 1 ? \"cell is\" : \"cells are\"} not a date —{\" \"}\n {[...byWord.entries()]\n .slice(0, 4)\n .map(([raw, lines]) => `“${raw}” (${linesWord(lines, lineWord)})`)\n .join(\", \")}\n {byWord.size > 4 ? ` +${byWord.size - 4}` : \"\"}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those cells</span>\n <PickOne\n label={`What cells of ${ask.header} that are not dates do`}\n value={dateMiss[ask.header] ?? \"empty\"}\n disabled={busy}\n onChange={(picked) => setDateMiss((held) => ({ ...held, [ask.header]: picked as \"empty\" | \"skip\" }))}\n options={[\n { value: \"empty\", label: \"are left empty\" },\n { value: \"skip\", label: \"skip their rows\" },\n ]}\n />\n </label>\n </div>\n );\n })}\n\n {ruleVerdicts.length > 0 ? (\n <RefusalNotice\n error={refusalOf(\n \"refused_by_rule\",\n `${refusedByRules} value${refusedByRules === 1 ? \"\" : \"s\"} in this file would be refused by ${\n ruleVerdicts.length === 1\n ? `the rules of ${fieldName(ruleVerdicts[0]!.field)}`\n : `the rules of ${ruleVerdicts.length} columns`\n } before anything is written. Nothing has been written yet.`,\n \"Change where those columns go, or fix the file and pick it again. To go ahead, the rest is written and every refused row is listed afterwards.\",\n )}\n actions={\n <label className=\"mt-1 flex items-center gap-1.5\" data-import-go-ahead=\"\">\n <input\n type=\"checkbox\"\n checked={goAheadAnyway}\n disabled={busy}\n onChange={(e) => setGoAheadAnyway(e.target.checked)}\n />\n Import the rest anyway\n </label>\n }\n />\n ) : null}\n\n {/* VISION-REACH G6: A STEP THAT FAILED SAYS SO WHERE THE PERSON IS LOOKING — beside the\n button they pressed, with the way to try again. It was printed at the top of a long\n rail, out of sight, and the button simply went back to \"Import 200 rows\". */}\n {problem ? (\n <div data-import-run-problem=\"\">\n <RefusalNotice\n error={problem}\n actions={\n <Button size=\"sm\" variant=\"outline\" className=\"mt-1\" disabled={busy} onClick={() => void run()}>\n Try again\n </Button>\n }\n />\n </div>\n ) : null}\n\n <div className=\"flex items-center gap-2\">\n <Button\n size=\"sm\"\n disabled={\n busy || !rights.write || rows.length === 0 || titleMissing || (ruleVerdicts.length > 0 && !goAheadAnyway)\n }\n onClick={() => void run()}\n >\n {phase === \"linking\"\n ? \"Linking the names…\"\n : phase === \"declaring\"\n ? \"Adding the columns…\"\n : phase === \"writing\"\n ? `Writing… ${progress} of ${effectiveRows.length}`\n : combining\n ? `Import ${effectiveRows.length} records from ${rows.length} rows`\n : `Import ${rows.length} row${rows.length === 1 ? \"\" : \"s\"}`}\n </Button>\n <span className={cn(\"text-muted-foreground\", titleMissing && \"text-destructive\")}>\n {/* FIX-11B F2: the button and the sentence beside it stopped\n contradicting each other — \"Import 1000 rows\" next to \"0 of 9\n columns go into this table\" was VERIFIER-10's finding and\n VERIFIER-11 wrote it down again. A run that cannot happen says\n WHY and what to do, where the person is looking. */}\n {titleMissing\n ? `Nothing goes into ${titleFieldLabel} yet, so these records would have no name. Choose the column above, then this will run.`\n : columnsSentence(mappedCount, plan.columns.length - leftOut.size, unmapped) +\n (leftOut.size > 0 ? ` · ${leftOut.size} left out` : \"\")}\n {fileHash || titleMissing\n ? \"\"\n : \" · this browser cannot recognize the file again, so importing it twice would write it twice\"}\n </span>\n </div>\n </>\n ) : null}\n\n {/* IMPORT-2: the column step's own answer, said before the rows are counted,\n because adding columns to a table is a different thing from adding rows\n to it and a person who did it deserves to be told. */}\n {columnsAdded && columnsAdded.length > 0 ? (\n <p data-import-columns-added=\"\">\n {columnsAdded.filter((c) => c.state === \"accepted\").length} column\n {columnsAdded.filter((c) => c.state === \"accepted\").length === 1 ? \"\" : \"s\"} added:{\" \"}\n {inFileOrder(columnsAdded.filter((c) => c.state === \"accepted\"), source?.parsed.headers ?? []).map((c) => c.label || c.column).join(\", \")}\n {columnsAdded.some((c) => c.state === \"refused\") ? (\n <span className=\"text-muted-foreground\">\n {\" \"}· {columnsAdded.filter((c) => c.state === \"refused\").map((c) => `${c.column} — ${c.reason ?? \"could not be added\"}`).join(\"; \")}\n </span>\n ) : null}\n </p>\n ) : null}\n\n {alreadyRan ? <p className=\"text-muted-foreground\">{alreadyRan}</p> : null}\n\n {outcomes.length > 0 || summary || ledger ? (\n <>\n <Separator />\n <div className=\"flex flex-wrap items-center gap-2\">\n {/* FIX-11B F2: THE STORE'S NUMBERS, FOR THE WHOLE RUN.\n This sentence used to be a tally of the `outcomes` array, which\n is a sample of one call's answers — so a 400-row file that landed\n 312 and refused 88 printed \"196 landed · 0 already here · 54\n refused\" and 88 rows went missing without a word. It is the\n ledger now: what the store counted, over every call. */}\n <span>\n {ledger\n ? `${ledger.written} landed · ${ledger.duplicate} already here · ${ledger.refused} refused, of ${ledger.seen} row${ledger.seen === 1 ? \"\" : \"s\"} offered`\n : `${counts.landed} landed · ${counts.duplicate} already here · ${counts.refused} refused`}\n </span>\n {ledger && !ledger.final && phase !== \"writing\" ? (\n <span className=\"text-destructive\">\n The run stopped here, so the rest of the file was never offered — these are the rows\n that were dealt with before it stopped, not the whole file.\n </span>\n ) : null}\n {(ledger ? ledger.refused + ledger.duplicate : counts.refused + counts.duplicate) > 0 ? (\n <>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"all\" && \"font-medium\")} onClick={() => setShow(\"all\")}>\n everything that did not land\n </button>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"refused\" && \"font-medium\")} onClick={() => setShow(\"refused\")}>\n refused\n </button>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"duplicate\" && \"font-medium\")} onClick={() => setShow(\"duplicate\")}>\n already here\n </button>\n </>\n ) : null}\n </div>\n {summary ? <p className=\"text-muted-foreground\">{summary}</p> : null}\n {/* VISION-REACH lane 5: THE ROWS THAT WERE NOT ADDED, SAID AS ONE LOUD LINE WITH ITS\n REASONS AND A FILE. \"43 refused\" at the end of a sentence was read as done; 43 near-\n identical rows below it were not read at all. The notice the table page keeps\n (`ImportNotice`) says the same thing until it is dismissed. */}\n {ledger && ledger.final && ledger.refused > 0 ? (\n <div data-import-refused-summary=\"\">\n <RefusalNotice\n error={refusalOf(\n \"refused_by_rule\",\n `${ledger.refused} of ${ledger.seen} rows were not added.`,\n \"Download them, fix the file or the names, and import again.\",\n )}\n actions={\n <div className=\"flex flex-col gap-1 pt-0.5\">\n <ul className=\"flex flex-col gap-0.5\" data-import-refused-reasons=\"\">\n {groupReasons(outcomes.filter((o) => o.outcome === \"refused\").map((o) => (o.outcome === \"refused\" ? o.reason : \"\"))).map((g) => (\n <li key={g.reason}>\n {g.count} row{g.count === 1 ? \"\" : \"s\"}: {g.example}\n </li>\n ))}\n </ul>\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"self-start\"\n onClick={() =>\n offerDownload(\n refusedFileName(fileName),\n refusedRowsCsv(\n outcomes.flatMap((o) => (o.outcome === \"refused\" ? [{ row: o.row, reason: o.reason, source: o.source }] : [])),\n (n) => (source ? sentLines?.[n - 1] ?? n : lineInYourFile(sentLines?.[n - 1] ?? n)),\n ),\n )\n }\n >\n Download the rows not added\n </Button>\n </div>\n }\n />\n </div>\n ) : null}\n {afterWrite && keptAside.length > 0 ? (\n <div data-import-kept-aside=\"\" className=\"flex flex-col gap-0.5\">\n <p>\n {keptAside.length} cell{keptAside.length === 1 ? \" was\" : \"s were\"} kept aside and left empty; every other value in those rows was written.\n </p>\n <ul className=\"flex flex-col gap-0.5 text-muted-foreground\">\n {keptAside.map((c) => (\n <li key={`${c.header}:${c.line}`}>\n {c.header}, {source ? `row ${c.line}` : `line ${lineInYourFile(c.line)}`}: {c.raw} — {c.why}\n </li>\n ))}\n </ul>\n </div>\n ) : null}\n {repeatsSkipped > 0 ? (\n <p className=\"text-muted-foreground\" data-import-repeats-skipped=\"\">\n {repeatsSkipped} repeated row{repeatsSkipped === 1 ? \"\" : \"s\"} skipped\n </p>\n ) : null}\n\n {/* THE ROWS THAT DID NOT LAND, WITH THE ROW ITSELF. A count nobody can\n act on is the thing the store now refuses to hand back, and this\n is where that matters: the line of the spreadsheet is right here. */}\n {/* FIX-11B F2: A SHORT LIST NEVER READS AS THE WHOLE STORY. The door\n caps the rows it hands back, and this table caps them again at 200.\n When either cap bites, the screen says so with the number it is\n short by, rather than letting a person count the lines and believe\n that is all there was. */}\n {ledger && show === \"all\" && ledger.refused + ledger.duplicate > interesting.length ? (\n <p className=\"text-muted-foreground\">\n {interesting.length} of the {ledger.refused + ledger.duplicate} row\n {ledger.refused + ledger.duplicate === 1 ? \" that\" : \"s that\"} did not land\n {interesting.length === 1 ? \" is\" : \" are\"} listed below by their {source ? \"row\" : \"line in your file\"} —\n the rest stay with this run and are not all shown at once.\n </p>\n ) : null}\n {interesting.length > 0 ? (\n <div className=\"max-h-64 overflow-auto rounded border\">\n <table className=\"w-full\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"Row\" : \"Line in your file\"}</th>\n <th className=\"px-2 py-1 text-left font-medium\">What happened</th>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"The row\" : \"The row in your file\"}</th>\n </tr>\n </thead>\n <tbody>\n {interesting.slice(0, 200).map((o) => (\n <tr key={`${o.outcome}-${o.row}`} className=\"border-t align-top\">\n <td className=\"px-2 py-1\">{source ? (sentLines?.[o.row - 1] ?? o.row) : lineInYourFile(sentLines?.[o.row - 1] ?? o.row)}</td>\n <td className=\"px-2 py-1\">\n {o.outcome === \"refused\" ? (\n <RefusalLine\n error={refusalOf(\"refused_by_rule\", o.reason, source ? \"Fix this row where it came from and save it again.\" : \"Fix this line in your file and import it again.\")}\n />\n ) : o.outcome === \"duplicate\" ? (\n <span className=\"text-muted-foreground\">{o.reason}</span>\n ) : (\n \"written\"\n )}\n </td>\n <td className=\"max-w-96 px-2 py-1 text-muted-foreground\">\n {o.outcome === \"refused\"\n ? Object.entries(o.source)\n .map(([k, v]) => `${k}: ${String(v ?? \"\")}`)\n .join(\" · \")\n : \"\"}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : null}\n\n {proposals.length > 0 ? (\n <ul className=\"flex flex-col gap-0.5\">\n {proposals.map((p) => (\n <li key={p.column} className=\"text-muted-foreground\">\n <span className=\"font-medium text-foreground\">{p.column}</span>\n {p.state === \"waiting\"\n ? \" is waiting in the approvals inbox.\"\n : p.state === \"accepted\"\n ? \" was added as a column.\"\n : p.state === \"ignored\"\n ? \" was left out.\"\n : p.state === \"refused\"\n ? ` could not be added: ${p.reason ?? \"\"}`\n : ` — ${p.state}`}\n </li>\n ))}\n </ul>\n ) : null}\n\n {/* FIX-12 F2: THE REPORT IS READ, THEN DISMISSED — IN THAT ORDER.\n The run used to close the panel itself the instant the last row\n landed, so this whole block existed for less than a paint on any\n file small enough to finish in one call. Nothing closes it now but\n this button, and the sentence beside it says where the refused rows\n live once it is pressed: on the run itself, in the list below. */}\n {phase === \"done\" ? (\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button size=\"sm\" onClick={() => onDone?.(ledger?.written ?? 0)}>\n Done\n </Button>\n {(ledger?.refused ?? 0) > 0 ? (\n <span className=\"text-muted-foreground\">\n The {ledger?.refused} row{ledger?.refused === 1 ? \"\" : \"s\"} that {ledger?.refused === 1 ? \"was\" : \"were\"} refused\n {ledger?.refused === 1 ? \" is\" : \" are\"} kept with this import — open {ledger?.refused === 1 ? \"it\" : \"them\"} again from the list of imports below, with the\n reason and the line from your file on each.\n </span>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null}\n\n {/* ── FIX-12 F2: THE RUNS THIS TABLE ALREADY HAD. ─────────────────────\n A refusal a person did not catch in the moment was unreachable: no\n screen asked the store for it, and the store had it the whole time.\n Every run this table has had is here, newest first, and one with\n refused rows opens them — the store's own sentence and the line of the\n file, the same two things the live report shows. */}\n {runsProblem ? <RefusalNotice error={runsProblem} /> : null}\n {runs && runs.length > 0 ? (\n <>\n <Separator />\n <p className=\"font-medium\">Imports into this table</p>\n <ul className=\"flex flex-col gap-1\">\n {runs.map((r) => (\n <li key={r.import_id} className=\"flex flex-col gap-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium\">{r.source_name ?? \"a file\"}</span>\n <span className=\"text-muted-foreground\">\n {new Date(r.opened_at).toLocaleString()} · {r.rows_written} landed ·{\" \"}\n {r.rows_duplicate} already here · {r.rows_refused} refused, of {r.rows_seen} row\n {r.rows_seen === 1 ? \"\" : \"s\"} offered\n </span>\n {r.rows_refused > 0 ? (\n <button\n type=\"button\"\n className=\"underline underline-offset-2\"\n aria-expanded={openRun === r.import_id}\n onClick={() => void openRefusals(r.import_id)}\n >\n {openRun === r.import_id\n ? \"hide the rows it refused\"\n : `see the ${r.rows_refused} row${r.rows_refused === 1 ? \"\" : \"s\"} it refused`}\n </button>\n ) : null}\n </div>\n {openRun === r.import_id ? (\n runProblem ? (\n <RefusalNotice error={runProblem} />\n ) : runRows ? (\n <>\n {runRows.note ? <p className=\"text-muted-foreground\">{runRows.note}</p> : null}\n <div className=\"max-h-64 overflow-auto rounded border\">\n <table className=\"w-full\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"Row\" : \"Line in your file\"}</th>\n <th className=\"px-2 py-1 text-left font-medium\">What happened</th>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"The row\" : \"The row in your file\"}</th>\n </tr>\n </thead>\n <tbody>\n {runRows.rows.map((row, i) => {\n const refusedRowSource = (row.source ?? {}) as Record<string, unknown>;\n return (\n <tr key={`${r.import_id}-${String(row.row ?? i)}`} className=\"border-t align-top\">\n <td className=\"px-2 py-1\">{typeof row.row === \"number\" ? lineInYourFile(row.row) : String(row.row ?? \"\")}</td>\n <td className=\"px-2 py-1\">\n <RefusalLine\n error={refusalOf(\n \"refused_by_rule\",\n String(row.reason ?? \"This row was refused.\"),\n \"Fix this line in your file and import it again.\",\n )}\n />\n </td>\n <td className=\"max-w-96 px-2 py-1 text-muted-foreground\">\n {Object.entries(refusedRowSource)\n .map(([k, v]) => `${k}: ${String(v ?? \"\")}`)\n .join(\" · \")}\n </td>\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n </>\n ) : (\n <p className=\"text-muted-foreground\">Reading the rows this import refused…</p>\n )\n ) : null}\n </li>\n ))}\n </ul>\n </>\n ) : null}\n\n {table.error ? <RefusalNotice error={table.error} onRetry={table.reload} /> : null}\n </div>\n );\n}\n","// src/importRuleCheck.ts — @ai-matrx/records-ui · lane REFUSAL-SWEEP (2026-09-23)\n//\n// THE IMPORT ASKS THE COLUMN RULES BEFORE IT WRITES.\n//\n// Until this file the wizard mapped a file's columns, pressed Import, and learnt\n// what each column's rules thought of the file from the store — row by row,\n// AFTER the write, as a list of refusals to go and fix. The bulk paste already\n// asked first (`pasteValues.ts`); this is the same question asked over a whole\n// file, through the SAME two bodies, so an import, a paste and a typed answer can\n// never disagree about one value:\n//\n// · `valueFromPastedText` — `@ai-matrx/records`' `coerceTypedAnswer`: does this\n// text mean a value of this column's kind at all?\n// · `predictValueRefusals` — `custom.validate_values` mirrored: would the\n// column's declared rules (min, max, length, pattern…) refuse it?\n//\n// Only the MAPPED column is judged for each cell. A required column the file\n// never mentions is not this column's refusal, and the wizard says that\n// elsewhere (the title column line).\n\nimport type { Field, RelationNameIndex } from \"@ai-matrx/records\";\nimport { predictValueRefusals } from \"@ai-matrx/records/core\";\n\nimport { valueFromPastedText, type ChoiceOptions } from \"./pasteValues\";\nimport { editorKindFor } from \"./parity\";\n\nexport interface ImportColumnVerdict {\n /** The column's header in the file. */\n header: string;\n /** The table's column it goes to. */\n field: Field;\n /** How many of the file's rows this column's rules would refuse. */\n refused: number;\n /** How many rows carried a value in this column at all. */\n judged: number;\n /** The first refusal, in the store's own words. */\n firstWhy: string;\n /** The line in the file (1 = first data row) and the text it carried. */\n firstLine: number;\n firstRaw: string;\n}\n\n/**\n * Every mapped column whose rules would refuse at least one row of the file.\n * An empty answer means the rules have nothing to say — never \"unchecked\".\n */\nexport interface ImportRefusedCell {\n /** The cell's column header in the file, its data row (1 = first data row) and the text it carried. */\n header: string;\n line: number;\n raw: string;\n /** The reason, in the store's own words. */\n why: string;\n}\n\n/** Every cell of the mapped columns the rules would refuse, in file order. The one judge. */\nexport function refusedCellsOf(\n fields: Field[],\n rows: Array<Record<string, string>>,\n mapping: Record<string, string>,\n choiceOptions?: ReadonlyMap<string, ChoiceOptions>,\n relationNames?: ReadonlyMap<string, RelationNameIndex>,\n): Array<ImportRefusedCell & { judged: number; field: Field }> {\n const byKey = new Map(fields.map((f) => [f.key, f]));\n const cells: Array<ImportRefusedCell & { judged: number; field: Field }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = byKey.get(key);\n if (!field) continue;\n const kind = String(editorKindFor(field));\n const isChoice = kind === \"select\" || kind === \"multi_select\";\n const options = choiceOptions?.get(key);\n if (isChoice && !options) continue;\n const named = relationNames?.get(key);\n if (kind === \"relation\" && !named) continue;\n let judged = 0;\n const mine: ImportRefusedCell[] = [];\n rows.forEach((row, i) => {\n const raw = String(row[header] ?? \"\").trim();\n if (raw === \"\") return;\n judged += 1;\n const meant = valueFromPastedText(field, raw, options, named);\n let why: string | null = null;\n if (\"unmatched\" in meant) return; // the enum ask names these words, with Add\n if (\"unmatchedNames\" in meant) return; // the relation ask names these, with its choices\n if (\"refusal\" in meant) why = meant.refusal;\n else {\n const predicted = predictValueRefusals([field], { [key]: meant.value }).filter(\n (p) => p.field_key === undefined || p.field_key === key,\n );\n if (predicted.length > 0) why = predicted[0]!.message;\n }\n if (why !== null) mine.push({ header, line: i + 1, raw, why });\n });\n for (const c of mine) cells.push({ ...c, judged, field });\n }\n return cells;\n}\n\nexport function checkImportRules(\n fields: Field[],\n rows: Array<Record<string, string>>,\n mapping: Record<string, string>,\n /**\n * A choice column's options, by field key (SAVE-AS-TABLE-EVERYWHERE). Without them a choice word\n * cannot be judged at all, and this used to say \"3 of 3 rows would be refused … its options have\n * not been read yet\" over rows whose words WERE choices — so a choice column is judged only once\n * its options are in hand, and a word it does not know is the enum ask's to raise, not this.\n */\n choiceOptions?: ReadonlyMap<string, ChoiceOptions>,\n /**\n * VISION-REACH G1: a relation column's target indexed by the file's names. A relation column is\n * judged only once its index is in hand, and a name matching nothing (or two records) is the\n * relation ask's to raise, with its choices — never a rule refusal.\n */\n relationNames?: ReadonlyMap<string, RelationNameIndex>,\n): ImportColumnVerdict[] {\n const verdicts = new Map<string, ImportColumnVerdict>();\n for (const c of refusedCellsOf(fields, rows, mapping, choiceOptions, relationNames)) {\n const have = verdicts.get(c.header);\n if (have) have.refused += 1;\n else verdicts.set(c.header, { header: c.header, field: c.field, refused: 1, judged: c.judged, firstWhy: c.why, firstLine: c.line, firstRaw: c.raw });\n }\n return [...verdicts.values()];\n}\n","// src/pasteValues.ts — @ai-matrx/records-ui\n//\n// WHAT A BLOCK OF SPREADSHEET TEXT MEANS TO THIS TABLE, WORKED OUT BEFORE ANY\n// OF IT IS WRITTEN.\n//\n// The clipboard hands over STRINGS. A column does not take strings — it takes a\n// number, a date, a tick, a document — and until a string has been turned into\n// one of those, nobody can say whether the store would accept it. Crew C, on\n// 2026-09-21, had fifty US airports in a spreadsheet and no way to get them in\n// but two hundred and fifty double-clicks; the grid had no paste at all. This\n// is the half that makes a paste answerable in advance: every cell is coerced\n// the way that column's own editor would coerce it, and then judged by the\n// store's OWN mirror of `custom.validate_values`, so the sentence a person\n// reads in the preview is the sentence the door would have said.\n//\n// THE COERCION IS `@ai-matrx/records`' `coerceTypedAnswer`, NOT A SECOND\n// OPINION. A column drawn as money must read a pasted \"$1,250.50\" as money; a\n// file that classified fields its own way would let a paste and a typed value\n// disagree about the same column, which is the class of defect the grid spent\n// September closing — and which the public booking page was still paying for\n// in September (\"Vehicle Year takes a number, and it was given a string\")\n// because the coercion lived in the grid and nowhere else.\n//\n// A CELL THAT CANNOT BE COERCED IS REFUSED, NEVER GUESSED. Writing 0 for\n// \"about twelve\" or today's date for \"soon\" is how a spreadsheet quietly\n// corrupts a table. The cell is left alone and the person is told, in words,\n// what that column takes.\n\nimport { predictValueRefusals } from \"@ai-matrx/records/core\";\nimport type { ChoiceOptions, Field, RelationNameIndex, StoredRecord, Uuid } from \"@ai-matrx/records\";\nimport { coerceTypedAnswer, optionKey } from \"@ai-matrx/records\";\nimport { calendarDayOf, hasTimePart, isDateField } from \"./dates\";\nimport { editorKindFor } from \"./parity\";\nimport { recordName } from \"./names\";\nimport { fieldName } from \"./names\";\n\n/** One pasted cell, after its column has had a look at it. */\nexport interface PastedCell {\n key: string;\n /**\n * The column's NAME, the way the grid's own header writes it. The preview\n * used to draw `key` in its header row, so the one screen that promises\n * \"exactly what will be stored\" printed `job_number` and `scheduled_date`\n * over columns the grid calls Job Number and Scheduled Date (FIX-10C F8,\n * 2026-09-22). One resolver, `fieldName`, everywhere a label is shown.\n */\n column: string;\n /** Exactly what was on the clipboard, kept so a refusal can quote it. */\n raw: string;\n /** What would be written. Meaningless when `refusal` is set. */\n value: unknown;\n /** The sentence that says why it will not be written, or null. */\n refusal: string | null;\n /**\n * WHAT THE PERSON WILL SEE IN THAT CELL once it is written — never the\n * machine id that is stored underneath it.\n *\n * 🚨 THIS IS THE OTHER HALF OF THE SAME DEFECT. A choice column stores the\n * OPTION RECORD'S ID (FLD-5/FLD-6), so the preview that says \"the values\n * below are exactly what will be stored\" printed\n * `530808bf-9f2d-4062-bc09-b8cc3b162f2a` where the person had pasted *Drain\n * Cleaning*. Both sentences were true and the screen was still lying, because\n * a person reads a screen to recognize their own data. So the plan carries\n * the WORDS beside the value: the id is what lands, the word is what is\n * shown, and `custom._words_for`'s display arm is the rule both obey.\n * `null` means the value shows itself (a number, a date, a piece of text).\n */\n display: string | null;\n}\n\n/** One row of the pasted block, and where it would land. */\nexport interface PastedRow {\n /** The record this row writes over, or null when a record would be created. */\n recordId: Uuid | null;\n /** 1-based, as a person counts rows in the thing they copied. */\n fromLine: number;\n cells: PastedCell[];\n}\n\n/** What the whole paste would do — the thing the preview draws. */\nexport interface PastePreviewPlan {\n rows: PastedRow[];\n /** Records that already exist and would be updated. */\n updates: number;\n /** Records that do not exist yet and would be created. */\n creates: number;\n /** Cells that would actually be written. */\n cells: number;\n /** Every cell that will be left alone, with its sentence. */\n refusals: Array<{ fromLine: number; column: string; raw: string; why: string }>;\n /** Cells with no column to land in — the block was wider than the table. */\n pastRightEdge: number;\n /**\n * Words a choice column did not recognize, per column, deduplicated and in\n * the order they were first pasted. The preview offers these back as ONE\n * explicit \"add these N options\" action; nothing here is ever created on its\n * own, because a typo turned into a lifecycle stage is a column nobody chose.\n */\n unmatchedOptions: Array<{ fieldKey: string; column: string; words: string[] }>;\n /**\n * Set when the pasted block's first line named this table's columns: it was read as a header\n * (matched BY NAME, as the Sheet does) and left out of the rows. `unmatched` are the pasted\n * columns whose name no column here answers to — they are not written, and the preview names them.\n */\n header?: { unmatched: string[] };\n /** Lines the person chose to drop (\"fill only the existing rows\"): how many were left out. */\n droppedLines?: number;\n}\n\n/**\n * A choice column's own options, ready to be matched against a pasted WORD.\n *\n * WHY THIS EXISTS. Until 2026-09-21 a word pasted into a choice column was\n * refused outright — \"a pasted word is not one of its options\" — which is true\n * of a raw string and useless to the person holding a spreadsheet whose Status\n * column says \"Completed\" fifty times. Airtable, the champion here, matches the\n * word to the option labeled Completed, and so does this. What it will NOT do\n * is invent an option: a typo would silently become a new lifecycle stage, and\n * every board, filter and rollup built on that column would quietly grow a\n * column nobody chose. Unmatched words are REFUSED, named, and offered back as\n * one explicit \"add these\" action in the preview.\n */\n/**\n * 🚨 THE CORE'S TYPE, RE-EXPORTED (TAILS-3, 2026-09-21). It was declared here\n * and the coercion that reads it now lives in `@ai-matrx/records`, so there is\n * one shape, not two that drift. `choiceOptionsOf` stays here because building\n * the index needs `recordName`, which is a screen concern.\n */\nexport type { ChoiceOptions };\n\n/** Index one field's option records the way a paste needs to read them. */\n/**\n * The WORD a stored choice value shows, out of the same index the coercion\n * matched against. `ChoiceOptions` is keyed word → id (that is the direction a\n * paste needs), so this walks the labels it already carries and answers the one\n * whose id matches. Deliberately not a second index: two maps that can disagree\n * about what an option is called is the class this whole file exists to avoid.\n */\nexport function wordForStoredChoice(options: ChoiceOptions | undefined, value: unknown): string | null {\n if (options === undefined || typeof value !== \"string\" || value === \"\") return null;\n for (const label of options.labels) {\n if (options.byWord.get(label.toLowerCase()) === value) return label;\n }\n return null;\n}\n\nexport function choiceOptionsOf(options: StoredRecord[]): ChoiceOptions {\n const byWord = new Map<string, string>();\n const labels: string[] = [];\n for (const option of options) {\n // WHAT IS STORED IS THE OPTION RECORD'S ID. FLD-5/FLD-6: every pick-list is\n // already a Table, so a list field holds the id of the option's record —\n // and `predictValueRefusals`, which is the store's own validator mirrored,\n // refuses anything that is not a uuid by name. Writing the option's slug\n // here would make the preview promise a write the door then refuses.\n const id = option.id as string;\n const key = optionKey(option);\n const label = recordName(option.data as never, null, \"\");\n if (label) {\n labels.push(label);\n // First one wins: two options with the same label are a data problem in\n // the choices Table, and silently preferring the later one would make a\n // paste land somewhere the person cannot see.\n if (!byWord.has(label.toLowerCase())) byWord.set(label.toLowerCase(), id);\n }\n // The KEY and the ID are matched too, because an export of this table\n // writes one of them and a round trip through a spreadsheet has to come\n // back in.\n if (key && !byWord.has(String(key).toLowerCase())) byWord.set(String(key).toLowerCase(), id);\n if (id && !byWord.has(id.toLowerCase())) byWord.set(id.toLowerCase(), id);\n }\n return { byWord, labels };\n}\n\n/**\n * Turn one clipboard string into the value this Field holds — or say, in a\n * sentence a person can act on, why it is not one.\n *\n * 🚨 IT IS ONE CALL NOW, AND THAT IS THE FIX (TAILS-3, 2026-09-21). This\n * function's body used to BE the coercion — a good one, and the only one,\n * while the two doors a STRANGER uses carried none. AGENT-BUILDS-2's closing\n * walk found Ironclad Mobile Mechanic's public booking page unbookable over\n * any table with a number field: \"Vehicle Year takes a number, and it was\n * given a string\". A capability scoped to the feature that surfaced it.\n *\n * So the body moved to `@ai-matrx/records`' `coerceTypedAnswer`, which the\n * public form, the public booking, a portal edit, a CSV import and this paste\n * all call. A clipboard cell and a typed-in answer are the same thing — a\n * string a person means as a value — and there is now ONE body that says what\n * they mean. The label stays this package's, so a refusal names the column the\n * way the grid's own header does.\n */\nexport function valueFromPastedText(\n field: Field,\n raw: string,\n /** This column's options, when the caller has loaded them. */\n options?: ChoiceOptions,\n /**\n * VISION-REACH G1: a relation column's target, indexed by the names the paste or file carries\n * (`client.relationNamesMatch` → `relationNameIndexOf`). Without it a name is refused.\n */\n relationNames?: RelationNameIndex,\n): ReturnType<typeof coerceTypedAnswer> {\n return coerceTypedAnswer(field, raw, {\n label: fieldName(field),\n ...(options ? { options } : {}),\n ...(relationNames ? { relationNames } : {}),\n });\n}\n\n/**\n * The whole plan, ready to be shown.\n *\n * `existingRowIds` are the rows the paste lands on, in the grid's order from\n * the anchor down; `overflow` are the block's remaining rows, which become new\n * records. `columnKeys` is the grid's column order from the anchor rightwards.\n */\nexport function planPastedBlock(args: {\n fields: Field[];\n /** This table's choice options, by field key. A choice column with no entry\n * here has not been read yet, and the planner says so rather than guessing. */\n options?: Map<string, ChoiceOptions>;\n /** Relation columns' targets indexed by name, by field key (VISION-REACH G1). */\n relationNames?: Map<string, RelationNameIndex>;\n /** Field key per pasted column, in order. A null means there is no column. */\n columnKeys: Array<string | null>;\n /** Rows landing on records that exist: recordId plus that row's raw cells. */\n onExisting: Array<{ recordId: Uuid; raw: Array<string | undefined> }>;\n /** Rows past the last row of the grid — each becomes a record. */\n onNew: Array<Array<string | undefined>>;\n /** Cells the grid already said have no column to land in. */\n pastRightEdge?: number;\n /** Carried onto the plan when the block's first line was read as a header. */\n header?: { unmatched: string[] };\n droppedLines?: number;\n}): PastePreviewPlan {\n const byKey = new Map(args.fields.map((f) => [f.key, f]));\n const rows: PastedRow[] = [];\n const refusals: PastePreviewPlan[\"refusals\"] = [];\n const unmatched = new Map<string, { column: string; words: string[] }>();\n let cells = 0;\n\n const lines: Array<{ recordId: Uuid | null; raw: Array<string | undefined> }> = [\n ...args.onExisting.map((r) => ({ recordId: r.recordId as Uuid | null, raw: r.raw })),\n ...args.onNew.map((raw) => ({ recordId: null, raw })),\n ];\n\n lines.forEach((line, index) => {\n const fromLine = index + 1;\n const built: PastedCell[] = [];\n const accepted: Record<string, unknown> = {};\n for (let c = 0; c < args.columnKeys.length; c += 1) {\n const key = args.columnKeys[c];\n if (key == null) continue;\n const field = byKey.get(key);\n const raw = line.raw[c];\n if (field === undefined || raw === undefined) continue;\n const judged = valueFromPastedText(field, raw, args.options?.get(key), args.relationNames?.get(key));\n if (\"refusal\" in judged) {\n if (\"unmatched\" in judged && judged.unmatched) {\n const seen = unmatched.get(key) ?? { column: fieldName(field), words: [] };\n for (const word of judged.unmatched) {\n if (!seen.words.some((w) => w.toLowerCase() === word.toLowerCase())) seen.words.push(word);\n }\n unmatched.set(key, seen);\n }\n built.push({ key, column: fieldName(field), raw, value: null, refusal: judged.refusal, display: null });\n refusals.push({ fromLine, column: fieldName(field), raw, why: judged.refusal });\n continue;\n }\n built.push({\n key,\n column: fieldName(field),\n raw,\n value: judged.value,\n refusal: null,\n // The words, resolved once here rather than by whichever screen draws\n // the plan — a second resolver is a second answer to \"what is this\n // called\", and the raw clipboard text is the honest fallback because it\n // is literally what the person typed for this cell.\n display: wordForStoredChoice(args.options?.get(key), judged.value) ?? (\"words\" in judged ? judged.words ?? null : null),\n });\n accepted[key] = judged.value;\n }\n\n // THE STORE'S OWN MIRROR, ASKED ONCE PER ROW. `predictValueRefusals` is\n // `custom.validate_values` reproduced in TypeScript, so a required field\n // left empty, a value outside a declared range, a pattern a format\n // enforces and a formula written into all come back HERE, in the store's\n // own words, instead of as fifty round trips that each fail.\n // These are the store rules' own sentences, mirrored here: a message and a field key, no\n // hint, details or SQLSTATE, so `.message` is the whole of what a person reads.\n const predicted = predictValueRefusals(args.fields, accepted);\n for (const refusal of predicted) {\n const key = refusal.field_key;\n if (key === undefined) continue;\n const cell = built.find((b) => b.key === key && b.refusal === null);\n if (!cell) continue;\n cell.refusal = refusal.message;\n cell.value = null;\n delete accepted[key];\n refusals.push({\n fromLine,\n column: fieldName(byKey.get(key) ?? ({ key } as Field)),\n raw: cell.raw,\n why: refusal.message,\n });\n }\n\n cells += Object.keys(accepted).length;\n rows.push({ recordId: line.recordId, fromLine, cells: built });\n });\n\n // A NEW RECORD WITH NOTHING LEFT IN IT IS NOT A RECORD. If every cell of a\n // pasted row was refused, writing a blank row would leave a person deleting\n // rows they never asked for.\n const keepers = rows.filter(\n (row) => row.recordId !== null || row.cells.some((c) => c.refusal === null),\n );\n\n return {\n rows: keepers,\n updates: keepers.filter((r) => r.recordId !== null).length,\n creates: keepers.filter((r) => r.recordId === null).length,\n cells,\n refusals,\n pastRightEdge: args.pastRightEdge ?? 0,\n ...(args.header ? { header: args.header } : {}),\n ...(args.droppedLines ? { droppedLines: args.droppedLines } : {}),\n unmatchedOptions: [...unmatched.entries()].map(([fieldKey, seen]) => ({\n fieldKey,\n column: seen.column,\n words: seen.words,\n })),\n };\n}\n\n/** What one row would actually be written as — the accepted cells only. */\nexport function documentOf(row: PastedRow): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const cell of row.cells) if (cell.refusal === null) out[cell.key] = cell.value;\n return out;\n}\n\n/** Letter case and spacing aside: \" Service ADDRESS \" reads as \"service address\". */\nconst sameWords = (text: string): string => text.trim().replace(/\\s+/g, \" \").toLowerCase();\n\n/**\n * IS THE FIRST LINE OF A PASTED BLOCK THE TABLE'S OWN COLUMN NAMES? Then it is a header, not a row.\n *\n * The Sheet's paste read the first line as headers and matched each BY NAME (case and spacing\n * blind; `paste-header-match.ts`); the grid wrote by position, so a block copied WITH its header\n * line landed the header as a record. This is the Sheet's rule, kept to what a person pasting into\n * a table that already has rows means:\n * · it takes at least two lines (a header with nothing under it is not a paste of data);\n * · at least one cell names a column, and at least half of the non-empty cells do — a data line\n * that happens to repeat one column's name is not a header;\n * · the lines are not all the same (one value tiled over a selection is not a header).\n * A name two columns share matches neither (it is ambiguous), and no column is filled twice.\n *\n * `columnKeys` are the pasted columns' landing columns in order, `lines` the raw cells aligned to\n * them. Returns null when the first line is data; otherwise the column each pasted column writes\n * to (null = unmatched), the header cells that matched nothing, and the lines without the header.\n */\nexport function readPasteHeader(args: {\n fields: Field[];\n columnKeys: string[];\n lines: Array<Array<string | undefined>>;\n}): { columnKeys: Array<string | null>; unmatched: string[]; lines: Array<Array<string | undefined>> } | null {\n const { fields, columnKeys, lines } = args;\n if (lines.length < 2 || columnKeys.length === 0) return null;\n const head = lines[0] ?? [];\n const sameAsFirst = lines.every((line) => columnKeys.every((_, c) => (line[c] ?? \"\") === (head[c] ?? \"\")));\n if (sameAsFirst) return null;\n\n const byName = new Map<string, Field[]>();\n for (const f of fields) {\n for (const name of new Set([sameWords(fieldName(f)), sameWords(f.key.replace(/_/g, \" \"))])) {\n byName.set(name, [...(byName.get(name) ?? []), f]);\n }\n }\n const taken = new Set<string>();\n const mapped: Array<string | null> = columnKeys.map(() => null);\n let named = 0;\n let filled = 0;\n columnKeys.forEach((_, c) => {\n const cell = head[c];\n if (cell === undefined || cell.trim() === \"\") return;\n filled += 1;\n const hits = [...new Set(byName.get(sameWords(cell)) ?? [])];\n // Name first: the column whose display name reads the same; a key spelled the same is the fallback.\n const named1 = hits.filter((f) => sameWords(fieldName(f)) === sameWords(cell));\n const pick = named1.length > 0 ? named1 : hits;\n if (pick.length !== 1) return;\n const only = pick[0]!;\n named += 1;\n if (taken.has(only.key)) return;\n taken.add(only.key);\n mapped[c] = only.key;\n });\n if (named === 0 || named * 2 < filled) return null;\n const unmatched = columnKeys.flatMap((_, c) => {\n const cell = head[c];\n return mapped[c] === null && cell !== undefined && cell.trim() !== \"\" ? [cell.trim()] : [];\n });\n return { columnKeys: mapped, unmatched, lines: lines.slice(1) };\n}\n\n/**\n * THE SAME PASTE, JUDGED AGAIN — after a choice column gained options, or with its new rows\n * dropped (\"fill only the existing rows\"). It reads the plan's own rows, so what was matched by\n * name, and what was left out, stays as it was.\n */\nexport function replanPastedBlock(\n plan: PastePreviewPlan,\n args: {\n fields: Field[];\n options?: Map<string, ChoiceOptions>;\n relationNames?: Map<string, RelationNameIndex>;\n },\n change: { dropNew?: boolean } = {},\n): PastePreviewPlan {\n const creating = plan.rows.filter((r) => r.recordId === null);\n const dropped = change.dropNew ? creating.length : 0;\n return planPastedBlock({\n ...args,\n columnKeys: plan.rows[0]?.cells.map((c) => c.key) ?? [],\n onExisting: plan.rows\n .filter((r) => r.recordId !== null)\n .map((r) => ({ recordId: r.recordId as Uuid, raw: r.cells.map((c) => c.raw) })),\n onNew: change.dropNew ? [] : creating.map((r) => r.cells.map((c) => c.raw)),\n pastRightEdge: plan.pastRightEdge,\n ...(plan.header ? { header: plan.header } : {}),\n droppedLines: (plan.droppedLines ?? 0) + dropped,\n });\n}\n\n/**\n * DID THE STORE KEEP WHAT WAS WRITTEN? Compared in the column's own terms, never as JSON text.\n *\n * The read-back asked the store for each pasted row again and compared `JSON.stringify` of the\n * stored value with the written one. The store normalizes on the way in — a day may come back as\n * an instant, a number as text, a choice by another spelling of the same option — so a whole\n * column of values that WERE in the table was counted \"not stored\". Each kind is read the way the\n * store holds it: a day by its calendar day (an instant by its moment), a number by its value\n * (0 is a number), a choice by the option it names (through the column's own options index), and\n * only anything else by its JSON.\n */\nexport function storedValueAgrees(\n field: Field | undefined,\n stored: unknown,\n written: unknown,\n options?: ChoiceOptions,\n): boolean {\n const empty = (v: unknown) => v === undefined || v === null || v === \"\";\n if (empty(stored) || empty(written)) return empty(stored) && empty(written);\n if (field !== undefined) {\n if (isDateField(field)) {\n if (hasTimePart(written)) {\n const a = new Date(stored as string).getTime();\n const b = new Date(written as string).getTime();\n if (!Number.isNaN(a) && !Number.isNaN(b)) return a === b;\n } else {\n // A day the store hands back as midnight UTC is still THAT day, in any viewer's zone.\n const dayOf = (v: unknown) => (typeof v === \"string\" && /^\\d{4}-\\d{2}-\\d{2}/.test(v.trim()) ? v.trim().slice(0, 10) : calendarDayOf(v));\n const a = dayOf(stored);\n const b = dayOf(written);\n if (a !== null && b !== null) return a === b;\n }\n }\n const kind = editorKindFor(field);\n if (kind === \"number\" || kind === \"currency\" || kind === \"percent\") {\n const a = typeof stored === \"number\" ? stored : Number(String(stored).trim());\n const b = typeof written === \"number\" ? written : Number(String(written).trim());\n if (Number.isFinite(a) && Number.isFinite(b)) return a === b;\n }\n if (options !== undefined && typeof stored === \"string\" && typeof written === \"string\") {\n const option = (v: string) => options.byWord.get(v.trim().toLowerCase()) ?? v.trim().toLowerCase();\n return option(stored) === option(written);\n }\n }\n return JSON.stringify(stored) === JSON.stringify(written);\n}\n\n/**\n * ONCE A HEADER LINE IS READ, NOTHING ON IT IS JUDGED OR REPORTED. The grid's per-cell check runs\n * before the header is known, so it refuses \"Qty\" for a number column and \"Ordered On\" for a date\n * column as if they were data. The header line lands on the anchor row, so every refusal on that\n * row was about a header cell; drop them. (A column-level refusal repeats on the data lines.)\n */\nexport function refusalsBeyondTheHeader<R extends { rowId: string | null }>(\n refusals: ReadonlyArray<R>,\n headerRowId: string | undefined,\n): R[] {\n return headerRowId === undefined ? [...refusals] : refusals.filter((r) => r.rowId !== headerRowId);\n}\n\n/**\n * The columns the grid turned away (they take no written value at all), said once each — but only\n * the ones THE BLOCK ACTUALLY WRITES. The grid judges a paste by position before a header line has\n * been read; once the header maps the block by name, a positional refusal for a column the block\n * no longer touches (a \"Qty holds a number\" for a Brand column that was left out) is about a cell\n * that is not being pasted, so it is dropped. `fromLine: 0` means \"no row\": a column-level answer.\n */\nexport function columnsTheGridTurnedAway(\n turnedAway: ReadonlyArray<{ columnId: string; reason: string }>,\n columnKeys: ReadonlyArray<string | null>,\n columnName: (columnId: string) => string,\n already: PastePreviewPlan[\"refusals\"],\n): PastePreviewPlan[\"refusals\"] {\n const said = new Map<string, string>();\n for (const refused of turnedAway) {\n if (!columnKeys.includes(refused.columnId)) continue;\n if (already.some((r) => r.column === columnName(refused.columnId))) continue;\n said.set(refused.columnId, refused.reason);\n }\n return [...said].map(([columnId, why]) => ({ fromLine: 0, column: columnName(columnId), raw: \"\", why }));\n}\n\n/**\n * WHAT THE SPREADSHEET PRIMITIVE'S PER-CELL CHECK MAY SAY about a pasted cell. That check holds no\n * options and no relation answers, so a choice cell or a relation cell judged there reads as\n * refused every time (\"Status is a list and its options have not been read yet\") while the write\n * stores it. Those two kinds are judged only by `planPastedBlock`, after the options and names are\n * in hand; every other kind is judged here.\n */\nexport function gridRefusalForPastedCell(field: Field, value: unknown): string | undefined {\n const kind = editorKindFor(field);\n if (kind === \"relation\" || kind === \"select\" || kind === \"multi_select\") return undefined;\n const judged = valueFromPastedText(field, value === null ? \"\" : String(value));\n return \"refusal\" in judged ? judged.refusal : undefined;\n}\n","// src/importKinds.ts — @ai-matrx/records-ui · VISION-REACH G14 (2026-10-02)\n//\n// WHAT A NEW COLUMN HOLDS, CHOSEN IN THE IMPORT PANEL, AND THE ROWS THAT REPEAT.\n//\n// THE BREAK (persona P02, an HOA treasurer, run 2): seven date columns of a dues file — Move-in,\n// Q1–Q4 paid, Submitted — were written \"2026-05-16\", \"Mar 31, 2026\", \"8.4.2026\" and \"5/2/2026\" in\n// one column. The store's plan read that mix as text, the panel offered no way to say \"these are\n// dates\", and the store's own cell reader takes only year-month-day and slashed dates — so every\n// one landed as Text and nothing could sort or count by date. The same file carried one homeowner's\n// row twice, and the import wrote it twice by default.\n//\n// Champions: Airtable's CSV import (a field type per column, unreadable cells left empty and\n// counted) and Google Sheets' import (one date reader for every common spelling; \"remove\n// duplicates\" offered as a one-click step). The ONE date reader is `readTypedDate` in\n// `@ai-matrx/records` — the same reader the grid, paste and forms use — so a date a person can type\n// into a cell is a date an import reads.\n\nimport { readTypedDate } from \"@ai-matrx/records\";\n\n/** The kinds a NEW column can be made as from the import panel. */\nexport type ImportKind = \"text\" | \"date\" | \"number\" | \"currency\" | \"checkbox\" | \"email\" | \"phone\" | \"url\";\n\nexport const IMPORT_KINDS: ReadonlyArray<{ kind: ImportKind; label: string }> = [\n { kind: \"text\", label: \"Text\" },\n { kind: \"date\", label: \"Date\" },\n { kind: \"number\", label: \"Number\" },\n { kind: \"currency\", label: \"Money\" },\n { kind: \"checkbox\", label: \"Checkbox\" },\n { kind: \"email\", label: \"Email\" },\n { kind: \"phone\", label: \"Phone\" },\n { kind: \"url\", label: \"Link\" },\n];\n\n/** The store's plan word for a column, as one of the kinds this panel offers (null: none fits). */\nexport function importKindOfPlan(type: string): ImportKind | null {\n if (type === \"text\" || type === \"long_text\") return \"text\";\n if (type === \"datetime\" || type === \"date\") return \"date\";\n if (type === \"number\" || type === \"range\" || type === \"integer\" || type === \"decimal\") return \"number\";\n if (type === \"currency\") return \"currency\";\n if (type === \"checkbox\" || type === \"boolean\") return \"checkbox\";\n if (type === \"email\" || type === \"phone\" || type === \"url\") return type;\n return null;\n}\n\n/** What `custom.field_declare` is handed for a column made as `kind`. */\nexport function declarationFor(kind: ImportKind): { type: \"text\" | \"datetime\" | \"number\" | \"currency\" | \"checkbox\" | \"email\" | \"phone\" | \"url\"; kind?: \"date\" } {\n if (kind === \"date\") return { type: \"datetime\", kind: \"date\" };\n return { type: kind };\n}\n\n/** One column's cells read as dates: the day each readable cell is, and every cell that is not. */\nexport interface ColumnDates {\n /** Row index (0-based) → the day (`YYYY-MM-DD`), or the instant when a time is kept. */\n read: Map<number, string>;\n /** Filled cells that are not a date, in file order. */\n unreadable: Array<{ row: number; raw: string }>;\n filled: number;\n}\n\nexport function datesOfColumn(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n opts: { withTime?: boolean; locale?: string } = {},\n): ColumnDates {\n const read = new Map<number, string>();\n const unreadable: Array<{ row: number; raw: string }> = [];\n let filled = 0;\n rows.forEach((r, i) => {\n const raw = String(r[header] ?? \"\").trim();\n if (raw === \"\") return;\n filled += 1;\n const got = readTypedDate(raw, { ...(opts.withTime ? { withTime: true } : {}), ...(opts.locale ? { locale: opts.locale } : {}) });\n if (got.ok) read.set(i, opts.withTime && got.instant ? got.instant : got.day);\n else unreadable.push({ row: i, raw });\n });\n return { read, unreadable, filled };\n}\n\n/**\n * Whether a column the store read as words is really dates: most of its filled cells read as one\n * (a few \"PAID\" notes in a paid-on column do not make it text). At least two cells must read.\n */\nexport function looksLikeDates(rows: ReadonlyArray<Record<string, string>>, header: string, locale?: string): boolean {\n const d = datesOfColumn(rows, header, locale ? { locale } : {});\n return d.read.size >= 2 && d.read.size / d.filled >= 0.6;\n}\n\n/**\n * Rows that repeat an EARLIER row exactly, over the columns that are sent (spacing at either end\n * ignored, nothing else). Answers the 0-based index of each repeat and the row it repeats.\n */\nexport function exactDuplicateRows(\n rows: ReadonlyArray<Record<string, string>>,\n headers: ReadonlyArray<string>,\n): Array<{ row: number; of: number }> {\n const seen = new Map<string, number>();\n const out: Array<{ row: number; of: number }> = [];\n rows.forEach((r, i) => {\n const cells = headers.map((h) => String(r[h] ?? \"\").trim());\n if (cells.every((c) => c === \"\")) return;\n const key = JSON.stringify(cells);\n const first = seen.get(key);\n if (first === undefined) seen.set(key, i);\n else out.push({ row: i, of: first });\n });\n return out;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\nconst PHONE = /^\\+?[\\d\\s().-]{7,20}$/;\nconst URLISH = /^(https?:\\/\\/|www\\.)\\S+$/i;\n\n/**\n * Whether a column the store read as words is really emails, phone numbers or web addresses: most of\n * its filled cells look like one (a few notes in the column do not make it text). Two cells at least.\n * A phone is 7-15 digits in the usual punctuation, so a plain count or a year is never one.\n */\nexport function looksLike(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n): \"email\" | \"phone\" | \"url\" | null {\n const cells = rows.map((r) => String(r[header] ?? \"\").trim()).filter((c) => c !== \"\");\n if (cells.length < 2) return null;\n const share = (test: (c: string) => boolean) => cells.filter(test).length / cells.length;\n if (share((c) => EMAIL.test(c)) >= 0.6) return \"email\";\n if (share((c) => URLISH.test(c)) >= 0.6) return \"url\";\n const isPhone = (c: string) => PHONE.test(c) && /[\\d]/.test(c) && c.replace(/\\D/g, \"\").length >= 7 && c.replace(/\\D/g, \"\").length <= 15 && /[()\\s.+-]/.test(c);\n if (share(isPhone) >= 0.6) return \"phone\";\n return null;\n}\n","// src/importCombine.ts — @ai-matrx/records-ui · VISION-REACH lane 5 (2026-10-03)\n//\n// ROWS THAT NAME THE SAME RECORD, COMBINED BEFORE THEY ARE WRITTEN.\n//\n// THE BREAK (persona P03, a PTA parent): families.csv had one row per STUDENT — a family with two\n// children is two rows with the same \"Family\" — and the import made one Families record per row, so\n// 33 families existed twice. Every pledge and volunteer row that then named one of them was refused\n// by the store as ambiguous (\"2 records called Cox family\"), 58 rows never landed, and the chat\n// answered from the rest. Google Sheets and Airtable never drop a row; and a person importing a\n// roster keyed by family name means ONE family per name.\n//\n// So the import panel counts how often the name column repeats, says so, and — when the repeating\n// rows look like the same record — combines them by default: one record per name, every other\n// column keeping every distinct value it held (\"Zoe; Max\"), joined the way the store's own list\n// cells split (`splitListCell`: `;`, `,` or `|`). Nothing is lost; the person can choose \"separate\n// records\" when each row really is its own thing (a pledge list named by family).\n\nimport { relationNameKey } from \"@ai-matrx/records\";\n\n/** How a name column repeats: distinct names against the rows that carry one. */\nexport interface TitleRepeats {\n distinct: number;\n filled: number;\n}\n\nexport function titleRepeats(rows: ReadonlyArray<Record<string, string>>, header: string): TitleRepeats {\n const seen = new Set<string>();\n let filled = 0;\n for (const r of rows) {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") continue;\n filled += 1;\n seen.add(key);\n }\n return { distinct: seen.size, filled };\n}\n\n/**\n * Whether rows sharing a name are plausibly ONE record rather than several events about it.\n *\n * The signal is an identity column: some OTHER column that never disagrees inside a group of\n * same-named rows and (mostly) differs between groups — a family's email or phone, a customer's\n * account number. A pledge list has none: amount, paid and date all vary within a family, and no\n * column pins the rows to one thing. Only groups of two or more rows are judged.\n */\nexport function sameRecordLikely(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n /**\n * Columns that can never be what pins a row to one record: an amount or a date describes the\n * thing, it does not identify it (a supply list's unit price is the same for every row of one\n * item, and nearly every item has its own price — that is not one record). */\n notIdentity?: ReadonlySet<string>,\n): boolean {\n const groups = new Map<string, Array<Record<string, string>>>();\n for (const r of rows) {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") continue;\n const held = groups.get(key);\n if (held) held.push(r);\n else groups.set(key, [r]);\n }\n const repeating = [...groups.values()].filter((g) => g.length > 1);\n if (repeating.length === 0) return false;\n const headers = new Set<string>();\n for (const r of rows) for (const h of Object.keys(r)) if (h !== header) headers.add(h);\n for (const h of headers) {\n if (notIdentity?.has(h)) continue;\n // Agrees inside every repeating group, with a value in each …\n let agrees = true;\n for (const g of repeating) {\n const values = new Set(g.map((r) => String(r[h] ?? \"\").trim()).filter((v) => v !== \"\"));\n if (values.size !== 1) {\n agrees = false;\n break;\n }\n }\n if (!agrees) continue;\n // … and tells the groups apart (an identity, not a constant like a school name).\n const perGroup = [...groups.values()].map((g) => String(g[0]?.[h] ?? \"\").trim()).filter((v) => v !== \"\");\n if (perGroup.length < 2) continue;\n if (new Set(perGroup.map((v) => v.toLowerCase())).size >= Math.ceil(perGroup.length * 0.9)) return true;\n }\n return false;\n}\n\n/** The combined rows, and for each the 1-based file lines it was made from. */\nexport interface CombinedRows {\n rows: Array<Record<string, string>>;\n lines: number[][];\n /** Columns that held more than one distinct value in some group — list cells now. */\n multiValued: Set<string>;\n}\n\nexport const LIST_JOIN = \"; \";\n\nexport function combineRows(rows: ReadonlyArray<Record<string, string>>, header: string): CombinedRows {\n const order: string[] = [];\n const groups = new Map<string, { rows: Array<Record<string, string>>; lines: number[] }>();\n const out: Array<Record<string, string>> = [];\n const outLines: number[][] = [];\n rows.forEach((r, i) => {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") {\n // A row with no name cannot be combined with anything; it goes as itself.\n out.push({ ...r });\n outLines.push([i + 1]);\n return;\n }\n const held = groups.get(key);\n if (held) {\n held.rows.push(r);\n held.lines.push(i + 1);\n } else {\n groups.set(key, { rows: [r], lines: [i + 1] });\n order.push(key);\n }\n });\n const multiValued = new Set<string>();\n for (const key of order) {\n const g = groups.get(key)!;\n const first = g.rows[0]!;\n const combined: Record<string, string> = {};\n for (const h of Object.keys(first)) {\n if (h === header) {\n combined[h] = String(first[h] ?? \"\").trim();\n continue;\n }\n const values: string[] = [];\n for (const r of g.rows) {\n const v = String(r[h] ?? \"\").trim();\n if (v !== \"\" && !values.some((x) => x.toLowerCase() === v.toLowerCase())) values.push(v);\n }\n if (values.length > 1) multiValued.add(h);\n combined[h] = values.join(LIST_JOIN);\n }\n out.push(combined);\n outLines.push(g.lines);\n }\n // Rows are kept in first-seen order of their name; nameless rows were pushed where they sat,\n // which is what a person scanning the file expects. Sort by the first source line.\n const index = out.map((row, i) => ({ row, lines: outLines[i]! }));\n index.sort((a, b) => a.lines[0]! - b.lines[0]!);\n return { rows: index.map((e) => e.row), lines: index.map((e) => e.lines), multiValued };\n}\n","// src/importRefusals.ts — @ai-matrx/records-ui · VISION-REACH lane 5 (2026-10-03)\n//\n// THE ROWS AN IMPORT REFUSED, GROUPED BY WHY, AND HANDED BACK AS A FILE.\n//\n// THE BREAK (persona P03): 43 of 220 pledge rows were refused and the only trace was a line in the\n// import rail — \"175 landed · 0 already here · 43 refused\" — and a list of 43 identical sentences\n// differing only in the family's name. The person closed the rail, the table looked complete, and\n// the chat said \"no missing or unmatched data\". Airtable's and Google Sheets' importers never drop a\n// row without a loud, persistent count and a way to get the rows back.\n//\n// These two helpers are shared by the import rail (right after the write) and by the notice the\n// table page keeps until it is dismissed: the same grouping, the same file.\n\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { toDelimited, type DelimitedCell } from \"@ai-matrx/kit/delimited\";\n\n/** One kind of refusal and how many rows it took. */\nexport interface ReasonGroup {\n /** The store's sentence with the quoted words and numbers folded, so 43 names read as one reason. */\n reason: string;\n count: number;\n /** The first sentence as the store wrote it, with its own name — for the person who wants one example. */\n example: string;\n}\n\n/** Fold the parts of a refusal that vary row to row: quoted words and bare numbers. */\nexport function reasonShape(reason: string): string {\n return reason\n .replace(/\"[^\"]*\"/g, \"\\\"…\\\"\")\n .replace(/“[^”]*”/g, \"“…”\")\n .replace(/\\b\\d+(?:[.,]\\d+)*\\b/g, \"N\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nexport function groupReasons(reasons: ReadonlyArray<string>): ReasonGroup[] {\n const groups = new Map<string, ReasonGroup>();\n for (const raw of reasons) {\n const reason = String(raw ?? \"\").trim();\n if (reason === \"\") continue;\n const shape = reasonShape(reason);\n const held = groups.get(shape);\n if (held) held.count += 1;\n else groups.set(shape, { reason: shape, count: 1, example: reason });\n }\n return [...groups.values()].sort((a, b) => b.count - a.count);\n}\n\n/** A refused row as the store's report hands it back (`custom.io_import_report`). */\nexport interface RefusedRow {\n /** The data row, 1-based (the file's line is this + 1). */\n row?: number | null;\n reason?: string | null;\n source?: Record<string, unknown> | null;\n}\n\n/** One source value as a cell for THE one writer: primitives as themselves, anything else as text. */\nfunction cell(value: unknown): DelimitedCell {\n if (value === null || value === undefined) return null;\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" ? value : String(value);\n}\n\n/**\n * The refused rows as a CSV a person opens in their spreadsheet: every column the file had, in the\n * order the first row carries them, then the line it sat on and the store's reason — so the file\n * can be fixed and imported again, or the rows kept as a record of what did not land.\n */\nexport function refusedRowsCsv(rows: ReadonlyArray<RefusedRow>, lineOf: (dataRow: number) => number = (n) => n + 1): string {\n const headers: string[] = [];\n for (const r of rows) for (const h of Object.keys(r.source ?? {})) if (!headers.includes(h)) headers.push(h);\n // THE one writer (kit `toDelimited`): spreadsheet-safe, a trailing line ending as before.\n return toDelimited(\n [\n [...headers, \"Line in your file\", \"Why it was not added\"],\n ...rows.map((r) => [\n ...headers.map((h) => cell((r.source ?? {})[h])),\n typeof r.row === \"number\" ? lineOf(r.row) : \"\",\n r.reason ?? \"\",\n ]),\n ],\n { trailingNewline: true },\n );\n}\n\n/** Hand the person a file, where a browser is present. Answers false where there is none. */\nexport function offerDownload(name: string, text: string, type = \"text/csv\"): boolean {\n if (typeof document === \"undefined\" || typeof URL === \"undefined\" || typeof URL.createObjectURL !== \"function\") return false;\n downloadFile(name, text, type);\n return true;\n}\n\n/** \"Lincoln pledges.csv\" → \"Lincoln pledges — rows not added.csv\". */\nexport function refusedFileName(sourceName: string | null | undefined): string {\n const base = (sourceName ?? \"import\").replace(/\\.(csv|xlsx)$/i, \"\");\n return `${base} — rows not added.csv`;\n}\n","\"use client\";\n\n// src/TablesHome.tsx — @ai-matrx/records-ui\n//\n// THE LIST OF A PERSON'S TABLES — AND IT IS NEVER A FLAT PILE.\n//\n// Four lanes, always, in this order: mine · my organization · system ·\n// community. The lane a Table is in is read off the Table record itself and is\n// not a guess:\n//\n// · mine — Shown to \"Only me\" (`shown_to = 'only_me'`)\n// · organization — the rest of the organization's own Tables\n// · system — `is_kernel` (REC-27: the Tables the platform ships)\n// · community — Published to the web (`published_to_web`), titled in the law's words\n//\n// ACCESS LADDER (custom data adoption, 2026-10-03): the words are the law's — \"Shown to\" and\n// \"Published to the web\". A store that does not answer `shown_to` / `published_to_web` yet is read\n// through its old lane word, `visibility`.\n//\n// A lane with nothing in it SAYS SO in one sentence that tells a person how it\n// fills up. An empty heading with nothing under it reads as \"broken\"; this\n// reads as \"nothing here yet, and here is what puts something here\".\n//\n// Creating and importing are both here, because both make a Table, and they go\n// through the store's own doors — `declareTable` walks Home → table_declare →\n// Fields, and the import mounts `ImportWizard` on the Table it just declared.\n\nimport { useEffect, useState } from \"react\";\nimport type { DashboardSummary, Table, Uuid } from \"@ai-matrx/records\";\nimport { useRecordsClient, useTables } from \"@ai-matrx/records/react\";\nimport { withTableFacts, type TableFact } from \"@ai-matrx/records/core\";\nimport { withTablePlacement, type TablePlacementFact } from \"@ai-matrx/records\";\nimport { Button, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { NewTableStart } from \"./NewTableStart\";\n\nimport { RefusalNotice } from \"./Refusal\";\nimport { BookingSlots } from \"./BookingSlots\";\nimport { realPlural, tableName } from \"./names\";\nimport { WhereItLives } from \"./WhereItLives\";\n\n// Which lane a table belongs to is pure, so `/helpers` carries it (records-ui front door, 2026-10-16).\nimport { PLATFORM_TABLE_PREFIX, laneFor, platformOwned, publishedToWeb, shownToOnlyMe, type TableLane } from \"./tableLanes\";\nexport { laneFor, platformOwned, type TableLane } from \"./tableLanes\";\n\n/** The five lanes, in the order a person reads them. Never a flat list. */\nexport const TABLE_LANES: readonly TableLane[] = [\"mine\", \"organization\", \"system\", \"community\", \"app\"];\n\nexport const LANE_TITLE: Record<TableLane, string> = {\n mine: \"Only me\",\n organization: \"Everyone\",\n system: \"System\",\n community: \"Published to the web\",\n app: \"Platform tables\",\n};\n\n/**\n * THE APP'S OWN BOOKKEEPING, MARKED AS SUCH.\n *\n * A saved view, a comment, a queued action and a form are records in Tables\n * this package declares in the organization's own store (`platformTable.ts`) —\n * which is what makes them shareable, historied and agent-writable. The price\n * is that using the product creates Tables in the person's own list: the\n * verdict of 19 September watched \"Saved views · 9 fields · records_ui_view\"\n * appear among somebody's data, and then \"Comments\" appear beside it the\n * moment a record was opened.\n *\n * They are not hidden — hiding a real Table from the person who owns it is its\n * own lie, and they hold that person's comments. They get their own lane,\n * last, with a sentence that says what they are.\n */\n\n/** What fills an empty lane. A heading with nothing under it must still teach. */\nexport const LANE_EMPTY: Record<TableLane, string> = {\n // 🚨 BOTH SENTENCES USED TO DESCRIBE A PRODUCT THAT DOES NOT EXIST\n // (VERIFIER-15 M2, VERIFIER-16 M6). \"New table makes one that only you can\n // see\" — New table makes one shared with the organization, and it lands under\n // My organization. \"A table you make is yours until you change its visibility\n // to internal\" — it is internal from the start, and no screen here changes a\n // table's visibility at all. An empty lane says what is true and names only a\n // control that exists.\n mine: \"No tables kept to only you.\",\n organization: \"No tables yet.\",\n system: \"No platform tables here.\",\n community: \"Nothing published to the web.\",\n app: \"No platform tables yet.\",\n};\n\n/** The store's sentence for who keeps a kept Table (`custom.table_facts`' `keeper_says`), when it said one. */\nfunction keeperSays(table: Table): string | null {\n const said = (table as unknown as { keeper_says?: unknown }).keeper_says;\n return typeof said === \"string\" && said.trim() ? said : null;\n}\n\n/** The sentence when the store's table facts are not there, so no section can be decided. */\nexport const SECTIONS_UNKNOWN =\n \"Who can see each table, and which you made, could not be read, so every table \" +\n \"is listed under Everyone and Only me is empty. That is not their real sharing.\";\n\n/**\n * THE FOUR VISIBILITY LANES — who can see a thing: me, my organization, the\n * signed-in community, the whole world. (Arman, 2026-09-15: mine · my\n * organization · community · world; `common-docs/systems/platform/access/DECISIONS.md`.)\n *\n * They are NOT the sections of the table list above (`TABLE_LANES`), which also\n * separate the platform's own tables and the app's bookkeeping — those are about\n * WHO MADE a table, and a person filtering \"what is visible to whom\" is asking a\n * different question. A table the store keeps for itself, or a kernel table, has\n * no visibility a person chose, so `visibilityLaneFor` answers `null` and a\n * filter over these four leaves it out rather than inventing a lane for it.\n *\n * From the record's own `visibility`, the store's closed four:\n * Only me → Only me · the default → Everyone · Everyone on AI Matrx → Everyone on AI Matrx ·\n * Published to the web → Published to the web (an older store: its `visibility` word).\n *\n * 🚨 WHY `link` IS WORLD (chair ruling, 2026-09-23). A link anyone can open\n * WITHOUT signing in is reachable by the world; being unlisted does not make it\n * narrower. Community is the lane for things any SIGNED-IN account can reach,\n * and the store has no signed-in-only link yet — so today nothing is in\n * Community, and a signed-in-only link lands there the day it exists. The chip\n * stays, because a lane that is empty today is still a lane a person chooses.\n */\nexport type VisibilityLane = \"mine\" | \"organization\" | \"community\" | \"world\";\n\nexport const VISIBILITY_LANES: readonly VisibilityLane[] = [\"mine\", \"organization\", \"community\", \"world\"];\n\n/**\n * THE LAW'S WORDS (access ladder Words table), and no other lane names: \"Shown to\" Only me /\n * Everyone / Everyone on AI Matrx, and \"Published to the web\" for anyone on the internet.\n * \"Everyone on AI Matrx\" is offered only on a Public table; a store Table is Organization, so\n * nothing lands there today.\n */\nexport const VISIBILITY_LANE_TITLE: Record<VisibilityLane, string> = {\n mine: \"Only me\",\n organization: \"Everyone\",\n community: \"Everyone on AI Matrx\",\n world: \"Published to the web\",\n};\n\n/** Which visibility lane one Table is in, or `null` when no person chose one for it. */\nexport function visibilityLaneFor(table: Table): VisibilityLane | null {\n if (table.is_kernel) return null;\n if ((table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX) || platformOwned(table)) return null;\n // Anyone on the internet — Published to the web.\n if (publishedToWeb(table)) return \"world\";\n if (table.shown_to === \"everyone_on_ai_matrx\") return \"community\";\n if (shownToOnlyMe(table)) return \"mine\";\n return \"organization\";\n}\n\nexport interface TablesHomeProps {\n /** Where a table opens. Absent and the card is a plain row with no pretend link. */\n /**\n * Opening a Table, and — with a second argument — opening it ON one of its\n * dashboards. The second argument is optional so every existing caller is\n * unchanged; a host that ignores it lands on the records, which is what it\n * did before, rather than on a screen it does not know how to address.\n */\n onOpenTable?: ((tableId: Uuid, dashboardId?: Uuid) => void) | undefined;\n /**\n * THE ORGANIZATION EVERY ROW HERE LIVES IN, BY NAME (lane SC-1-TAILS; access-is-personal: a\n * list filtered by one organization says which). Each row carries a quiet \"Lives in <name>\"\n * chip that, pressed, asks the store where that table lives and — for its owner — where else\n * it can go. Absent: the list asks the store once, for its first table. When the store cannot\n * name it, the chips are absent rather than a row of \"unknown\".\n */\n organizationName?: string | null | undefined;\n /**\n * ONLY THE WAYS TO MAKE A TABLE — New table, Start from a template, and the import that\n * follows — and none of the lists (lane UI-FIX-18, VERIFIER-18 M3). A host page that already\n * lists the organization's tables, dashboards and booking pages (matrx-frontend's\n * organization hub) passes this, so one page never draws two full lists of the same tables.\n * Default false: the package's own home, lists and all.\n */\n makingOnly?: boolean | undefined;\n /**\n * THE HOST'S OWN BUTTONS ASK (merged-grid review 2, J6: \"New table\" sat ~1,700 px down /data,\n * then as a row of its own). A host whose page header already has an action bar puts \"New table\"\n * THERE and passes how many times it was pressed; this list then draws no button row of its own,\n * and opens the name box when asked. Absent: the list draws its own buttons, as before.\n */\n askedBy?: { create: number } | undefined;\n /**\n * WHERE \"START FROM A TEMPLATE\" LEADS (lane TEMPLATES, RETIRE-1): the host's published-template\n * gallery (matrx-frontend: /make's gallery, read through custom.templates and installed through\n * custom.template_install). The package's own example list was retired onto that one family.\n * Absent: no such button — never one that goes nowhere.\n */\n templatesHref?: string | undefined;\n /** Where a person describes a table in a sentence (matrx-frontend: /make). Absent: no such choice. */\n describeHref?: string | undefined;\n /** Where an outside database is connected as a table. Absent: no such choice. */\n connectHref?: string | undefined;\n /** The host closes its frame (the New table dialog). Absent: Cancel just closes the making screen. */\n onCancel?: (() => void) | undefined;\n className?: string | undefined;\n}\n\nexport function TablesHome({ onOpenTable, organizationName, makingOnly = false, askedBy, templatesHref, describeHref, connectHref, onCancel, className }: TablesHomeProps) {\n const client = useRecordsClient();\n const tables = useTables();\n\n const me = client.config.actor.user_id ?? null;\n /**\n * WHO CAN SEE EACH TABLE, AND WHICH ONES I MADE — `client.tableFacts()`, asked\n * HERE because this is a screen that sorts tables into sections, and folded onto\n * the list with `withTableFacts`. It is not part of `tableList()` (records 0.57.3):\n * a screen that only lists tables never pays for it. `null` = the store's\n * catalog has no such door (nothing asked, nothing said); `failed` = the store\n * HAS it and it did not answer, and then the page says so.\n */\n const [facts, setFacts] = useState<\n { phase: \"reading\" } | { phase: \"read\"; rows: TableFact[] | null } | { phase: \"failed\" }\n >({ phase: \"reading\" });\n useEffect(() => {\n let alive = true;\n void client.tableFacts().then((answered) => {\n if (!alive) return;\n setFacts(answered.ok ? { phase: \"read\", rows: answered.data } : { phase: \"failed\" });\n });\n return () => {\n alive = false;\n };\n }, [client]);\n // The placement facts ride on the same door (SC-1: `platform_owned`, `keeper_says`, …); a store\n // whose door answers only the three older columns leaves every Table as it was.\n const listed =\n facts.phase === \"read\"\n ? withTablePlacement(\n withTableFacts(tables.data ?? [], facts.rows, me),\n facts.rows as unknown as TablePlacementFact[] | null,\n )\n : (tables.data ?? []);\n /**\n * \"SHOW EVERYTHING\" (SCOPES-CONTEXT-TRANSITION SC-1', finished by SC-1-TAILS). What the app keeps\n * for itself — a column's choices, the context system's scope tables, its own bookkeeping — is\n * marked and never hidden from its owner, but it is not the organization's own data, so it sits\n * behind one control that says how many there are. The owner (2026-09-23): \"There should be\n * options for someone to see all, but not at random.\"\n */\n const [showEverything, setShowEverything] = useState(false);\n const keptCount = listed.filter((t) => laneFor(t) === \"app\").length;\n /** Where every row lives, by name: the host's, or the store's answer for the first table. */\n const [askedName, setAskedName] = useState<string | null>(null);\n const firstTableId = listed[0]?.id ?? null;\n useEffect(() => {\n if (organizationName || !firstTableId) return;\n let alive = true;\n void client.tableHome({ table_id: firstTableId }).then((answered) => {\n if (alive && answered.ok && answered.data) setAskedName(answered.data.organization.name);\n });\n return () => {\n alive = false;\n };\n }, [client, organizationName, firstTableId]);\n const livesIn = organizationName || askedName;\n /** A Table the person signed in made. `created_by` comes from `custom.table_facts`. */\n const isMine = (t: Table): boolean =>\n Boolean(me) && laneFor(t) !== \"system\" && laneFor(t) !== \"app\" && t.created_by === me;\n /**\n * WHETHER THE SECTIONS CAN BE DECIDED AT ALL. Only a door the store HAS can fail\n * to answer: without it this page behaves exactly as it did before, and says\n * nothing about a read nobody made (the door-presence pattern).\n */\n const sectionsKnown = facts.phase !== \"failed\";\n // Opened by the host's own button (a dialog): open from the FIRST paint, so the frame never\n // draws empty and then fills (zero layout shift on open).\n const [creating, setCreating] = useState(() => (askedBy?.create ?? 0) > 0);\n // The host's header pressed \"New table\" (a count, so every press opens).\n const createAsked = askedBy?.create ?? 0;\n useEffect(() => {\n if (createAsked > 0) setCreating(true);\n }, [createAsked]);\n const hostButtons = askedBy !== undefined;\n // SCR-16. THE ORGANIZATION'S DASHBOARDS, ON THE RECORDS HOME.\n //\n // A dashboard is about ONE Table, so it lives on that Table's page — but a\n // person who wants to know how the work is going does not start by\n // remembering which Table the answer is in. `custom.dashboards` with no\n // table id answers the whole organization, narrowed to the Tables this\n // person can already open, so this list can never reveal a Table.\n const [boards, setBoards] = useState<DashboardSummary[] | null>(null);\n useEffect(() => {\n // A page that draws only the ways to make a table lists no dashboards, so it asks for none.\n if (makingOnly) return;\n let cancelled = false;\n void client.dashboards({}).then((result) => {\n if (cancelled) return;\n // A REFUSAL HERE IS NOT THE PAGE'S REFUSAL. The Tables are what this\n // screen is for; a store with no dashboards door yet simply has no\n // section, and the Tables below are untouched.\n setBoards(result.ok ? result.data : []);\n });\n return () => {\n cancelled = true;\n };\n }, [client, makingOnly]);\n\n return (\n <div className={cn(\"flex min-h-0 flex-col gap-4\", className)}>\n {creating ? (\n <div className={cn(\"min-h-0\", hostButtons ? \"flex-1\" : \"h-[36rem] max-w-2xl rounded-lg border\")}>\n <NewTableStart\n templatesHref={templatesHref}\n describeHref={describeHref}\n connectHref={connectHref}\n existingTables={listed.filter((t) => laneFor(t) !== \"system\" && laneFor(t) !== \"app\")}\n onOpenTable={(id) => onOpenTable?.(id)}\n onMade={() => tables.reload()}\n onCancel={() => {\n setCreating(false);\n onCancel?.();\n }}\n />\n </div>\n ) : hostButtons ? null : (\n <div className=\"flex items-center gap-2\" data-tables-home-making=\"\">\n <Button size=\"sm\" onClick={() => setCreating(true)}>\n New table\n </Button>\n {templatesHref ? (\n <Button asChild size=\"sm\" variant=\"ghost\">\n <a href={templatesHref} data-tables-home-templates=\"\">\n Start from a template\n </a>\n </Button>\n ) : null}\n </div>\n )}\n\n {tables.error ? <RefusalNotice error={tables.error} /> : null}\n {!makingOnly && tables.loading && !tables.data ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-6 w-40\" />\n <Skeleton className=\"h-16 w-full\" />\n </div>\n ) : null}\n\n {/* PRODUCTS row 14, the owner's side. A booking page is the ONE thing on\n this store whose whole point is a link somebody else opens, so the\n organization's pages — with what is coming up, what is being held right\n now, and the link — belong on the home rather than only inside whichever\n table the appointments happen to land in. The picker a visitor uses is\n the public route's; nothing here computes an offer. Absent when this\n organization has no booking pages. */}\n {makingOnly ? null : <BookingSlots />}\n\n {!makingOnly && boards && boards.length > 0 ? (\n <section className=\"space-y-1.5\">\n <div className=\"flex items-baseline gap-2\">\n <h2 className=\"text-sm font-medium\">Dashboards</h2>\n <span className=\"text-xs opacity-60\">{boards.length}</span>\n </div>\n <ul className=\"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3\">\n {boards.map((board) => (\n <li key={board.dashboard_id}>\n <button\n type=\"button\"\n disabled={!board.table_id}\n onClick={() =>\n board.table_id ? onOpenTable?.(board.table_id, board.dashboard_id) : undefined\n }\n className={cn(\n \"w-full rounded-md border px-3 py-2 text-left transition-colors\",\n onOpenTable && board.table_id ? \"hover:bg-accent\" : \"cursor-default\",\n )}\n >\n <span className=\"block truncate text-sm\">{board.name}</span>\n <span className=\"block truncate text-xs opacity-60\">\n {board.block_count} block{board.block_count === 1 ? \"\" : \"s\"}\n {\" · \"}\n {(() => {\n const owner = tables.data?.find((t) => t.id === board.table_id);\n return owner ? tableName(owner) : \"its table\";\n })()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </section>\n ) : null}\n\n {!makingOnly && tables.data && !sectionsKnown ? (\n <p className=\"text-xs text-muted-foreground\">{SECTIONS_UNKNOWN}</p>\n ) : null}\n\n {!makingOnly && tables.data && keptCount > 0 ? (\n <div data-tables-show-everything={showEverything ? \"on\" : \"off\"} className=\"flex items-center text-xs\">\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-2 text-xs\"\n aria-pressed={showEverything}\n onClick={() => setShowEverything((on) => !on)}\n >\n {showEverything ? \"✓ \" : \"\"}Include system tables ({keptCount})\n </Button>\n </div>\n ) : null}\n\n {!makingOnly && tables.data\n ? TABLE_LANES.filter((lane) => lane !== \"app\" || showEverything).map((lane) => {\n // MINE IS WHAT I MADE (chair ruling, 2026-09-23), whatever its\n // visibility — so a new internal table is under Mine AND under My\n // organization. Every other section is still one visibility.\n const rows = listed.filter((t) =>\n lane === \"mine\" ? laneFor(t) === \"mine\" || isMine(t) : laneFor(t) === lane,\n );\n return (\n <section key={lane} className=\"space-y-1.5\">\n <div className=\"flex items-baseline gap-2\">\n <h2 className=\"text-sm font-medium\">{LANE_TITLE[lane]}</h2>\n <span className=\"text-xs opacity-60\">{rows.length}</span>\n </div>\n {rows.length === 0 ? (\n <p className=\"text-xs opacity-70\">{LANE_EMPTY[lane]}</p>\n ) : (\n <ul className=\"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3\">\n {rows.map((table) => (\n <li key={table.id} className=\"flex flex-col rounded-md border\">\n <button\n type=\"button\"\n onClick={() => onOpenTable?.(table.id)}\n className={cn(\n \"w-full rounded-md px-3 py-2 text-left transition-colors\",\n onOpenTable ? \"hover:bg-accent\" : \"cursor-default\",\n )}\n >\n {/* The Table's NAME, never its token: `records_ui_view`\n and `v78_widget2` are machine names and no product\n a person judges puts one on a card. */}\n <span className=\"block truncate text-sm\">{tableName(table)}</span>\n <span className=\"block truncate text-xs opacity-60\">\n {table.fields.length} field{table.fields.length === 1 ? \"\" : \"s\"}\n {realPlural(table) && realPlural(table) !== table.name\n ? ` · ${realPlural(table)}`\n : \"\"}\n </span>\n {/* WHO KEEPS IT, in the store's own sentence — a kept table is marked, never a mystery. */}\n {lane === \"app\" && keeperSays(table) ? (\n <span className=\"mt-0.5 block text-xs text-muted-foreground\">{keeperSays(table)}</span>\n ) : null}\n </button>\n {livesIn ? (\n <div className=\"px-2 pb-1.5\">\n <WhereItLives\n variant=\"row\"\n tableId={table.id}\n knownOrganizationName={livesIn}\n onMoved={() => tables.reload()}\n />\n </div>\n ) : null}\n </li>\n ))}\n </ul>\n )}\n </section>\n );\n })\n : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/NewTableStart.tsx — @ai-matrx/records-ui\n//\n// THE NEW TABLE SCREEN: every way to make a table, each one a clear choice (Arman, 2026-10-10:\n// \"quality, standards, elegant AND DO NOT LOSE MY FEATURES\").\n//\n// · Blank — a name, and optionally every column at once (typed chips, changeable).\n// · Import a file — CSV, TSV or Excel, picked or DROPPED ANYWHERE on this screen, or pasted.\n// It never asks for a name first: the name comes from the file and stays editable. The\n// separator and \"First row is column names\" are guessed and changeable, the rows are shown\n// back, and the rows can go into a NEW table or one that already exists. Then `ImportWizard`\n// takes them as its `source` — column kinds, mapping onto existing columns, the write and the\n// report are the one importer's, never a second pipeline.\n// · Start from a template · Describe it · Connect a database — the host's doors, when it has them.\n//\n// Layout: a scrolling body and a pinned footer holding the one primary action, enabled the moment\n// it is valid. The host gives this a fixed height (a dialog, a sheet), so moving between steps\n// never resizes the frame.\n\nimport { useCallback, useMemo, useRef, useState, type DragEvent, type ReactNode } from \"react\";\nimport type { Table, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsError } from \"@ai-matrx/records\";\nimport { tableShapeChanged, useRecordsClient } from \"@ai-matrx/records/react\";\nimport {\n BasicInput,\n Button,\n Label,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n Switch,\n Textarea,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { Tile } from \"@ai-matrx/design-system/controls\";\nimport { NEW_COLUMN_TYPES, columnsFrom, fieldsForNewColumns, type NewColumn, type NewColumnType } from \"./newTableColumns\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { refusalFromThrown } from \"./refusals\";\nimport { ImportWizard, type ImportSource } from \"./ImportWizard\";\nimport { declareTable, tokenFor } from \"./createTable\";\nimport { tableName } from \"./names\";\nimport {\n IMPORT_ACCEPT,\n IMPORT_SEPARATORS,\n firstRowLooksLikeHeader,\n gridFromFile,\n gridFromText,\n importFromGrid,\n importText,\n separatorWords,\n tableNameFromFile,\n type ImportSeparator,\n type ReadGrid,\n} from \"./importFileRead\";\n\nexport interface NewTableStartProps {\n /** The host's template gallery. Absent: no template choice. */\n templatesHref?: string | undefined;\n /** Where a person describes the table in a sentence (the host's /make). Absent: no such choice. */\n describeHref?: string | undefined;\n /** Where an outside database is connected. Absent: no such choice. */\n connectHref?: string | undefined;\n /** Tables an import can go into instead of a new one. */\n existingTables?: readonly Table[] | undefined;\n onOpenTable?: ((tableId: Uuid) => void) | undefined;\n /** A table was made (refresh any list behind this screen). */\n onMade?: (() => void) | undefined;\n onCancel: () => void;\n className?: string | undefined;\n}\n\ntype Step =\n | { at: \"choose\" }\n | { at: \"import\" }\n | { at: \"wizard\"; tableId: Uuid; source: ImportSource; made: boolean };\n\nconst NEW_TABLE = \"__new__\";\nconst PREVIEW_ROWS = 6;\n\n/**\n * THE TITLE COLUMN OF AN IMPORTED TABLE keeps the first pasted header's name (CD-IO-03 walk 2026-10-21: \"Zeta\" became\n * \"Title\", so the person's own column name was lost). The first column fills the title, so it is born with that name.\n */\nexport function importTitleField(headers: readonly string[]) {\n const label = headers[0]?.trim() || \"Title\";\n return { key: \"title\", label, type: \"text\" as const, sort: 10, required: false };\n}\n\nexport function NewTableStart({\n templatesHref,\n describeHref,\n connectHref,\n existingTables,\n onOpenTable,\n onMade,\n onCancel,\n className,\n}: NewTableStartProps) {\n const client = useRecordsClient();\n const [step, setStep] = useState<Step>({ at: \"choose\" });\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<RecordsError | null>(null);\n\n // Blank\n const [name, setName] = useState(\"\");\n const nameTyped = useRef(\"\");\n nameTyped.current = name;\n const [columnWords, setColumnWords] = useState(\"\");\n const [columns, setColumns] = useState<NewColumn[]>([]);\n\n // Import\n const [fileName, setFileName] = useState<string | null>(null);\n const [file, setFile] = useState<File | null>(null);\n const [pasted, setPasted] = useState<string | null>(null);\n const [read, setRead] = useState<ReadGrid | null>(null);\n const [separator, setSeparator] = useState<ImportSeparator>(\"auto\");\n const [headerRow, setHeaderRow] = useState(true);\n const [importName, setImportName] = useState(\"\");\n const [target, setTarget] = useState<string>(NEW_TABLE);\n const [dragging, setDragging] = useState(false);\n const fileInput = useRef<HTMLInputElement | null>(null);\n\n const parsed = useMemo(() => (read ? importFromGrid(read.grid, headerRow) : null), [read, headerRow]);\n const intoTables = useMemo(\n () => (existingTables ?? []).filter((t) => !t.is_kernel).slice().sort((a, b) => tableName(a).localeCompare(tableName(b))),\n [existingTables],\n );\n\n const readFile = useCallback(async (picked: File, sep: ImportSeparator) => {\n setError(null);\n try {\n const grid = await gridFromFile(picked, sep);\n setRead(grid);\n return grid;\n } catch (thrown) {\n setRead(null);\n setError(refusalFromThrown(thrown, \"That file could not be read.\", \"Save it again as CSV or Excel and pick it again.\", \"invalid_argument\"));\n return null;\n }\n }, []);\n\n const takeFile = useCallback(\n async (picked: File | null | undefined) => {\n if (!picked) return;\n setFile(picked);\n setPasted(null);\n setFileName(picked.name);\n setSeparator(\"auto\");\n setImportName((was) => was || nameTyped.current.trim() || tableNameFromFile(picked.name));\n setStep({ at: \"import\" });\n const grid = await readFile(picked, \"auto\");\n if (grid) setHeaderRow(firstRowLooksLikeHeader(grid.grid));\n },\n [readFile],\n );\n\n const takePaste = useCallback((text: string, sep: ImportSeparator) => {\n setPasted(text);\n if (!text.trim()) {\n setRead(null);\n return;\n }\n const grid = gridFromText(text, sep);\n setRead(grid);\n setHeaderRow(firstRowLooksLikeHeader(grid.grid));\n }, []);\n\n const changeSeparator = useCallback(\n (sep: ImportSeparator) => {\n setSeparator(sep);\n if (file) void readFile(file, sep);\n else if (pasted !== null) takePaste(pasted, sep);\n },\n [file, pasted, readFile, takePaste],\n );\n\n const onDrop = useCallback(\n (e: DragEvent<HTMLDivElement>) => {\n if (!e.dataTransfer?.types?.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(false);\n if (step.at === \"wizard\") return;\n void takeFile(e.dataTransfer.files?.[0]);\n },\n [step.at, takeFile],\n );\n\n const createBlank = useCallback(async () => {\n const trimmed = name.trim();\n if (!trimmed || busy) return;\n setBusy(true);\n setError(null);\n const result = await declareTable(client, {\n name: trimmed,\n slug: tokenFor(trimmed),\n ...(columns.length > 0 ? { fields: fieldsForNewColumns(columns) } : {}),\n });\n setBusy(false);\n if (!result.ok) {\n setError(result.error);\n return;\n }\n onMade?.();\n onOpenTable?.(result.data);\n }, [busy, client, columns, name, onMade, onOpenTable]);\n\n const importReady = Boolean(parsed && parsed.rows.length > 0 && parsed.headers.length > 0 && (target !== NEW_TABLE || importName.trim()));\n\n const continueImport = useCallback(async () => {\n if (!parsed || !importReady || busy) return;\n const source: ImportSource = { name: fileName ?? \"Pasted rows\", parsed, text: importText(parsed) };\n if (target !== NEW_TABLE) {\n setStep({ at: \"wizard\", tableId: target as Uuid, source, made: false });\n return;\n }\n const trimmed = importName.trim();\n setBusy(true);\n setError(null);\n const result = await declareTable(client, { name: trimmed, slug: tokenFor(trimmed), fields: [importTitleField(parsed.headers)] });\n setBusy(false);\n if (!result.ok) {\n setError(result.error);\n return;\n }\n onMade?.();\n setStep({ at: \"wizard\", tableId: result.data, source, made: true });\n }, [busy, client, fileName, importName, importReady, onMade, parsed, target]);\n\n /** The import made this table's columns after the table was first read: open it on what it holds now. */\n const openImported = (tableId: Uuid) => {\n tableShapeChanged(tableId);\n onOpenTable?.(tableId);\n };\n\n const back = () => {\n setError(null);\n setStep({ at: \"choose\" });\n };\n\n let body: ReactNode;\n let footer: ReactNode;\n if (step.at === \"choose\") {\n body = (\n <div className=\"flex flex-col gap-5\" data-tables-home-making=\"\">\n <section className=\"flex flex-col gap-2\" aria-label=\"Blank table\">\n <Label htmlFor=\"new-table-name\" className=\"text-xs font-medium text-muted-foreground\">\n Name\n </Label>\n <BasicInput\n id=\"new-table-name\"\n autoFocus\n value={name}\n placeholder=\"Table name\"\n onChange={(e) => setName(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") void createBlank();\n }}\n className=\"h-9 text-base sm:text-sm\"\n />\n <NewTableColumns\n words={columnWords}\n columns={columns}\n onWords={(text) => {\n setColumnWords(text);\n setColumns((was) =>\n columnsFrom(text).map((c) => was.find((w) => w.label.toLowerCase() === c.label.toLowerCase()) ?? c),\n );\n }}\n onType={(index, type) =>\n setColumns((was) =>\n was.map((c, i) =>\n i === index ? { label: c.label, type, ...(type === \"select\" || type === \"multi_select\" ? { options: c.options ?? [] } : {}) } : c,\n ),\n )\n }\n onCreate={() => void createBlank()}\n />\n </section>\n\n <div className=\"flex items-center gap-3 text-xs text-muted-foreground\" aria-hidden>\n <span className=\"h-px flex-1 bg-border\" />\n or\n <span className=\"h-px flex-1 bg-border\" />\n </div>\n\n <Tile\n data-new-table-import=\"\"\n onClick={() => fileInput.current?.click()}\n icon={<Icon d={ICON.upload} />}\n title=\"Import a file\"\n line=\"CSV, Excel or TSV · drop it here\"\n {...(dragging ? { selected: true } : {})}\n />\n <input\n ref={fileInput}\n type=\"file\"\n accept={IMPORT_ACCEPT}\n aria-label=\"Choose a file to import\"\n tabIndex={-1}\n className=\"sr-only\"\n onChange={(e) => {\n void takeFile(e.target.files?.[0]);\n e.target.value = \"\";\n }}\n />\n\n <div className=\"grid grid-cols-1 gap-2 sm:grid-cols-2\">\n <ChoiceCard\n icon={ICON.paste}\n title=\"Paste rows\"\n words=\"From a spreadsheet\"\n onClick={() => {\n setFile(null);\n setFileName(null);\n setRead(null);\n setPasted(\"\");\n setSeparator(\"auto\");\n // A name already typed on the first step is the table's name here too, never lost on the way.\n setImportName((was) => was || name.trim());\n setStep({ at: \"import\" });\n }}\n />\n {templatesHref ? (\n <ChoiceCard icon={ICON.template} title=\"Start from a template\" words=\"Ready-made tables\" href={templatesHref} data-tables-home-templates=\"\" />\n ) : null}\n {describeHref ? <ChoiceCard icon={ICON.spark} title=\"Describe it\" words=\"Say what it tracks\" href={describeHref} /> : null}\n {connectHref ? <ChoiceCard icon={ICON.database} title=\"Connect a database\" words=\"Sync a Postgres table\" href={connectHref} /> : null}\n </div>\n </div>\n );\n footer = (\n <>\n <Button variant=\"ghost\" onClick={onCancel}>\n Cancel\n </Button>\n <Button disabled={busy || name.trim().length === 0} onClick={() => void createBlank()} data-new-table-create=\"\">\n {busy ? \"Creating…\" : \"Create table\"}\n </Button>\n </>\n );\n } else if (step.at === \"import\") {\n const pasteMode = pasted !== null;\n body = (\n <div className=\"flex flex-col gap-4\" data-new-table-import-step=\"\">\n {pasteMode ? (\n <Textarea\n autoFocus\n value={pasted}\n rows={5}\n placeholder=\"Paste rows copied from a spreadsheet\"\n aria-label=\"Pasted rows\"\n onChange={(e) => takePaste(e.target.value, separator)}\n className=\"font-mono text-xs\"\n />\n ) : (\n <div className=\"flex min-w-0 items-center gap-3 rounded-lg border px-3 py-2.5\">\n <span className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary\">\n <Icon d={ICON.file} />\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-sm font-medium\" data-new-table-file=\"\">\n {fileName}\n </span>\n <span className=\"block text-xs text-muted-foreground\" data-new-table-counts=\"\">\n {parsed ? `${parsed.rows.length} ${parsed.rows.length === 1 ? \"row\" : \"rows\"} · ${parsed.headers.length} columns` : \"Reading…\"}\n </span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => fileInput.current?.click()}>\n Change\n </Button>\n <input\n ref={fileInput}\n type=\"file\"\n accept={IMPORT_ACCEPT}\n aria-label=\"Choose a file to import\"\n tabIndex={-1}\n className=\"sr-only\"\n onChange={(e) => {\n void takeFile(e.target.files?.[0]);\n e.target.value = \"\";\n }}\n />\n </div>\n )}\n\n <div className=\"grid grid-cols-1 gap-3 sm:grid-cols-2\">\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium text-muted-foreground\">Add to</Label>\n <Select value={target} onValueChange={setTarget}>\n <SelectTrigger aria-label=\"Add to\" className=\"h-9\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NEW_TABLE}>A new table</SelectItem>\n {intoTables.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {tableName(t)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n {target === NEW_TABLE ? (\n <div className=\"flex flex-col gap-1.5\">\n <Label htmlFor=\"new-table-import-name\" className=\"text-xs font-medium text-muted-foreground\">\n Table name\n </Label>\n <BasicInput\n id=\"new-table-import-name\"\n value={importName}\n placeholder=\"Table name\"\n onChange={(e) => setImportName(e.target.value)}\n className=\"h-9 text-base sm:text-sm\"\n />\n </div>\n ) : null}\n </div>\n\n <div className=\"flex flex-wrap items-center gap-x-5 gap-y-2\">\n <label className=\"flex items-center gap-2 text-sm\">\n <Switch checked={headerRow} onCheckedChange={setHeaderRow} aria-label=\"First row is column names\" size=\"sm\" />\n First row is column names\n </label>\n {read && read.format === \"csv\" ? (\n <div className=\"flex items-center gap-2 text-sm\">\n <span className=\"text-muted-foreground\">Separator</span>\n <Select value={separator} onValueChange={(v) => changeSeparator(v as ImportSeparator)}>\n <SelectTrigger size=\"sm\" aria-label=\"Separator\" className=\"h-8 w-[9.5rem]\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {IMPORT_SEPARATORS.map((s) => (\n <SelectItem key={s.value} value={s.value}>\n {s.value === \"auto\" ? `Detect (${separatorWords(read.separator)})` : s.words}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ) : null}\n </div>\n\n {parsed && parsed.headers.length > 0 ? (\n <div className=\"min-w-0 overflow-x-auto rounded-lg border\" data-new-table-preview=\"\">\n <table className=\"w-full border-collapse text-xs\">\n <thead className=\"bg-muted/50\">\n <tr>\n {parsed.headers.map((h) => (\n <th key={h} className=\"whitespace-nowrap border-b px-2.5 py-1.5 text-left font-medium\">\n {h}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {parsed.rows.slice(0, PREVIEW_ROWS).map((row, i) => (\n <tr key={i} className=\"border-b last:border-b-0\">\n {parsed.headers.map((h) => (\n <td key={h} className=\"max-w-[14rem] truncate whitespace-nowrap px-2.5 py-1.5 text-muted-foreground\">\n {row[h] || \" \"}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n {parsed.rows.length > PREVIEW_ROWS ? (\n <p className=\"border-t px-2.5 py-1.5 text-xs text-muted-foreground\">\n +{parsed.rows.length - PREVIEW_ROWS} more {parsed.rows.length - PREVIEW_ROWS === 1 ? \"row\" : \"rows\"}\n </p>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n footer = (\n <>\n <Button variant=\"ghost\" className=\"mr-auto\" onClick={back}>\n Back\n </Button>\n <Button variant=\"ghost\" onClick={onCancel}>\n Cancel\n </Button>\n <Button disabled={!importReady || busy} onClick={() => void continueImport()} data-new-table-continue=\"\">\n {busy ? \"Creating…\" : \"Next: columns\"}\n </Button>\n </>\n );\n } else {\n body = (\n <div data-new-table-wizard=\"\">\n <ImportWizard tableId={step.tableId} source={step.source} autoRun={step.made} onWrote={() => tableShapeChanged(step.tableId)} onDone={() => openImported(step.tableId)} />\n </div>\n );\n footer = (\n <>\n {!step.made ? (\n <Button variant=\"ghost\" className=\"mr-auto\" onClick={() => setStep({ at: \"import\" })}>\n Back\n </Button>\n ) : null}\n <Button variant=\"outline\" onClick={() => openImported(step.tableId)} data-new-table-open=\"\">\n Open the table\n </Button>\n </>\n );\n }\n\n return (\n <div\n className={cn(\"relative flex h-full min-h-0 flex-col\", className)}\n data-new-table-start={step.at}\n onDragOver={(e) => {\n if (step.at === \"wizard\" || !e.dataTransfer?.types?.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(true);\n }}\n onDragLeave={(e) => {\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;\n setDragging(false);\n }}\n onDrop={onDrop}\n >\n <div className=\"min-h-0 flex-1 overflow-y-auto px-5 py-4\">\n {body}\n {error ? <RefusalNotice error={error} className=\"mt-3\" /> : null}\n </div>\n <div className=\"flex shrink-0 items-center justify-end gap-2 border-t px-5 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\">{footer}</div>\n {dragging && step.at !== \"wizard\" ? (\n <div className=\"pointer-events-none absolute inset-2 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-background/90 text-sm font-medium text-primary\">\n Drop to import\n </div>\n ) : null}\n </div>\n );\n}\n\nfunction ChoiceCard({\n icon,\n title,\n words,\n href,\n onClick,\n ...rest\n}: {\n icon: string;\n title: string;\n words: string;\n href?: string;\n onClick?: () => void;\n [data: `data-${string}`]: string;\n}) {\n return href ? (\n <Tile asChild icon={<Icon d={icon} />} title={title} line={words} {...rest}>\n <a href={href} />\n </Tile>\n ) : (\n <Tile icon={<Icon d={icon} />} title={title} line={words} onClick={onClick} {...rest} />\n );\n}\n\nconst ICON = {\n upload: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12\",\n file: \"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h8\",\n paste: \"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2M9 2h6v4H9z\",\n template: \"M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z\",\n spark: \"M12 3l1.9 5.8L20 10l-6.1 1.2L12 17l-1.9-5.8L4 10l6.1-1.2zM19 17l.8 2.2L22 20l-2.2.8L19 23l-.8-2.2L16 20l2.2-.8z\",\n database: \"M12 8c4.97 0 9-1.34 9-3s-4.03-3-9-3-9 1.34-9 3 4.03 3 9 3zM3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5M3 12c0 1.66 4 3 9 3s9-1.34 9-3\",\n} as const;\n\nfunction Icon({ d }: { d: string }) {\n return (\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={d} />\n </svg>\n );\n}\n\n/**\n * THE NEW TABLE'S COLUMNS, ALL AT ONCE (v7 item 2). Paste a header row, a list, or write a sentence;\n * each column shows as a chip with its type, which can be changed before the one press that makes it.\n */\nexport function NewTableColumns({\n words,\n columns,\n onWords,\n onType,\n onCreate,\n}: {\n words: string;\n columns: readonly NewColumn[];\n onWords: (text: string) => void;\n onType: (index: number, type: NewColumnType) => void;\n onCreate: () => void;\n}) {\n return (\n <div className=\"flex flex-col gap-2\" data-new-table-columns=\"\">\n <Textarea\n value={words}\n rows={2}\n placeholder=\"Columns (optional): name, email, phone, start date, status\"\n aria-label=\"Columns\"\n onChange={(e) => onWords(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && (e.metaKey || e.ctrlKey)) onCreate();\n }}\n className=\"min-h-[3.5rem] text-base sm:text-sm\"\n />\n {columns.length > 0 ? (\n <ul className=\"flex flex-wrap gap-1.5\" data-new-table-column-chips=\"\">\n {columns.map((column, i) => (\n <li\n key={`${column.label}-${i}`}\n className=\"flex items-center gap-1 rounded-md border border-border py-0.5 pl-2 pr-0.5 text-xs\"\n data-new-table-column={column.type}\n >\n <span className=\"max-w-[12rem] truncate\">{column.label}</span>\n <Select value={column.type} onValueChange={(v) => onType(i, v as NewColumnType)}>\n <SelectTrigger size=\"sm\" aria-label={`${column.label} holds`} className=\"h-6 border-0 px-1.5 text-[11px] text-muted-foreground shadow-none\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {NEW_COLUMN_TYPES.map((t) => (\n <SelectItem key={t.type} value={t.type}>\n {t.words}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n}\n","// src/newTableColumns.ts — @ai-matrx/records-ui · lane TABLE-EXPERIENCE (v7 item 2)\n//\n// A NEW TABLE TAKES ALL ITS COLUMNS AT ONCE. Before this, five columns meant five Add-column dialogs\n// (70–80 s). Now the New table box takes a header row pasted from a spreadsheet, a list (one column a\n// line), or a sentence (\"clients with name, email, phone, start date and status\") and reads it into\n// typed columns, which the person sees as chips and makes with ONE press.\n//\n// The type comes from the column's NAME — a header row has no values to read yet — by the same\n// words a person would use. It is a proposal: every chip's type can be changed before the press.\n\nimport { RESOLVABLE_FIELD_TYPE_WORDS } from \"@ai-matrx/records/templates\";\nimport { tokenFor, type NewFieldSpec } from \"./createTable\";\nimport { parseDelimited } from \"@ai-matrx/kit/delimited\";\nimport { uniqueLabels } from \"./tableShape\";\n\n/** The types a new column can be given from the New table box, in the words the chip shows. */\nexport const NEW_COLUMN_TYPES = [\n { type: \"text\", words: \"Text\" },\n { type: \"rich_text\", words: \"Formatted text\" },\n { type: \"number\", words: \"Number\" },\n { type: \"currency\", words: \"Money\" },\n { type: \"percent\", words: \"Percent\" },\n { type: \"date\", words: \"Date\" },\n { type: \"datetime\", words: \"Date and time\" },\n { type: \"checkbox\", words: \"Yes / no\" },\n { type: \"select\", words: \"Choice\" },\n { type: \"multi_select\", words: \"Several choices\" },\n { type: \"email\", words: \"Email\" },\n { type: \"phone\", words: \"Phone\" },\n { type: \"url\", words: \"Link\" },\n] as const;\n\nexport type NewColumnType = (typeof NEW_COLUMN_TYPES)[number][\"type\"];\n\nexport interface NewColumn {\n label: string;\n type: NewColumnType;\n /** A choice column's starting choices (a Status starts as Notion's three). */\n options?: string[];\n}\n\n/** The most columns one box makes — a paste of a whole sheet's header stays a table, not a wall. */\nexport const MOST_NEW_COLUMNS = 40;\n\nconst BULLET = /^\\s*(?:[-*•]|\\d+[.)])\\s+/;\n\n/** What a person types in the brackets, in their words, for the store's own type words. */\nconst TYPE_WORD_ALIASES: Record<string, NewColumnType> = {\n choice: \"select\",\n dropdown: \"select\",\n status: \"select\",\n list: \"select\",\n choices: \"multi_select\",\n tags: \"multi_select\",\n money: \"currency\",\n boolean: \"checkbox\",\n bool: \"checkbox\",\n \"yes/no\": \"checkbox\",\n \"yes / no\": \"checkbox\",\n link: \"url\",\n integer: \"number\",\n decimal: \"number\",\n float: \"number\",\n string: \"text\",\n long_text: \"rich_text\",\n \"formatted text\": \"rich_text\",\n \"date and time\": \"datetime\",\n \"date time\": \"datetime\",\n};\n\n/** The column type a bracketed word names, or undefined. Only words the store resolves count. */\nfunction typeFromWord(raw: string): NewColumnType | undefined {\n const word = raw.trim().toLowerCase();\n if (word === \"\") return undefined;\n const type = TYPE_WORD_ALIASES[word] ?? NEW_COLUMN_TYPES.find((t) => t.type === word.replace(/[\\s-]+/g, \"_\"))?.type;\n if (!type) return undefined;\n // The store's one date word is \"datetime\" (a date is its kind); the rest are its own words.\n return RESOLVABLE_FIELD_TYPE_WORDS.includes(type === \"date\" ? \"datetime\" : type) ? type : undefined;\n}\n\n/** The text with everything inside (...) or [...] blanked, same length — so a split can ignore it. */\nfunction maskBrackets(text: string): string {\n let depth = 0;\n let out = \"\";\n for (const ch of text) {\n if (ch === \"(\" || ch === \"[\") {\n depth++;\n out += depth === 1 ? ch : \"\\u0000\";\n } else if ((ch === \")\" || ch === \"]\") && depth > 0) {\n depth--;\n out += depth === 0 ? ch : \"\\u0000\";\n } else out += depth > 0 ? \"\\u0000\" : ch;\n }\n return out;\n}\n\n/** Split `text` on `sep` only where it sits outside every bracket. */\nfunction splitOutsideBrackets(text: string, sep: RegExp): string[] {\n const masked = maskBrackets(text);\n const parts: string[] = [];\n let from = 0;\n const re = new RegExp(sep.source, sep.flags.includes(\"g\") ? sep.flags : sep.flags + \"g\");\n for (const m of masked.matchAll(re)) {\n if (m[0] === \"\") continue;\n parts.push(text.slice(from, m.index));\n from = m.index! + m[0].length;\n }\n parts.push(text.slice(from));\n return parts;\n}\n\ninterface ColumnSpec {\n label: string;\n type?: NewColumnType;\n options?: string[];\n}\n\n/** One column part: `Name`, `Name (type)`, `Name (choice: a, b, c)`. A stray bracket never stays in a name. */\nfunction specFromPart(part: string): ColumnSpec {\n const clean = (t: string) => t.replace(/^[\"'\\s]+|[\"'.\\s]+$/g, \"\").replace(/\\s+/g, \" \");\n const m = /^(.*?)\\s*[(\\[]([^()\\[\\]]*)[)\\]]\\s*$/.exec(part.trim());\n if (m) {\n const inner = m[2]!;\n const colon = inner.indexOf(\":\");\n const type = typeFromWord(colon >= 0 ? inner.slice(0, colon) : inner);\n const name = clean(m[1]!);\n if (type && name !== \"\") {\n const options =\n colon >= 0\n ? [...new Set(inner.slice(colon + 1).split(/\\s*[,;|]\\s*/).map(clean).filter((o) => o !== \"\"))]\n : undefined;\n return { label: name, type, ...(options && options.length > 0 && (type === \"select\" || type === \"multi_select\") ? { options } : {}) };\n }\n }\n // Not a type: a balanced note like \"Cost (USD)\" stays; an unbalanced bracket never does.\n const withoutPairs = part.replace(/\\([^()\\[\\]]*\\)|\\[[^()\\[\\]]*\\]/g, \"\");\n const label = /[()\\[\\]]/.test(withoutPairs) ? part.replace(/[()\\[\\]]/g, \" \") : part;\n return { label: clean(label) };\n}\n\nfunction specsFrom(text: string): ColumnSpec[] {\n const trimmed = text.trim();\n if (trimmed === \"\") return [];\n let parts: string[];\n const firstLine = trimmed.split(/\\r?\\n/)[0]!;\n if (firstLine.includes(\"\\t\")) {\n // A header row pasted from a spreadsheet or one of our exports: THE one reader (quotes, guard).\n parts = parseDelimited(trimmed, { delimiter: \"\\t\", strayQuotes: \"literal\" }).data[0] ?? [];\n } else if (/\\r?\\n/.test(trimmed)) {\n parts = trimmed.split(/\\r?\\n/).map((line) => line.replace(BULLET, \"\"));\n } else {\n let line = trimmed;\n const masked = maskBrackets(line);\n const colon = masked.indexOf(\":\");\n if (colon >= 0) line = line.slice(colon + 1);\n else {\n const withAt = masked.toLowerCase().lastIndexOf(\" with \");\n if (withAt >= 0) line = line.slice(withAt + \" with \".length);\n }\n parts = splitOutsideBrackets(line, /\\s*[,;|]\\s*|\\s+and\\s+|\\s*&\\s*/i);\n }\n const specs = parts\n .map(specFromPart)\n .filter((c) => c.label !== \"\")\n .map((c) => (c.label === c.label.toLowerCase() ? { ...c, label: c.label[0]!.toUpperCase() + c.label.slice(1) } : c));\n const seen = new Set<string>();\n const once = specs.filter((c) => {\n const k = c.label.toLowerCase();\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n const labels = uniqueLabels(once.map((c) => c.label));\n return once.map((c, i) => ({ ...c, label: labels[i]! })).slice(0, MOST_NEW_COLUMNS);\n}\n\n/**\n * The column NAMES a person typed or pasted, in order, each once. Empty when there are none.\n * A tab means a spreadsheet header row; several lines mean a list; otherwise one line split on\n * commas, semicolons, pipes and a last \"and\" — after \"with\" or a colon when it is a sentence.\n * Only OUTSIDE brackets: \"Status (choice: a, b)\" is one column.\n */\nexport function columnNamesFrom(text: string): string[] {\n return specsFrom(text).map((c) => c.label);\n}\n\nconst STATUS_CHOICES = [\"Not started\", \"In progress\", \"Done\"];\nconst PRIORITY_CHOICES = [\"Low\", \"Medium\", \"High\"];\n\n/** What a column of this NAME most likely holds. Text when nothing in the name says otherwise. */\nexport function columnFromName(label: string): NewColumn {\n const w = label.toLowerCase();\n const has = (re: RegExp) => re.test(w);\n if (has(/^(is|has|can|did|was)\\b|\\?$/)) return { label, type: \"checkbox\" };\n if (has(/\\be-?mail/)) return { label, type: \"email\" };\n if (has(/\\b(phone|mobile|cell|tel|telephone|whatsapp)\\b/)) return { label, type: \"phone\" };\n if (has(/\\b(url|website|web site|site|link|linkedin|instagram|tiktok|youtube)\\b/)) return { label, type: \"url\" };\n if (has(/\\b(status|stage)\\b/)) return { label, type: \"select\", options: STATUS_CHOICES };\n if (has(/\\bpriority\\b/)) return { label, type: \"select\", options: PRIORITY_CHOICES };\n if (has(/\\b(tags|labels|platforms|channels|skills)\\b/)) return { label, type: \"multi_select\" };\n if (has(/\\b(type|category|kind|tier|plan|platform|channel|source|level)\\b/)) return { label, type: \"select\" };\n if (has(/\\b(time|at|scheduled|starts|ends|appointment)\\b/) && !has(/\\b(date|day)\\b/)) return { label, type: \"datetime\" };\n if (has(/\\b(date|day|birthday|deadline|due|dob|born|joined|since|until|start|end|published|posted)\\b/)) return { label, type: \"date\" };\n if (has(/\\b(price|cost|amount|revenue|budget|fee|fees|salary|paid|total|spend|value|rate card|mrr|arr)\\b|\\$/)) return { label, type: \"currency\" };\n if (has(/%|\\b(percent|percentage|rate|ratio|margin|completion)\\b/)) return { label, type: \"percent\" };\n if (has(/\\b(count|qty|quantity|number of|age|score|hours|minutes|units|followers|views|likes|stars|rating|points|#)\\b|^#|^no\\.? /)) return { label, type: \"number\" };\n if (has(/\\b(done|completed|approved|active|signed|confirmed)\\b/)) return { label, type: \"checkbox\" };\n if (has(/\\b(notes?|description|details|comments?|summary|bio|brief|body|content|caption|script)\\b/)) return { label, type: \"rich_text\" };\n return { label, type: \"text\" };\n}\n\n/** Every column the words name, typed. */\nexport function columnsFrom(text: string): NewColumn[] {\n return specsFrom(text).map((c) =>\n c.type ? { label: c.label, type: c.type, ...(c.options && c.options.length > 0 ? { options: c.options } : {}) } : columnFromName(c.label),\n );\n}\n\n/** The columns as the table's own declaration (`declareTable`'s `fields`). */\nexport function fieldsForNewColumns(columns: readonly NewColumn[]): NewFieldSpec[] {\n const keys = new Set<string>();\n return columns.map((column, i) => {\n let key = tokenFor(column.label) || `column_${i + 1}`;\n while (keys.has(key)) key = `${key}_${i + 1}`;\n keys.add(key);\n const base = { key, label: column.label, sort: (i + 1) * 10, required: false };\n switch (column.type) {\n case \"date\":\n return { ...base, type: \"datetime\", kind: \"date\" as const };\n case \"datetime\":\n return { ...base, type: \"datetime\", kind: \"datetime\" as const };\n case \"currency\":\n return { ...base, type: \"currency\", unit: \"$\" };\n case \"select\":\n case \"multi_select\":\n return { ...base, type: column.type, multi: column.type === \"multi_select\", options: column.options ?? [] };\n default:\n return { ...base, type: column.type };\n }\n });\n}\n","// src/importFileRead.ts — @ai-matrx/records-ui\n//\n// READING A FILE INTO ROWS, WITH THE TWO QUESTIONS A FILE CAN GET WRONG ASKED OUT LOUD.\n//\n// The New table dialog's import reads the file HERE, shows it back as a preview, and hands the\n// result to `ImportWizard` as its `source` — so the plan, the column kinds, the mapping and the\n// write all stay the wizard's (one importer). What this adds is what the old table system had\n// and the bare parse never did:\n//\n// · the separator — guessed (comma, tab, semicolon, pipe) and changeable;\n// · \"First row is column names\" — guessed, and changeable;\n// · headers made usable — trimmed, a blank one named \"Column 3\", and a repeated one kept as\n// \"Notes 2\" instead of silently overwriting the first \"Notes\" column's values.\n\nimport { parseDelimited, toDelimited } from \"@ai-matrx/kit/delimited\";\nimport type { ParsedImport } from \"@ai-matrx/records/core\";\n\n/** What separates the cells of a text file. `auto` = guessed from the text. */\nexport type ImportSeparator = \"auto\" | \",\" | \"\\t\" | \";\" | \"|\";\n\nexport const IMPORT_SEPARATORS: ReadonlyArray<{ value: ImportSeparator; words: string }> = [\n { value: \"auto\", words: \"Detect\" },\n { value: \",\", words: \"Comma\" },\n { value: \"\\t\", words: \"Tab\" },\n { value: \";\", words: \"Semicolon\" },\n { value: \"|\", words: \"Pipe\" },\n];\n\n/** The words for a separator the reader settled on. */\nexport function separatorWords(separator: string | null): string {\n return IMPORT_SEPARATORS.find((s) => s.value === separator)?.words ?? \"Comma\";\n}\n\n/** The file types the import takes, as the native input's `accept`. */\nexport const IMPORT_ACCEPT = \".csv,.tsv,.txt,.xlsx,.xls\";\n\nexport interface ReadGrid {\n /** Every non-empty line as cells, header row included. */\n grid: string[][];\n /** The separator used; null for a workbook. */\n separator: string | null;\n format: \"csv\" | \"xlsx\";\n}\n\n/** Text as a grid of cells. A leading byte-order mark is dropped. */\nexport function gridFromText(text: string, separator: ImportSeparator = \"auto\"): ReadGrid {\n const clean = text.replace(/^/, \"\");\n const parsed = parseDelimited(clean, {\n ...(separator === \"auto\" ? {} : { delimiter: separator }),\n skipEmptyLines: \"greedy\",\n });\n const grid = (parsed.data as unknown[][]).map((line) => line.map((cell) => (cell == null ? \"\" : String(cell))));\n return { grid, separator: parsed.meta.delimiter ?? \",\", format: \"csv\" };\n}\n\n/** Whether a file name is a workbook rather than text. */\nexport function isWorkbook(name: string): boolean {\n return /\\.xlsx?$/i.test(name);\n}\n\n/** A file as a grid: text files through `gridFromText`, workbooks through the one workbook reader (first sheet). */\nexport async function gridFromFile(file: File, separator: ImportSeparator = \"auto\"): Promise<ReadGrid> {\n if (isWorkbook(file.name)) {\n const { readWorkbookBytes } = await import(\"@ai-matrx/print/xlsx\");\n const sheet = (await readWorkbookBytes(await file.arrayBuffer())).sheets[0];\n const raw = sheet ? (sheet.grid({ raw: false, defval: \"\" }) as unknown[][]) : [];\n const grid = raw\n .map((line) => line.map((cell) => (cell == null ? \"\" : String(cell))))\n .filter((line) => line.some((cell) => cell.trim().length > 0));\n return { grid, separator: null, format: \"xlsx\" };\n }\n return gridFromText(await file.text(), separator);\n}\n\nconst NUMERIC = /^\\s*[-+]?[$€£]?\\s*\\d[\\d,]*(\\.\\d+)?\\s*%?\\s*$/;\nconst DATEISH = /^\\s*(\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}|\\d{1,2}[-/]\\d{1,2}[-/]\\d{2,4})\\b/;\nconst EMAILISH = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/**\n * Whether the first line reads as column names: every cell filled, none repeated, and none that\n * looks like a value (a number, a date, an email). Two lines that look alike = no header.\n */\nexport function firstRowLooksLikeHeader(grid: readonly string[][]): boolean {\n const first = grid[0];\n if (!first || first.length === 0) return true;\n const filled = first.filter((c) => c.trim().length > 0);\n if (filled.length === 0) return false;\n if (filled.some((c) => NUMERIC.test(c) || DATEISH.test(c) || EMAILISH.test(c.trim()))) return false;\n return true;\n}\n\n/** Headers a person can map: trimmed, blanks named by position, repeats numbered. */\nexport function usableHeaders(raw: readonly string[], width: number): string[] {\n const taken = new Set<string>();\n const out: string[] = [];\n for (let i = 0; i < width; i++) {\n const base = String(raw[i] ?? \"\").replace(/\\s+/g, \" \").trim() || `Column ${i + 1}`;\n let name = base;\n for (let n = 2; taken.has(name.toLowerCase()); n++) name = `${base} ${n}`;\n taken.add(name.toLowerCase());\n out.push(name);\n }\n return out;\n}\n\n/** The grid as the wizard's rows. With no header row, every line is a row and columns are \"Column 1\"…. */\nexport function importFromGrid(grid: readonly string[][], firstRowIsHeader: boolean): ParsedImport {\n const width = grid.reduce((w, line) => Math.max(w, line.length), 0);\n const headers = usableHeaders(firstRowIsHeader ? (grid[0] ?? []) : [], width);\n const body = firstRowIsHeader ? grid.slice(1) : grid;\n const rows = body\n .filter((line) => line.some((cell) => cell.trim().length > 0))\n .map((line) => {\n const row: Record<string, string> = {};\n headers.forEach((h, i) => {\n row[h] = String(line[i] ?? \"\");\n });\n return row;\n });\n return { headers, rows };\n}\n\n/** The rows as CSV text — the import's identity (the same rows twice write nothing). */\nexport function importText(parsed: ParsedImport): string {\n return toDelimited([parsed.headers, ...parsed.rows.map((r) => parsed.headers.map((h) => r[h] ?? \"\"))]);\n}\n\n/** A table name from a file name: `clinic-patient_intake 2026.csv` → \"Clinic patient intake 2026\". */\nexport function tableNameFromFile(fileName: string): string {\n const stem = fileName.replace(/\\.[^.]+$/, \"\").replace(/[-_.]+/g, \" \").replace(/\\s+/g, \" \").trim();\n if (!stem) return \"\";\n return stem.charAt(0).toUpperCase() + stem.slice(1);\n}\n","\"use client\";\n\n// src/BookingSlots.tsx — @ai-matrx/records-ui · PRODUCTS row 14, THE OWNER'S SIDE\n//\n// A BOOKING PAGE IS AN `anon_form`, SO THIS IS `FormsPanel` FOR BOOKINGS.\n// It lists the booking pages this organization has, with the four numbers that\n// make the list worth opening, copies the visitor's link, and opens or closes a\n// page. That is the whole job.\n//\n// 🚨 WHAT THIS REPLACED, AND WHY IT HAD TO (lane SCREENS-2, 2026-09-20).\n// The first version of this component was a SLOT PICKER for a signed-in person,\n// and every one of its assumptions was wrong for the product it was named after:\n//\n// · It called `tableList`, `personKernelId`, `recordWrite`, `workSlotsDeclare`,\n// `workSlotHolds`, `workSlotHold` and `workSlotRelease` — seven doors granted\n// to `authenticated`. THE VISITOR IT WAS DESIGNED FOR HAS NO ACCOUNT and can\n// reach none of them.\n// · It built its OWN slot grid in the browser from an `availability` prop — a\n// second idea of what is on offer. A visitor with a wrong clock, or a console,\n// could hold a time the organization never offered.\n// · It declared its own slots Table under the slug `records_ui_slots_<tableId>`,\n// a THIRD slots Table beside the `booking_slots_<tableId>` one\n// `custom.booking_declare` finds-or-makes — so a page opened through the\n// component and a page opened through the link protected different indexes.\n//\n// THE PICKER ALREADY EXISTS AND IS CORRECT: `app/(link)/b/[bookingId]/BookingPicker.tsx`\n// in matrx-frontend, server-fed and server-lane, holding through `custom.booking_hold`.\n// The offer is `custom.booking_public`'s and the browser never computes it.\n//\n// ABSENT, NEVER DEAD. Opening or closing a booking page decides whether strangers\n// may take an organization's time, so it needs `admin` on the Table the\n// appointments land in. Someone without it sees the pages, the numbers and the\n// links, and NO open/close control at all — not a grayed one. The levels come\n// from the store in ONE call (`custom.my_levels`), never guessed here.\n\nimport { copyText } from \"@ai-matrx/kit/clipboard\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useRecordsClient, useMyLevels, type Uuid } from \"@ai-matrx/records/react\";\nimport { bookingPath, type BookingSummary, type RecordsError } from \"@ai-matrx/records\";\nimport { Badge, Button, Skeleton, cn } from \"@ai-matrx/design-system\";\n\nimport { BookingBuilder } from \"./BookingBuilder\";\nimport { BuildOrAsk } from \"./BuildOrAsk\";\nimport { ArchiveItemMenu } from \"./BuiltOnArchive\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { useRecordsUi } from \"./host\";\nimport { BOOKING_PAGE_STATE_LABEL } from \"./enumLabels\";\n\nexport interface BookingSlotsProps {\n /**\n * One Table's booking pages. Omitted — on the Records home — it is every\n * booking page in this organization, which is the same door asked the wider\n * question, never a second list.\n */\n tableId?: Uuid | null | undefined;\n /**\n * THE BOOKING PAGE A LINK NAMED (`?rail=bookings&item=<page>`, lane HUB-FIX,\n * VERIFIER-16 M4). It is marked and scrolled to. A page this rail does not\n * list is said out loud, never swapped for another.\n */\n activeBookingId?: Uuid | null | undefined;\n className?: string | undefined;\n}\n\n/** The sentence when a link named a booking page this rail does not list. */\nexport const BOOKING_NOT_HERE_LINE =\n \"The link named a booking page this table does not have — it may have been closed for good, or \" +\n \"it writes into another table. The booking pages this table does have are listed here.\";\n\n/**\n * THERE USED TO BE NO WAY TO MAKE A BOOKING PAGE FROM THIS SCREEN.\n *\n * The reasoning was `FormsPanel`'s: a person says \"let clients book a 30-minute\n * consult with me on Tuesday and Thursday afternoons\", the agent writes the\n * Table, the availability and the page in one call (`booking_propose`) and hands\n * back the link, and a builder button would make the slow path the obvious one.\n * That is still the recommendation and it is still named first.\n *\n * But the product walk of 2026-09-21 found this rail saying exactly that, on a\n * real table, with nothing to press. A person who did not know what to say had\n * no way to a booking page at all. `BookingBuilder` is the other way: four\n * decisions, in place, in this rail, through the same `custom.booking_declare`\n * door the agent calls.\n */\nconst WHAT_A_BOOKING_PAGE_IS =\n \"A booking page offers times you are free and writes each appointment into this table as an \" +\n \"ordinary record.\";\n\n/**\n * The sentence this package would put in a person's mouth.\n *\n * 🚨 IT READS AS ENGLISH (lane RECORDS-UI-FIX, guide re-walk 2026-09-23). With no table\n * name it read \"a 30-minute appointments slot\" — a plural noun where an adjective goes.\n * A table's name is a plural collection (\"Jobs\", \"Appointments\"), so it is never glued in\n * front of \"slot\"; the table is named after it, when there is one.\n */\nexport function bookingSuggestion(tableName: string | null | undefined): string {\n const name = tableName?.trim();\n return name\n ? `Let clients book a 30-minute appointment on Tuesday and Thursday afternoons, and put each one in ${name}.`\n : \"Let clients book a 30-minute appointment on Tuesday and Thursday afternoons.\";\n}\n\nconst NO_ADMIN =\n \"Opening a booking page lets people with no account take time in your calendar, so it needs \" +\n \"Full access on the table the appointments land in.\";\n\n/** The store's own word for the page's state, said the way a person would. THE one map — see `enumLabels.ts`. */\nexport const STATE_WORDS: Record<string, string> = BOOKING_PAGE_STATE_LABEL;\n\nexport function BookingSlots({ tableId, activeBookingId, className }: BookingSlotsProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const [pages, setPages] = useState<BookingSummary[] | null>(null);\n const [error, setError] = useState<RecordsError | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [copied, setCopied] = useState<string | null>(null);\n const [shown, setShown] = useState<string | null>(null);\n // BUILDING IS A MODE OF THIS RAIL: the list a person is looking at is where\n // the new page appears, so nothing has to be found again afterwards.\n const [building, setBuilding] = useState(false);\n /** The store's own sentence after an archive (MAKE-HOME 6a). */\n const [archivedSaid, setArchivedSaid] = useState<string | null>(null);\n // A PAGE THAT EXISTS CAN BE CHANGED (lane HANDOVER, 2026-09-29). Cedar Ridge's booking page had\n // been saved with its hours in UTC (2 AM slots for a clinic), and its card offered only \"Copy link\"\n // and \"Close\": nothing on the screen could change its hours, time zone or title. \"Change it\"\n // opens the same builder on that page, which re-states it rather than making a second one.\n const [changing, setChanging] = useState<{ formId: string; tableId: string } | null>(null);\n\n const load = useCallback(async () => {\n const answered = await client.bookings(tableId ? { table_id: tableId } : {});\n if (!answered.ok) {\n setError(answered.error);\n setPages([]);\n return;\n }\n setError(null);\n setPages(answered.data);\n }, [client, tableId]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n /**\n * ONE call for every page's level, not one per row. The question is \"may I\n * open this?\", and the store answers it about the TABLE the appointments land\n * in — which is the thing publishing actually exposes.\n */\n const subjectIds = useMemo(\n () =>\n Array.from(\n new Set([\n ...(pages ?? []).map((p) => p.table_id as Uuid),\n // THE EMPTY STATE ASKS THE SAME QUESTION. There is no page to read a\n // table off yet, and the empty state's two buttons need the answer\n // about the table this rail is standing in — otherwise the rail\n // offers a viewer both ways into an act the door will refuse.\n ...(tableId ? [tableId] : []),\n ]),\n ),\n [pages, tableId],\n );\n const levels = useMyLevels(subjectIds);\n\n /**\n * MAY THIS PERSON OPEN A BOOKING PAGE ON THIS TABLE? The store's word, never\n * this screen's guess, and `false` while the answer is still in flight — the\n * empty state stays quiet rather than blinking a refusal on and off.\n */\n const levelsKnown = !levels.loading && Boolean(levels.data);\n const mayBuildHere = levelsKnown && Boolean(tableId) && levels.data?.[tableId as Uuid] === \"admin\";\n\n const toggle = useCallback(\n async (page: BookingSummary) => {\n setBusy(page.form_id);\n const wanted = page.published_at === null || page.closed_at !== null;\n const answered = await client.anonPublish({ form_id: page.form_id as Uuid, published: wanted });\n setBusy(null);\n if (!answered.ok) {\n setError(answered.error);\n return;\n }\n await load();\n },\n [client, load],\n );\n\n // THE LINK IS THE PRODUCT. A clipboard that is unavailable (an insecure\n // origin, a locked-down browser) shows the address rather than failing quietly.\n const copy = useCallback(async (url: string, formId: string) => {\n if (await copyText(url)) {\n setCopied(formId);\n setShown(null);\n window.setTimeout(() => setCopied(null), 1600);\n } else {\n setShown(url);\n }\n }, []);\n\n if (pages === null) return <Skeleton className={cn(\"h-32 w-full\", className)} />;\n\n // ABSENT, NOT EMPTY. On the Records home this is a list of what the\n // organization HAS; an organization with no booking pages gets no heading and\n // no explanation it did not ask for. Asked about ONE table, the same emptiness\n // is worth a sentence — that is the screen where somebody came looking.\n if (pages.length === 0 && !tableId && !error && !building) return null;\n\n const origin = host.publicOrigin ?? (typeof window === \"undefined\" ? \"\" : window.location.origin);\n\n return (\n <section className={cn(\"flex flex-col gap-3\", className)} data-testid=\"booking-slots\">\n <header className=\"flex items-center gap-2\">\n <h3 className=\"text-sm font-medium\">Bookings</h3>\n <span className=\"text-xs text-muted-foreground\">\n {pages.length === 0 ? \"none yet\" : `${pages.length}`}\n </span>\n <div className=\"flex-1\" />\n {/* ONE-ROW HEADER. The act that makes a booking page lives beside the\n count, so the second one is as easy to make as the first. */}\n {tableId && pages.length > 0 ? (\n <Button size=\"sm\" variant={building ? \"secondary\" : \"ghost\"} onClick={() => setBuilding((b) => !b)}>\n {building ? \"Done building\" : \"Build a booking page\"}\n </Button>\n ) : null}\n </header>\n\n {error ? <RefusalNotice error={error} /> : null}\n {archivedSaid ? (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"booking-archived-said\">\n {archivedSaid}\n </p>\n ) : null}\n {activeBookingId && !pages.some((p) => p.form_id === activeBookingId) ? (\n <p className=\"rounded-md border border-amber-600/40 bg-amber-500/5 px-3 py-2 text-xs leading-relaxed text-amber-700 dark:border-amber-400/40 dark:text-amber-300\">\n {BOOKING_NOT_HERE_LINE}\n </p>\n ) : null}\n\n {changing ? (\n <BookingBuilder\n tableId={changing.tableId as Uuid}\n bookingId={changing.formId as Uuid}\n onSaved={() => {\n void load();\n }}\n onClose={() => setChanging(null)}\n />\n ) : null}\n\n {building && tableId ? (\n <BookingBuilder\n tableId={tableId}\n onSaved={() => {\n void load();\n }}\n onClose={() => setBuilding(false)}\n />\n ) : null}\n\n {pages.length === 0 && !building ? (\n tableId ? (\n <BuildOrAsk\n mayBuild={mayBuildHere}\n whyNot={mayBuildHere ? null : levelsKnown ? NO_ADMIN : null}\n onBuild={() => setBuilding(true)}\n {...(host.onAskForOne\n ? {\n onAsk: () =>\n host.onAskForOne?.({\n kind: \"booking\",\n tableId,\n suggestion: bookingSuggestion(null),\n }),\n }\n : {})}\n suggestion={bookingSuggestion(null)}\n buildLabel=\"Build the booking page\"\n >\n {WHAT_A_BOOKING_PAGE_IS}\n </BuildOrAsk>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {WHAT_A_BOOKING_PAGE_IS} Open the table the appointments should land in to make one.\n </p>\n )\n ) : null}\n\n <ul className=\"flex flex-col gap-2\">\n {pages.map((page) => {\n const url = `${origin}${bookingPath(page.form_id)}`;\n const mayOpen = levels.data?.[page.table_id] === \"admin\";\n const open = page.published_at !== null && page.closed_at === null;\n return (\n <li\n key={page.form_id}\n data-testid=\"booking-page\"\n data-linked={page.form_id === activeBookingId ? \"true\" : undefined}\n ref={page.form_id === activeBookingId ? (el) => el?.scrollIntoView({ block: \"nearest\" }) : undefined}\n className={cn(\n \"rounded-md border p-2.5\",\n page.form_id === activeBookingId && \"border-primary ring-1 ring-primary\",\n )}\n >\n <div className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium\">\n {page.title ?? page.slug}\n </span>\n <Badge variant={page.state === \"open\" ? \"default\" : \"secondary\"}>{page.state}</Badge>\n <ArchiveItemMenu\n kind=\"booking\"\n id={page.form_id as Uuid}\n title={page.title ?? page.slug}\n mayArchive={mayOpen}\n onArchived={(sentence) => {\n setArchivedSaid(sentence);\n void load();\n }}\n onRefused={setError}\n />\n </div>\n\n <p className=\"mt-0.5 text-xs text-muted-foreground\">\n {STATE_WORDS[page.state] ?? page.state}\n </p>\n\n {/* THE NUMBERS ARE THE STORE'S. A screen that counted appointments\n in the browser would drift from the index that protects a slot\n — and it would drift in the comfortable direction. */}\n <p className=\"mt-1.5 text-xs\">\n <span className=\"font-medium\">{page.upcoming}</span> coming up\n {\" · \"}\n <span className=\"font-medium\">{page.booked}</span> booked in all\n {page.held > 0 ? (\n <>\n {\" · \"}\n <span className=\"font-medium\">{page.held}</span> being held right now\n </>\n ) : null}\n {page.cancelled > 0 ? (\n <>\n {\" · \"}\n <span className=\"font-medium\">{page.cancelled}</span> canceled\n </>\n ) : null}\n <span className=\"text-muted-foreground\"> · {page.slot_minutes} minutes each</span>\n </p>\n\n {/* THE NEXT APPOINTMENT, IN WORDS, in the organization's own zone —\n which is the zone the visitor was offered times in. A time drawn\n in the reader's zone would quietly disagree with the page. */}\n <p className=\"mt-1 text-xs text-muted-foreground\">{nextInWords(page)}</p>\n\n <div className=\"mt-2 flex flex-wrap items-center gap-1.5\">\n <Button size=\"sm\" variant=\"outline\" onClick={() => void copy(url, page.form_id)}>\n {copied === page.form_id ? \"Copied\" : \"Copy link\"}\n </Button>\n {mayOpen ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => setChanging({ formId: page.form_id, tableId: page.table_id })}\n >\n Change it\n </Button>\n ) : null}\n {mayOpen ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n disabled={busy === page.form_id}\n onClick={() => void toggle(page)}\n >\n {busy === page.form_id ? \"…\" : open ? \"Close\" : \"Open\"}\n </Button>\n ) : null}\n </div>\n\n {shown && shown === url ? (\n <p className=\"mt-1.5 break-all rounded border border-dashed px-2 py-1 text-xs\">\n This browser would not let the page copy for you, so here it is to copy by hand: {url}\n </p>\n ) : null}\n </li>\n );\n })}\n </ul>\n\n {/* ONLY ONCE THE STORE HAS ANSWERED. While `custom.my_levels` is still in\n flight nothing is claimed in either direction — a sentence that said\n \"you are not an admin\" for one render and then took it back is the\n screen guessing out loud. */}\n {pages.length > 0 && !levels.loading && levels.data && subjectIds.every((id) => levels.data?.[id] !== \"admin\") ? (\n <p className=\"text-xs text-muted-foreground\">{NO_ADMIN}</p>\n ) : null}\n </section>\n );\n}\n\n/**\n * The next appointment, as a sentence. `next_at` is the store's answer over\n * every appointment this person may see — not over the page this screen loaded.\n */\nexport function nextInWords(page: Pick<BookingSummary, \"next_at\" | \"timezone\" | \"state\">): string {\n if (!page.next_at) {\n return page.state === \"open\"\n ? \"Nothing booked yet.\"\n : \"Nothing booked.\";\n }\n const at = new Date(page.next_at);\n if (Number.isNaN(at.getTime())) return \"Nothing booked yet.\";\n let said: string;\n try {\n said = at.toLocaleString(undefined, {\n timeZone: page.timezone,\n weekday: \"long\",\n month: \"long\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n } catch {\n // An unknown zone is a fact about the page, not a reason to draw nothing.\n said = at.toLocaleString(undefined, {\n weekday: \"long\",\n month: \"long\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n }\n return `Next: ${said} (${page.timezone}).`;\n}\n","\"use client\";\n\n// src/BookingBuilder.tsx — @ai-matrx/records-ui · PRODUCTS row 14, the builder\n//\n// \"LET CLIENTS BOOK A 30-MINUTE CONSULT\" — BUILT BY HAND, IN UNDER TWO MINUTES.\n//\n// The champion is Calendly, and the thing Calendly gets right is that the whole\n// page is four decisions: how long a meeting is, which hours of the week you are\n// free, how much room you want between appointments, and what the person sees\n// after they book. Everything else is a default somebody can change later. So\n// that is this screen, in that order, and nothing more.\n//\n// WHAT IT IS NOT. It is not a second booking system and it is not a slot picker:\n// the visitor's picker is `app/(link)/b/[bookingId]/BookingPicker.tsx`, which is\n// server-fed and holds through `custom.booking_hold`. This screen never computes\n// a slot. It declares the page (`custom.booking_declare`), shows what the STORE\n// normalized the offer to, and opens the link (`custom.anon_publish`) — the same\n// one act that opens a form, because a booking page IS an `anon_form`.\n//\n// THE THREE QUESTIONS A PERSON MAY NOT ASK. `slot`, `status` and `booked_with`\n// are the store's to fill in, and `custom.booking_declare` refuses a payload\n// naming any of them BY NAME. So this screen offers the Table's OTHER fields as\n// the questions a visitor answers, and never draws the three it would be refused\n// for — an offered control that is always refused is the dead control law 4\n// forbids, and hiding the refusal instead of the control would be worse.\n//\n// IT SHOWS WHAT CAME BACK, NEVER WHAT IT SENT. The store owns every default: a\n// page declared with an empty availability comes back in the organization's own\n// timezone, Monday to Friday, nine to five, thirty minutes. The offer under the\n// Save button is `availability` as the door answered it, so the screen and the\n// visitor's page cannot hold two ideas of what is free.\n//\n// PUBLISHING IS A SEPARATE ACT and it says so. `booking_declare` writes the page\n// and does NOT open it; a person who saved and walked away has a draft, not an\n// open calendar. The publish row is the same component the Forms rail uses.\n\nimport { copyText } from \"@ai-matrx/kit/clipboard\";\nimport { ErrorBox } from \"@ai-matrx/design-system\";\nimport { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useFields, useRecordsClient, useTable, type Uuid } from \"@ai-matrx/records/react\";\n\nimport { formatDurationMinutes } from \"@ai-matrx/kit/format\";\nimport {\n bookingPath,\n type BookingAvailability,\n type BookingSummary,\n type BookingWindow,\n type Field,\n type RecordsError,\n} from \"@ai-matrx/records\";\nimport { BasicInput, BasicTextarea, Button, Checkbox, Label, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { Select } from \"@ai-matrx/design-system/controls\";\n\nimport {\n BOOKING_TOKENS,\n DEFAULT_REMINDER_OFFSETS,\n REMINDER_CHOICES,\n messagesFromPresentation,\n messagesToPresentation,\n type BookingMessageNotice,\n type BookingMessages,\n} from \"./bookingMessages\";\nimport { askableFields, requiredLeftUnasked, whyNotAskable } from \"./publicQuestions\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { TimeZoneInput, ownTimeZone } from \"./TimeZoneInput\";\nimport { useRecordsUi, useTableRights } from \"./host\";\nimport { fieldName, singularNoun } from \"./names\";\nimport { editorKindFor } from \"./parity\";\n\n/**\n * THE THREE THE STORE FILLS IN. Named here so this screen never offers them —\n * `custom.booking_declare` refuses a question naming any of the three, and a\n * control that is always refused is a dead control.\n */\nexport const STORE_ANSWERS_THESE = [\"slot\", \"status\", \"booked_with\"] as const;\n\n/** Monday first, because a working week is what a person is describing. */\nconst DAYS: Array<{ weekday: number; label: string }> = [\n { weekday: 1, label: \"Mon\" },\n { weekday: 2, label: \"Tue\" },\n { weekday: 3, label: \"Wed\" },\n { weekday: 4, label: \"Thu\" },\n { weekday: 5, label: \"Fri\" },\n { weekday: 6, label: \"Sat\" },\n { weekday: 0, label: \"Sun\" },\n];\n\n/** The lengths a consultation actually is. The store takes any number; these are the ones people pick. */\nconst LENGTHS = [15, 20, 30, 45, 60, 90, 120];\n\nexport interface BookingBuilderProps {\n /** The Table the appointments land in. An appointment is an ordinary record in it. */\n tableId: Uuid;\n /** Re-state an existing page rather than making a second one over the same Table. */\n bookingId?: Uuid | null | undefined;\n /** Called after a save, so the list this opened from re-reads the store. */\n onSaved?: ((page: { form_id: string }) => void) | undefined;\n onClose?: (() => void) | undefined;\n /**\n * A NEW PAGE, whatever the table already has (lane MAKE-HOME, 2026-10-02). Without it and without\n * `bookingId` the builder opens the table's first page; a host whose person pressed \"make a\n * booking page\" (the /make hub) passes this, and the first Save makes a second page beside the\n * old one. After that Save the builder keeps editing the page it just made.\n */\n startNew?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** One window a person is describing, before the store has normalized it. */\ninterface DraftWindow extends BookingWindow {\n on: boolean;\n}\n\n/**\n * THE SCREEN STARTS WHERE THE STORE STARTS (walk 2, 2026-09-21).\n *\n * `custom._booking_availability` substitutes Monday-to-Friday, nine to five,\n * for an empty window list, on purpose — its own comment says a booking page\n * that offered nothing \"would look broken rather than unconfigured\". This\n * screen started with every day OFF and every row reading \"not taking\n * bookings\", so a person who saved without touching the days was told the page\n * offered nothing and got a page offering the whole working week. The screen\n * and the store now start from the same place, and an EXISTING page is drawn\n * from what it actually holds.\n */\nconst WORKING_WEEK = new Set([1, 2, 3, 4, 5]);\n\nfunction draftWindows(availability: BookingAvailability | null): DraftWindow[] {\n return DAYS.map((day) => {\n const found = availability?.windows.find((w) => w.weekday === day.weekday);\n return {\n weekday: day.weekday,\n from: found?.from ?? \"09:00\",\n to: found?.to ?? \"17:00\",\n on: availability ? Boolean(found) : WORKING_WEEK.has(day.weekday),\n };\n });\n}\n\nexport function BookingBuilder({ tableId, bookingId, onSaved, onClose, startNew, className }: BookingBuilderProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const table = useTable(tableId);\n const rights = useTableRights(table.data);\n const fields = useFields(tableId);\n\n const [existing, setExisting] = useState<BookingSummary | null>(null);\n const [loaded, setLoaded] = useState(false);\n const [error, setError] = useState<RecordsError | null>(null);\n const [saving, setSaving] = useState(false);\n const [publishing, setPublishing] = useState(false);\n const [copied, setCopied] = useState(false);\n\n const [title, setTitle] = useState(\"\");\n const [minutes, setMinutes] = useState(30);\n const [buffer, setBuffer] = useState(0);\n const [lead, setLead] = useState(120);\n const [perDay, setPerDay] = useState(8);\n const [days, setDays] = useState(30);\n // THE CLOCK THE HOURS ARE IN (lane HANDOVER, 2026-09-28). An organization with no time zone\n // of its own got a page \"in UTC\", so a clinic's 9-to-5 opened at 2 AM its own time. A new page\n // starts in the owner's own zone (Calendly's default), a saved one in the zone it was saved in,\n // and the zone is on the screen to change.\n const [timezone, setTimezone] = useState<string>(() => ownTimeZone());\n const [windows, setWindows] = useState<DraftWindow[]>(() => draftWindows(null));\n const [asked, setAsked] = useState<string[]>([]);\n const [confirmation, setConfirmation] = useState(\"\");\n // WHAT THE BOOKER IS EMAILED (BOOKING-NOTIFY). Held whole and sent back on every Save: Save\n // re-states the page, so a screen that dropped this would erase the owner's switches.\n const [messages, setMessages] = useState<BookingMessages>({});\n // EVERYTHING THE PAGE ALREADY HOLDS THAT THIS SCREEN DOES NOT EDIT. Save re-states the whole page\n // (the store takes absent as \"none\"), so what is not carried back is erased: the owner's intro,\n // endings and per-question wording, the cap, the accept and notify Rules, the link name.\n const [stored, setStored] = useState<{\n presentation: Record<string, unknown>;\n questions: Array<Record<string, unknown>>;\n submissionCap: number | null;\n quarantineRuleId: Uuid | null;\n notifyRuleId: Uuid | null;\n slug: string | null;\n thankYouTitle: string | null;\n } | null>(null);\n // The offer as the STORE normalized it — what the visitor's page will show.\n const [offer, setOffer] = useState<BookingAvailability | null>(null);\n const [formId, setFormId] = useState<Uuid | null>((bookingId as Uuid | null) ?? null);\n /** The page a `startNew` builder made with its first Save; it is the page from then on. */\n const madeRef = useRef<Uuid | null>(null);\n\n const publicOrigin = host.publicOrigin ?? (typeof window === \"undefined\" ? \"\" : window.location.origin);\n\n /**\n * THE QUESTIONS A VISITOR MAY BE ASKED — this Table's own Fields, minus the\n * three the store fills in. A form is a view on a real Table, so there is no\n * way on this screen to invent a question that lands nowhere.\n */\n const askable = useMemo(\n () => askableFields(fields.data ?? [], STORE_ANSWERS_THESE as readonly string[]),\n [fields.data],\n );\n /** A required column this page leaves unasked: every booking would be refused (said, never blocking). */\n const unfillable = requiredLeftUnasked(fields.data ?? [], asked, STORE_ANSWERS_THESE as readonly string[]);\n /** The Fields a visitor could never answer, named with the reason (walk 2). */\n const leftOut = useMemo(\n () => whyNotAskable(fields.data ?? [], STORE_ANSWERS_THESE as readonly string[]),\n [fields.data],\n );\n\n const load = useCallback(async () => {\n const answered = await client.bookings({ table_id: tableId });\n if (!answered.ok) {\n setError(answered.error);\n setLoaded(true);\n return;\n }\n // A new page (startNew) is the page this builder saved, once it has saved one — never the first.\n const wanted = bookingId ?? (startNew ? madeRef.current : null);\n const mine = wanted\n ? (answered.data.find((p) => p.form_id === wanted) ?? null)\n : startNew\n ? null\n : (answered.data[0] ?? null);\n setExisting(mine);\n if (mine) {\n setFormId(mine.form_id as Uuid);\n // A PAGE THAT EXISTS OPENS WITH ITS OWN QUESTIONS AND HOURS (lane HANDOVER, 2026-09-29).\n // \"Change it\" opened Cedar Ridge's booking page with its title and clock but no questions and\n // the opening guess for its hours, so saving was refused (\"has to ask the person something\")\n // and, had it gone through, would have replaced the page's real hours. The page's own\n // presentation (the forms door answers booking pages too) is what the builder starts from.\n const pages = await client.forms({ table_id: tableId });\n const page = pages.ok ? pages.data.find((f) => f.form_id === mine.form_id) : undefined;\n const presentation = (page?.presentation ?? {}) as Record<string, unknown>;\n const questions = Array.isArray(presentation[\"questions\"])\n ? (presentation[\"questions\"] as Array<{ field?: unknown; hidden?: unknown }>)\n : [];\n // The page's stored list also carries the store's own hidden columns (slot, status,\n // booked_with); those are the store's to fill, and sending them back is refused.\n const keys = questions\n .filter((q) => q.hidden !== true)\n .map((q) => (typeof q.field === \"string\" ? q.field : \"\"))\n .filter((k) => k !== \"\" && !(STORE_ANSWERS_THESE as readonly string[]).includes(k));\n if (keys.length > 0) setAsked(keys);\n setMessages(messagesFromPresentation(presentation));\n const thankYou = presentation[\"thank_you\"] as { title?: unknown; body?: unknown } | null | undefined;\n if (thankYou && typeof thankYou.body === \"string\") setConfirmation(thankYou.body);\n setStored({\n presentation,\n questions: questions as Array<Record<string, unknown>>,\n submissionCap: page?.submission_cap ?? null,\n quarantineRuleId: (page?.quarantine_rule_id as Uuid | null | undefined) ?? null,\n notifyRuleId: (page?.notify_rule_id as Uuid | null | undefined) ?? null,\n slug: page?.slug ?? null,\n thankYouTitle: typeof thankYou?.title === \"string\" ? thankYou.title : null,\n });\n const block = presentation[\"booking\"];\n if (block && typeof block === \"object\" && Array.isArray((block as { windows?: unknown }).windows)) {\n setOffer(block as BookingAvailability);\n }\n }\n setLoaded(true);\n }, [client, tableId, bookingId, startNew]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n // The name a person would give it, from the Table they are standing on — never\n // \"Booking 1\". A real business's booking page is named after the work.\n useEffect(() => {\n if (title !== \"\" || !table.data) return;\n setTitle(existing?.title ?? `Book a ${minutes}-minute ${singularNoun(table.data, \"appointment\")}`);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [table.data, existing]);\n\n useEffect(() => {\n if (!existing) return;\n setMinutes(existing.slot_minutes);\n if (existing.timezone && existing.timezone !== \"UTC\") setTimezone(existing.timezone);\n }, [existing]);\n\n // Once the store has said what a page actually offers, the day rows are ITS\n // answer — never the screen's opening guess sitting on top of a real page.\n useEffect(() => {\n if (!offer) return;\n setWindows(draftWindows(offer));\n setMinutes(offer.slot_minutes);\n setBuffer(offer.buffer_minutes);\n setLead(offer.lead_minutes);\n setPerDay(offer.max_per_day);\n setDays(offer.days);\n // A page kept in UTC before the screen sent a zone starts in the owner's own clock instead.\n if (offer.timezone && offer.timezone !== \"UTC\") setTimezone(offer.timezone);\n }, [offer]);\n\n const availability = useCallback(\n (): Partial<BookingAvailability> => ({\n timezone,\n slot_minutes: minutes,\n buffer_minutes: buffer,\n lead_minutes: lead,\n max_per_day: perDay,\n days,\n windows: windows\n .filter((w) => w.on)\n .map((w) => ({ weekday: w.weekday, from: w.from, to: w.to })),\n }),\n [timezone, minutes, buffer, lead, perDay, days, windows],\n );\n\n // A NEW PAGE SAVES ON ITS FIRST PRESS (lane MAKE-HOME 1b): it starts asking the table's required\n // columns and the ones that say who is booking (Calendly's page works with its defaults), or the\n // first askable column — never an empty list the store refuses. Once, and never over a saved page.\n const startedAsking = useRef(false);\n useEffect(() => {\n if (startedAsking.current || !loaded || existing || formId || !fields.data) return;\n startedAsking.current = true;\n if (asked.length > 0) return;\n const keys = askable.filter((f) => f.required || isWhoField(f)).map((f) => f.key);\n const first = askable[0]?.key;\n setAsked(keys.length > 0 ? keys : first ? [first] : []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaded, existing, formId, fields.data, askable]);\n\n const [addingWho, setAddingWho] = useState(false);\n /** Adds a Name and an Email column to this table and asks both on the page. */\n async function addWho() {\n setAddingWho(true);\n setError(null);\n for (const spec of [\n { label: \"Name\", plain: \"text\" as const },\n { label: \"Email\", parity_type: \"email\" as const },\n ]) {\n const made = await client.fieldDeclare({ table_id: tableId, spec });\n if (!made.ok) {\n setAddingWho(false);\n setError(made.error);\n return;\n }\n }\n fields.reload();\n setAddingWho(false);\n setWhoAdded(true);\n }\n // Once the two columns are there, the page asks them — the owner pressed the button to be told\n // who booked, not to add columns and then tick them.\n const [whoAdded, setWhoAdded] = useState(false);\n useEffect(() => {\n if (!whoAdded) return;\n const who = askable.filter((f) => isWhoField(f)).map((f) => f.key);\n if (who.length === 0) return;\n setAsked((prev) => [...prev, ...who.filter((k) => !prev.includes(k))]);\n setWhoAdded(false);\n }, [whoAdded, askable]);\n\n async function save() {\n setSaving(true);\n setError(null);\n const written = await client.bookingDeclare({\n table_id: tableId,\n title: title.trim() === \"\" ? \"Book a time\" : title.trim(),\n // The Fields a visitor is asked for, in the order this screen shows them.\n // The questions as the page words them (ask / help / required), for the ones still asked.\n questions: asked.map(\n (key) => stored?.questions.find((q) => (q[\"field\"] ?? q[\"key\"]) === key) ?? { field: key },\n ),\n availability: availability(),\n presentation: {\n // Everything else the page holds, as it is. The store re-adds `questions` and `booking`.\n ...Object.fromEntries(\n Object.entries(stored?.presentation ?? {}).filter(\n ([k]) => ![\"questions\", \"booking\", \"thank_you\", \"booking_messages\"].includes(k),\n ),\n ),\n // THE SENTENCE AFTER THE BOOKING. It is the thank-you screen every other\n // public surface in this package uses, so one component renders it.\n thank_you:\n confirmation.trim() === \"\" ? null : { title: stored?.thankYouTitle ?? \"You're booked\", body: confirmation.trim() },\n ...(messagesToPresentation(messages) ? { booking_messages: messagesToPresentation(messages) } : {}),\n },\n ...(stored\n ? {\n submission_cap: stored.submissionCap,\n quarantine_rule_id: stored.quarantineRuleId,\n notify_rule_id: stored.notifyRuleId,\n slug: stored.slug,\n }\n : {}),\n ...(formId ? { form_id: formId } : {}),\n });\n setSaving(false);\n if (!written.ok) {\n setError(written.error);\n return;\n }\n // WHAT CAME BACK, not what was sent: the store owns every default.\n setOffer(written.data.availability);\n setFormId(written.data.form_id as Uuid);\n madeRef.current = written.data.form_id as Uuid;\n onSaved?.({ form_id: written.data.form_id });\n await load();\n }\n\n async function publish(wanted: boolean) {\n if (!formId) return;\n setPublishing(true);\n const answered = await client.anonPublish({ form_id: formId, published: wanted });\n setPublishing(false);\n if (!answered.ok) {\n setError(answered.error);\n return;\n }\n await load();\n onSaved?.({ form_id: formId });\n }\n\n if (!loaded || (fields.loading && !fields.data)) return <Skeleton className={cn(\"h-64 w-full\", className)} />;\n\n // ABSENT, NEVER DEAD. A booking page lets people with no account take time in\n // this organization's calendar, so the store asks for `admin` on the Table —\n // and when a person does not hold it there is no builder at all, with the\n // store's own reason in its place.\n if (!rights.structure) {\n return (\n <p className={cn(\"text-xs text-muted-foreground\", className)}>\n {rights.why(\"structure\") ??\n \"Making a booking page needs Full access on this table, because it lets people with no account take time in your calendar.\"}\n </p>\n );\n }\n\n const url = formId ? `${publicOrigin}${bookingPath(formId)}` : null;\n const shown = offer ?? null;\n\n return (\n // THE RAIL IS 384px WIDE AND THE VIEWPORT IS NOT (walk 1, 2026-09-21):\n // every split below is a CONTAINER query, so this screen is the same\n // screen in a rail, a dialog and a full page.\n <section className={cn(\"@container flex flex-col gap-3\", className)}>\n {/* ONE-ROW HEADER. No repeated name, no second title bar. */}\n <header className=\"flex items-center gap-2\">\n <h3 className=\"text-sm font-medium\">{existing ? \"Booking page\" : \"New booking page\"}</h3>\n <div className=\"flex-1\" />\n <Button size=\"sm\" disabled={saving} onClick={() => void save()}>\n {saving ? \"Saving…\" : \"Save\"}\n </Button>\n {onClose ? (\n <Button size=\"sm\" variant=\"ghost\" onClick={onClose}>\n Close\n </Button>\n ) : null}\n </header>\n {!existing && !formId && fields.data && STORE_ANSWERS_THESE.some((k) => !fields.data!.some((f) => f.key === k)) ? (\n <p className=\"text-xs text-muted-foreground\" data-booking-adds-columns=\"\">\n Saving adds three columns to this table: Appointment, Status, With\n </p>\n ) : null}\n\n {error ? <RefusalNotice error={error} /> : null}\n\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">What it is called</Label>\n <BasicInput value={title} onChange={(e) => setTitle(e.target.value)} />\n </label>\n\n <div className=\"grid grid-cols-1 gap-2 @md:grid-cols-2\">\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">How long one appointment is</Label>\n <Select\n aria-label=\"How long one appointment is\"\n value={String(minutes)}\n onValueChange={(v) => setMinutes(Number(v))}\n options={LENGTHS.map((n) => ({ value: String(n), label: `${n} minutes` }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Gap kept after each one</Label>\n <Select\n aria-label=\"Gap kept after each one\"\n value={String(buffer)}\n onValueChange={(v) => setBuffer(Number(v))}\n options={[0, 5, 10, 15, 30].map((n) => ({ value: String(n), label: n === 0 ? \"No gap — back to back\" : `${n} minutes` }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Earliest somebody may book</Label>\n <Select\n aria-label=\"Earliest somebody may book\"\n value={String(lead)}\n onValueChange={(v) => setLead(Number(v))}\n options={[0, 60, 120, 240, 1440].map((n) => ({\n value: String(n),\n label: n === 0 ? \"Right away\" : n === 1440 ? \"A day from now\" : `${formatDurationMinutes(n, { style: \"long\" })} from now`,\n }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Most in one day</Label>\n <BasicInput\n type=\"number\"\n min={1}\n value={perDay}\n onChange={(e) => setPerDay(Math.max(1, Number(e.target.value) || 1))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">How far ahead the page offers</Label>\n <Select\n aria-label=\"How far ahead the page offers\"\n value={String(days)}\n onValueChange={(v) => setDays(Number(v))}\n options={[7, 14, 30, 60, 90].map((n) => ({ value: String(n), label: `${n} days` }))}\n />\n </label>\n {/* Type to find a zone: four hundred of them are a search, not a list to scroll. */}\n <TimeZoneInput label=\"Time zone the hours are in\" value={timezone} onChange={setTimezone} />\n </div>\n\n {/* THE HOURS OF THE WEEK. One row per day, the day itself the switch — the\n shape a person already knows from every calendar they have used. */}\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium\">Hours you are free</Label>\n {windows.map((w, i) => (\n <div key={w.weekday} className=\"flex items-center gap-2\">\n <label className=\"flex w-20 items-center gap-1.5 text-xs\">\n <Checkbox\n checked={w.on}\n onCheckedChange={(on) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, on: Boolean(on) } : x)))\n }\n />\n {DAYS[i]?.label}\n </label>\n {w.on ? (\n <>\n <BasicInput\n type=\"time\"\n className=\"h-8 w-28\"\n value={w.from}\n onChange={(e) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, from: e.target.value } : x)))\n }\n />\n <span className=\"text-xs text-muted-foreground\">to</span>\n <BasicInput\n type=\"time\"\n className=\"h-8 w-28\"\n value={w.to}\n onChange={(e) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, to: e.target.value } : x)))\n }\n />\n </>\n ) : (\n <span className=\"text-xs text-muted-foreground\">not taking bookings</span>\n )}\n </div>\n ))}\n </div>\n\n {/* WHAT THE PERSON BOOKING IS ASKED. This Table's own Fields, minus the\n three the store fills in — so an appointment is a record, complete. */}\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium\">What to ask the person booking</Label>\n {askable.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">\n This table has no fields yet, so there is nothing a booking page could ask for. Add a\n field first — every question is one of this table&apos;s own fields.\n </p>\n ) : (\n <div className=\"flex flex-wrap gap-x-4 gap-y-1.5\">\n {askable.map((f) => (\n <label key={f.key} className=\"flex items-center gap-1.5 text-xs\">\n <Checkbox\n checked={asked.includes(f.key)}\n onCheckedChange={(on) =>\n setAsked((prev) => (on ? [...prev, f.key] : prev.filter((k) => k !== f.key)))\n }\n />\n {fieldName(f)}\n </label>\n ))}\n </div>\n )}\n {/* WHO IS BOOKING (lane HANDOVER, 2026-09-28). Cedar Ridge's Visits names its patient by a\n link a stranger cannot follow, so its page asked nobody who they were and an appointment\n arrived with no one to call. Calendly always asks a name and an email; a table with\n neither gets them in one press, and the page asks them. */}\n {!asksWhoTheyAre(askable) ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded border border-dashed px-2 py-1.5\" data-booking-who=\"\">\n <p className=\"text-xs text-muted-foreground\">\n Nobody booking is asked who they are, so you would not know who booked or how to reach them.\n </p>\n <Button size=\"sm\" variant=\"outline\" disabled={addingWho} onClick={() => void addWho()}>\n {addingWho ? \"Adding…\" : \"Ask their name and email\"}\n </Button>\n </div>\n ) : null}\n <p className=\"text-xs text-muted-foreground\">\n The time, whether it is booked or canceled, and who it is with are filled in for you\n — a booking page cannot ask a visitor for any of the three.\n </p>\n {leftOut ? <p className=\"text-xs text-muted-foreground\">{leftOut}</p> : null}\n {unfillable ? (\n <ErrorBox\n className=\"rounded border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive\"\n message={unfillable}\n operation=\"Build a booking page\"\n origin=\"records-ui/BookingBuilder\"\n />\n ) : null}\n </div>\n\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">What they see after booking</Label>\n <BasicTextarea\n rows={2}\n value={confirmation}\n placeholder=\"You're booked. We'll send a reminder the day before — reply to that message to move it.\"\n onChange={(e) => setConfirmation(e.target.value)}\n />\n </label>\n\n\n {/* WHAT THE BOOKER IS EMAILED. Every notice is on until it is switched off; an empty box\n means the default words. The store sends them (custom.booking_messages). */}\n <div className=\"flex flex-col gap-2\" data-booking-messages=\"\">\n <Label className=\"text-xs font-medium\">Emails to the person who books</Label>\n {(\n [\n [\"confirmation\", \"Confirmation, with a calendar file\"],\n [\"changed\", \"When they move it\"],\n [\"cancelled\", \"When they cancel\"],\n ] as const\n ).map(([key, label]) => (\n <MessageRow\n key={key}\n label={label}\n value={messages[key]}\n onChange={(n) => setMessages((m) => ({ ...m, [key]: n }))}\n />\n ))}\n <MessageRow\n label=\"Reminders\"\n value={messages.reminders}\n onChange={(n) => setMessages((m) => ({ ...m, reminders: { ...m.reminders, ...n } }))}\n >\n <div className=\"flex flex-wrap gap-x-3 gap-y-1\">\n {REMINDER_CHOICES.map((c) => {\n const offsets = messages.reminders?.offsets ?? [...DEFAULT_REMINDER_OFFSETS];\n return (\n <label key={c.minutes} className=\"flex items-center gap-1.5 text-xs\">\n <Checkbox\n checked={offsets.includes(c.minutes)}\n onCheckedChange={(on) =>\n setMessages((m) => ({\n ...m,\n reminders: {\n ...m.reminders,\n offsets: on === true ? [...offsets, c.minutes] : offsets.filter((o) => o !== c.minutes),\n },\n }))\n }\n />\n {c.label}\n </label>\n );\n })}\n </div>\n </MessageRow>\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={messages.host?.on !== false}\n onCheckedChange={(on) => setMessages((m) => ({ ...m, host: { on: on === true } }))}\n />\n Tell me when someone books, moves or cancels\n </label>\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={messages.sms?.on === true}\n onCheckedChange={(on) => setMessages((m) => ({ ...m, sms: { on: on === true } }))}\n />\n Offer text reminders (booker ticks Text me reminders)\n </label>\n <p className=\"text-xs text-muted-foreground\">Words can use {BOOKING_TOKENS.join(\" \")}</p>\n </div>\n\n {/* THE OFFER, AS THE STORE NORMALIZED IT. Shown only after a save, because\n before one there is nothing the store has agreed to. */}\n {shown ? (\n <p className=\"rounded-md border bg-muted/40 p-2.5 text-xs\">\n Saved. The page offers {shown.slot_minutes}-minute appointments in {shown.timezone}, up to{\" \"}\n {shown.max_per_day} a day, {shown.days} days ahead\n {shown.buffer_minutes > 0 ? `, with ${shown.buffer_minutes} minutes between them` : \"\"}:{\" \"}\n {shown.windows\n .map(\n (w) => `${DAYS.find((d) => d.weekday === w.weekday)?.label ?? w.weekday} ${w.from}–${w.to}`,\n )\n .join(\", \")}\n .\n </p>\n ) : null}\n\n {/* PUBLISHING IS ITS OWN ACT, and until it happens the link does not\n answer. Saying so is the difference between a draft and an open\n calendar somebody thinks they have. */}\n {url ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded-md border p-2.5\">\n <span className=\"min-w-0 flex-1 break-all text-xs\">{url}</span>\n <Button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n void copyText(url).then((landed) => {\n setCopied(landed);\n if (landed) window.setTimeout(() => setCopied(false), 1600);\n });\n }}\n >\n {copied ? \"Copied\" : \"Copy link\"}\n </Button>\n <Button\n size=\"sm\"\n disabled={publishing}\n onClick={() => void publish(!(existing?.published_at && !existing.closed_at))}\n >\n {publishing\n ? \"…\"\n : existing?.published_at && !existing.closed_at\n ? \"Unpublish\"\n : \"Publish\"}\n </Button>\n <p className=\"w-full text-xs text-muted-foreground\">\n {existing?.published_at && !existing.closed_at\n ? \"Open. Anyone with this link can book a time.\"\n : \"Not open yet — the link does not take bookings until you publish it.\"}\n </p>\n </div>\n ) : null}\n </section>\n );\n}\n\n/** One notice: a switch, and its words when it is on. An empty box is the default words. */\nfunction MessageRow({\n label,\n value,\n onChange,\n children,\n}: {\n label: string;\n value: BookingMessageNotice | undefined;\n onChange: (next: BookingMessageNotice) => void;\n children?: ReactNode;\n}) {\n const on = value?.on !== false;\n return (\n <div className=\"flex flex-col gap-1.5 rounded-md border p-2\">\n <label className=\"flex items-center gap-2 text-xs font-medium\">\n <Checkbox checked={on} onCheckedChange={(next) => onChange({ ...value, on: next === true })} />\n {label}\n </label>\n {on ? (\n <>\n {children}\n <BasicInput\n aria-label={`${label}: subject`}\n placeholder=\"Subject (blank = the default)\"\n value={value?.subject ?? \"\"}\n onChange={(e) => onChange({ ...value, subject: e.target.value })}\n />\n <BasicTextarea\n aria-label={`${label}: message`}\n rows={2}\n placeholder=\"Message (blank = the default)\"\n value={value?.body ?? \"\"}\n onChange={(e) => onChange({ ...value, body: e.target.value })}\n />\n </>\n ) : null}\n </div>\n );\n}\n\n/** A column that says who somebody is: a name, an email or a phone. */\nfunction isWhoField(field: Field): boolean {\n const kind = editorKindFor(field);\n return kind === \"email\" || kind === \"phone\" || /\\bname\\b/i.test(fieldName(field));\n}\n\n/** Whether the page can already ask who is booking: an email or a phone column it may ask. */\nfunction asksWhoTheyAre(askable: readonly Field[]): boolean {\n return askable.some((f) => {\n const kind = editorKindFor(f);\n return kind === \"email\" || kind === \"phone\";\n });\n}\n","// src/bookingMessages.ts — @ai-matrx/records-ui · what a booking page says to the person who booked.\n//\n// BOOKING-NOTIFY. The words and switches live on the page as `presentation.booking_messages`; the\n// SENDER is the store (`custom.booking_messages`, called by the confirm, reschedule and cancel\n// doors), so the screen only edits this one object and hands it back whole on every Save.\n// 🚨 Save re-states the whole page, so a screen that did not read this object and send it back\n// would silently erase an owner's switches and wording the next time anyone pressed Save.\n//\n// Every notice is ON until an owner switches it off, and an empty word box means \"use the default\".\n\nexport interface BookingMessageNotice {\n on?: boolean;\n subject?: string;\n body?: string;\n}\n\nexport interface BookingMessages {\n confirmation?: BookingMessageNotice;\n changed?: BookingMessageNotice;\n cancelled?: BookingMessageNotice;\n reminders?: BookingMessageNotice & { offsets?: number[] };\n host?: { on?: boolean };\n /** Offer \"Text me reminders\" on the public page. OFF until an owner switches it on (it spends their texting number). */\n sms?: { on?: boolean };\n}\n\n/** The reminders a new page sends: the day before and the hour before (minutes before the start). */\nexport const DEFAULT_REMINDER_OFFSETS: readonly number[] = [1440, 60];\n\n/** The offsets an owner can pick from, in minutes before the start. */\nexport const REMINDER_CHOICES: ReadonlyArray<{ minutes: number; label: string }> = [\n { minutes: 10080, label: \"1 week before\" },\n { minutes: 2880, label: \"2 days before\" },\n { minutes: 1440, label: \"1 day before\" },\n { minutes: 180, label: \"3 hours before\" },\n { minutes: 60, label: \"1 hour before\" },\n { minutes: 15, label: \"15 minutes before\" },\n];\n\n/** The merge fields a message may use, exactly the ones the store fills. */\nexport const BOOKING_TOKENS: readonly string[] = [\n \"{{booker.name}}\",\n \"{{time}}\",\n \"{{title}}\",\n \"{{calendar.google}}\",\n \"{{calendar.outlook}}\",\n];\n\nfunction notice(raw: unknown): BookingMessageNotice | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const r = raw as Record<string, unknown>;\n const out: BookingMessageNotice = {};\n if (typeof r[\"on\"] === \"boolean\") out.on = r[\"on\"];\n if (typeof r[\"subject\"] === \"string\" && r[\"subject\"].trim() !== \"\") out.subject = r[\"subject\"];\n if (typeof r[\"body\"] === \"string\" && r[\"body\"].trim() !== \"\") out.body = r[\"body\"];\n return out;\n}\n\n/** `presentation.booking_messages` back into the screen's words; unknown keys are kept as they are not ours to drop. */\nexport function messagesFromPresentation(presentation: unknown): BookingMessages {\n const raw = presentation && typeof presentation === \"object\" ? (presentation as Record<string, unknown>)[\"booking_messages\"] : null;\n if (!raw || typeof raw !== \"object\") return {};\n const r = raw as Record<string, unknown>;\n const out: BookingMessages = {};\n for (const k of [\"confirmation\", \"changed\", \"cancelled\"] as const) {\n const n = notice(r[k]);\n if (n) out[k] = n;\n }\n const rem = notice(r[\"reminders\"]);\n const offsets = (r[\"reminders\"] as { offsets?: unknown } | undefined)?.offsets;\n if (rem || Array.isArray(offsets)) {\n out.reminders = {\n ...(rem ?? {}),\n ...(Array.isArray(offsets)\n ? { offsets: offsets.map(Number).filter((n) => Number.isInteger(n) && n > 0) }\n : {}),\n };\n }\n const host = r[\"host\"] as { on?: unknown } | undefined;\n if (host && typeof host.on === \"boolean\") out.host = { on: host.on };\n const sms = r[\"sms\"] as { on?: unknown } | undefined;\n if (sms && typeof sms.on === \"boolean\") out.sms = { on: sms.on };\n return out;\n}\n\n/** The screen's words as the store reads them. Empty means \"use the default\", so it is not sent. */\nexport function messagesToPresentation(m: BookingMessages): BookingMessages | null {\n const out: BookingMessages = {};\n for (const k of [\"confirmation\", \"changed\", \"cancelled\"] as const) {\n const n = m[k];\n if (n && (n.on === false || n.subject?.trim() || n.body?.trim())) {\n out[k] = {\n ...(n.on === false ? { on: false } : {}),\n ...(n.subject?.trim() ? { subject: n.subject.trim() } : {}),\n ...(n.body?.trim() ? { body: n.body.trim() } : {}),\n };\n }\n }\n const rem = m.reminders;\n if (rem) {\n const offsets = rem.offsets && rem.offsets.length > 0 ? [...new Set(rem.offsets)].sort((a, b) => b - a) : null;\n const custom = offsets && (offsets.length !== DEFAULT_REMINDER_OFFSETS.length || offsets.some((o, i) => o !== DEFAULT_REMINDER_OFFSETS[i]));\n if (rem.on === false || custom || rem.subject?.trim() || rem.body?.trim()) {\n out.reminders = {\n ...(rem.on === false ? { on: false } : {}),\n ...(custom && offsets ? { offsets } : {}),\n ...(rem.subject?.trim() ? { subject: rem.subject.trim() } : {}),\n ...(rem.body?.trim() ? { body: rem.body.trim() } : {}),\n };\n }\n }\n if (m.host?.on === false) out.host = { on: false };\n if (m.sms?.on === true) out.sms = { on: true };\n return Object.keys(out).length > 0 ? out : null;\n}\n","\"use client\";\n\n// src/publicQuestions.ts — @ai-matrx/records-ui\n//\n// WHAT A STRANGER CAN ACTUALLY ANSWER.\n//\n// WHAT WALK 2 FOUND (lane BUILDERS, 2026-09-21). Ironclad Mobile Mechanic built\n// a booking page over his `Service Calls` table and ticked \"Customer\", because\n// of course the page should ask who is booking. `Customer` is a RELATION Field\n// pointing at his Customers table. A visitor typed her name, the page sent it,\n// and the store refused at the last step with\n//\n// Customer points at something that is not there\n//\n// — correctly: a relation holds the IDENTITY of a record, and a stranger with\n// no account cannot see that Table, cannot search it, and has no id to give.\n// Her slot stayed held and she lost the booking.\n//\n// THE CONTROL WAS THE DEFECT, not the refusal. A tick that can only ever end in\n// a refusal is the dead control law 4 forbids, and the builder was offering\n// several of them on every real Table. So the question list is now the Fields a\n// person with NO ACCOUNT can answer, and the ones left out are NAMED with the\n// reason rather than silently missing — a manager who wonders where \"Customer\"\n// went is told, in the same place she would have ticked it.\n//\n// IT IS NOT A DENY-LIST OF TYPES SOMEBODY WILL FORGET TO EXTEND. The question it\n// asks is the one that matters: does answering this need something only a\n// signed-in member of this organization has?\n//\n// · `relation` — the id of a record in a Table the visitor cannot open.\n// · `member` — a person in an organization the visitor does not belong to.\n// · `attachment` — a file in the organization's own store; a public upload\n// door is a real feature, not a checkbox, and until it exists a stranger\n// has nowhere to put the bytes.\n// · `formula`, `lookup`, `rollup` — computed. Nobody answers them, including\n// the owner; asking would write into something the store derives.\n//\n// Everything else — text, number, money, percent, date, email, phone, url, a\n// choice from a list — is answerable by anybody with the link, which is why the\n// class-signup form in walk 1 worked on its first try.\n\nimport type { Field } from \"@ai-matrx/records\";\n\n/** Why a Field cannot be asked of somebody with no account, in a person's words. */\nconst CANNOT_ASK: Record<string, string> = {\n relation:\n \"points at a record in another table, and somebody with no account cannot see that table to pick from it\",\n member:\n \"is a person in this organization, and somebody outside it has no way to choose one\",\n attachment:\n \"holds a file in your own files, and a public page has nowhere to put one yet\",\n formula: \"is calculated, so there is nothing for anybody to answer\",\n lookup: \"is read through a relation, so it fills in by itself\",\n rollup: \"is added up, so there is nothing for anybody to answer\",\n};\n\n/** Can somebody with no account and no membership answer this question? */\nexport function publiclyAnswerable(field: Field): boolean {\n return !(field.type in CANNOT_ASK);\n}\n\n/** The Fields a public page may ask for, in the Table's own order. */\nexport function askableFields(fields: readonly Field[], hidden: readonly string[] = []): Field[] {\n return fields.filter((f) => publiclyAnswerable(f) && !hidden.includes(f.key));\n}\n\n/**\n * THE ONES LEFT OUT, NAMED. Absent is fine; absent and unexplained is the dead\n * end this package does not ship. Returns null when nothing was left out.\n */\nexport function whyNotAskable(\n fields: readonly Field[],\n hidden: readonly string[] = [],\n): string | null {\n const left = fields.filter((f) => !publiclyAnswerable(f) && !hidden.includes(f.key));\n if (left.length === 0) return null;\n const said = left.map((f) => `${f.label || f.key} ${CANNOT_ASK[f.type]}`);\n return said.length === 1\n ? `${said[0]}, so it is not offered here.`\n : `These are not offered here: ${said.join(\"; \")}.`;\n}\n\n/**\n * A REQUIRED COLUMN THE PAGE LEAVES UNASKED MEANS EVERY ANSWER IS REFUSED (lane HANDOVER, 2026-09-29).\n *\n * Cedar Ridge Physical Therapy's booking page over Visits: a front-desk member picked a time,\n * answered, pressed Book it and read \"Patient is required\". Visits requires a Patient (a link to\n * another record), which no public page can ask, so no booking could ever be made — and nothing on\n * the builder said so. This is said while the page is being made, with the remedy; it offers, it\n * does not stop the save (validation offers, never blocks). `storeFills` are the columns the store\n * writes itself (a booking page's slot, status and who it is with).\n */\nexport function requiredLeftUnasked(\n fields: readonly Field[],\n asked: readonly string[],\n storeFills: readonly string[] = [],\n): string | null {\n const missing = fields.filter(\n (f) => f.required === true && !asked.includes(f.key) && !storeFills.includes(f.key) && !COMPUTED.has(f.type),\n );\n if (missing.length === 0) return null;\n const said = missing.map((f) => {\n const name = f.label || f.key;\n return publiclyAnswerable(f)\n ? `${name} is required — tick it so this page asks it`\n : `${name} is required and this page cannot ask it (${SHORT_WHY[f.type] ?? \"a stranger cannot answer it\"}) — make it optional in this table's settings`;\n });\n return `Every answer would be refused as this page stands: ${said.join(\"; \")}.`;\n}\n\n/** Why a stranger cannot answer it, in a few words for a sentence. */\nconst SHORT_WHY: Record<string, string> = {\n relation: \"it points at a record in another table\",\n member: \"it is a person in this organization\",\n attachment: \"it holds a file\",\n};\n\n/** Columns the store works out itself: never asked, never \"missing\". */\nconst COMPUTED = new Set([\"formula\", \"lookup\", \"rollup\"]);\n","// THE CLOCK A TIME IS READ IN — one control for every screen that asks a time of day\n// (lane HANDOVER, 2026-09-28).\n//\n// A booking page's hours and a summary's \"every Monday at 8\" are both read by the store in a\n// named zone and fall back to UTC when none is given. Both screens start at the zone of the\n// person at the keyboard and let them type to find another (four hundred zones are a search,\n// not a list to scroll). One control, so the next screen that asks a time inherits it.\n\nimport { useId } from \"react\";\nimport { BasicInput, Label } from \"@ai-matrx/design-system\";\n\n/** The zone of the person at the keyboard, which is where a new schedule's hours start. */\nexport function ownTimeZone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n } catch {\n return \"UTC\";\n }\n}\n\nconst TIME_ZONES: readonly string[] = (() => {\n try {\n return (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.(\"timeZone\") ?? [];\n } catch {\n return [];\n }\n})();\n\nexport function TimeZoneInput({\n label,\n value,\n onChange,\n className,\n}: {\n /** What the zone is for, in the screen's words (\"Time zone the hours are in\"). */\n label: string;\n value: string;\n onChange: (zone: string) => void;\n className?: string | undefined;\n}) {\n const listId = useId();\n return (\n <label className={className ?? \"flex flex-col gap-1\"}>\n <Label className=\"text-xs font-medium\">{label}</Label>\n <BasicInput\n list={listId}\n value={value}\n onChange={(e) => onChange(e.target.value)}\n className=\"h-9 text-sm\"\n aria-label={label}\n />\n <datalist id={listId}>\n {TIME_ZONES.map((zone) => (\n <option key={zone} value={zone} />\n ))}\n </datalist>\n </label>\n );\n}\n","\"use client\";\n\n// src/BuildOrAsk.tsx — @ai-matrx/records-ui · the empty state of every builder\n//\n// THE PRODUCT WALK THAT MADE THIS FILE (2026-09-21). A non-technical expert\n// opened a real table she had just filled with her own business's records, and\n// the Forms, Bookings and Portals rails each said the same thing: none yet, ask\n// an agent for one in a sentence. There was no other way in. Four screens of\n// this package could make the thing and none of them was reachable, so the\n// agent was not the FASTER path — it was the ONLY path, and a person who did\n// not know what to say to it was finished.\n//\n// THE RULING THIS ENCODES: the agent path stays, and it stays FIRST in the\n// sentence, because saying it out loud really is faster. But a person may\n// always build the thing by hand, in under two minutes, without leaving the\n// rail they are standing in. Two buttons, one row, every rail identical — so\n// somebody who learns it on forms already knows it on portals.\n//\n// ABSENT, NEVER DEAD (law 4). \"Ask an agent\" is a HOST port: only a server can\n// honestly speak as an agent, and a browser that stamped itself one would be\n// claiming to be one. A host that has not bound the port gets no button at all\n// — not a grayed one — and the sentence says plainly that asking in words needs\n// an agent this screen cannot reach. \"Build it\" is absent the same way when the\n// store says this person does not hold the level the act needs, and the store's\n// own reason is shown in its place.\n//\n// AND THE SAME LAW BINDS THE AGENT HALF (chair ruling, 2026-09-21). Measured on\n// Ironclad Mobile Mechanic's Service Calls table: a dispatcher at VIEWER read\n// the rail's true sentence — \"Making one needs the admin level on it\" — and\n// then pressed the fully live \"Ask an agent\" button beside it. The composer\n// opened, \"make me a signup form\" was accepted, the agent read the table and\n// worked for about five minutes. It created nothing and never said why; the\n// rail was identical before and after. That is a control that is neither absent\n// nor honest, and an agent burning money answering nothing.\n//\n// So `mayBuild` gates BOTH ways in, not just the button on the right. Asking an\n// agent is not a lesser act than building by hand — it is the SAME act, said\n// out loud, through the same doors, and it hits the same refusal. A door the\n// store has shut shows no way through it and one sentence saying why. This is\n// gated HERE, in the one component every rail mounts, so forms, bookings,\n// portals, dashboards and every rail added after this inherit it rather than\n// each re-deciding it.\n\nimport type { ReactNode } from \"react\";\nimport { Button, cn } from \"@ai-matrx/design-system\";\n\n/** What a person is asking to have made, in the store's own word for it. */\nexport type BuildableKind = \"form\" | \"booking\" | \"portal\" | \"digest\";\n\nexport interface BuildOrAskProps {\n /**\n * The sentence that says what this thing IS, in a practitioner's words —\n * never \"You have no forms.\" A person who does not already know what a\n * booking page does is not helped by being told they have none.\n */\n children: ReactNode;\n /** Pressed, the builder opens in place. Absent when `mayBuild` is false. */\n onBuild: () => void;\n /** The store's answer, never a guess on this screen. */\n mayBuild: boolean;\n /**\n * WHY NOT, in the store's words, shown where the button would have been.\n * A missing control with no explanation is the same dead end as a dead one.\n */\n whyNot?: string | null | undefined;\n /**\n * The host's agent port. Unbound, the second button is absent and the\n * sentence below names what is missing. Bound but `mayBuild` false, it is\n * absent too: an agent asked to do what this person may not do gets refused\n * by the same doors, five minutes later, with nothing to show for it.\n */\n onAsk?: (() => void) | undefined;\n /** The words a person would actually say, offered as the starting sentence. */\n suggestion: string;\n /** \"Build the form\", \"Build the booking page\" — the act, never \"New\". */\n buildLabel: string;\n /** The agent button's words. Default \"Ask an agent\"; a layout's empty state says \"Ask AI\". */\n askLabel?: string | undefined;\n /**\n * What the person may change before pressing — a column's name and its choices (`ViewNeeds`).\n * Drawn between the sentence and the buttons, and only when they may build.\n */\n editor?: ReactNode;\n /** What to say when no agent is bound. Default `NO_AGENT_PORT`. */\n noAgentSentence?: string | undefined;\n /** The build is in flight: the button says so and does not take a second press. */\n building?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** What this package tells a host that has bound no agent. One sentence, one remedy. */\nexport const NO_AGENT_PORT =\n \"Asking for one in words needs an agent, which this screen reaches through its host's \" +\n \"`onAskForOne` port — it is not bound here, so build it below instead.\";\n\nexport function BuildOrAsk({\n children,\n onBuild,\n mayBuild,\n whyNot,\n onAsk,\n suggestion,\n buildLabel,\n askLabel = \"Ask an agent\",\n editor,\n building = false,\n noAgentSentence = NO_AGENT_PORT,\n className,\n}: BuildOrAskProps) {\n /**\n * THE ONE GATE ON BOTH WAYS IN. Saying it out loud and building it by hand\n * are the same act through the same doors, so the store's answer decides\n * both. `mayBuild` first, deliberately: a person who may not build is offered\n * nothing at all, whether or not the host bound an agent.\n */\n const mayAsk = mayBuild && Boolean(onAsk);\n\n return (\n <div className={cn(\"rounded-md border border-dashed p-3\", className)}>\n <p className=\"text-xs text-muted-foreground\">{children}</p>\n\n {/* TWO WAYS, ONE ROW. The agent is named first because it is faster; the\n builder is a button of equal weight beside it because it is the one\n that always works. When the store has shut the door, this row is empty\n and the sentence underneath carries the whole answer. */}\n {mayBuild && editor ? <div className=\"mt-2.5\">{editor}</div> : null}\n {mayBuild ? (\n <div className=\"mt-2.5 flex flex-wrap items-center gap-2\">\n {mayAsk ? (\n <Button size=\"sm\" variant=\"outline\" onClick={onAsk}>\n {askLabel}\n </Button>\n ) : null}\n <Button size=\"sm\" onClick={onBuild} disabled={building} aria-busy={building || undefined}>\n {buildLabel}\n </Button>\n </div>\n ) : null}\n\n {/* WHAT THE SENTENCE UNDER THE ROW SAYS, in the only three states there\n are. A shut door says the store's own reason and NOTHING else — the\n unbound-port sentence ends \"build it below instead\", which is a lie to\n somebody who may not build, and the suggested wording is an invitation\n to an act that cannot happen. */}\n {!mayBuild ? (\n whyNot ? (\n <p className=\"mt-2 text-xs text-muted-foreground\">{whyNot}</p>\n ) : null\n ) : mayAsk ? (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n You would say something like: “{suggestion}”\n </p>\n ) : (\n <p className=\"mt-2 text-xs text-muted-foreground\">{noAgentSentence}</p>\n )}\n </div>\n );\n}\n","\"use client\";\n\n// src/BuiltOnArchive.tsx — @ai-matrx/records-ui · lane MAKE-HOME wave 6a (2026-10-03)\n//\n// THE WAY OUT AND THE WAY BACK FOR WHAT IS BUILT ON A TABLE: its forms, its booking pages and its\n// checklists. Before this, none of the three had any way out — an old intake form stayed in the\n// rail forever — because the store had no door. CHAIR-DOORS-3B landed `custom.form_archive` /\n// `form_restore` / `forms_archived` and `checklist_templates_archived` (a checklist template is a\n// record: `record_delete` archives it, `record_restore` brings it back).\n//\n// ONE PRIMITIVE EACH, REUSED:\n// · `ArchiveItemMenu` — the ⋯ on one item of the Forms, Bookings and Checklists rails. It is the\n// platform's own row menu: a design-system DropdownMenu drawing an `ObjectAction` list through\n// `ObjectActionMenuItems`, the renderer every table menu uses. No new chrome row.\n// · `ArchivedBuiltOn` — the archived ones, in the table's Archived view beside its archived\n// rows and columns, each with Restore (the archived-items law: every archive has a way back).\n//\n// ABSENT OR HONEST, NEVER DEAD. Archive is drawn disabled with its reason for somebody below the\n// rung the door asks (admin on the table); Restore is absent with the store's reason when the store\n// says it cannot come back (`can_restore` false — its table is archived).\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport {\n archivedWhen,\n BUILT_KIND_WORD,\n type ArchivedChecklistTemplate,\n type ArchivedForm,\n type RecordsError,\n} from \"@ai-matrx/records\";\nimport { useRecordsClient, type Uuid } from \"@ai-matrx/records/react\";\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuTrigger,\n} from \"@ai-matrx/design-system\";\n\nimport { ObjectActionMenuItems } from \"./ObjectActionMenuItems\";\nimport type { ObjectAction } from \"./objectActions\";\nimport { RefusalNotice } from \"./Refusal\";\n\nexport type BuiltKind = \"form\" | \"booking\" | \"checklist\";\n\n/** The one action this menu carries today, in the shape every table menu draws. */\nexport function archiveItemActions(args: {\n kind: BuiltKind;\n whyNot?: string | null | undefined;\n run: () => void | Promise<void>;\n}): ObjectAction[] {\n return [\n {\n id: \"archive\",\n label: \"Archive\",\n icon: \"archive\",\n group: \"danger\",\n verb: \"archive\",\n destructive: true,\n ...(args.whyNot ? { disabledReason: args.whyNot } : {}),\n run: args.run,\n },\n ];\n}\n\n/** Why a person below the door's rung may not archive it (≤ 60 chars, the menu's reason line). */\nexport const ARCHIVE_NEEDS_ADMIN = \"Needs Full access on this table\";\n\nexport interface ArchiveItemMenuProps {\n kind: BuiltKind;\n /** The form's or booking page's form id, or the checklist template's record id. */\n id: Uuid;\n title: string;\n /** False → the action is drawn disabled with `ARCHIVE_NEEDS_ADMIN`. */\n mayArchive: boolean;\n /** The store's own sentence after it archived; the rail shows it and re-reads its list. */\n onArchived: (sentence: string) => void;\n onRefused: (error: RecordsError) => void;\n}\n\n/** THE ⋯ ON ONE ITEM. Archiving is reversible, so it acts at once and says what happened. */\nexport function ArchiveItemMenu({ kind, id, title, mayArchive, onArchived, onRefused }: ArchiveItemMenuProps) {\n const client = useRecordsClient();\n const run = async () => {\n if (kind === \"checklist\") {\n const done = await client.recordDelete({ record_id: id });\n if (!done.ok) return onRefused(done.error);\n onArchived(`The checklist \"${title}\" is archived. It waits in this table's Archived view.`);\n return;\n }\n const done = await client.formArchive({ form_id: id });\n if (!done.ok) return onRefused(done.error);\n onArchived(done.data.sentence);\n };\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-7 w-7 p-0\"\n aria-label={`More for ${title}`}\n title=\"More\"\n data-built-item-menu={kind}\n >\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"currentColor\" aria-hidden=\"true\">\n <circle cx=\"5\" cy=\"12\" r=\"1.75\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.75\" />\n <circle cx=\"19\" cy=\"12\" r=\"1.75\" />\n </svg>\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-56\">\n <ObjectActionMenuItems\n actions={archiveItemActions({ kind, whyNot: mayArchive ? null : ARCHIVE_NEEDS_ADMIN, run })}\n />\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n\n/** One archived thing, whichever door listed it. */\ninterface ArchivedThing {\n kind: BuiltKind;\n id: Uuid;\n title: string;\n archivedAt: string;\n /** Null = may be restored; a sentence = why not, said in place of the button. */\n whyNot: string | null;\n}\n\nexport function archivedThings(forms: ArchivedForm[], checklists: ArchivedChecklistTemplate[]): ArchivedThing[] {\n const fromForms = forms.map<ArchivedThing>((f) => ({\n kind: f.kind === \"booking\" ? \"booking\" : \"form\",\n id: f.form_id,\n title: f.title?.trim() || f.slug,\n archivedAt: f.archived_at,\n whyNot: f.can_restore ? null : f.table_archived ? \"Its table is archived\" : \"Needs Full access on this table\",\n }));\n const fromChecklists = checklists.map<ArchivedThing>((c) => ({\n kind: \"checklist\",\n id: c.template_id,\n title: c.name?.trim() || \"A checklist with no name\",\n archivedAt: c.archived_at,\n whyNot: c.table_archived ? \"Its table is archived\" : null,\n }));\n return [...fromForms, ...fromChecklists].sort((a, b) => (a.archivedAt < b.archivedAt ? 1 : -1));\n}\n\n/**\n * THE ARCHIVED FORMS, BOOKING PAGES AND CHECKLISTS OF ONE TABLE, each with Restore. Drawn in the\n * table's Archived view; nothing at all while there are none (the view's own rows say \"empty\").\n */\nexport function ArchivedBuiltOn({ tableId, onRestored }: { tableId: Uuid; onRestored?: (() => void) | undefined }) {\n const client = useRecordsClient();\n const [things, setThings] = useState<ArchivedThing[] | null>(null);\n const [error, setError] = useState<RecordsError | null>(null);\n const [restoring, setRestoring] = useState<Uuid | null>(null);\n const [refusal, setRefusal] = useState<{ id: Uuid; error: RecordsError } | null>(null);\n const [said, setSaid] = useState<string | null>(null);\n\n const read = useCallback(async () => {\n const [forms, checklists] = await Promise.all([\n client.formsArchived({ table_id: tableId }),\n client.checklistTemplatesArchived({ about_table_id: tableId }),\n ]);\n if (!forms.ok) return setError(forms.error);\n if (!checklists.ok) return setError(checklists.error);\n setError(null);\n setThings(archivedThings(forms.data, checklists.data));\n }, [client, tableId]);\n\n useEffect(() => {\n void read();\n }, [read]);\n\n const restore = async (thing: ArchivedThing) => {\n setRestoring(thing.id);\n setRefusal(null);\n setSaid(null);\n if (thing.kind === \"checklist\") {\n const done = await client.recordRestore({ record_id: thing.id });\n setRestoring(null);\n if (!done.ok) return setRefusal({ id: thing.id, error: done.error });\n setSaid(`The checklist \"${thing.title}\" is back.`);\n } else {\n const done = await client.formRestore({ form_id: thing.id });\n setRestoring(null);\n if (!done.ok) return setRefusal({ id: thing.id, error: done.error });\n setSaid(done.data.sentence);\n }\n await read();\n onRestored?.();\n };\n\n if (error) return <RefusalNotice error={error} />;\n if (!things || (things.length === 0 && !said)) return null;\n return (\n <section className=\"flex flex-col gap-1\" data-testid=\"archived-built-on\">\n <span className=\"text-sm font-medium\">Forms, bookings and checklists</span>\n {said ? (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"archived-built-on-said\">\n {said}\n </p>\n ) : null}\n <ul className=\"flex flex-col gap-1\">\n {things.map((thing) => (\n <li\n key={thing.id}\n data-testid=\"archived-built-thing\"\n data-kind={thing.kind}\n data-id={thing.id}\n className=\"flex flex-wrap items-center gap-2 rounded-md border px-3 py-2\"\n >\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <span className=\"truncate text-sm\">{thing.title}</span>\n <span className=\"truncate text-xs text-muted-foreground\">\n {BUILT_KIND_WORD[thing.kind]} · archived {archivedWhen(thing.archivedAt)}\n </span>\n {refusal && refusal.id === thing.id ? <RefusalNotice error={refusal.error} className=\"mt-2\" /> : null}\n </div>\n {thing.whyNot ? (\n <span className=\"text-xs text-muted-foreground\">{thing.whyNot}</span>\n ) : (\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={restoring === thing.id}\n data-testid=\"archived-built-restore\"\n onClick={() => void restore(thing)}\n >\n {restoring === thing.id ? \"Bringing it back…\" : \"Restore\"}\n </Button>\n )}\n </li>\n ))}\n </ul>\n </section>\n );\n}\n","// src/ObjectActionMenuItems.tsx — @ai-matrx/records-ui\n//\n// The header ⋯ renderer of the ONE action list (`objectActions.ts`). It draws\n// `toDropdownEntries(actions)` inside a design-system `DropdownMenuContent` and\n// nothing else: no item of its own, no filter, no reorder — G1 holds it to the\n// same ids in the same order as every other renderer.\n//\n// Each entry draws its glyph (`objectActionIcons.tsx`). A disabled action shows its\n// reason as a muted inline line, because a disabled Radix item takes no hover and a\n// `title` alone is unreachable on a phone.\n\nimport {\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n} from \"@ai-matrx/design-system\";\nimport { toDropdownEntries, type ObjectAction } from \"./objectActions\";\nimport { ObjectActionGlyph } from \"./objectActionIcons\";\n\nfunction ActionItem({ action }: { action: ObjectAction }) {\n const disabled = action.disabledReason !== undefined;\n return (\n <DropdownMenuItem\n disabled={disabled}\n onSelect={() => {\n if (!disabled) void action.run();\n }}\n title={action.disabledReason}\n data-object-action={action.id}\n className={action.destructive ? \"text-destructive focus:text-destructive\" : undefined}\n >\n <ObjectActionGlyph name={action.icon} className=\"mr-2 h-4 w-4 shrink-0\" />\n <span className=\"flex min-w-0 flex-col\">\n <span>{action.label}</span>\n {disabled ? (\n <span className=\"truncate text-xs text-muted-foreground\" data-object-action-reason=\"\">\n {action.disabledReason}\n </span>\n ) : null}\n </span>\n {action.shortcut ? <DropdownMenuShortcut>{action.shortcut}</DropdownMenuShortcut> : null}\n </DropdownMenuItem>\n );\n}\n\nexport interface ObjectActionMenuItemsProps {\n actions: readonly ObjectAction[];\n}\n\nexport function ObjectActionMenuItems({ actions }: ObjectActionMenuItemsProps) {\n return (\n <>\n {toDropdownEntries(actions).map((entry) => {\n if (entry.kind === \"separator\") return <DropdownMenuSeparator key={entry.id} />;\n if (entry.kind === \"item\") return <ActionItem key={entry.action.id} action={entry.action} />;\n return (\n <DropdownMenuSub key={entry.id}>\n <DropdownMenuSubTrigger data-object-action-group={entry.id}>\n {entry.icon ? <ObjectActionGlyph name={entry.icon} className=\"mr-2 h-4 w-4 shrink-0\" /> : null}\n {entry.label}\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n {entry.actions.map((a) => (\n <ActionItem key={a.id} action={a} />\n ))}\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n );\n })}\n </>\n );\n}\n","// src/objectActionIcons.tsx — @ai-matrx/records-ui\n//\n// The glyphs of the ONE action list (`ObjectActionIcon`), inlined. This package and\n// design-system take no icon-library dependency (policy C19), so each name maps to the\n// exact Lucide geometry (lucide v1.48.0, ISC; \"history\" is its alias rotate-ccw-clock) — a\n// host that draws the same name with lucide-react sees the same glyph. Exhaustive by type:\n// a new name fails typecheck here until it is drawn.\n\nimport type { SVGAttributes } from \"react\";\nimport type { ObjectActionIcon } from \"./objectActions\";\n\ntype Glyph = ReadonlyArray<readonly [string, Record<string, string | number>]>;\n\nconst GLYPHS: Record<ObjectActionIcon, Glyph> = {\n \"folder-open\": [[\"path\",{\"d\":\"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2\"}]],\n \"external-link\": [[\"path\",{\"d\":\"M15 3h6v6\"}],[\"path\",{\"d\":\"M10 14 21 3\"}],[\"path\",{\"d\":\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"}]],\n \"link\": [[\"path\",{\"d\":\"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\"}],[\"path\",{\"d\":\"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\"}]],\n \"pencil\": [[\"path\",{\"d\":\"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\"}],[\"path\",{\"d\":\"m15 5 4 4\"}]],\n \"copy\": [[\"rect\",{\"width\":\"14\",\"height\":\"14\",\"x\":\"8\",\"y\":\"8\",\"rx\":\"2\",\"ry\":\"2\"}],[\"path\",{\"d\":\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"}]],\n \"folder-input\": [[\"path\",{\"d\":\"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1\"}],[\"path\",{\"d\":\"M2 13h10\"}],[\"path\",{\"d\":\"m9 16 3-3-3-3\"}]],\n \"star\": [[\"path\",{\"d\":\"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z\"}]],\n \"star-off\": [[\"path\",{\"d\":\"m10.344 4.688 1.181-2.393a.53.53 0 0 1 .95 0l2.31 4.679a2.12 2.12 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.237 3.152\"}],[\"path\",{\"d\":\"m17.945 17.945.43 2.505a.53.53 0 0 1-.771.56l-4.618-2.428a2.12 2.12 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a8 8 0 0 0 .4-.099\"}],[\"path\",{\"d\":\"m2 2 20 20\"}]],\n \"share-2\": [[\"circle\",{\"cx\":\"18\",\"cy\":\"5\",\"r\":\"3\"}],[\"circle\",{\"cx\":\"6\",\"cy\":\"12\",\"r\":\"3\"}],[\"circle\",{\"cx\":\"18\",\"cy\":\"19\",\"r\":\"3\"}],[\"line\",{\"x1\":\"8.59\",\"x2\":\"15.42\",\"y1\":\"13.51\",\"y2\":\"17.49\"}],[\"line\",{\"x1\":\"15.41\",\"x2\":\"8.59\",\"y1\":\"6.51\",\"y2\":\"10.49\"}]],\n \"download\": [[\"path\",{\"d\":\"M12 15V3\"}],[\"path\",{\"d\":\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"}],[\"path\",{\"d\":\"m7 10 5 5 5-5\"}]],\n \"upload\": [[\"path\",{\"d\":\"M12 3v12\"}],[\"path\",{\"d\":\"m17 8-5-5-5 5\"}],[\"path\",{\"d\":\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"}]],\n \"columns-3\": [[\"rect\",{\"width\":\"18\",\"height\":\"18\",\"x\":\"3\",\"y\":\"3\",\"rx\":\"2\"}],[\"path\",{\"d\":\"M9 3v18\"}],[\"path\",{\"d\":\"M15 3v18\"}]],\n \"settings\": [[\"path\",{\"d\":\"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915\"}],[\"circle\",{\"cx\":\"12\",\"cy\":\"12\",\"r\":\"3\"}]],\n \"history\": [[\"path\",{\"d\":\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\"}],[\"path\",{\"d\":\"M3 3v5h5\"}],[\"path\",{\"d\":\"M12 7v5l4 2\"}]],\n \"blocks\": [[\"path\",{\"d\":\"M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2\"}],[\"rect\",{\"x\":\"14\",\"y\":\"2\",\"width\":\"8\",\"height\":\"8\",\"rx\":\"1\"}]],\n \"file-text\": [[\"path\",{\"d\":\"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\"}],[\"path\",{\"d\":\"M14 2v5a1 1 0 0 0 1 1h5\"}],[\"path\",{\"d\":\"M10 9H8\"}],[\"path\",{\"d\":\"M16 13H8\"}],[\"path\",{\"d\":\"M16 17H8\"}]],\n \"calendar-clock\": [[\"path\",{\"d\":\"M16 14v2.2l1.6 1\"}],[\"path\",{\"d\":\"M16 2v3\"}],[\"path\",{\"d\":\"M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338\"}],[\"path\",{\"d\":\"M3 9h5.859\"}],[\"path\",{\"d\":\"M8 2v3\"}],[\"circle\",{\"cx\":\"16\",\"cy\":\"16\",\"r\":\"6\"}]],\n \"list-checks\": [[\"path\",{\"d\":\"M13 5h8\"}],[\"path\",{\"d\":\"M13 12h8\"}],[\"path\",{\"d\":\"M13 19h8\"}],[\"path\",{\"d\":\"m3 17 2 2 4-4\"}],[\"path\",{\"d\":\"m3 7 2 2 4-4\"}]],\n \"bell\": [[\"path\",{\"d\":\"M10.268 21a2 2 0 0 0 3.464 0\"}],[\"path\",{\"d\":\"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326\"}]],\n \"door-open\": [[\"path\",{\"d\":\"M10 21H2\"}],[\"path\",{\"d\":\"M10 3H7a2 2 0 00-2 2v16\"}],[\"path\",{\"d\":\"M14 12h.01\"}],[\"path\",{\"d\":\"M19 21V5a2 2 0 00-1.675-1.974l-6.163-1.013A1 1 0 0010 3v18a1 1 0 001.124.992z\"}],[\"path\",{\"d\":\"M22 21h-3\"}]],\n \"inbox\": [[\"polyline\",{\"points\":\"22 12 16 12 14 15 10 15 8 12 2 12\"}],[\"path\",{\"d\":\"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z\"}]],\n \"layout-dashboard\": [[\"rect\",{\"width\":\"7\",\"height\":\"9\",\"x\":\"3\",\"y\":\"3\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"5\",\"x\":\"14\",\"y\":\"3\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"9\",\"x\":\"14\",\"y\":\"12\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"5\",\"x\":\"3\",\"y\":\"16\",\"rx\":\"1\"}]],\n \"archive-restore\": [[\"rect\",{\"width\":\"20\",\"height\":\"5\",\"x\":\"2\",\"y\":\"3\",\"rx\":\"1\"}],[\"path\",{\"d\":\"M4 8v11a2 2 0 0 0 2 2h2\"}],[\"path\",{\"d\":\"M20 8v11a2 2 0 0 1-2 2h-2\"}],[\"path\",{\"d\":\"m9 15 3-3 3 3\"}],[\"path\",{\"d\":\"M12 12v9\"}]],\n \"archive\": [[\"rect\",{\"width\":\"20\",\"height\":\"5\",\"x\":\"2\",\"y\":\"3\",\"rx\":\"1\"}],[\"path\",{\"d\":\"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8\"}],[\"path\",{\"d\":\"M10 12h4\"}]],\n \"link-2\": [[\"path\",{\"d\":\"M9 17H7A5 5 0 0 1 7 7h2\"}],[\"path\",{\"d\":\"M15 7h2a5 5 0 1 1 0 10h-2\"}],[\"line\",{\"x1\":\"8\",\"x2\":\"16\",\"y1\":\"12\",\"y2\":\"12\"}]],\n \"layout-grid\": [[\"rect\",{\"width\":\"7\",\"height\":\"7\",\"x\":\"3\",\"y\":\"3\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"7\",\"x\":\"14\",\"y\":\"3\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"7\",\"x\":\"14\",\"y\":\"14\",\"rx\":\"1\"}],[\"rect\",{\"width\":\"7\",\"height\":\"7\",\"x\":\"3\",\"y\":\"14\",\"rx\":\"1\"}]],\n \"git-merge\": [[\"circle\",{\"cx\":\"18\",\"cy\":\"18\",\"r\":\"3\"}],[\"circle\",{\"cx\":\"6\",\"cy\":\"6\",\"r\":\"3\"}],[\"path\",{\"d\":\"M6 21V9a9 9 0 0 0 9 9\"}]],\n \"split\": [[\"path\",{\"d\":\"M16 3h5v5\"}],[\"path\",{\"d\":\"M8 3H3v5\"}],[\"path\",{\"d\":\"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3\"}],[\"path\",{\"d\":\"m15 9 6-6\"}]],\n \"arrow-up-from-line\": [[\"path\",{\"d\":\"m18 9-6-6-6 6\"}],[\"path\",{\"d\":\"M12 3v14\"}],[\"path\",{\"d\":\"M5 21h14\"}]],\n \"corner-down-right\": [[\"polyline\",{\"points\":\"15 10 20 15 15 20\"}],[\"path\",{\"d\":\"M4 4v7a4 4 0 0 0 4 4h12\"}]],\n \"lock\": [[\"rect\",{\"width\":\"18\",\"height\":\"11\",\"x\":\"3\",\"y\":\"11\",\"rx\":\"2\",\"ry\":\"2\"}],[\"path\",{\"d\":\"M7 11V7a5 5 0 0 1 10 0v4\"}]],\n \"lock-open\": [[\"rect\",{\"width\":\"18\",\"height\":\"11\",\"x\":\"3\",\"y\":\"11\",\"rx\":\"2\",\"ry\":\"2\"}],[\"path\",{\"d\":\"M7 11V7a5 5 0 0 1 9.9-1\"}]],\n \"eraser\": [[\"path\",{\"d\":\"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21\"}],[\"path\",{\"d\":\"M22 21H7\"}],[\"path\",{\"d\":\"m5 11 9 9\"}]],\n \"printer\": [[\"path\",{\"d\":\"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\"}],[\"path\",{\"d\":\"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6\"}],[\"rect\",{\"x\":\"6\",\"y\":\"14\",\"width\":\"12\",\"height\":\"8\",\"rx\":\"1\"}]],\n};\n\nexport function ObjectActionGlyph({ name, ...props }: { name: ObjectActionIcon } & SVGAttributes<SVGSVGElement>) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n data-object-action-icon={name}\n {...props}\n >\n {GLYPHS[name].map(([tag, attrs], i) => {\n const El = tag as \"path\";\n return <El key={i} {...(attrs as SVGAttributes<SVGPathElement>)} />;\n })}\n </svg>\n );\n}\n","\"use client\";\n\n// src/WhereItLives.tsx — @ai-matrx/records-ui (lanes SC-1' / SC-1-TAILS)\n//\n// THE ONE UI BUILDER FOR \"WHICH ORGANIZATION IS THIS IN, AND MOVE IT\".\n//\n// The owner, 2026-09-23: \"I am not seeing how I can see what org this data is in. Is there an easy\n// way to see that or do we need to add something that makes it easy to see and set the org for\n// something?\" A chip that names the organization a Table lives in — read FROM THE TABLE through\n// `client.tableHome` (custom.table_home), never from the organization the screen is bound to —\n// and, on press, says what the store says: who may move it, what holds it where it is, and each\n// of the person's other organizations with either a Move button or the sentence why it cannot go\n// there. Picking one says the consequence first (what rides along, who stops seeing it) in the\n// same panel, and only \"Move it\" asks `client.tableMove`, which moves it or hands back the store's\n// one sentence, shown as it came.\n//\n// It lived in matrx-frontend first (features/unified-data/where-it-lives). It is here because the\n// package's own screens (TablesHome) list tables too, and a package screen cannot reach a host\n// component: one builder, in the one place every host can mount it.\n//\n// Champion: Notion's \"Move to\" (every page names its workspace in the breadcrumb and moves from the\n// same place) and Linear's \"Move to team\" (the consequence is said before the move).\n\nimport { useEffect, useState } from \"react\";\nimport type { TableHome, TableHomeDestination, Uuid } from \"@ai-matrx/records\";\nimport { moveConsequence } from \"@ai-matrx/records\";\nimport { useRecordsClient } from \"@ai-matrx/records/react\";\nimport { useRecordsUi } from \"./host\";\nimport { hintForAPerson } from \"./Refusal\";\nimport { Button, ErrorBox, Popover, PopoverContent, PopoverTrigger } from \"@ai-matrx/design-system\";\nimport { refusalSaid } from \"./refusalSaid\";\n\ntype Answer =\n | { state: \"found\"; home: TableHome }\n /** Not given to this person — or not there. The store says the same for both, on purpose. */\n | { state: \"not-given\" }\n /** The door is not on this database yet. Said, never a pretend organization. */\n | { state: \"door-absent\" }\n /** We could not ask. NOT an answer about the person's access. */\n | { state: \"unavailable\"; why: string };\n\nexport interface WhereItLivesProps {\n tableId: Uuid;\n /**\n * The name the screen already holds (a list whose rows all live in one organization), shown\n * until the store answers — and, on a row, instead of asking at all until the chip is pressed:\n * forty rows are not forty reads.\n */\n knownOrganizationName?: string | null | undefined;\n /** After a move lands: the host re-reads (the list, its rows, the page). */\n onMoved?: ((to: { id: Uuid; name: string }) => void) | undefined;\n /**\n * `row` is quieter, for a list; `header` for an object page's own row; `title` rides the page\n * header beside the object's name (Linear's team beside the issue title) — no frame, muted.\n */\n /**\n * `anchor` draws no chip at all: the panel opens over the place it is mounted when `openAsked`\n * increases — the table menu's \"Move to…\" (lane TABLE-ACTIONS) opens this same panel.\n */\n variant?: \"header\" | \"row\" | \"title\" | \"anchor\" | undefined;\n /** Each increase opens the panel (the menu's \"Move to…\"). */\n openAsked?: number | undefined;\n}\n\nexport function WhereItLives({ tableId, knownOrganizationName, onMoved, variant = \"header\", openAsked = 0 }: WhereItLivesProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const [answer, setAnswer] = useState<Answer | null>(null);\n const [attempt, setAttempt] = useState(0);\n const [open, setOpen] = useState(false);\n const [armed, setArmed] = useState(variant === \"anchor\" ? false : variant !== \"row\" || !knownOrganizationName);\n useEffect(() => {\n if (openAsked <= 0) return;\n setArmed(true);\n setOpen(true);\n }, [openAsked]);\n const [choosing, setChoosing] = useState<TableHomeDestination | null>(null);\n const [moving, setMoving] = useState(false);\n const [said, setSaid] = useState<{ tone: \"done\" | \"refused\"; text: string } | null>(null);\n\n useEffect(() => {\n if (!armed) return;\n let alive = true;\n setAnswer(null);\n void client.tableHome({ table_id: tableId }).then((answered) => {\n if (!alive) return;\n if (answered.ok) {\n setAnswer(answered.data ? { state: \"found\", home: answered.data } : { state: \"not-given\" });\n } else if (answered.error.code === \"door_absent\") {\n setAnswer({ state: \"door-absent\" });\n } else {\n setAnswer({ state: \"unavailable\", why: refusalSaid(answered.error) });\n }\n });\n return () => {\n alive = false;\n };\n }, [client, tableId, attempt, armed]);\n\n const home = answer?.state === \"found\" ? answer.home : null;\n const name = home?.organization.name ?? knownOrganizationName ?? null;\n // Absent, never a blank or a guess.\n const label =\n name ??\n (answer === null || !armed\n ? \"Reading where this lives…\"\n : answer.state === \"not-given\"\n ? \"Not shared with you\"\n : answer.state === \"door-absent\"\n ? \"Its organization is not named here yet\"\n : \"Could not ask where this lives\");\n\n async function move(to: TableHomeDestination) {\n if (!home) return;\n setMoving(true);\n const moved = await client.tableMove({\n table_id: home.table.id,\n to_organization_id: to.id,\n expected_version: home.table.version,\n });\n setMoving(false);\n if (!moved.ok) {\n // A REFUSAL IS SAID WHERE SHE PRESSED, AND THE PANEL STAYS (MOVE-AND-OUTSIDER, VERIFIER-19\n // finding 1: the panel closed and the screen said nothing). The store's own sentence, then\n // its remedy when it gave one, on the same confirm — so \"Try again\" and \"Cancel\" are right\n // there. Nothing is re-read: a re-read would swap the panel for \"Asking…\" under her.\n // A hint written for an engineer (a lane codename, a SQLSTATE) is never shown (UI-FIX-19).\n const hint = hintForAPerson(moved.error.hint);\n const sentence = refusalSaid(moved.error);\n setSaid({ tone: \"refused\", text: `Nothing moved. ${sentence}${hint && !sentence.includes(hint) ? ` ${hint}` : \"\"}` });\n return;\n }\n setChoosing(null);\n const done = `${moved.data.tableName} now lives in ${moved.data.to.name}.`;\n // THE CONFIRMATION OUTLIVES THE HOST'S RE-READ (UI-FIX-19, MOVE-AND-OUTSIDER). `onMoved` makes\n // a host re-read, and an object page re-mounts its header — this chip with it — so a sentence\n // held in this chip's state died unread: the person saw the new organization's name and no\n // \"it moved\". The host's toasts live outside the page, so when the host binds them the\n // sentence is said THERE, and only there (one home per sentence); unbound, it is said here.\n if (host.notify) host.notify.success(done);\n else setSaid({ tone: \"done\", text: done });\n setAttempt((n) => n + 1);\n onMoved?.(moved.data.to);\n }\n\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n if (next) setArmed(true);\n if (!next) {\n setChoosing(null);\n setSaid(null);\n }\n setOpen(next);\n }}\n >\n <PopoverTrigger asChild>\n {variant === \"anchor\" ? (\n <span aria-hidden className=\"pointer-events-none inline-block h-0 w-0\" data-where-it-lives-anchor={tableId} />\n ) : (\n <button\n type=\"button\"\n data-where-it-lives={tableId}\n data-where-it-lives-organization={home?.organization.id ?? \"\"}\n onClick={(e) => e.stopPropagation()}\n className={\n variant === \"row\"\n ? \"inline-flex max-w-[14rem] items-center gap-1 rounded px-1 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground\"\n : variant === \"title\"\n ? \"inline-flex min-w-0 max-w-full items-center gap-1 rounded px-1 text-[11px] font-normal text-muted-foreground hover:bg-muted hover:text-foreground sm:text-xs\"\n : \"inline-flex max-w-[28rem] items-center gap-1 rounded-md border border-border bg-muted/40 px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground\"\n }\n title={name ? `Lives in ${name}` : label}\n >\n <svg aria-hidden viewBox=\"0 0 24 24\" className=\"h-3 w-3 shrink-0\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n <rect x=\"4\" y=\"2\" width=\"16\" height=\"20\" rx=\"2\" />\n <path d=\"M9 22v-4h6v4M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01\" />\n </svg>\n <span className=\"truncate\">{label}</span>\n </button>\n )}\n </PopoverTrigger>\n <PopoverContent\n align=\"start\"\n className=\"w-80 p-3 text-xs\"\n onClick={(e) => e.stopPropagation()}\n // Only the person closes it (a press outside, Escape). Focus moving elsewhere — a toast,\n // the error pill, the grid re-rendering behind it — is not her closing it, and must never\n // take the store's answer off the screen.\n onFocusOutside={(e) => e.preventDefault()}\n >\n {answer === null ? (\n <p className=\"text-muted-foreground\">Finding where this table lives&hellip;</p>\n ) : answer.state === \"not-given\" ? (\n <p className=\"text-muted-foreground\">This table has not been shared with you, so where it lives is not yours to see.</p>\n ) : answer.state === \"door-absent\" || answer.state === \"unavailable\" ? (\n <div className=\"space-y-2\">\n {knownOrganizationName ? (\n <p>\n Lives in <span className=\"font-medium text-foreground\">{knownOrganizationName}</span>.\n </p>\n ) : null}\n <p className=\"text-muted-foreground\">\n {answer.state === \"door-absent\"\n ? \"Moving it to another organization is not available on this database yet.\"\n : `Where this lives could not be found, so nothing here says anything about your access. ${answer.why}`}\n </p>\n {answer.state === \"unavailable\" ? (\n <Button size=\"sm\" variant=\"outline\" className=\"h-7 text-xs\" onClick={() => setAttempt((n) => n + 1)}>\n Ask again\n </Button>\n ) : null}\n </div>\n ) : (\n <div className=\"space-y-2\" data-where-it-lives-panel={answer.home.table.id}>\n <p>\n <span className=\"text-muted-foreground\">{answer.home.table.name} lives in </span>\n <span className=\"font-medium text-foreground\">{answer.home.organization.name}</span>.\n </p>\n {said && !(said.tone === \"refused\" && choosing) ? (\n <p data-where-it-lives-said={said.tone} className={said.tone === \"refused\" ? \"text-destructive\" : \"text-foreground\"}>\n {said.text}\n </p>\n ) : null}\n {choosing ? (\n // THE CONSEQUENCE, SAID BEFORE THE MOVE, in the same panel — no second dialog.\n <div className=\"space-y-2\" data-where-it-lives-confirm={choosing.id}>\n <p className=\"font-medium text-foreground\">\n Move {answer.home.table.name} to {choosing.name}\n <SharedNameAddress to={choosing} all={answer.home.destinations} />?\n </p>\n <p className=\"text-muted-foreground\">{moveConsequence(answer.home, choosing)}</p>\n {said?.tone === \"refused\" ? (\n <ErrorBox\n data-where-it-lives-said=\"refused\"\n className=\"text-destructive\"\n message={said.text}\n operation={`Move ${answer.home.table.name} to ${choosing.name}`}\n origin=\"records-ui/WhereItLives\"\n />\n ) : null}\n <div className=\"flex gap-2\">\n <Button size=\"sm\" className=\"h-7 text-xs\" disabled={moving} onClick={() => void move(choosing)}>\n {moving ? `Moving to ${choosing.name}…` : said?.tone === \"refused\" ? \"Try again\" : \"Move it\"}\n </Button>\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-7 text-xs\"\n disabled={moving}\n onClick={() => {\n // Back to the list, re-read: what the store says now may differ from before.\n const wasRefused = said?.tone === \"refused\";\n setChoosing(null);\n setSaid(null);\n if (wasRefused) setAttempt((n) => n + 1);\n }}\n >\n Cancel\n </Button>\n </div>\n </div>\n ) : !answer.home.mayMove ? (\n <p className=\"text-muted-foreground\">{answer.home.whyNot}</p>\n ) : answer.home.heldBy.length > 0 ? (\n <div className=\"space-y-1\">\n <p className=\"font-medium text-foreground\">It cannot move yet:</p>\n <ul className=\"list-disc space-y-1 pl-4 text-muted-foreground\">\n {answer.home.heldBy.map((line) => (\n <li key={line}>{line}</li>\n ))}\n </ul>\n </div>\n ) : answer.home.destinations.length === 0 ? (\n <p className=\"text-muted-foreground\">You are not a member of any other organization, so there is nowhere else to move it.</p>\n ) : (\n <div className=\"space-y-1\">\n <p className=\"font-medium text-foreground\">Move it to</p>\n <ul className=\"max-h-64 space-y-1 overflow-y-auto pr-1\">\n {answer.home.destinations.map((to) => (\n <li key={to.id}>\n {to.ok ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"h-7 w-full justify-start text-xs\"\n data-where-it-lives-move={to.id}\n onClick={() => {\n setSaid(null);\n setChoosing(to);\n }}\n >\n {to.name}\n <SharedNameAddress to={to} all={answer.home.destinations} />\n </Button>\n ) : (\n <p className=\"text-muted-foreground\">\n <span className=\"text-foreground\">{to.name}</span>\n <SharedNameAddress to={to} all={answer.home.destinations} /> &mdash; {to.why}\n </p>\n )}\n </li>\n ))}\n </ul>\n </div>\n )}\n </div>\n )}\n </PopoverContent>\n </Popover>\n );\n}\n\n/**\n * THE SAME NAME, TOLD APART (UI-FIX-19, VERIFIER-19 #9). A destination whose name another\n * destination also carries is drawn with its web address — the way GitHub shows owner/name — so\n * three organizations called \"Ironclad Mobile Mechanic\" are three rows a person can tell apart.\n * A list of distinct names is unchanged.\n */\nexport function sharedNameAddress(\n to: Pick<TableHomeDestination, \"id\" | \"name\" | \"slug\">,\n all: ReadonlyArray<Pick<TableHomeDestination, \"id\" | \"name\">>,\n): string | null {\n const name = to.name.trim();\n if (!all.some((other) => other.id !== to.id && other.name.trim() === name)) return null;\n return to.slug ?? to.id.slice(0, 8);\n}\n\nfunction SharedNameAddress({\n to,\n all,\n}: {\n to: Pick<TableHomeDestination, \"id\" | \"name\" | \"slug\">;\n all: ReadonlyArray<Pick<TableHomeDestination, \"id\" | \"name\">>;\n}) {\n const address = sharedNameAddress(to, all);\n return address ? (\n <span className=\"ml-1.5 font-normal text-muted-foreground\" data-where-it-lives-address=\"\">\n {address}\n </span>\n ) : 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/writeOnTheWinningVersion.ts — @ai-matrx/records-ui · moved whole to @ai-matrx/records/versions (2026-10-08); one instance (askOnce's cache) for both packages.\nexport * from \"@ai-matrx/records/versions\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,aAAAA,YAAW,WAAAC,UAAS,UAAAC,SAAQ,YAAAC,iBAAgB;AACrD,SAAS,oBAAAC,mBAAkB,eAAAC,cAAa,aAAAC,kBAA4B;AAEpE;AAAA,EACE,UAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,E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,cAAc,YAAY,OAAe,IAAI,UAAU;AAAA;AAAA,UAJjE,GAAG,OAAO,IAAI,KAAK,IAAI,KAAK;AAAA,QAKnC,IACE;AAAA,SACN;AAAA,OAEJ;AAAA,KAEJ;AAEJ;","names":["useEffect","useMemo","useRef","useState","useRecordsClient","useMyLevels","useTables","Button","Checkbox","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","relationNameKey","predictValueRefusals","cell","predictValueRefusals","best","titleKey","titleTakesWords","relationNameKey","at","inFileOrder","take","refusalOf","table","useEffect","useState","useRecordsClient","Button","Skeleton","cn","useCallback","useMemo","useState","useRecordsClient","Button","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","parseDelimited","toDelimited","cell","Fragment","jsx","jsxs","useRecordsClient","useState","useMemo","useCallback","Button","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","cn","copyText","useCallback","useEffect","useMemo","useState","useRecordsClient","bookingPath","Badge","Button","Skeleton","cn","useCallback","useEffect","useMemo","useRef","useState","useFields","useRecordsClient","useTable","BasicInput","Button","Label","cn","Select","BasicInput","Label","jsx","jsxs","Fragment","jsx","jsxs","useRecordsClient","useTable","useFields","useState","useRef","useMemo","useCallback","useEffect","cn","Button","Label","BasicInput","Select","Button","cn","jsx","jsxs","useCallback","useEffect","useState","useRecordsClient","Button","jsx","Fragment","jsx","jsxs","jsx","jsxs","useRecordsClient","done","Button","useState","useCallback","useEffect","Fragment","jsx","jsxs","tableName","useRecordsClient","useState","useCallback","useEffect","useMemo","copyText","Skeleton","cn","Button","bookingPath","Badge","useEffect","useState","useRecordsClient","Button","ErrorBox","jsx","jsxs","useRecordsClient","useState","useEffect","Button","ErrorBox","jsx","jsxs","useRecordsClient","useState","useEffect","cn","Button","Skeleton","Fragment","jsx","jsxs","typeWord","useRecordsClient","useMemo","useState","useTables","useMyLevels","useRef","useEffect","cn","refusalOf","tableName","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Button","Checkbox"]}
1
+ {"version":3,"sources":["../src/SaveToTable.tsx","../src/unfinishedTable.ts","../src/ImportWizard.tsx","../src/importRuleCheck.ts","../src/pasteValues.ts","../src/importKinds.ts","../src/importCombine.ts","../src/importRefusals.ts","../src/TablesHome.tsx","../src/NewTableStart.tsx","../src/newTableColumns.ts","../src/importFileRead.ts","../src/BookingSlots.tsx","../src/BookingBuilder.tsx","../src/bookingMessages.ts","../src/publicQuestions.ts","../src/TimeZoneInput.tsx","../src/BuildOrAsk.tsx","../src/BuiltOnArchive.tsx","../src/ObjectActionMenuItems.tsx","../src/objectActionIcons.tsx","../src/WhereItLives.tsx","../src/tableLanes.ts","../src/writeOnTheWinningVersion.ts"],"sourcesContent":["\"use client\";\n\n// src/SaveToTable.tsx — @ai-matrx/records-ui · lane SAVE-AS-TABLE-EVERYWHERE\n//\n// SAVE WHAT YOU ARE LOOKING AT AS A TABLE — THE ONE SCREEN. Arman, 2026-09-29: anywhere\n// information appears in a shape the system understands (a markdown table, a list or a few bullet\n// points, key:value lines, a CSV/TSV paste, a kind value, an agent's answer, a note, a transcript\n// section, a form result) the SAME action exists — save it as a new table, or add its rows to a\n// table you already have with the columns matched. Every menu in every host opens THIS screen; no\n// surface builds its own.\n//\n// WHAT IT DOES AND WHOSE DOORS IT USES.\n// · The rows are read by `readTableShapes` (the one shape reader) — a list offers its splits.\n// · A NEW table: the person sees every column's label and proposed type (`guessColumn`) and\n// changes any of it; \"Make the table\" is `declareTable` (the one birth — the store takes the\n// declared types and mints nothing a person sees), then the rows go through the store's import\n// doors (`importBegin` / `importRows` / `importFinish`) exactly as a file's do, with the rows'\n// sha-256 as the run's identity, so saving the same answer twice writes nothing and says so.\n// · AN EXISTING table: `ImportWizard` with these rows as its source — the store's plan matches\n// the columns by name, offers the ones the table lacks, asks about choice words it does not\n// know (the enum ask), and reports what landed.\n// There is no write here that the file import, the grid's paste or the agent's `import_propose`\n// does not also make.\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useRecordsClient, useMyLevels, useTables, type Uuid } from \"@ai-matrx/records/react\";\nimport type { RecordsError } from \"@ai-matrx/records\";\nimport {\n Button,\n Checkbox,\n ConfirmDialog,\n Input,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { addFields, declareTable, tokenFor, type NewFieldSpec } from \"./createTable\";\nimport { choiceWordsOwed, findUnfinishedTable } from \"./unfinishedTable\";\nimport { ImportWizard } from \"./ImportWizard\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { refusal as refusalOf, refusalFromThrown } from \"./refusals\";\nimport { fieldTypeChoice } from \"./fieldTypes\";\nimport { laneFor } from \"./TablesHome\";\nimport {\n guessColumn,\n readTableShapes,\n shapeOfGrid,\n shapeOfValue,\n type ColumnGuess,\n type GuessedFieldType,\n type TableShape,\n} from \"./tableShape\";\nimport { tablePickerEntries } from \"./tablePicking\";\nimport { changeRecordsAt, readTableVersionNow } from \"./recordVersions\";\nimport { updateOnTheWinningVersion } from \"./writeOnTheWinningVersion\";\n\n/** What the person is saving. Exactly one of `text`, `value` or `grid` carries the rows. */\nexport interface SaveToTableSource {\n /** Markdown, a CSV or TSV paste, a note, an answer — every shape in it is offered. */\n text?: string | undefined;\n /** A kind value or JSON rows. */\n value?: unknown;\n /** Rows a host already holds (a rendered table's headers and cells). */\n grid?: { headers: string[]; rows: string[][]; /** What the rows came out of (\"table\", \"sheet\"); the offered line says \"from a <it>\". Default \"table\". */ from?: string | undefined } | undefined;\n /** What it came from, in words — the name a new table is offered, and the import's source name. */\n title?: string | null | undefined;\n}\n\nexport interface SaveToTableProps {\n source: SaveToTableSource;\n /** When the text holds several shapes, the one to open on (the one the person right-clicked). */\n shapeIndex?: number | undefined;\n /** Open a table (after it was made, or rows were added). Absent: no \"Open\" button is drawn. */\n onOpenTable?: ((tableId: Uuid) => void) | undefined;\n /** The rows landed — `new` when this screen made the table. */\n onSaved?: ((tableId: Uuid, how: \"new\" | \"existing\") => void) | undefined;\n /** The person is finished (the report's Done). */\n onClose?: (() => void) | undefined;\n /**\n * \"Turn into a table\" — ONE click: make the new table at once with the proposed name and column\n * types (no form first), then show the result with Open. The screen stays the full one for a\n * person who wants to change it next time; this only presses \"Make the table\" for them.\n */\n makeAtOnce?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** The types a NEW table's column is offered here — the ones a text value can honestly be. */\nexport const SAVE_TO_TABLE_TYPES: readonly GuessedFieldType[] = [\n \"text\",\n \"long_text\",\n \"number\",\n \"currency\",\n \"percent\",\n \"datetime\",\n \"checkbox\",\n \"select\",\n \"email\",\n \"url\",\n \"phone\",\n];\n\ninterface ColumnDraft {\n header: string;\n label: string;\n guess: ColumnGuess;\n /** A choice column's words as the person edits them, comma separated. */\n options: string;\n /** Kept in the new table (the JSON dialog's \"Use\" box, adopted 2026-09-29). */\n use: boolean;\n}\n\n/** The shapes a source holds, top to bottom. */\nexport function shapesOfSource(source: SaveToTableSource): TableShape[] {\n if (source.grid) {\n const s = shapeOfGrid(source.grid.headers, source.grid.rows, source.title ?? null, source.grid.from);\n return s ? [s] : [];\n }\n if (source.value !== undefined) {\n const s = shapeOfValue(source.value, source.title ?? null);\n return s ? [s] : [];\n }\n return readTableShapes(source.text ?? \"\");\n}\n\nfunction draftsFor(headers: string[], rows: Array<Record<string, string>>): ColumnDraft[] {\n return headers.map((header) => {\n const guess = guessColumn(rows.map((r) => r[header] ?? \"\"));\n return { header, label: header, guess, options: (guess.options ?? []).join(\", \"), use: true };\n });\n}\n\n/** Unique keys from labels: the store's own token rule, a second \"notes\" becomes `notes_2`. */\nfunction keysFor(labels: string[]): string[] {\n const used = new Set<string>();\n return labels.map((label, i) => {\n const base = tokenFor(label) === \"table\" && !/table/i.test(label) ? `column_${i + 1}` : tokenFor(label);\n let key = base;\n let n = 2;\n while (used.has(key)) key = `${base}_${n++}`;\n used.add(key);\n return key;\n });\n}\n\n/** A name no table of yours already has: \"Home exercises\" → \"Home exercises 2\". */\nfunction freeName(name: string, taken: readonly string[]): string {\n const lower = new Set(taken.map((t) => t.trim().toLowerCase()));\n const base = name.trim() || \"Saved table\";\n if (!lower.has(base.toLowerCase())) return base;\n for (let n = 2; n < 100; n += 1) if (!lower.has(`${base} ${n}`.toLowerCase())) return `${base} ${n}`;\n return `${base} ${Date.now()}`;\n}\n\nasync function sha256Text(text: string): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction typeWord(t: GuessedFieldType): string {\n return fieldTypeChoice(t)?.label ?? t;\n}\n\nexport function SaveToTable({ source, shapeIndex = 0, onOpenTable, onSaved, onClose, makeAtOnce = false, className }: SaveToTableProps) {\n const client = useRecordsClient();\n const shapes = useMemo(() => shapesOfSource(source), [source]);\n const [which, setWhich] = useState(() => Math.min(Math.max(0, shapeIndex), Math.max(0, shapes.length - 1)));\n const shape = shapes[which] ?? null;\n const [split, setSplit] = useState<string>(\"\");\n const reading = shape?.splits.find((s) => s.delimiter === split) ?? null;\n const headers = reading?.headers ?? shape?.headers ?? [];\n const rows = reading?.rows ?? shape?.rows ?? [];\n\n const [target, setTarget] = useState<\"new\" | \"existing\">(\"new\");\n const tables = useTables();\n // Tables a person keeps (`tablePicking.ts`) — never a platform table or one the app keeps.\n const own = tablePickerEntries(tables.data ?? [])\n .entries.map((e) => e.table)\n .filter((t) => laneFor(t) !== \"system\");\n const levels = useMyLevels(own.map((t) => t.id));\n const writable = own\n .filter((t) => {\n const level = levels.data?.[t.id];\n return level === \"edit_content\" || level === \"editor\" || level === \"admin\";\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n const [tableId, setTableId] = useState<string>(\"\");\n\n const proposedName = shape?.name ?? source.title ?? \"Saved table\";\n const [name, setName] = useState<string | null>(null);\n // ADOPTED FROM THE DIALOGS THIS SCREEN REPLACED (2026-09-29): a new table's description (the\n // \"Save as data\" dialog and the JSON dialog both had one), and — for rows added to a table the\n // person has — \"replace what it holds\", done as an archive the person confirms first.\n const [description, setDescription] = useState(\"\");\n const [replaceAsked, setReplaceAsked] = useState(false);\n const [replacing, setReplacing] = useState(false);\n const [replaced, setReplaced] = useState<{ tableId: string; count: number } | null>(null);\n const [drafts, setDrafts] = useState<ColumnDraft[] | null>(null);\n const columns = drafts ?? draftsFor(headers, rows);\n const [problem, setProblem] = useState<RecordsError | null>(null);\n const [phase, setPhase] = useState<\"ready\" | \"making\" | \"writing\" | \"done\">(\"ready\");\n const [made, setMade] = useState<{ tableId: Uuid; sentence: string } | null>(null);\n\n const sourceName = source.title?.trim() || shape?.name || \"the rows above\";\n // makeAtOnce: press \"Make the table\" once, as soon as the person's tables are known (so the new\n // name never collides with one they have).\n const makeRef = useRef<(() => Promise<void>) | null>(null);\n const madeAtOnce = useRef(false);\n const tablesKnown = tables.data !== undefined;\n useEffect(() => {\n if (!makeAtOnce || madeAtOnce.current || !shape || !tablesKnown || !makeRef.current) return;\n madeAtOnce.current = true;\n void makeRef.current();\n }, [makeAtOnce, shape, tablesKnown]);\n const sourceText = useMemo(() => JSON.stringify({ headers, rows }), [headers, rows]);\n // ONE object per reading, so the wizard plans these rows once — a fresh object every render would\n // be a fresh source every render.\n const wizardSource = useMemo(\n () => ({ name: sourceName, parsed: { headers, rows }, text: sourceText }),\n [sourceName, headers, rows, sourceText],\n );\n\n if (!shape) {\n return (\n <div className={cn(\"flex flex-col gap-2 text-sm\", className)} data-save-to-table=\"\">\n <p className=\"text-muted-foreground\">\n Nothing here reads as rows — a table, a list, lines of “Name: value”, CSV or pasted spreadsheet cells can be\n saved as a table.\n </p>\n </div>\n );\n }\n\n const chooseShape = (i: number) => {\n setWhich(i);\n setSplit(\"\");\n setDrafts(null);\n setName(null);\n };\n\n const make = async () => {\n setProblem(null);\n const kept = columns.filter((c) => c.use);\n if (kept.length === 0) {\n setProblem(refusalOf(\"invalid_argument\", \"Every column is left out.\", \"Keep at least one column, then make the table.\"));\n return;\n }\n const labels = kept.map((c) => c.label.trim() || c.header);\n if (new Set(labels.map((l) => l.toLowerCase())).size !== labels.length) {\n setProblem(refusalOf(\"invalid_argument\", \"Two columns have the same name.\", \"Rename one of them, then make the table.\"));\n return;\n }\n const keys = keysFor(labels);\n const fields: NewFieldSpec[] = kept.map((c, i) => {\n const options = c.options.split(\",\").map((o) => o.trim()).filter(Boolean);\n return {\n key: keys[i]!,\n label: labels[i]!,\n type: c.guess.type,\n sort: (i + 1) * 10,\n ...(c.guess.type === \"select\" ? { options } : {}),\n ...(c.guess.type === \"currency\" && c.guess.unit ? { unit: c.guess.unit } : {}),\n ...(c.guess.type === \"datetime\" && c.guess.kind ? { kind: c.guess.kind } : {}),\n };\n });\n setPhase(\"making\");\n try {\n // AN EARLIER TRY THAT WAS CUT OFF (the page closed mid-make) IS FINISHED, NEVER DUPLICATED:\n // same name, made in the last day, no rows, no column this save lacks (`unfinishedTable.ts`).\n const earlier = await findUnfinishedTable(client, name ?? proposedName, fields.map((f) => f.key), rows.length);\n let tableName: string;\n let newId: Uuid;\n if (earlier) {\n tableName = (name ?? proposedName).trim();\n newId = earlier.tableId;\n const lacking = fields.filter((f) => !earlier.haveKeys.has(f.key));\n const added = await addFields(client, newId, lacking);\n if (!added.ok) {\n setProblem(added.error);\n setPhase(\"ready\");\n return;\n }\n // The earlier try's choice columns hold the words of ITS rows: top them up with this save's.\n const present = await client.fields({ table_id: newId });\n if (present.ok) {\n for (const owed of choiceWordsOwed(present.data, fields)) {\n const topped = await client.fieldUpdate({ field_id: owed.fieldId, patch: { options_add: owed.words } });\n if (!topped.ok) {\n setProblem(topped.error);\n setPhase(\"ready\");\n return;\n }\n }\n }\n } else {\n tableName = freeName(name ?? proposedName, (tables.data ?? []).map((t) => t.name));\n const born = await declareTable(client, { name: tableName, fields });\n if (!born.ok) {\n setProblem(born.error);\n setPhase(\"ready\");\n return;\n }\n newId = born.data;\n }\n if (description.trim()) {\n // The table's own description, written the way its settings write it; a refusal is said\n // beside the result and never undoes the table.\n // The table was just made here: its version is the one it was made at, read once.\n const described = await updateOnTheWinningVersion(\n client,\n newId,\n { description: description.trim() },\n await readTableVersionNow(client, newId),\n { description: null },\n );\n if (!described.ok) setProblem(described.error);\n }\n if (rows.length === 0) {\n setMade({ tableId: newId, sentence: `“${tableName}” was made with ${kept.length} column${kept.length === 1 ? \"\" : \"s\"} and no rows yet.` });\n setPhase(\"done\");\n onSaved?.(newId, \"new\");\n return;\n }\n setPhase(\"writing\");\n const mapping: Record<string, string> = {};\n kept.forEach((c, i) => {\n mapping[c.header] = keys[i]!;\n });\n const opened = await client.importBegin({\n table_id: newId,\n format: \"csv\",\n source_name: sourceName,\n source_columns: kept.map((c) => c.header),\n file_hash: await sha256Text(sourceText),\n file_bytes: sourceText.length,\n policy: { on_duplicate: \"skip\", unmapped: \"ignore\" },\n });\n if (!opened.ok) {\n setProblem(opened.error);\n setMade({ tableId: newId, sentence: `“${tableName}” was made, and its rows were not written.` });\n setPhase(\"done\");\n return;\n }\n // A column the person left out is not sent at all — not even for the store to ignore.\n const sent = rows.map((r) => Object.fromEntries(kept.map((c) => [c.header, r[c.header] ?? \"\"])));\n let take = opened.data.rows_per_call ?? 250;\n let at = 0;\n while (at < sent.length) {\n const batch = sent.slice(at, at + take);\n const answered = await client.importRows({ import_id: opened.data.import_id, rows: batch, mapping });\n if (!answered.ok) {\n setProblem(answered.error);\n break;\n }\n at += batch.length;\n if (answered.data.rows_per_call) take = answered.data.rows_per_call;\n }\n const finished = await client.importFinish({ import_id: opened.data.import_id, unmapped: \"ignore\" });\n const sentence = finished.ok\n ? `“${tableName}” was made with ${kept.length} column${kept.length === 1 ? \"\" : \"s\"}. ${finished.data.message}`\n : `“${tableName}” was made.`;\n if (!finished.ok) setProblem(finished.error);\n setMade({ tableId: newId, sentence });\n setPhase(\"done\");\n onSaved?.(newId, \"new\");\n } catch (thrown) {\n setProblem(refusalFromThrown(thrown, \"The table could not be made.\", \"Try again in a moment.\", \"internal\"));\n setPhase(\"ready\");\n }\n };\n\n makeRef.current = make;\n const busy = phase === \"making\" || phase === \"writing\";\n\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-3 text-sm\", className)} data-save-to-table=\"\">\n {/* WHAT WAS READ — and, when the text holds several shapes, which one. */}\n <div className=\"flex flex-wrap items-center gap-2\">\n {shapes.length > 1 ? (\n <Select value={String(which)} onValueChange={(v) => chooseShape(Number(v))} disabled={busy || phase === \"done\"}>\n <SelectTrigger size=\"sm\" aria-label=\"Which of these to save\" className=\"min-w-[16rem]\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {shapes.map((s, i) => (\n <SelectItem key={i} value={String(i)}>\n {s.name ? `${s.name} — ` : \"\"}\n {s.said}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <span className=\"text-muted-foreground\" data-save-to-table-said=\"\">\n {shape.name ? `${shape.name} — ` : \"\"}\n {shape.said}\n </span>\n )}\n {shape.splits.length > 0 ? (\n <Select\n value={split || \"__one__\"}\n onValueChange={(v) => {\n setSplit(v === \"__one__\" ? \"\" : v);\n setDrafts(null);\n }}\n disabled={busy || phase === \"done\"}\n >\n <SelectTrigger size=\"sm\" aria-label=\"How to read the list\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__one__\">One column</SelectItem>\n {shape.splits.map((s) => (\n <SelectItem key={s.delimiter} value={s.delimiter}>\n {s.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : null}\n </div>\n\n {/* THE ROWS, AS THEY WILL LAND — the first few, under the names they will have. */}\n <div className=\"max-h-48 overflow-auto rounded border\">\n <table className=\"w-full border-collapse text-xs\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n {columns.map((c) => (\n <th key={c.header} className=\"border-b px-2 py-1 text-left font-medium\">\n {c.label || c.header}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {rows.slice(0, 8).map((r, i) => (\n <tr key={i} className=\"border-b last:border-0\">\n {columns.map((c) => (\n <td key={c.header} className=\"max-w-[16rem] truncate px-2 py-1 align-top\">\n {r[c.header] ?? \"\"}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n {rows.length > 8 ? <p className=\"-mt-2 text-xs text-muted-foreground\">and {rows.length - 8} more</p> : null}\n\n {phase === \"done\" && made ? (\n <div className=\"flex flex-col gap-2\" data-save-to-table-done=\"\">\n <p>{made.sentence}</p>\n {problem ? <RefusalNotice error={problem} /> : null}\n <div className=\"flex gap-2\">\n {onOpenTable ? (\n <Button size=\"sm\" onClick={() => onOpenTable(made.tableId)}>\n Open the table\n </Button>\n ) : null}\n {onClose ? (\n <Button size=\"sm\" variant=\"outline\" onClick={onClose}>\n Done\n </Button>\n ) : null}\n </div>\n </div>\n ) : (\n <>\n {/* WHERE THE ROWS GO. */}\n <div className=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label=\"Where to save these rows\">\n <Button\n size=\"sm\"\n variant={target === \"new\" ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={target === \"new\"}\n disabled={busy}\n onClick={() => setTarget(\"new\")}\n >\n A new table\n </Button>\n <Button\n size=\"sm\"\n variant={target === \"existing\" ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={target === \"existing\"}\n disabled={busy}\n onClick={() => setTarget(\"existing\")}\n >\n Add to a table\n </Button>\n </div>\n\n {target === \"new\" ? (\n <div className=\"flex flex-col gap-2\" data-save-to-table-new=\"\">\n <label className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium\">Table name</span>\n <Input\n value={name ?? proposedName}\n onChange={(e) => setName(e.target.value)}\n disabled={busy}\n aria-label=\"Table name\"\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium\">Description (optional)</span>\n <Input\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n disabled={busy}\n aria-label=\"Table description\"\n placeholder=\"What these rows are for\"\n />\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium\">Columns</span>\n {columns.map((c, i) => (\n <div\n key={c.header}\n className=\"grid grid-cols-[auto_minmax(8rem,1fr)_minmax(9rem,12rem)] items-center gap-2\"\n data-save-to-table-column={c.header}\n >\n <Checkbox\n checked={c.use}\n disabled={busy}\n aria-label={`Keep the column ${c.label || c.header}`}\n onCheckedChange={(v) => setDrafts(columns.map((d, j) => (j === i ? { ...d, use: v === true } : d)))}\n />\n <Input\n value={c.label}\n aria-label={`Name of the column ${c.header}`}\n disabled={busy || !c.use}\n onChange={(e) =>\n setDrafts(columns.map((d, j) => (j === i ? { ...d, label: e.target.value } : d)))\n }\n />\n <Select\n value={c.guess.type}\n disabled={busy || !c.use}\n onValueChange={(v) =>\n setDrafts(\n columns.map((d, j) => {\n if (j !== i) return d;\n const type = v as GuessedFieldType;\n const again = guessColumn(rows.map((r) => r[d.header] ?? \"\"));\n const words = type === \"select\" && !d.options ? (again.options ?? Array.from(new Set(rows.map((r) => (r[d.header] ?? \"\").trim()).filter(Boolean)))).join(\", \") : d.options;\n return { ...d, guess: { ...d.guess, type }, options: words };\n }),\n )\n }\n >\n <SelectTrigger size=\"sm\" aria-label={`What the column ${c.label || c.header} holds`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {SAVE_TO_TABLE_TYPES.map((t) => (\n <SelectItem key={t} value={t}>\n {typeWord(t)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {c.guess.type === \"select\" && c.use ? (\n <Input\n className=\"col-span-2 col-start-2\"\n value={c.options}\n aria-label={`The choices of ${c.label || c.header}`}\n disabled={busy}\n onChange={(e) =>\n setDrafts(columns.map((d, j) => (j === i ? { ...d, options: e.target.value } : d)))\n }\n />\n ) : null}\n </div>\n ))}\n </div>\n {problem ? <RefusalNotice error={problem} /> : null}\n <div className=\"flex items-center gap-2\">\n <Button size=\"sm\" disabled={busy} onClick={() => void make()}>\n {phase === \"making\"\n ? \"Making the table…\"\n : phase === \"writing\"\n ? \"Writing the rows…\"\n : rows.length === 0\n ? \"Make the table with these columns\"\n : `Make the table with ${rows.length} row${rows.length === 1 ? \"\" : \"s\"}`}\n </Button>\n <span className=\"text-xs text-muted-foreground\">Nothing is made until you press it.</span>\n </div>\n </div>\n ) : (\n <div className=\"flex flex-col gap-2\" data-save-to-table-existing=\"\">\n {tables.loading || levels.loading ? (\n <p className=\"text-muted-foreground\">Reading your tables…</p>\n ) : tables.error ? (\n <RefusalNotice error={tables.error} />\n ) : writable.length === 0 ? (\n <p className=\"text-muted-foreground\">\n There is no table in this organization you can add rows to. Make a new one instead.\n </p>\n ) : (\n <Select value={tableId} onValueChange={setTableId} disabled={busy}>\n <SelectTrigger size=\"sm\" aria-label=\"Which table to add the rows to\" className=\"min-w-[16rem]\">\n <SelectValue placeholder=\"Choose a table\" />\n </SelectTrigger>\n <SelectContent>\n {writable.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {t.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n {tableId ? (\n <div className=\"flex flex-col gap-1\" data-save-to-table-replace=\"\">\n {replaced?.tableId === tableId ? (\n <p className=\"text-xs text-muted-foreground\">\n {replaced.count === 0\n ? \"The table held no rows, so nothing was archived.\"\n : `${replaced.count} row${replaced.count === 1 ? \"\" : \"s\"} it held moved to the archive, where ${replaced.count === 1 ? \"it\" : \"they\"} can be restored. The rows below go in their place.`}\n </p>\n ) : (\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={replaceAsked}\n disabled={busy || replacing}\n onCheckedChange={(v) => setReplaceAsked(v === true)}\n aria-label=\"Replace what this table holds\"\n />\n Replace what this table holds (its current rows move to the archive first)\n </label>\n )}\n </div>\n ) : null}\n <ConfirmDialog\n open={replaceAsked && Boolean(tableId) && replaced?.tableId !== tableId}\n onOpenChange={(open) => {\n if (!open && !replacing) setReplaceAsked(false);\n }}\n variant=\"destructive\"\n title={`Move every row of “${writable.find((t) => t.id === tableId)?.name ?? \"this table\"}” to the archive?`}\n description=\"Restorable from Archived items\"\n confirmLabel={replacing ? \"Archiving…\" : \"Archive them\"}\n cancelLabel=\"Keep them\"\n busy={replacing}\n onConfirm={async () => {\n setReplacing(true);\n setProblem(null);\n const ids: Uuid[] = [];\n for (let offset = 0; ; offset += 500) {\n const page = await client.listPage({ table_id: tableId as Uuid, limit: 500, offset });\n if (!page.ok) {\n setProblem(page.error);\n setReplacing(false);\n return;\n }\n ids.push(...page.data.rows.map((r) => r.id as Uuid));\n if (page.data.rows.length + (page.data.locked ?? 0) < 500) break;\n }\n for (let at = 0; at < ids.length; at += 200) {\n const archived = await changeRecordsAt(client, {\n table_id: tableId as Uuid,\n changes: ids.slice(at, at + 200).map((record_id) => ({ op: \"archive\" as const, record_id })),\n });\n if (!archived.ok) {\n setProblem(archived.error);\n setReplacing(false);\n setReplaced({ tableId, count: at });\n return;\n }\n }\n setReplaced({ tableId, count: ids.length });\n setReplacing(false);\n setReplaceAsked(false);\n }}\n />\n {problem && target === \"existing\" ? <RefusalNotice error={problem} /> : null}\n {tableId ? (\n <ImportWizard\n key={`${tableId}:${which}:${split}`}\n tableId={tableId as Uuid}\n source={wizardSource}\n onWrote={() => onSaved?.(tableId as Uuid, \"existing\")}\n onDone={() => (onOpenTable ? onOpenTable(tableId as Uuid) : onClose?.())}\n />\n ) : null}\n </div>\n )}\n </>\n )}\n </div>\n );\n}\n","// src/unfinishedTable.ts — @ai-matrx/records-ui\n//\n// A NEW TABLE IS FOUR ACTS, AND THE PAGE CAN GO AWAY BETWEEN ANY TWO OF THEM.\n//\n// \"Make the table\" declares the table, declares each column, then sends the rows. A person who\n// closes the tab, reloads, or leaves while that runs (1-4 s on a real connection) leaves a table\n// with no rows — and the retry used to see the name taken and make \"… 2\" beside it, so every\n// interrupted try left a husk and the next one a twin.\n//\n// The store has no transaction a client can hold across those calls, so the half-made table is\n// recognized instead of prevented: a table with the very name being asked for, made by this person in the last day,\n// holding no rows (or only some of this save's rows, within minutes), whose columns are all among the ones about to be written, IS the earlier try. The\n// retry finishes it — adds the columns it lacks, sends the rows — and never makes a twin. A table\n// that has more rows than this save carries, or any column this save does not carry, is somebody's table and is left alone.\n\nimport type { Table, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\n\n/** How long a half-made table with NO rows stays \"the earlier try\". */\nexport const UNFINISHED_WINDOW_MS = 24 * 60 * 60 * 1000;\n/**\n * How long a table that holds SOME of this save's rows (never more than the save carries) stays \"the\n * earlier try\": the page can go away after the rows are sent and before the host links them, so the\n * retry finds the table full. Sending the same rows again is safe (the import skips duplicates).\n */\nexport const FILLED_WINDOW_MS = 15 * 60 * 1000;\n\nexport interface UnfinishedTable {\n tableId: Uuid;\n /** The column keys it already has. */\n haveKeys: ReadonlySet<string>;\n}\n\nexport async function findUnfinishedTable(\n client: Pick<RecordsClient, \"tableList\" | \"tableRowCounts\" | \"recordHeaders\" | \"fields\">,\n wantedName: string,\n wantedKeys: readonly string[],\n /** How many rows this save carries. */\n wantedRows: number,\n now: number = Date.now(),\n): Promise<UnfinishedTable | null> {\n const name = wantedName.trim().toLowerCase();\n if (!name) return null;\n const listed = await client.tableList();\n if (!listed.ok) return null;\n const named = listed.data.filter((t: Table) => !t.is_kernel && t.name.trim().toLowerCase() === name);\n if (named.length === 0) return null;\n // A Table's own birth time and maker are not in the list the read door answers; the header door has them.\n const headers = await client.recordHeaders({ ids: named.map((t) => t.id) });\n if (!headers.ok) return null;\n const madeAt = new Map<string, number>();\n for (const h of headers.data) {\n const at = Date.parse(h.created_at);\n if (h.mine && h.deleted_at === null && Number.isFinite(at) && now - at <= UNFINISHED_WINDOW_MS) madeAt.set(h.id, at);\n }\n const candidates = named.filter((t) => madeAt.has(t.id));\n if (candidates.length === 0) return null;\n const counted = await client.tableRowCounts({ table_ids: candidates.map((t) => t.id) });\n if (!counted.ok) return null;\n const rowsOf = new Map(counted.data.map((c) => [c.table_id as string, c.visible_rows]));\n const wanted = new Set(wantedKeys);\n // Newest first: the latest try is the one being retried.\n const ordered = [...candidates].sort((a, b) => (madeAt.get(b.id) ?? 0) - (madeAt.get(a.id) ?? 0));\n for (const t of ordered) {\n const rows = rowsOf.get(t.id) ?? 0;\n if (rows > 0 && (rows > wantedRows || now - (madeAt.get(t.id) ?? 0) > FILLED_WINDOW_MS)) continue;\n const read = await client.fields({ table_id: t.id });\n if (!read.ok) continue;\n const have = new Set(read.data.map((f) => f.key));\n if ([...have].every((k) => wanted.has(k))) return { tableId: t.id, haveKeys: have };\n }\n return null;\n}\n\n/**\n * A retry that FINISHES an earlier try also owes it this save's choice words. The earlier try made each\n * choice column with the words of ITS rows; a retry (or a different answer saved under the same name\n * within the day) carries other words, and a choice column refuses a word it does not have — every row\n * of the save came back \"refused\" with the table sitting empty. `options_add` is idempotent (a live\n * same-words choice adds nothing), so every choice column this save carries and the table already has is\n * topped up with this save's words, never narrowed.\n */\nexport function choiceWordsOwed(\n existing: ReadonlyArray<{ id: string; key: string }>,\n wanted: ReadonlyArray<{ key: string; type: string; options?: readonly string[] }>,\n): Array<{ fieldId: string; words: string[] }> {\n const idOf = new Map(existing.map((f) => [f.key, f.id]));\n const owed: Array<{ fieldId: string; words: string[] }> = [];\n for (const f of wanted) {\n const fieldId = idOf.get(f.key);\n const words = [...new Set((f.options ?? []).map((w) => w.trim()).filter(Boolean))];\n if (f.type === \"select\" && fieldId && words.length > 0) owed.push({ fieldId, words });\n }\n return owed;\n}\n","\"use client\";\n\n// src/ImportWizard.tsx — @ai-matrx/records-ui · SCR-10, SCR-N-7\n//\n// DROP A FILE, SEE WHAT THE STORE MAKES OF IT, FIX WHAT IT GOT WRONG, RUN IT,\n// AND CLICK THROUGH TO THE ROWS THAT DID NOT LAND.\n//\n// WHAT CHANGED, AND WHY IT HAD TO. Until lane IMPORT this screen parsed the file\n// and then called `recordWrite` once per row — one HTTP round trip each. At the\n// five thousand rows a real spreadsheet holds that is five thousand round trips\n// and about half an hour of a person watching a progress bar; there was no\n// duplicate check, so importing a corrected file made a second copy of\n// everything; nothing recorded that a value came from a file; and a refusal\n// carried a row NUMBER into a file this screen no longer had, so \"row 3,184 was\n// refused\" was information nobody could act on.\n//\n// Now the bytes are parsed here (Postgres cannot unzip a workbook) and\n// EVERYTHING after the parse is the store's: `importPlan` says what each column\n// is, `importBegin` gives the run the file's sha-256 as its identity so a\n// re-import doubles nothing, `importRows` writes a BATCH through the one write\n// door and answers one outcome per row, and `importFinish` sends the columns\n// this table does not have to the ONE approvals inbox. This screen holds no\n// import logic of its own — if it did, a file imported from here and the same\n// file imported by the agent would land differently.\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useFields, useRecordsClient, useTable, type Field, type Uuid } from \"@ai-matrx/records/react\";\nimport {\n importCsv,\n importXlsx,\n type ImportColumnPlan,\n type ImportOutcome,\n type ImportPlan,\n type ImportProposal,\n type ImportRun,\n type ParsedImport,\n} from \"@ai-matrx/records/core\";\nimport {\n Badge,\n Button,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n Separator,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { relationNameIndexOf, relationNameKey, relationNamesIn, splitListCell, type RecordsError, type RelationNameIndex } from \"@ai-matrx/records\";\nimport { RefusalLine, RefusalNotice } from \"./Refusal\";\nimport { refusal as refusalOf, refusalFromThrown } from \"./refusals\";\nimport { checkImportRules, refusedCellsOf, type ImportRefusedCell } from \"./importRuleCheck\";\nimport { useTableRights } from \"./host\";\nimport { FilePicker } from \"./FilePicker\";\nimport { fieldName } from \"./names\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { fieldTypeLabel } from \"./parity\";\nimport { fieldTypeChoice } from \"./fieldTypes\";\nimport { editorKindFor } from \"./parity\";\nimport { choiceOptionsOf, valueFromPastedText, type ChoiceOptions } from \"./pasteValues\";\nimport { useChoiceNudge } from \"./choiceNudge\";\nimport { IMPORT_KINDS, datesOfColumn, declarationFor, exactDuplicateRows, importKindOfPlan, looksLike, looksLikeDates, type ImportKind } from \"./importKinds\";\nimport { PickOne } from \"./PickOne\";\nimport { combineRows, sameRecordLikely, titleRepeats } from \"./importCombine\";\nimport { groupReasons, offerDownload, refusedFileName, refusedRowsCsv } from \"./importRefusals\";\n\n/**\n * IMPORT-2: THE ONLY BATCH SIZE THIS SCREEN KNOWS, AND IT IS A FALLBACK.\n *\n * Until 2026-09-22 this screen sent 250 rows a call because 250 was written\n * here. MEASURED on the main database that day with a real 1,000-row dispatch\n * file: 250 rows cost 3.6–4.0 s on a quiet database and 8.2 s — SQLSTATE 57014,\n * PostgREST's ~8 s ceiling, the whole call rolled back — on a loaded one. A\n * batch size is not this screen's to choose: it depends on how many columns the\n * table has, what the guards on them cost, and what the database is busy with.\n *\n * So the STORE says it. `importBegin` answers `rows_per_call` for the first\n * call, and every `importRows` answers the `rows_per_call` it measured on\n * itself for the next one. This constant is used only if a store older than\n * IMPORT-2 answers neither.\n */\nconst BATCH = 250;\n/**\n * How many values of a column the store judges its kind by (VISION-REACH G4). It was the first 40\n * rows, so twelve last names in forty rows read as \"a few repeating words\" and became a choice\n * list; the whole file (up to this many rows) is what a column's kind is read from now.\n */\nconst SAMPLES = 2000;\n\n/** How many new columns one \"add the columns\" call declares (VISION-REACH G6). */\nconst COLUMNS_PER_CALL = 3;\n\n/**\n * What a row does with a name its relation column cannot link. `merge` (VISION-REACH lane 5): the\n * records of one name in the other table are combined into one, through the store's own merge door,\n * so the row links instead of being refused — the way out of \"2 records called Cox family\" when the\n * duplicates are the other table's problem, not this file's.\n */\ntype UnlinkedChoice = \"create\" | \"empty\" | \"skip\" | \"merge\";\n\n/**\n * FIX-11B F9: THE NARROWEST A \"GOES TO\" CONTROL MAY EVER BE, IN PIXELS.\n *\n * VERIFIER-11 measured all seven of them at **10 px** in a 416 px right rail at\n * 1600x1000 — slivers on the one screen where the whole import is decided, so\n * the person could not read what ANY column was mapped to. A `<table>` with\n * `table-fixed` and a `<colgroup>` was supposed to hold them open and did not:\n * a table's fixed layout is only a HINT once its container is narrower than the\n * declared widths, and a bare `<select>` has no intrinsic width to defend\n * itself with. So the row is a GRID whose \"Goes to\" track is `minmax(14rem, …)`\n * — a floor a container cannot argue with — and the control is the design\n * system's `Select`, which is a button and carries its own minimum.\n *\n * `check:import-mapping-is-readable` measures the real control in a real\n * browser against this number and goes red below it.\n */\nexport const GOES_TO_MIN_PX = 224; // 14rem\n\n/**\n * Radix's Select has no empty value — an empty string is how it says \"nothing is\n * chosen\" — so \"leave this column out\" is a real, named choice with a token of\n * its own rather than an absence the control cannot represent.\n */\nconst ABSENT = \"__absent__\";\n/** \"Leave this column out\" on its own (VISION-REACH G4) — never sent, never offered as a column. */\nconst LEAVE = \"__leave__\";\n/**\n * THE NAME COLUMN'S WORDS, FROM A COLUMN THAT ALSO KEEPS ITS OWN COLUMN (VISION-REACH lane 5). A\n * pledge list has no name of its own; a person names each pledge by its family — and \"Family\" must\n * ALSO link to Families. One header cannot go two places in the mapping, so the rows carry the words\n * a second time under this key, mapped to the title column. Never shown, never offered as a column.\n */\nexport const TITLE_COPY = \"__name__\";\n\n/** A relation column this import is about to make, as the Field the relation ask reads. */\nfunction planRelationField(c: ImportColumnPlan): Field {\n return {\n id: `plan:${c.field_key}`,\n key: c.field_key,\n label: c.label || c.header,\n name: null,\n type: \"relation\",\n multi: false,\n dated: false,\n rules: [],\n config: {},\n required: false,\n default: null,\n sort: null,\n relation_target: c.relation_target ?? null,\n relation_max: null,\n on_target_delete: null,\n } as unknown as Field;\n}\n\n/**\n * FIX-11B F2: THE COLUMN A RECORD IS NAMED BY, GUESSED THE WAY A PERSON WOULD.\n *\n * An import that creates its own columns used to leave the table's title column\n * empty, so all 312 records it wrote read `—` in the first column of the grid —\n * every one of them nameless, in a store whose own rule is that a record without\n * a title cannot be a chip (REC-2). Nothing was broken; nobody had been ASKED.\n * So the wizard asks, and opens on the answer a person would have given: a\n * header that says it is the name, else the first column the file's own plan\n * typed as text.\n */\nfunction obviousTitleColumn(\n columns: ImportColumnPlan[],\n rows: ReadonlyArray<Record<string, string>> = [],\n /** The table's name column's label and the table's own names (VISION-REACH G4). */\n names: { title?: string | null; table?: string | null; singular?: string | null } = {},\n): string | null {\n // VISION-REACH G4: THE COLUMN THAT SAYS WHAT THIS TABLE NAMES. The dry run's physicians table\n // opened on \"Patient name\" because the header ended in \"name\". A header spelled like the name\n // column wins; else the header sharing the most words with the name column and the table\n // (\"Referring physician\" for Referring physicians / Physician name), \"name\" and \"id\" not counting.\n const words = (t: string | null | undefined) =>\n new Set(\n (t ?? \"\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .map((w) => w.replace(/s$/, \"\"))\n .filter((w) => w.length > 1 && w !== \"name\" && w !== \"id\"),\n );\n const flat = (t: string) => t.toLowerCase().replace(/[^a-z0-9]+/g, \" \").trim();\n // VISION-REACH lane 5 (persona P03): A NAME IS WORDS THAT TELL ROWS APART. \"Date received\" — mostly\n // blank, dates where filled — became every pledge's name because it was the only text column left.\n // A column whose values are mostly numbers or read as dates is never a name, whatever the plan\n // typed it; and a column of words that points at another table (Family) may be one — the wizard\n // then keeps the link too (TITLE_COPY).\n const valuesOf = (c: ImportColumnPlan) => rows.map((r) => String(r[c.header] ?? \"\").trim()).filter(Boolean);\n // \"Sep 20\", \"20 Sep\", \"9/20\", \"2026-09-20\": a day written any common way, with or without a year.\n const MONTH = \"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\\\\.?\";\n const dateish = new RegExp(`^(?:${MONTH}\\\\s+\\\\d{1,2}(?:,?\\\\s*\\\\d{2,4})?|\\\\d{1,2}\\\\s+${MONTH}(?:\\\\s+\\\\d{2,4})?|\\\\d{1,4}[/.-]\\\\d{1,2}(?:[/.-]\\\\d{1,4})?)$`, \"i\");\n const worded = (c: ImportColumnPlan) => {\n const v = valuesOf(c);\n // Empty, or blank on most rows (a \"Date received\" that unpaid pledges leave empty), is no name.\n if (v.length === 0 || (rows.length > 0 && v.length / rows.length < 0.5)) return false;\n const numeric = v.filter((x) => /^[\\d\\s.,:$%-]+$/.test(x)).length;\n if (numeric / v.length > 0.4) return false;\n const dates = v.filter((x) => dateish.test(x)).length;\n if (dates / v.length > 0.4) return false;\n return !looksLikeDates(rows, c.header);\n };\n const wordy = columns.filter((c) => (c.type === \"text\" || c.type === \"long_text\" || c.type === \"select\" || c.type === \"relation\") && worded(c));\n const texty = wordy.filter((c) => c.type === \"text\" || c.type === \"long_text\");\n if (names.title) {\n const exact = columns.find((c) => flat(c.header) === flat(names.title!));\n if (exact) return exact.header;\n }\n const wanted = new Set([...words(names.title), ...words(names.table), ...words(names.singular)]);\n if (wanted.size > 0) {\n let best: { header: string; score: number } | null = null;\n for (const c of wordy) {\n const overlap = [...words(c.header)].filter((w) => wanted.has(w)).length;\n if (overlap === 0) continue;\n const distinct = new Set(valuesOf(c).map((v) => v.toLowerCase())).size;\n const score = overlap * 100000 + distinct;\n if (!best || score > best.score) best = { header: c.header, score };\n }\n if (best) return best.header;\n }\n // Else the first column of words whose every value is different — what a name does.\n for (const c of texty) {\n const values = valuesOf(c);\n if (new Set(values.map((v) => v.toLowerCase())).size === values.length) return c.header;\n }\n const says = /^(title|name|record|customer|client|company|job|item|subject|label|description|room|patient|product|task|project)\\b|(\\bname|\\btitle)$/i;\n const named = wordy.find((c) => says.test(c.header.trim()));\n if (named) return named.header;\n // VERIFIER-30 #2: \"the first text column\" named every record of a rooms paste after its FLOOR\n // (\"1\", \"1\", \"Lower\"). A name is words and it tells rows apart: the column of words whose values\n // are most often different from each other, first column breaking ties.\n let best: { header: string; score: number } | null = null;\n for (const c of texty) {\n const score = new Set(valuesOf(c).map((v) => v.toLowerCase())).size;\n if (!best || score > best.score) best = { header: c.header, score };\n }\n if (best && best.score > 0) return best.header;\n // No column of plain words: a column of words that points at another table names the rows\n // (\"Cox family\" on every pledge), and the wizard keeps its link as well.\n const pointing = wordy[0];\n if (pointing) return pointing.header;\n // Nothing in this file is a name. The panel asks rather than naming records by a date or a number.\n return null;\n}\n\n/**\n * ROWS THAT ARE NOT A FILE (lane SAVE-AS-TABLE-EVERYWHERE, 2026-09-29): a table in a chat answer,\n * a list in a note, a CSV paste, a kind value — already read into headers and rows by\n * `readTableShapes`. The wizard plans, maps, asks and writes them exactly as it does a file's rows,\n * through the same doors, so \"add these rows to that table\" has ONE importer whatever it came from.\n */\nexport interface ImportSource {\n /** What the rows came from, in words (\"Home exercises after knee surgery\"). */\n name: string;\n parsed: ParsedImport;\n /** The text the rows were read from; its sha-256 is the run's identity, so the same rows twice write nothing. */\n text: string;\n}\n\nexport interface ImportWizardProps {\n tableId: Uuid;\n /** Rows to import instead of a file. When present the file control is not offered. */\n source?: ImportSource | undefined;\n /**\n * FIX-12 F2: THE PERSON SAYS WHEN THEY ARE FINISHED WITH AN IMPORT — NOT THE\n * LAST ROW.\n *\n * This used to fire the moment `io_import_finish` answered, and every host\n * wires it to close the rail. So the screen that finally knew the truth — the\n * ledger sentence, the refusal list, the columns that went to the inbox — was\n * unmounted in the same tick it became true. VERIFIER-12 watched a 40-row file\n * land 28 and refuse 12 and saw NOTHING at all: the whole run fitted inside\n * one call, so the report existed for less than a paint. A long file only\n * looked better because the person had time to read the PROGRESS; its report\n * was destroyed just as fast.\n *\n * It is now the \"Done\" button on the report, and nothing else calls it.\n */\n onDone?: ((written: number) => void) | undefined;\n /**\n * FIX-12 F2: the rows landed. Fired when the run finishes, for a host that\n * needs to refresh behind the panel — never for closing it.\n */\n onWrote?: ((written: number) => void) | undefined;\n /**\n * A BRAND-NEW TABLE HAS NOTHING TO REVIEW (2026-10-11). \"Next: columns\" in the New table window\n * made the table and stopped at this screen; a person who read the button as \"make my table\" was\n * left with an empty table holding only Title. With `autoRun` the import runs by itself the moment\n * the plan is ready and the Import button would be pressable, and the report is what is shown.\n */\n autoRun?: boolean | undefined;\n className?: string | undefined;\n}\n\ntype Phase = \"waiting\" | \"reading\" | \"planning\" | \"ready\" | \"linking\" | \"declaring\" | \"writing\" | \"done\";\n\n/** VISION-REACH G4: kinds whose values a text-like column would hold as mere words. */\nconst TYPED_VALUES = new Set([\"datetime\", \"number\", \"currency\", \"percent\", \"checkbox\"]);\nfunction valuesLookTyped(type: string): boolean {\n return TYPED_VALUES.has(type);\n}\n/** Whether a column of `target` kind takes values the store read as `values`. */\nfunction kindTakes(target: string, values: string): boolean {\n if (target === values) return true;\n const numeric = [\"number\", \"currency\", \"percent\"];\n return numeric.includes(target) && numeric.includes(values);\n}\n\n/** \"line 4\", \"lines 4, 9, 12\", \"lines 4, 9 and 6 more\" — where a name sits in the file. */\nfunction linesWord(lines: number[], word: (row: number) => string): string {\n const shown = lines.slice(0, 3).map(word).join(\", \");\n return lines.length > 3 ? `${shown} +${lines.length - 3}` : shown;\n}\n\n/**\n * The file's identity. Web Crypto is in every browser this app supports and in\n * Node 18+; where it genuinely is not, the import still runs and SAYS that it\n * cannot recognize this file again — never a fabricated hash, which would make\n * two different files look like the same one and silently skip the second.\n */\nasync function sha256(bytes: ArrayBuffer | Uint8Array): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * ONE WORD PER TYPE, EVERYWHERE. `FIELD_TYPE_CHOICES` is the list the \"Add\n * field\" panel offers and the settings row reads back; the wizard reads the\n * same one, so a column called \"Money\" here is called \"Money\" there. A store\n * word this list has no sentence for shows as itself rather than as nothing —\n * `parityTypesWithNoExplanation()` fails the suite the moment that happens.\n */\nfunction typeWord(t: string): string {\n // 🚨 NEVER THE STORE'S OWN TOKEN (VERIFIER-15 M5, VERIFIER-16 M8). A column this\n // table already has arrives with the FIELD's type, and the store's word for a\n // number is `range` — which this printed at a person as \"range\". A matched\n // column is named from its Field (`fieldTypeLabel`, below); this is the word for\n // everything else, and a token it has no sentence for is written out, not shown raw.\n if (t === \"range\") return fieldTypeChoice(\"number\")?.label ?? \"Number\";\n return fieldTypeChoice(t)?.label ?? (t === \"relation\" ? \"Points at another table\" : humanizeIdentifier(t));\n}\n\n/**\n * THE LINE A PERSON SEES IN THEIR SPREADSHEET (VERIFIER-16 M8).\n *\n * The store numbers a file's rows from 1 across the whole run, and so does\n * `checkImportRules` — the first ROW UNDER THE HEADER is 1. The file a person has\n * open puts its column names on line 1, so that row is on line 2. Every place this\n * wizard says \"line\" goes through here, so the refused `-3` on line 3 of the file\n * is called line 3 and never line 2.\n */\nexport function lineInYourFile(dataRow: number): number {\n return dataRow + 1;\n}\n\n/**\n * B4-03 (2026-09-30): the footer says where EVERY column goes. \"1 of 4 columns go into this table\"\n * read as \"three are dropped\" to an Editor whose three went to the approvals inbox — and they were\n * dropped, until the store kept their values with the waiting column. Now it says so.\n */\nexport function columnsSentence(mapped: number, total: number, unmapped: \"propose\" | \"create\" | \"ignore\"): string {\n const rest = total - mapped;\n if (rest <= 0) return `${mapped} of ${total} columns go into this table`;\n if (unmapped === \"create\") return `${total} of ${total} columns go into this table · ${rest} new`;\n if (unmapped === \"ignore\") return `${mapped} of ${total} columns go into this table · ${rest} left out`;\n return `${mapped} of ${total} go in now · ${rest} wait for approval with their values`;\n}\n\n/** THE REPORT NAMES COLUMNS IN THE ORDER THE FILE HAD THEM (walk 2026-10-17: the store answers in the order\n * it made them — typed ones first — so \"Email, Phone, Supplier…\" read differently from the paste). */\nexport function inFileOrder<T extends { column: string }>(added: T[], headers: string[]): T[] {\n const at = (c: T) => {\n const i = headers.indexOf(c.column);\n return i < 0 ? headers.length : i;\n };\n return added.map((c, i) => ({ c, i })).sort((a, b) => at(a.c) - at(b.c) || a.i - b.i).map((x) => x.c);\n}\n\nexport function ImportWizard({ tableId, source, onDone, onWrote, autoRun, className }: ImportWizardProps) {\n const client = useRecordsClient();\n const table = useTable(tableId);\n const fields = useFields(tableId);\n const rights = useTableRights(table.data);\n\n const [phase, setPhase] = useState<Phase>(\"waiting\");\n // 🚨 A REFUSAL, NEVER ITS RAW MESSAGE (lane REFUSAL-SWEEP, 2026-09-23). Six\n // of these setters handed the store's `error.message` straight to a red\n // paragraph, past the machine-identity filter every other screen goes through.\n const [problem, setProblem] = useState<RecordsError | null>(null);\n const [parsed, setParsed] = useState<ParsedImport | null>(null);\n const [rows, setRows] = useState<Array<Record<string, string>>>([]);\n const [plan, setPlan] = useState<ImportPlan | null>(null);\n const [mapping, setMapping] = useState<Record<string, string>>({});\n const [dedupeKey, setDedupeKey] = useState<string>(\"\");\n /** VISION-REACH G4: the file's columns a person left out by name. Stripped before anything is sent. */\n const [leftOut, setLeftOut] = useState<Set<string>>(() => new Set());\n /** VISION-REACH lane 5: the header whose words name each record while it also keeps its own column. */\n const [titleFrom, setTitleFrom] = useState<string | null>(null);\n /** Rows with the same name become one record (`combine`) or stay several (`each`); null = the panel's default. */\n const [combine, setCombine] = useState<\"combine\" | \"each\" | null>(null);\n /** The person chose what makes a row the same row; the panel's default stops moving it. */\n const [dedupeChosen, setDedupeChosen] = useState(false);\n /** VISION-REACH G1: each mapped relation column's target, indexed by the names the file carries. */\n const [relationIndex, setRelationIndex] = useState<Map<string, RelationNameIndex>>(() => new Map());\n const [relationProblem, setRelationProblem] = useState<RecordsError | null>(null);\n /** What the rows naming an unlinkable record do, per relation column. */\n const [unlinkedChoice, setUnlinkedChoice] = useState<Record<string, { unmatched: UnlinkedChoice; ambiguous: UnlinkedChoice }>>({});\n const [onDuplicate, setOnDuplicate] = useState<\"skip\" | \"update\">(\"skip\");\n /** VISION-REACH G14: what a NEW column is made as, when the person chose it. */\n const [kindChoice, setKindChoice] = useState<Record<string, ImportKind>>({});\n /** VISION-REACH G14: what a date column's unreadable cells do, per header. */\n const [dateMiss, setDateMiss] = useState<Record<string, \"empty\" | \"skip\">>({});\n /** VISION-REACH G14: rows repeating an earlier row exactly are skipped unless the person says not. */\n const [skipRepeats, setSkipRepeats] = useState(true);\n /** The file row (1-based) each sent row came from, so a refusal names the person's own line. */\n const [sentLines, setSentLines] = useState<number[] | null>(null);\n const [repeatsSkipped, setRepeatsSkipped] = useState(0);\n const [unmapped, setUnmapped] = useState<\"propose\" | \"create\" | \"ignore\">(\"propose\");\n // VERIFIER-30 #2: someone who manages this table ADDS the columns it lacks — sending them to the\n // approvals inbox \"for approval\" by the very person importing read as data loss (three rows landed\n // with a Title and nothing else). The inbox stays the default, and the only choice, for everyone\n // else; a person who picks another answer keeps it.\n const [unmappedChosen, setUnmappedChosen] = useState(false);\n useEffect(() => {\n if (rights.admin && !unmappedChosen) setUnmapped(\"create\");\n }, [rights.admin, unmappedChosen]);\n const [fileName, setFileName] = useState<string>(\"\");\n const [fileHash, setFileHash] = useState<string | null>(null);\n const [fileBytes, setFileBytes] = useState<number | null>(null);\n const [format, setFormat] = useState<\"csv\" | \"xlsx\">(\"csv\");\n const [outcomes, setOutcomes] = useState<ImportOutcome[]>([]);\n const [progress, setProgress] = useState<number>(0);\n const [summary, setSummary] = useState<string | null>(null);\n const [proposals, setProposals] = useState<ImportProposal[]>([]);\n const [alreadyRan, setAlreadyRan] = useState<string | null>(null);\n /** IMPORT-2: what the \"add the columns\" step made, shown as its own line. */\n const [columnsAdded, setColumnsAdded] = useState<ImportProposal[] | null>(null);\n const [show, setShow] = useState<\"refused\" | \"duplicate\" | \"all\">(\"all\");\n /**\n * FIX-11B F2: THE STORE'S OWN COUNT OF THIS RUN, NOT THIS SCREEN'S TALLY.\n *\n * VERIFIER-11 watched a 400-row file land 312 records and refuse 88 while the\n * only sentence on screen read \"196 landed · 0 already here · 54 refused\" — a\n * report about ONE batch of 250, for a run of 400. The number came from\n * counting the `outcomes` array this screen happened to be holding, and an\n * outcomes array is a SAMPLE: the door caps what it hands back, and a batch it\n * could not answer for at all contributes nothing to it. A tally of a sample\n * can never be the truth about a run.\n *\n * Every `io_import_rows` answer carries what the STORE wrote in that call —\n * `rows_seen`, `rows_written`, `rows_duplicate`, `rows_refused` — and\n * `io_import_finish` carries the run's final totals off the ledger. This is\n * the sum of the former while the run goes, replaced by the latter when it\n * ends. The screen prints THIS, and never a count of its own array.\n */\n const [ledger, setLedger] = useState<{\n seen: number;\n written: number;\n duplicate: number;\n refused: number;\n final: boolean;\n } | null>(null);\n\n /**\n * FIX-12 F2: THE RUNS THIS TABLE ALREADY HAD — SO A REFUSAL CAN BE FOUND\n * AFTERWARDS, WHICH IS THE OTHER HALF OF THE SAME DEFECT.\n *\n * The store has always kept them: `custom.io_import` holds up to 500 refused\n * rows per run, each with the store's sentence and the whole source row, and\n * `custom.io_import_report` / `custom.io_imports` hand them back. No screen in\n * this package had ever asked. So a person who blinked at the wrong moment —\n * or whose file was small enough to finish between two paints — had no way\n * back to the twelve rows that did not land, and re-opening Import mentioned\n * neither the run nor the refusals. These two calls are that way back.\n */\n const [runs, setRuns] = useState<ImportRun[] | null>(null);\n const [openRun, setOpenRun] = useState<string | null>(null);\n const [runRows, setRunRows] = useState<{\n import_id: string;\n rows: Array<Record<string, unknown>>;\n kept: number;\n total: number;\n note: string | null;\n } | null>(null);\n const [runProblem, setRunProblem] = useState<RecordsError | null>(null);\n const [runsProblem, setRunsProblem] = useState<RecordsError | null>(null);\n\n const loadRuns = useCallback(async () => {\n const answered = await client.imports({ table_id: tableId, limit: 10 });\n // Nothing fails silently: the list of earlier runs that could not be read\n // says so, instead of the section simply never appearing.\n if (answered.ok) {\n setRuns(answered.data);\n setRunsProblem(null);\n } else setRunsProblem(answered.error);\n }, [client, tableId]);\n\n useEffect(() => {\n void loadRuns();\n }, [loadRuns]);\n\n const openRefusals = useCallback(\n async (importId: string) => {\n setRunProblem(null);\n if (openRun === importId) {\n setOpenRun(null);\n setRunRows(null);\n return;\n }\n setOpenRun(importId);\n setRunRows(null);\n const answered = await client.importReport({\n import_id: importId as Uuid,\n state: \"refused\",\n limit: 200,\n });\n if (!answered.ok) {\n setRunProblem(answered.error);\n return;\n }\n setRunRows({\n import_id: answered.data.import_id,\n rows: answered.data.rows,\n kept: answered.data.kept,\n total: answered.data.total,\n note: answered.data.note,\n });\n },\n [client, openRun],\n );\n\n const declared = useMemo(() => fields.data ?? [], [fields.data]);\n\n // ── THE NAME COLUMN, AND ROWS THAT SHARE A NAME (VISION-REACH lane 5, 2026-10-03) ─────────\n // Everything below that reads the file's rows reads `effectiveRows`: the rows as they will be\n // written. When the name column repeats and the repeating rows look like one record (persona\n // P03's families file: one row per student, two or three per family), they are combined — one\n // record per name, every other column keeping every value it held — unless the person says each\n // row is its own record. The choice is shown before the write, never made behind their back.\n const titleKey = table.data?.title_field ?? null;\n const titleHeader: string | null =\n titleFrom ?? (titleKey ? (Object.entries(mapping).find(([h, key]) => key === titleKey && h !== TITLE_COPY)?.[0] ?? null) : null);\n // A row that repeats an earlier row EXACTLY is the G14 \"skip repeated rows\" question, not this\n // one: the name repeats here when rows share a name and differ elsewhere (two students, one family).\n const distinctRows = useMemo(() => {\n const headers = (plan?.columns ?? []).map((c) => c.header).filter((h) => !leftOut.has(h));\n const exact = new Set(exactDuplicateRows(rows, headers).map((r) => r.row));\n return exact.size === 0 ? rows : rows.filter((_, i) => !exact.has(i));\n }, [rows, plan, leftOut]);\n const titleStats = useMemo(() => (titleHeader ? titleRepeats(distinctRows, titleHeader) : null), [distinctRows, titleHeader]);\n const titleRepeating = Boolean(titleStats && titleStats.filled > 0 && titleStats.distinct < titleStats.filled);\n // An amount, a date or a yes/no never says \"these rows are the same record\" — it describes the row.\n const notIdentity = useMemo(() => {\n const out = new Set<string>();\n for (const c of plan?.columns ?? []) {\n const k = importKindOfPlan(c.type);\n if (k === \"currency\" || k === \"date\" || k === \"checkbox\" || looksLikeDates(distinctRows, c.header)) out.add(c.header);\n }\n return out;\n }, [plan, distinctRows]);\n const combineDefault: \"combine\" | \"each\" = useMemo(\n () => (titleRepeating && titleHeader && sameRecordLikely(distinctRows, titleHeader, notIdentity) ? \"combine\" : \"each\"),\n [distinctRows, titleHeader, titleRepeating, notIdentity],\n );\n const combining = titleRepeating && (combine ?? combineDefault) === \"combine\";\n const combined = useMemo(() => (combining && titleHeader ? combineRows(rows, titleHeader) : null), [combining, rows, titleHeader]);\n const effectiveRows = combined?.rows ?? rows;\n // One record per name means the name is what makes a row the same row — so a corrected file\n // imported again brings those records up to date instead of doubling them.\n useEffect(() => {\n if (dedupeChosen) return;\n setDedupeKey(combining && titleKey ? titleKey : \"\");\n }, [combining, titleKey, dedupeChosen]);\n\n /**\n * EVERYTHING AFTER THE PARSE, for a file and for rows that were never a file: the store says\n * what each column is (`importPlan`), and the wizard opens on the name column a person would\n * have picked.\n */\n const planFrom = useCallback(\n async (result: ParsedImport, meta: { name: string; bytes: number | null; hash: string | null; format: \"csv\" | \"xlsx\" }) => {\n setFormat(meta.format);\n setFileName(meta.name);\n setFileBytes(meta.bytes);\n setFileHash(meta.hash);\n setParsed(result);\n setRows(result.rows);\n setLeftOut(new Set());\n setTitleFrom(null);\n setCombine(null);\n setDedupeChosen(false);\n setRelationIndex(new Map());\n setUnlinkedChoice({});\n setKindChoice({});\n setDateMiss({});\n setSkipRepeats(true);\n setSentLines(null);\n setRepeatsSkipped(0);\n\n // EVERY header, mapped or not — the store decides what each one is, and\n // it knows things this screen cannot (the roster, the other tables).\n setPhase(\"planning\");\n const columns = result.headers.map((header) => ({\n header,\n samples: result.rows\n .slice(0, SAMPLES)\n .map((r) => r[header])\n .filter((v): v is string => typeof v === \"string\" && v.trim() !== \"\"),\n }));\n const answered = await client.importPlan({ table_id: tableId, columns });\n if (!answered.ok) {\n setProblem(answered.error);\n setPhase(\"waiting\");\n return;\n }\n setPlan(answered.data);\n const next: Record<string, string> = {};\n for (const column of answered.data.columns) {\n if (column.matched) next[column.header] = column.field_key;\n }\n\n // FIX-11B F2: THE NAME COLUMN IS CHOSEN HERE, NOT LEFT EMPTY.\n // If the store already matched a header onto this Table's title column,\n // that is the answer and nothing is guessed. Otherwise the wizard opens\n // on the column a person would have picked and says so on screen — it is\n // a choice shown, never a choice made behind their back.\n const titleKey = table.data?.title_field ?? null;\n // BREAKER-3 B3-09: the guess never takes a header the store already placed (its \"Exercise\"\n // went to Exercise, then the guess moved it onto `id`), and never names records by a column\n // that is not words — a number, a record number or a time is not a name.\n const titleField = titleKey ? answered.data.fields.find((f) => f.key === titleKey) : undefined;\n const titleTakesWords = !titleField || !/^(range|number|integer|currency|percent|autonumber|created_time|modified_time|boolean|checkbox|date|datetime)$/i.test(String(titleField.type ?? \"\"));\n if (titleKey && titleTakesWords && !Object.values(next).includes(titleKey)) {\n const unplaced = answered.data.columns.filter((c) => !(c.header in next));\n const guess = obviousTitleColumn(unplaced, result.rows, {\n title: titleField?.label ?? null,\n table: table.data?.name ?? null,\n singular: (table.data as { label_singular?: string | null } | null | undefined)?.label_singular ?? null,\n });\n if (guess) {\n const guessed = answered.data.columns.find((c) => c.header === guess);\n // A column of names that points at another table names the records AND keeps its link.\n if (guessed?.type === \"relation\" && guessed.relation_target) {\n next[TITLE_COPY] = titleKey;\n setTitleFrom(guess);\n } else next[guess] = titleKey;\n }\n }\n setMapping(next);\n setPhase(\"ready\");\n },\n [client, tableId, table.data],\n );\n\n const reset = useCallback(() => {\n setPhase(\"reading\");\n setProblem(null);\n setOutcomes([]);\n setSummary(null);\n setProposals([]);\n setAlreadyRan(null);\n setProgress(0);\n setLedger(null);\n }, []);\n\n const take = useCallback(\n async (file: File) => {\n reset();\n try {\n const xlsx = file.name.toLowerCase().endsWith(\".xlsx\");\n const bytes = await file.arrayBuffer();\n // THE PARSE IS A PARSE. It is not given the Fields and cannot decide a\n // mapping: every heading and every value comes through, and the STORE\n // decides what each column is. See `ParsedImport`.\n const result = xlsx ? await importXlsx(bytes) : importCsv(new TextDecoder().decode(bytes));\n await planFrom(result, { name: file.name, bytes: file.size, hash: await sha256(bytes), format: xlsx ? \"xlsx\" : \"csv\" });\n } catch (thrown) {\n setProblem(\n refusalFromThrown(\n thrown,\n \"That file could not be read, so nothing was imported.\",\n \"Save it again as CSV or Excel and pick it again.\",\n \"invalid_argument\",\n ),\n );\n setPhase(\"waiting\");\n }\n },\n [planFrom, reset],\n );\n\n // ROWS THAT ARE NOT A FILE: planned the moment the table's fields are known, once per source.\n const [tookSource, setTookSource] = useState<ImportSource | null>(null);\n useEffect(() => {\n if (!source || tookSource === source || !fields.data || !table.data) return;\n setTookSource(source);\n reset();\n const bytes = new TextEncoder().encode(source.text);\n void sha256(bytes).then((hash) =>\n planFrom(source.parsed, { name: source.name, bytes: bytes.byteLength, hash, format: \"csv\" }),\n );\n }, [source, tookSource, fields.data, table.data, planFrom, reset]);\n\n // ── THE ENUM ASK (lane SAVE-AS-TABLE-EVERYWHERE, 2026-09-29) ─────────────\n // A word going into a choice column that names none of its choices is refused by the store, row\n // by row (`custom._resolve_choice_words`). The grid's paste has always asked first; an import did\n // not, so \"Discharge\" in a pasted list landed as a refused row the person met only in the report.\n // The words are listed BEFORE the write, per column, with the one explicit act — add them — that\n // the grid's paste offers, and the organization's own choice setting decides whether it is asked\n // (`ask`), done as the import runs (`always_add`), or not offered (`never_add`).\n const nudge = useChoiceNudge();\n // BREAKER-3 B3-09: rows from a chat answer or a note are not \"your file\". With a source the\n // wizard counts them as the rows they are (\"Row 2\"), never as lines of a file that does not exist.\n const inYourRows = source ? \"in the rows you are saving\" : \"in your file\";\n const lineWord = (dataRow: number) => (source ? `Row ${dataRow}` : `Line ${lineInYourFile(dataRow)}`);\n const [choiceIndex, setChoiceIndex] = useState<Map<string, ChoiceOptions>>(() => new Map());\n const [addingWords, setAddingWords] = useState<string | null>(null);\n const isChoice = (f: Field) => {\n const kind = String(editorKindFor(f));\n return kind === \"select\" || kind === \"multi_select\";\n };\n const mappedChoiceFields = declared.filter((f) => isChoice(f) && Object.values(mapping).includes(f.key));\n const choiceKeysToRead = mappedChoiceFields.filter((f) => !choiceIndex.has(f.key)).map((f) => f.key).join(\",\");\n const readChoices = useCallback(\n async (wanted: Field[]) => {\n const read = await Promise.all(\n wanted.map(async (f) => {\n const got = await client.fieldOptions({ field_id: f.id });\n return got.ok ? ([f.key, choiceOptionsOf(got.data ?? [])] as const) : null;\n }),\n );\n setChoiceIndex((held) => {\n const next = new Map(held);\n for (const entry of read) if (entry) next.set(entry[0], entry[1]);\n return next;\n });\n },\n [client],\n );\n useEffect(() => {\n if (!choiceKeysToRead) return;\n void readChoices(mappedChoiceFields.filter((f) => choiceKeysToRead.split(\",\").includes(f.key)));\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the fields still unread\n }, [choiceKeysToRead, readChoices]);\n const newChoiceWords = useMemo(() => {\n const out: Array<{ field: Field; header: string; words: string[] }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = declared.find((f) => f.key === key);\n if (!field || !isChoice(field)) continue;\n const options = choiceIndex.get(key);\n if (!options) continue;\n const words: string[] = [];\n for (const row of effectiveRows) {\n const raw = row[header];\n if (typeof raw !== \"string\" || raw.trim() === \"\") continue;\n const read = valueFromPastedText(field, raw, options);\n if (\"unmatched\" in read && read.unmatched) {\n for (const w of read.unmatched) if (!words.some((x) => x.toLowerCase() === w.toLowerCase())) words.push(w);\n }\n }\n if (words.length > 0) out.push({ field, header, words });\n }\n return out;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- isChoice is pure\n }, [mapping, declared, choiceIndex, effectiveRows]);\n const addChoiceWords = useCallback(\n async (field: Field, words: string[]): Promise<boolean> => {\n setAddingWords(field.key);\n const existing = choiceIndex.get(field.key)?.labels ?? [];\n const written = await client.fieldUpdate({ field_id: field.id, patch: { options: [...existing, ...words] } });\n setAddingWords(null);\n if (!written.ok) {\n setProblem(written.error);\n return false;\n }\n await readChoices([field]);\n return true;\n },\n [client, choiceIndex, readChoices],\n );\n\n // ── THE RELATION ASK (VISION-REACH G1, 2026-10-02) ─────────────────────────\n // A file names the record a row points at. The store is asked ONCE per relation column which\n // records those names name (`relationNamesMatch` — the same matcher its write doors use), and\n // every name that matches nothing, or two records, is listed here with its lines and a choice\n // BEFORE anything is written: add it to the other table, leave the link empty, or skip the row\n // (the store then refuses that row by name and keeps it in the report). Never a guessed link.\n const mappedRelations = useMemo(() => {\n const out: Array<{ header: string; field: Field }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = declared.find((f) => f.key === key);\n if (field && editorKindFor(field) === \"relation\" && field.relation_target) out.push({ header, field });\n }\n // VISION-REACH lane 5: a relation column this import is about to MAKE (\"Create and import\" —\n // the plan typed it as pointing at another table and the columns are added) meets the same ask\n // as one the table already has. Persona P03 never saw the ask: the column did not exist yet,\n // so every ambiguous name was met only as a refusal afterwards.\n if (unmapped === \"create\" && rights.admin) {\n for (const c of plan?.columns ?? []) {\n if (leftOut.has(c.header) || c.header in mapping || c.type !== \"relation\" || !c.relation_target) continue;\n out.push({ header: c.header, field: planRelationField(c) });\n }\n }\n return out;\n }, [mapping, declared, plan, leftOut, unmapped, rights.admin]);\n const relationSignature = mappedRelations.map((r) => `${r.header}>${r.field.key}`).join(\"|\");\n const readRelationNames = useCallback(\n async (wanted: Array<{ header: string; field: Field }>): Promise<Map<string, RelationNameIndex> | null> => {\n const next = new Map<string, RelationNameIndex>();\n for (const { header, field } of wanted) {\n const names = effectiveRows.flatMap((r) => relationNamesIn(field, String(r[header] ?? \"\")));\n const got = await client.relationNamesMatch({ table_id: field.relation_target as Uuid, names });\n if (!got.ok) {\n setRelationProblem(got.error);\n return null;\n }\n next.set(field.key, relationNameIndexOf(got.data));\n }\n setRelationProblem(null);\n setRelationIndex(next);\n return next;\n },\n [client, effectiveRows],\n );\n useEffect(() => {\n if (mappedRelations.length === 0) {\n setRelationIndex(new Map());\n return;\n }\n void readRelationNames(mappedRelations);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on which columns are relations\n }, [relationSignature, readRelationNames]);\n\n const relationAsks = useMemo(() => {\n return mappedRelations.flatMap(({ header, field }) => {\n const index = relationIndex.get(field.key);\n if (!index) return [];\n const unmatched = new Map<string, number[]>();\n const ambiguous = new Map<string, { count: number; lines: number[] }>();\n let linked = 0;\n let named = 0;\n effectiveRows.forEach((row, i) => {\n const names = relationNamesIn(field, String(row[header] ?? \"\"));\n if (String(row[header] ?? \"\").trim() === \"\") return;\n named += 1;\n let ok = true;\n for (const name of names) {\n const hits = index.byName.get(relationNameKey(name)) ?? [];\n if (hits.length === 1) continue;\n ok = false;\n if (hits.length === 0) unmatched.set(name, [...(unmatched.get(name) ?? []), i + 1]);\n else ambiguous.set(name, { count: hits.length, lines: [...(ambiguous.get(name)?.lines ?? []), i + 1] });\n }\n if (ok) linked += 1;\n });\n return [{ header, field, index, linked, named, unmatched: [...unmatched.entries()], ambiguous: [...ambiguous.entries()] }];\n });\n }, [mappedRelations, relationIndex, effectiveRows]);\n const choiceFor = (key: string) => unlinkedChoice[key] ?? { unmatched: \"skip\" as UnlinkedChoice, ambiguous: \"skip\" as UnlinkedChoice };\n\n // ── WHAT A NEW COLUMN HOLDS, AND THE DATES (VISION-REACH G14, 2026-10-02) ─────────────────────\n // A new column is made as the kind the person picks (Text, Date, Number, Money, Checkbox), opened\n // on the store's plan — except a column the plan read as words whose cells mostly read as dates,\n // which opens on Date. Every date column, new or already here, is read by the ONE date reader\n // (`readTypedDate`) before it is sent, so \"Mar 31, 2026\", \"8.4.2026\" and \"2026-05-16\" in one\n // column all land as days; a cell that is not a date is listed with its line and a choice.\n const makesColumns = unmapped === \"create\" && rights.admin;\n const guessedKind = useMemo(() => {\n const out: Record<string, ImportKind | null> = {};\n for (const c of plan?.columns ?? []) {\n const k = importKindOfPlan(c.type);\n out[c.header] = (k === \"text\" || c.type === \"select\") && looksLikeDates(effectiveRows, c.header) ? \"date\" : k;\n // Words whose cells are emails, phone numbers or web addresses open on that kind.\n if (out[c.header] === \"text\") out[c.header] = looksLike(effectiveRows, c.header) ?? \"text\";\n // A column that now holds \"K; 3\" because two rows were combined is a list of words, kept as\n // text — never a dropdown whose one choice is \"K; 3\", and never refused.\n if (combined?.multiValued.has(c.header) && (k === null || c.type === \"select\")) out[c.header] = \"text\";\n }\n return out;\n }, [plan, effectiveRows, combined]);\n const kindOf = (header: string): ImportKind | null => kindChoice[header] ?? guessedKind[header] ?? null;\n const newColumns = (plan?.columns ?? []).filter((c) => !leftOut.has(c.header) && !(c.header in mapping));\n const dateAsks = useMemo(() => {\n const out: Array<{ header: string; label: string; withTime: boolean; dates: ReturnType<typeof datesOfColumn> }> = [];\n for (const c of plan?.columns ?? []) {\n if (leftOut.has(c.header)) continue;\n const key = mapping[c.header];\n if (key) {\n const f = declared.find((d) => d.key === key);\n if (!f || String(editorKindFor(f)) !== \"datetime\") continue;\n const withTime = String(f.config?.[\"kind\"] ?? \"date\") === \"datetime\";\n out.push({ header: c.header, label: fieldName(f), withTime, dates: datesOfColumn(effectiveRows, c.header, { withTime }) });\n } else if (makesColumns && (kindChoice[c.header] ?? guessedKind[c.header]) === \"date\") {\n out.push({ header: c.header, label: c.header, withTime: false, dates: datesOfColumn(effectiveRows, c.header) });\n }\n }\n return out;\n }, [plan, leftOut, mapping, declared, effectiveRows, makesColumns, kindChoice, guessedKind]);\n /** Rows that repeat an earlier row exactly over the columns that are sent. */\n const repeats = useMemo(\n () => exactDuplicateRows(effectiveRows, (plan?.columns ?? []).map((c) => c.header).filter((h) => !leftOut.has(h))),\n [effectiveRows, plan, leftOut],\n );\n\n const [goAheadAnyway, setGoAheadAnyway] = useState(false);\n // The cells the rules refuse, kept aside (blanked in what is sent, listed with their reason in the\n // report) when the person says to import the rest anyway — so one refused cell costs the row nothing else.\n const refusedCells = useMemo(\n () => (goAheadAnyway ? refusedCellsOf(declared, effectiveRows, mapping, choiceIndex, relationIndex) : []),\n [goAheadAnyway, declared, effectiveRows, mapping, choiceIndex, relationIndex],\n );\n const [keptAside, setKeptAside] = useState<ImportRefusedCell[]>([]);\n\n /**\n * THE ROWS AS THEY ARE SENT: the left-out columns stripped, and every relation cell turned into\n * the record ids the person saw it link to — so what the panel showed is what is written. A name\n * the person chose to skip stays as written, and the store refuses that row in its own words.\n */\n const rowsToSend = useCallback(\n (index: Map<string, RelationNameIndex>): { rows: Array<Record<string, string>>; lines: number[] } => {\n const repeated = new Set(skipRepeats ? repeats.map((r) => r.row) : []);\n const lines: number[] = [];\n const sent: Array<Record<string, string>> = [];\n effectiveRows.forEach((row, at) => {\n if (repeated.has(at)) return;\n const out: Record<string, string> = {};\n for (const [header, value] of Object.entries(row)) if (!leftOut.has(header)) out[header] = value;\n for (const c of refusedCells) if (c.line === at + 1 && c.header in out) out[c.header] = \"\";\n // The name column's words, carried a second time when they come from a column that keeps\n // its own column (a relation): the record is named by them AND linked through them.\n if (titleFrom) out[TITLE_COPY] = String(row[titleFrom] ?? \"\").trim();\n for (const { header, field } of mappedRelations) {\n const named = index.get(field.key);\n const text = String(row[header] ?? \"\").trim();\n if (!named || text === \"\") continue;\n const parts = field.multi ? splitListCell(text) : [text];\n const ids: string[] = [];\n let skip = false;\n for (const part of parts) {\n const hits = relationNamesIn(field, part).length === 0 ? null : (named.byName.get(relationNameKey(part)) ?? []);\n if (hits === null) ids.push(part); // an id: the store decides it is there\n else if (hits.length === 1) ids.push(hits[0]!.id);\n else if ((hits.length === 0 ? choiceFor(field.key).unmatched : choiceFor(field.key).ambiguous) !== \"empty\") skip = true;\n }\n if (!skip) out[header] = ids.join(\"; \");\n }\n // G14: a date cell goes as the day it reads as; one that is not a date goes empty, or as\n // written when the person chose to skip those rows (the store then refuses it by name).\n for (const ask of dateAsks) {\n const raw = String(row[ask.header] ?? \"\").trim();\n if (raw === \"\") continue;\n const day = ask.dates.read.get(at);\n if (day !== undefined) out[ask.header] = day;\n else if ((dateMiss[ask.header] ?? \"empty\") === \"empty\") out[ask.header] = \"\";\n }\n sent.push(out);\n // A combined row names the FIRST line it was made from; a refusal then points at a line a\n // person can find, and the combined lines are listed with the combine notice.\n lines.push(combined?.lines[at]?.[0] ?? at + 1);\n });\n return { rows: sent, lines };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- choiceFor reads unlinkedChoice\n [effectiveRows, combined, titleFrom, leftOut, mappedRelations, unlinkedChoice, dateAsks, dateMiss, repeats, skipRepeats, refusedCells],\n );\n\n const run = useCallback(async () => {\n if (!plan) return;\n setProblem(null);\n // The organization adds new choices without asking: they are added now, before a row is sent.\n if (nudge === \"always_add\" && rights.admin) {\n for (const ask of newChoiceWords) {\n if (!(await addChoiceWords(ask.field, ask.words))) return;\n }\n }\n setOutcomes([]);\n setColumnsAdded(null);\n setProgress(0);\n setLedger(null);\n\n // ── VISION-REACH lane 5: THE DUPLICATES THE PERSON CHOSE TO COMBINE, BEFORE ANY ROW. ──\n // \"2 records called Cox family\" in Families: the first keeps its id, every other one is merged\n // into it through the store's own merge door (values kept as alternates, links moved, the loser\n // archived and aliased), and the names are read again so every row links to the one record.\n let index = relationIndex;\n const toMerge = relationAsks.filter((ask) => choiceFor(ask.field.key).ambiguous === \"merge\" && ask.ambiguous.length > 0);\n if (toMerge.length > 0) {\n setPhase(\"linking\");\n for (const ask of toMerge) {\n for (const [name] of ask.ambiguous) {\n const hits = ask.index.byName.get(relationNameKey(name)) ?? [];\n const winner = hits[0];\n if (!winner) continue;\n for (const loser of hits.slice(1)) {\n const merged = await client.migrateMerge({\n winner_id: winner.id as Uuid,\n loser_id: loser.id as Uuid,\n note: `Combined while importing ${fileName || \"rows\"}: both were called \"${name}\".`,\n });\n if (!merged.ok) {\n setProblem(merged.error);\n setPhase(\"ready\");\n return;\n }\n }\n }\n }\n const reread = await readRelationNames(mappedRelations);\n if (!reread) {\n setPhase(\"ready\");\n return;\n }\n index = reread;\n }\n\n // ── VISION-REACH G1: THE RECORDS THE PERSON CHOSE TO ADD, BEFORE ANY ROW. ──\n const toMake = relationAsks.filter((ask) => choiceFor(ask.field.key).unmatched === \"create\" && ask.unmatched.length > 0);\n if (toMake.length > 0) {\n setPhase(\"linking\");\n for (const ask of toMake) {\n const title = ask.index.titleField;\n if (!title) continue;\n const made = await client.recordWriteMany({\n table_id: ask.field.relation_target as Uuid,\n rows: ask.unmatched.map(([name]) => ({ [title]: name })),\n });\n if (!made.ok) {\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n }\n const reread = await readRelationNames(mappedRelations);\n if (!reread) {\n setPhase(\"ready\");\n return;\n }\n index = reread;\n }\n const { rows: sendRows, lines: sendLines } = rowsToSend(index);\n setKeptAside(refusedCells.map(({ header, line, raw, why }) => ({ header, line, raw, why })));\n setSentLines(sendLines);\n setRepeatsSkipped(effectiveRows.length - sendRows.length);\n\n // ── IMPORT-2: THE COLUMNS FIRST, AS THEIR OWN STEP. ────────────────────\n // \"Columns this table does not have are added straight away\" used to happen\n // inside the first writing call — eight `field_declare` calls on top of 250\n // record writes, which is what pushed that call over the client ceiling —\n // and it happened AFTER `importBegin`, so a person could not name one of the\n // new columns as the file's duplicate key. It is a step of its own now: the\n // person sees \"8 columns added\", and only then do the rows go.\n let sendMapping: Record<string, string> = mapping;\n // VISION-REACH G14: A NEW COLUMN THE PERSON (OR THE DATE READING) MADE A DIFFERENT KIND is\n // declared as that kind through the one field door, under the key the plan gave it; the rest of\n // the new columns are left to the store's column step below, exactly as before.\n if (makesColumns) {\n const typed = newColumns.filter((c) => {\n const k = kindOf(c.header);\n return k !== null && k !== importKindOfPlan(c.type);\n });\n if (typed.length > 0) setPhase(\"declaring\");\n for (const c of typed) {\n const made = await client.fieldDeclare({\n table_id: tableId,\n spec: { label: c.label || c.header, key: c.field_key, ...declarationFor(kindOf(c.header)!) },\n });\n if (!made.ok) {\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n sendMapping = { ...sendMapping, [c.header]: c.field_key };\n setMapping(sendMapping);\n }\n }\n if (unmapped === \"create\" && rights.admin) {\n setPhase(\"declaring\");\n // VISION-REACH G6: A FEW COLUMNS A CALL. Twelve columns in one call took the dry run past the\n // database's ceiling (each new column is its own Field record, its own guards and its own\n // change notice — measured ~0.1–0.3 s apiece on the clone) and the screen said nothing. Three\n // a call stays far inside it, and a retry picks up where it stopped: a column already added\n // is matched by its header, never added twice.\n const fresh = (plan?.columns ?? [])\n .map((c) => c.header)\n .filter((h) => !leftOut.has(h) && !(h in sendMapping));\n const added: ImportProposal[] = [];\n for (let at = 0; at < fresh.length; at += COLUMNS_PER_CALL) {\n const group = fresh.slice(at, at + COLUMNS_PER_CALL);\n // The column step reads the rows AS THE FILE SPELLS THEM: a relation is recognized by the\n // names matching the other table's name column, so the ids the rows will be sent with\n // would read as text here and the column would be made as text.\n const made = await client.importDeclareColumns({\n table_id: tableId,\n rows: effectiveRows.map((r) => Object.fromEntries(group.map((h) => [h, r[h] ?? \"\"]))),\n mapping: sendMapping,\n });\n if (!made.ok) {\n setColumnsAdded(added.length > 0 ? added : null);\n setProblem(made.error);\n setPhase(\"ready\");\n return;\n }\n added.push(...made.data.columns_added);\n // A header the store matched to a column it already had is a mapping, and\n // the rows must be sent with it or they would go nowhere.\n // VERIFIER-30 #2: THE MAPPING THE STORE ANSWERED IS THE ONE THE ROWS GO WITH. It used to be\n // set into state only, and the loop below then sent the mapping this render closed over —\n // without the columns just added — so every added column's values went nowhere.\n if (made.data.mapping) {\n sendMapping = { ...sendMapping, ...made.data.mapping };\n setMapping(sendMapping);\n }\n }\n setColumnsAdded(added);\n }\n if (makesColumns && plan) {\n // THE FILE'S COLUMN ORDER (walk 2026-10-10: Item, Supplier, Phone, Email, Website, Qty, Status came out\n // Title, Email, Phone, Supplier, Qty, Status, Website — the columns made as another kind went first).\n // The columns just made are put in the order the file had them, the first one still the title.\n const wantedKeys = plan.columns.map((c) => c.header).filter((h) => !leftOut.has(h)).map((h) => sendMapping[h]).filter((k): k is string => Boolean(k));\n const now = await client.fields({ table_id: tableId });\n if (now.ok) {\n const order = new Map(wantedKeys.map((k, i) => [k, i]));\n const current = now.data.filter((f) => order.has(f.key)).sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)).map((f) => f.key);\n const inFileOrder = current.every((k, i) => k === wantedKeys.filter((w) => current.includes(w))[i]);\n if (!inFileOrder) {\n const slots = now.data.filter((f) => order.has(f.key)).map((f) => f.sort ?? 0).sort((a, b) => a - b);\n const byKey = new Map(now.data.map((f) => [f.key, f]));\n const present = wantedKeys.filter((k) => byKey.has(k));\n for (let i = 0; i < present.length; i += 1) {\n const f = byKey.get(present[i]!)!;\n const to = slots[i] ?? (i + 1) * 10;\n if ((f.sort ?? 0) !== to) await client.fieldUpdate({ field_id: f.id as Uuid, patch: { sort: to } });\n }\n }\n }\n }\n\n setPhase(\"writing\");\n const opened = await client.importBegin({\n table_id: tableId,\n format,\n source_name: fileName,\n source_columns: plan.columns.map((c) => c.header).filter((h) => !leftOut.has(h)),\n file_hash: fileHash,\n file_bytes: fileBytes,\n dedupe_key: dedupeKey || null,\n policy: { on_duplicate: onDuplicate, unmapped },\n });\n if (!opened.ok) {\n setProblem(opened.error);\n setPhase(\"ready\");\n return;\n }\n // THE SAME FILE TWICE. The store refuses to run it again and says when it\n // ran and what landed — this screen shows exactly that and writes nothing.\n if (opened.data.already) {\n setAlreadyRan(opened.data.message);\n setSummary(opened.data.message);\n setPhase(\"done\");\n return;\n }\n\n const importId = opened.data.import_id;\n const collected: ImportOutcome[] = [];\n const told = { seen: 0, written: 0, duplicate: 0, refused: 0 };\n // IMPORT-2: the store sizes the call. It opens with a number of its own and\n // every answer carries the one it measured on itself, so a busy afternoon\n // makes the batches smaller instead of making the call fail.\n let take = opened.data.rows_per_call ?? BATCH;\n let at = 0;\n while (at < sendRows.length) {\n const batch = sendRows.slice(at, at + take);\n const answered = await client.importRows({ import_id: importId, rows: batch, mapping: sendMapping });\n if (!answered.ok) {\n setProblem(answered.error);\n setOutcomes([...collected]);\n // The run STOPPED here. What the ledger says is what really landed\n // before it stopped, and the sentence beside it says the rest of the\n // file was never offered — never a total that reads like a finished run.\n setLedger({ ...told, final: false });\n setPhase(\"ready\");\n return;\n }\n collected.push(...answered.data.outcomes);\n setOutcomes([...collected]);\n // FIX-11B F2: the store's own numbers for THIS call, added to the run's.\n // `outcomes` is a sample; these four are what the ledger was moved by.\n told.seen += answered.data.rows_seen;\n told.written += answered.data.rows_written;\n told.duplicate += answered.data.rows_duplicate;\n told.refused += answered.data.rows_refused;\n setLedger({ ...told, final: false });\n at += batch.length;\n setProgress(Math.min(at, sendRows.length));\n if (answered.data.rows_per_call) take = answered.data.rows_per_call;\n }\n\n const finished = await client.importFinish({ import_id: importId, unmapped });\n if (!finished.ok) {\n setProblem(finished.error);\n setPhase(\"done\");\n return;\n }\n setSummary(finished.data.message);\n setProposals(finished.data.proposals);\n // FIX-11B F2: the run's FINAL totals, off the store's ledger, replace the\n // running sum. If the two ever disagree the ledger is right — it counted the\n // writes, this screen counted answers about them.\n setLedger({\n seen: finished.data.rows_seen,\n written: finished.data.rows_written,\n duplicate: finished.data.rows_duplicate,\n refused: finished.data.rows_refused,\n final: true,\n });\n setPhase(\"done\");\n // FIX-12 F2: the host is TOLD the rows landed, and the panel STAYS. Closing\n // it is the person's act, on the report, once they have read it.\n onWrote?.(finished.data.rows_written);\n void loadRuns();\n // eslint-disable-next-line react-hooks/exhaustive-deps -- choiceFor and kindOf read state\n }, [newColumns, makesColumns, kindChoice, guessedKind, addChoiceWords, client, dedupeKey, effectiveRows, fileBytes, fileHash, fileName, format, leftOut, loadRuns, mappedRelations, mapping, newChoiceWords, nudge, onDuplicate, onWrote, plan, readRelationNames, refusedCells, relationAsks, relationIndex, rights.admin, rowsToSend, tableId, unmapped, unlinkedChoice]);\n\n const counts = useMemo(() => {\n let landed = 0;\n let duplicate = 0;\n let refused = 0;\n for (const o of outcomes) {\n if (o.outcome === \"landed\") landed += 1;\n else if (o.outcome === \"duplicate\") duplicate += 1;\n else refused += 1;\n }\n return { landed, duplicate, refused };\n }, [outcomes]);\n\n const interesting = useMemo(\n () => outcomes.filter((o) => (show === \"all\" ? o.outcome !== \"landed\" : o.outcome === show)),\n [outcomes, show],\n );\n\n const mappedCount = Object.keys(mapping).filter((h) => h !== TITLE_COPY).length;\n\n /**\n * FIX-11B F2: THE RUN'S TRUE NUMBERS, AND WHO SAID THEM.\n *\n * `ledger` is the store's. `counts` is this screen's tally of the outcome\n * entries it was handed. They are shown as ONE sentence built from the ledger,\n * and when the screen holds fewer entries than the run refused, it says that\n * out loud instead of letting a short list read as the whole story.\n */\n const titleMappedTo = titleHeader;\n /**\n * REC-2: a Table that declares a title column may not be imported without one — when that column\n * takes WORDS. A table named by a number, a record number or a time (BREAKER-3 B3-09: `id`) gets\n * no \"what each record is called\" question and is never held for one.\n */\n const titleDeclared = titleKey ? declared.find((f) => f.key === titleKey) : undefined;\n const titleTakesWords = !titleDeclared || !/^(range|number|integer|currency|percent|autonumber|created_time|modified_time|boolean|checkbox|date|datetime)$/i.test(String(editorKindFor(titleDeclared)));\n const titleMissing = Boolean(titleKey) && titleTakesWords && titleMappedTo === null;\n const titleFieldLabel: string =\n (titleKey ? plan?.fields.find((f) => f.key === titleKey)?.label : null) ||\n (titleKey ? declared.find((f) => f.key === titleKey)?.label : null) ||\n \"the name column\";\n const busy = phase === \"reading\" || phase === \"planning\" || phase === \"linking\" || phase === \"declaring\" || phase === \"writing\";\n\n // THE COLUMN RULES, ASKED BEFORE THE WRITE (lane REFUSAL-SWEEP). Per mapped\n // column: how many of the file's rows its declared rules would refuse, in the\n // store's own words — so the person fixes the mapping or the file first, or\n // says in so many words that the rest should go ahead.\n const ruleVerdicts = useMemo(\n () => checkImportRules(declared, effectiveRows, mapping, choiceIndex, relationIndex),\n [declared, effectiveRows, mapping, choiceIndex, relationIndex],\n );\n const ruleVerdictOf = useMemo(() => new Map(ruleVerdicts.map((v) => [v.header, v])), [ruleVerdicts]);\n const refusedByRules = ruleVerdicts.reduce((n, v) => n + v.refused, 0);\n // AT-DBFIX 2: the go-ahead is forgotten when the VERDICTS change, never when the same verdicts are\n // merely worked out again (a fields read that lands a new array of the same columns re-ran this\n // effect and unchecked the box under the person's finger, leaving \"Import 9 rows\" disabled).\n const verdictKey = ruleVerdicts.map((v) => `${v.header}:${v.refused}/${v.judged}`).join(\"|\");\n useEffect(() => setGoAheadAnyway(false), [verdictKey]);\n\n // `autoRun`: press Import once, for the person, when it is pressable.\n const [autoRan, setAutoRan] = useState(false);\n useEffect(() => {\n if (!autoRun || autoRan || !source || phase !== \"ready\" || !plan) return;\n if (busy || !rights.write || rows.length === 0 || titleMissing || ruleVerdicts.length > 0) return;\n setAutoRan(true);\n void run();\n }, [autoRun, autoRan, source, phase, plan, busy, rights.write, rows.length, titleMissing, ruleVerdicts, run]);\n\n /**\n * 🚨 AFTER A WRITE, THE WIZARD IS A REPORT — NEVER THE SAME IMPORT AGAIN\n * (VERIFIER-16 H1). A run landed 2 rows and the panel then showed, at once, the\n * result line, the pre-write notice \"…Nothing has been written yet\" (now false),\n * and a live \"Import 3 rows\" that would have written the file a second time. So\n * once this file has been offered to the store — finished, stopped part-way, or\n * turned away as a file already imported — every step that belongs BEFORE a write\n * (what each record is called, the mapping, the options, the rule notice and the\n * Import button) is gone, and what stays is what landed and what was refused.\n * Another run means choosing a file again, which starts the wizard afresh.\n */\n const afterWrite =\n !busy && (phase === \"done\" || alreadyRan !== null || (ledger !== null && ledger.seen > 0));\n\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-2 text-xs\", className)}>\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium\">Import</span>\n <span className=\"text-muted-foreground\">{table.data?.name}</span>\n {/* A file cannot be mapped before the store has said which Fields apply,\n and the rights that decide whether a column may be ADDED are read\n from the Table — so the chooser waits for both answers rather than\n showing an admin a mapping with their own choices missing. */}\n {fields.data && table.data ? null : (\n <span className=\"ml-auto text-muted-foreground\">\n {fields.data ? \"Reading this table…\" : \"Reading this table's fields…\"}\n </span>\n )}\n </div>\n\n {/* 🚨 THE ONE FILE CONTROL, NOT THE BROWSER'S (FIX-10C F10, 2026-09-22).\n This was the browser's own bare file input — `[Choose File] No file chosen`\n in the browser's own font, with nothing said about what a good file\n looks like and no way to back out. Airtable and Notion both explain\n this moment. `FilePicker` is the design-system-built control, shared\n by every screen in this package that takes a file. */}\n {source && !afterWrite ? (\n <p className=\"text-muted-foreground\" data-import-source=\"\">\n From {source.name} — {source.parsed.rows.length} row{source.parsed.rows.length === 1 ? \"\" : \"s\"}. Nothing is written until you press Import.\n </p>\n ) : null}\n {fields.data && table.data && !source ? (\n <FilePicker\n label=\"Choose a file\"\n inputLabel=\"Choose a file to import\"\n accept=\".csv,.xlsx\"\n disabled={busy}\n chosenName={fileName || null}\n hint={\n <>\n A spreadsheet or CSV whose FIRST ROW is the column names — Job Number, Customer,\n Scheduled Date — and one row per record under it. Every column is shown back to you\n with what this table made of it, and nothing is written until you press Import.\n </>\n }\n onFile={(file) => void take(file)}\n {...(fileName\n ? {\n onClear: () => {\n setPlan(null);\n setParsed(null);\n setFileName(\"\");\n setProblem(null);\n setPhase(\"waiting\");\n },\n }\n : {})}\n />\n ) : null}\n\n {problem && !(plan && parsed && !afterWrite) ? <RefusalNotice error={problem} /> : null}\n {phase === \"reading\" ? <p className=\"text-muted-foreground\">Reading the file…</p> : null}\n {phase === \"planning\" ? <p className=\"text-muted-foreground\">Working out what each column is…</p> : null}\n\n {plan && parsed && afterWrite ? (\n <p className=\"text-muted-foreground\" data-import-after-write=\"\">\n {source\n ? `These rows have been sent to this table${ledger && !ledger.final ? \", but the run stopped part-way.\" : \". What landed and what was refused is below.\"}`\n : fileName\n ? `${fileName} has been sent to this table`\n : \"This file has been sent to this table\"}\n {source\n ? null\n : ledger && !ledger.final\n ? \", but the run stopped part-way. Importing it again would write the rows that already landed a second time, so fix the file (or keep only the rows below the ones that landed) and choose it again.\"\n : \". What landed and what was refused is below. To import another file, choose it above.\"}\n </p>\n ) : null}\n\n {plan && parsed && !afterWrite ? (\n <>\n {/* ── FIX-11B F2: WHAT EACH RECORD WILL BE CALLED ────────────────\n An import that made its own columns used to leave this Table's\n title column empty, and 312 records landed with `—` in the first\n column of the grid — every one of them nameless. Nothing was\n broken; nobody had been ASKED. So it is asked here, first, opened\n on the column a person would have picked, and the run is REFUSED\n while it is unanswered (a Table that declares no title column\n never sees this block at all). */}\n {titleKey && titleTakesWords ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded border bg-muted/40 px-2 py-1.5\">\n <span className=\"font-medium\">What each record is called</span>\n <Select\n value={titleMappedTo ?? \"\"}\n disabled={busy}\n onValueChange={(chosen) => {\n const planned = plan.columns.find((c) => c.header === chosen);\n const keepsLink = Boolean(planned && planned.type === \"relation\" && planned.relation_target && !(chosen in mapping));\n setMapping((m) => {\n const next = { ...m };\n for (const [header, key] of Object.entries(next)) {\n if (key === titleKey) delete next[header];\n }\n if (chosen) next[keepsLink ? TITLE_COPY : chosen] = titleKey;\n return next;\n });\n setTitleFrom(keepsLink ? chosen : null);\n setCombine(null);\n if (chosen) setLeftOut((held) => (held.has(chosen) ? new Set([...held].filter((h) => h !== chosen)) : held));\n }}\n >\n <SelectTrigger\n size=\"sm\"\n aria-label=\"Which column each record is named by\"\n className=\"min-w-[14rem]\"\n >\n <SelectValue placeholder=\"— choose the column —\" />\n </SelectTrigger>\n <SelectContent>\n {plan.columns.map((c) => (\n <SelectItem key={c.header} value={c.header}>\n {c.header}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <span className=\"text-muted-foreground\">\n {titleMappedTo\n ? titleFrom\n ? `names each record in ${titleFieldLabel} and still links to the other table.`\n : `goes into ${titleFieldLabel}, so every record this file makes has a name you can read in the grid and on a chip.`\n : `Nothing goes into ${titleFieldLabel} yet, so every record this file makes would land with no name at all. Pick the column that says what each row IS.`}\n </span>\n </div>\n ) : null}\n\n {/* THE MAPPING, COLUMN BY COLUMN, WITH THE TYPE AND WHY. Nothing is\n hidden and nothing is only a badge: every column says what the\n store made of it, in a sentence, and every one can be changed. */}\n {/* 🚨 IT FITS, OR IT SCROLLS — IT NEVER CLIPS (FIX-11B F9, 2026-09-22).\n FIX-10C declared these widths on a `<table className=\"table-fixed\">`\n with a `<colgroup>`; VERIFIER-11 then measured every \"Goes to\"\n control at **10 px** in a 416 px rail at 1600x1000. A table's fixed\n layout is a HINT the moment the container is narrower than the\n declared widths, and a bare `<select>` has no intrinsic width of its\n own to defend — so the four columns collapsed and the header row\n drew \"Goes to\" on top of \"Column in the file\".\n This is a GRID. `minmax(14rem, …)` is a floor no container can argue\n with, the whole row declares the width it needs and the rail scrolls\n it, and the control is the design system's `Select` — a button that\n carries its own minimum. `check:import-mapping-is-readable` measures\n the real control in a real browser and goes red below\n GOES_TO_MIN_PX. */}\n {/* 🚨 IT FITS THE RAIL, SO NOTHING IS OUT OF SIGHT (VERIFIER-15 M5,\n VERIFIER-16 M8). The mapping was a four-column row 52rem wide inside a\n 26rem rail, so \"Kind\", \"First values\" and the per-column refusal sat\n past the rail's right edge and were only seen by scrolling a table\n sideways. Each column of the file is now ONE BLOCK that reads top to\n bottom — its name, where it goes, what it is, what would be refused,\n its first values — the way Airtable's and Notion's import panels list\n fields. The \"Goes to\" control keeps its 14rem floor\n (`check:import-mapping-is-readable`). */}\n <div className=\"flex w-full min-w-0 flex-col rounded border\" data-import-mapping=\"\">\n {plan.columns.map((column: ImportColumnPlan) => {\n const to = mapping[column.header] ?? \"\";\n const absent =\n unmapped === \"ignore\" ? \"— leave it out —\" : unmapped === \"create\" ? \"— add it as a new column —\" : \"— offer it as a new column —\";\n // WHAT IT IS = WHERE IT GOES NOW (VERIFIER-30 #4). The store's plan describes a column it\n // did NOT match by what its values look like (\"Points at another record … a record in\n // 'Visit type choices'\"); once the person — or the name-column guess — sends it into one\n // of this table's columns, it becomes that column's value, so the chip and the sentence\n // are that column's, never the plan's guess about an unplaced column.\n const planField = column.field_id ? declared.find((f) => f.id === column.field_id) : undefined;\n const placedField = to ? declared.find((f) => f.key === to) : undefined;\n const matchedField = placedField ?? planField;\n const whyNow =\n placedField && placedField.id !== column.field_id\n ? `Goes into ${fieldName(placedField)}, which holds ${fieldTypeLabel(placedField).toLowerCase()} values.`\n : column.why;\n return (\n <div\n key={column.header}\n data-import-column={column.header}\n className=\"flex min-w-0 flex-col gap-1 border-t px-2 py-1.5 first:border-t-0\"\n >\n <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"min-w-[8rem] flex-1 break-words font-medium\">{column.header}</span>\n <span className=\"text-muted-foreground\">goes to</span>\n <Select\n value={leftOut.has(column.header) ? LEAVE : to || ABSENT}\n disabled={busy}\n onValueChange={(chosen) => {\n setMapping((m) => {\n const next = { ...m };\n if (chosen === ABSENT || chosen === LEAVE) delete next[column.header];\n else next[column.header] = chosen;\n return next;\n });\n setLeftOut((held) => {\n const next = new Set(held);\n if (chosen === LEAVE) next.add(column.header);\n else next.delete(column.header);\n return next;\n });\n }}\n >\n <SelectTrigger\n size=\"sm\"\n aria-label={`Where ${column.header} goes`}\n data-goes-to={column.header}\n className=\"min-w-[14rem] flex-1\"\n >\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {/* ABSENT IS NOT DROPPED. Leaving a column unmapped is a\n real choice and it says what then happens to it. */}\n <SelectItem value={ABSENT}>{absent}</SelectItem>\n {/* VISION-REACH G4: one column left out on its own, whatever the rest do. */}\n {unmapped !== \"ignore\" ? <SelectItem value={LEAVE}>— leave it out —</SelectItem> : null}\n {plan.fields.map((f) => (\n <SelectItem key={f.field_id} value={f.key}>\n {f.label || f.key}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"min-w-0\">\n {/* VISION-REACH G14: a column this import ADDS is made as the kind chosen here. */}\n {makesColumns && !to && !leftOut.has(column.header) ? (\n <PickOne\n label={`What ${column.header} holds`}\n attrs={{ \"data-import-kind\": column.header }}\n className=\"h-6 text-[11px]\"\n value={kindOf(column.header) ?? \"\"}\n disabled={busy}\n onChange={(picked) => {\n const chosen = picked as ImportKind | \"\";\n setKindChoice((held) => {\n const next = { ...held };\n if (chosen === \"\") delete next[column.header];\n else next[column.header] = chosen;\n return next;\n });\n }}\n options={[\n ...(importKindOfPlan(column.type) === null ? [{ value: \"\", label: typeWord(column.type) }] : []),\n ...IMPORT_KINDS.map((k) => ({ value: k.kind, label: k.label })),\n ]}\n />\n ) : (\n <Badge\n variant={column.matched ? \"secondary\" : \"outline\"}\n className=\"text-[11px] font-normal\"\n data-import-kind={column.header}\n >\n {matchedField ? fieldTypeLabel(matchedField) : typeWord(column.type)}\n </Badge>\n )}\n {column.unit ? <span className=\"ml-1 opacity-60\">{column.unit}</span> : null}\n <p className=\"mt-0.5 break-words text-muted-foreground\">\n {makesColumns && !to && kindOf(column.header) === \"date\" && importKindOfPlan(column.type) !== \"date\"\n ? \"Most of these values read as dates.\"\n : whyNow}\n </p>\n {column.ambiguous ? (\n <p className=\"text-destructive\">Check a date you know before you run this.</p>\n ) : null}\n {column.collides_with ? (\n <p className=\"text-destructive\">Two columns in this file would make the same column.</p>\n ) : null}\n {/* VISION-REACH G4: a column sent somewhere its values do not look like. */}\n {placedField && placedField.id !== column.field_id && valuesLookTyped(column.type) &&\n !kindTakes(String(editorKindFor(placedField)), column.type) ? (\n <p className=\"text-amber-600 dark:text-amber-400\" data-import-kind-mismatch={column.header}>\n These look like {typeWord(column.type).toLowerCase()} values — check where this goes.\n </p>\n ) : null}\n {ruleVerdictOf.get(column.header) ? (\n (() => {\n const v = ruleVerdictOf.get(column.header)!;\n return (\n <div data-import-rule-refusal={column.header} className=\"mt-1\">\n <RefusalLine\n error={refusalOf(\n \"refused_by_rule\",\n `${v.refused} of ${v.judged} row${v.judged === 1 ? \"\" : \"s\"} would be refused by ${fieldName(v.field)}'s rules. ${v.firstWhy}`,\n `Send this column somewhere else, fix those rows ${inYourRows}, or import the rest and they are listed afterwards.`,\n )}\n />\n {/* The file's own text, verbatim — the screen's content,\n never filtered, so \"WO-4473\" is not eaten as an id. */}\n <p className=\"text-muted-foreground\" data-import-rule-sample=\"\">\n {lineWord(v.firstLine)} {inYourRows}: {v.firstRaw}\n </p>\n </div>\n );\n })()\n ) : null}\n </div>\n {(column.samples ?? []).length > 0 ? (\n <p className=\"break-words text-muted-foreground\">\n First values: {(column.samples ?? []).slice(0, 3).map(String).join(\" · \")}\n </p>\n ) : null}\n </div>\n );\n })}\n </div>\n\n <Separator />\n\n {/* VISION-REACH lane 5: THE NAME COLUMN REPEATS, SAID BEFORE THE WRITE. Persona P03's\n families file carried one row per student; 173 rows made 173 \"families\" and 33 of\n them twice. The count is shown, the default is the panel's reading of the rows\n (combine when some other column pins the rows to one record), and either answer is\n one click. */}\n {titleRepeating && titleHeader && titleStats ? (\n <div\n className=\"flex flex-wrap items-center gap-2 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n data-import-combine={combining ? \"combine\" : \"each\"}\n >\n <span>\n {titleHeader} repeats: {titleStats.distinct} names on {titleStats.filled} rows.\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Rows with the same {titleHeader}</span>\n <PickOne\n label={`What rows with the same ${titleHeader} become`}\n value={combine ?? combineDefault}\n disabled={busy}\n onChange={(picked) => setCombine(picked as \"combine\" | \"each\")}\n options={[\n { value: \"combine\", label: \"are one record; other columns keep every value\" },\n { value: \"each\", label: \"are separate records\" },\n ]}\n />\n </label>\n {combined && combined.multiValued.size > 0 ? (\n <span className=\"text-muted-foreground\" data-import-combine-lists=\"\">\n Lists in {[...combined.multiValued].join(\", \")}\n </span>\n ) : null}\n </div>\n ) : null}\n\n <div className=\"flex flex-wrap items-center gap-3\">\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Same row means the same</span>\n <PickOne\n label=\"What makes a row the same row\"\n value={dedupeKey}\n disabled={busy}\n onChange={(picked) => {\n setDedupeChosen(true);\n setDedupeKey(picked);\n }}\n options={[{ value: \"\", label: \"— nothing; write every row —\" }, ...declared.map((f) => ({ value: f.key, label: fieldName(f) }))]}\n />\n </label>\n {dedupeKey ? (\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">and when it is already here</span>\n <PickOne\n label=\"What happens to a row that is already here\"\n value={onDuplicate}\n disabled={busy}\n onChange={(picked) => setOnDuplicate(picked as \"skip\" | \"update\")}\n options={[\n { value: \"skip\", label: \"leave it alone\" },\n { value: \"update\", label: \"bring it up to date\" },\n ]}\n />\n </label>\n ) : null}\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Columns this table does not have</span>\n <PickOne\n label=\"What happens to a column this table does not have\"\n value={unmapped}\n disabled={busy}\n onChange={(picked) => {\n setUnmappedChosen(true);\n setUnmapped(picked as \"propose\" | \"create\" | \"ignore\");\n }}\n options={[\n { value: \"propose\", label: \"go to the approvals inbox\" },\n // SCR-N-7: adding a column outright is gated by the SAME right as the grid's \"+\",\n // and it is ABSENT rather than disabled for anybody else — a dead control that\n // explains nothing is the thing this platform forbids. The default choice above\n // does the same job for them, so nobody is stuck.\n ...(rights.admin ? [{ value: \"create\", label: \"are added straight away\" }] : []),\n { value: \"ignore\", label: \"are left out\" },\n ]}\n />\n </label>\n </div>\n\n {repeats.length > 0 ? (\n <label className=\"flex items-center gap-1.5\" data-import-repeats=\"\">\n <input type=\"checkbox\" checked={skipRepeats} disabled={busy} onChange={(e) => setSkipRepeats(e.target.checked)} />\n Skip {repeats.length} repeated row{repeats.length === 1 ? \"\" : \"s\"} ({linesWord(repeats.map((r) => r.row + 1), lineWord)})\n </label>\n ) : null}\n\n {newChoiceWords.map((ask) => {\n const words = ask.words.map((w) => `“${w}”`).join(\", \");\n const column = fieldName(ask.field);\n const canAdd = rights.admin && nudge !== \"never_add\";\n return (\n <div\n key={ask.field.key}\n className=\"flex flex-wrap items-center gap-2 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n data-import-new-choices={ask.field.key}\n >\n <span>\n {ask.words.length === 1 ? `${words} is not one of ${column}'s choices.` : `${words} are not among ${column}'s choices.`}{\" \"}\n {nudge === \"always_add\" && rights.admin\n ? `Your organization adds new choices without asking, so ${ask.words.length === 1 ? \"it is\" : \"they are\"} added when you import.`\n : canAdd\n ? `Add ${ask.words.length === 1 ? \"it\" : \"them\"}, or the rows that use ${ask.words.length === 1 ? \"it\" : \"them\"} are refused.`\n : `The rows that use ${ask.words.length === 1 ? \"it\" : \"them\"} are refused${rights.admin ? \" (your organization does not add new choices from an import)\" : \" — only someone who manages this table can add choices\"}.`}\n </span>\n {canAdd && nudge !== \"always_add\" ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={busy || addingWords !== null}\n onClick={() => void addChoiceWords(ask.field, ask.words)}\n >\n {addingWords === ask.field.key ? \"Adding…\" : `Add to ${column}`}\n </Button>\n ) : null}\n </div>\n );\n })}\n\n {relationProblem ? <RefusalNotice error={relationProblem} /> : null}\n {relationAsks.map((ask) => {\n const column = fieldName(ask.field);\n const table = ask.index.tableName;\n const choice = choiceFor(ask.field.key);\n const setChoice = (patch: Partial<{ unmatched: UnlinkedChoice; ambiguous: UnlinkedChoice }>) =>\n setUnlinkedChoice((held) => ({ ...held, [ask.field.key]: { ...choice, ...patch } }));\n const clean = ask.unmatched.length === 0 && ask.ambiguous.length === 0;\n return (\n <div\n key={ask.field.key}\n data-import-relation={ask.field.key}\n className={cn(\n \"flex flex-col gap-1 rounded border px-2 py-1.5\",\n clean ? \"bg-muted/40\" : \"border-amber-500/40 bg-amber-500/5\",\n )}\n >\n <span data-import-relation-linked=\"\">\n {column}: {ask.linked} of {ask.named} rows link to {table} by name\n </span>\n {ask.unmatched.length > 0 ? (\n <div className=\"flex flex-col gap-1\" data-import-relation-unmatched=\"\">\n <span>\n Not in {table}:{\" \"}\n {ask.unmatched\n .slice(0, 6)\n .map(([name, lines]) => `“${name}” (${linesWord(lines, lineWord)})`)\n .join(\", \")}\n {ask.unmatched.length > 6 ? ` +${ask.unmatched.length - 6}` : \"\"}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those rows</span>\n <PickOne\n label={`What rows naming a record not in ${table} do`}\n value={choice.unmatched}\n disabled={busy}\n onChange={(picked) => setChoice({ unmatched: picked as UnlinkedChoice })}\n options={[\n ...(ask.index.titleField ? [{ value: \"create\", label: `add the names to ${table}` }] : []),\n { value: \"empty\", label: \"import with no link\" },\n { value: \"skip\", label: \"are skipped\" },\n ]}\n />\n </label>\n </div>\n ) : null}\n {ask.ambiguous.length > 0 ? (\n <div className=\"flex flex-col gap-1\" data-import-relation-ambiguous=\"\">\n <span>\n More than one record in {table}:{\" \"}\n {ask.ambiguous\n .slice(0, 6)\n .map(([name, seen]) => `“${name}” ×${seen.count} (${linesWord(seen.lines, lineWord)})`)\n .join(\", \")}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those rows</span>\n <PickOne\n label={`What rows naming more than one record in ${table} do`}\n value={choice.ambiguous}\n disabled={busy}\n onChange={(picked) => setChoice({ ambiguous: picked as UnlinkedChoice })}\n options={[\n { value: \"merge\", label: `combine the duplicates in ${table}` },\n { value: \"empty\", label: \"import with no link\" },\n { value: \"skip\", label: \"are skipped\" },\n ]}\n />\n </label>\n </div>\n ) : null}\n </div>\n );\n })}\n\n {dateAsks\n .filter((ask) => ask.dates.unreadable.length > 0)\n .map((ask) => {\n const miss = ask.dates.unreadable;\n const byWord = new Map<string, number[]>();\n for (const m of miss) byWord.set(m.raw, [...(byWord.get(m.raw) ?? []), m.row + 1]);\n return (\n <div\n key={ask.header}\n data-import-dates={ask.header}\n className=\"flex flex-col gap-1 rounded border border-amber-500/40 bg-amber-500/5 px-2 py-1.5\"\n >\n <span>\n {ask.label}: {miss.length} {miss.length === 1 ? \"cell is\" : \"cells are\"} not a date —{\" \"}\n {[...byWord.entries()]\n .slice(0, 4)\n .map(([raw, lines]) => `“${raw}” (${linesWord(lines, lineWord)})`)\n .join(\", \")}\n {byWord.size > 4 ? ` +${byWord.size - 4}` : \"\"}\n </span>\n <label className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">Those cells</span>\n <PickOne\n label={`What cells of ${ask.header} that are not dates do`}\n value={dateMiss[ask.header] ?? \"empty\"}\n disabled={busy}\n onChange={(picked) => setDateMiss((held) => ({ ...held, [ask.header]: picked as \"empty\" | \"skip\" }))}\n options={[\n { value: \"empty\", label: \"are left empty\" },\n { value: \"skip\", label: \"skip their rows\" },\n ]}\n />\n </label>\n </div>\n );\n })}\n\n {ruleVerdicts.length > 0 ? (\n <RefusalNotice\n error={refusalOf(\n \"refused_by_rule\",\n `${refusedByRules} value${refusedByRules === 1 ? \"\" : \"s\"} in this file would be refused by ${\n ruleVerdicts.length === 1\n ? `the rules of ${fieldName(ruleVerdicts[0]!.field)}`\n : `the rules of ${ruleVerdicts.length} columns`\n } before anything is written. Nothing has been written yet.`,\n \"Change where those columns go, or fix the file and pick it again. To go ahead, the rest is written and every refused row is listed afterwards.\",\n )}\n actions={\n <label className=\"mt-1 flex items-center gap-1.5\" data-import-go-ahead=\"\">\n <input\n type=\"checkbox\"\n checked={goAheadAnyway}\n disabled={busy}\n onChange={(e) => setGoAheadAnyway(e.target.checked)}\n />\n Import the rest anyway\n </label>\n }\n />\n ) : null}\n\n {/* VISION-REACH G6: A STEP THAT FAILED SAYS SO WHERE THE PERSON IS LOOKING — beside the\n button they pressed, with the way to try again. It was printed at the top of a long\n rail, out of sight, and the button simply went back to \"Import 200 rows\". */}\n {problem ? (\n <div data-import-run-problem=\"\">\n <RefusalNotice\n error={problem}\n actions={\n <Button size=\"sm\" variant=\"outline\" className=\"mt-1\" disabled={busy} onClick={() => void run()}>\n Try again\n </Button>\n }\n />\n </div>\n ) : null}\n\n <div className=\"flex items-center gap-2\">\n <Button\n size=\"sm\"\n disabled={\n busy || !rights.write || rows.length === 0 || titleMissing || (ruleVerdicts.length > 0 && !goAheadAnyway)\n }\n onClick={() => void run()}\n >\n {phase === \"linking\"\n ? \"Linking the names…\"\n : phase === \"declaring\"\n ? \"Adding the columns…\"\n : phase === \"writing\"\n ? `Writing… ${progress} of ${effectiveRows.length}`\n : combining\n ? `Import ${effectiveRows.length} records from ${rows.length} rows`\n : `Import ${rows.length} row${rows.length === 1 ? \"\" : \"s\"}`}\n </Button>\n <span className={cn(\"text-muted-foreground\", titleMissing && \"text-destructive\")}>\n {/* FIX-11B F2: the button and the sentence beside it stopped\n contradicting each other — \"Import 1000 rows\" next to \"0 of 9\n columns go into this table\" was VERIFIER-10's finding and\n VERIFIER-11 wrote it down again. A run that cannot happen says\n WHY and what to do, where the person is looking. */}\n {titleMissing\n ? `Nothing goes into ${titleFieldLabel} yet, so these records would have no name. Choose the column above, then this will run.`\n : columnsSentence(mappedCount, plan.columns.length - leftOut.size, unmapped) +\n (leftOut.size > 0 ? ` · ${leftOut.size} left out` : \"\")}\n {fileHash || titleMissing\n ? \"\"\n : \" · this browser cannot recognize the file again, so importing it twice would write it twice\"}\n </span>\n </div>\n </>\n ) : null}\n\n {/* IMPORT-2: the column step's own answer, said before the rows are counted,\n because adding columns to a table is a different thing from adding rows\n to it and a person who did it deserves to be told. */}\n {columnsAdded && columnsAdded.length > 0 ? (\n <p data-import-columns-added=\"\">\n {columnsAdded.filter((c) => c.state === \"accepted\").length} column\n {columnsAdded.filter((c) => c.state === \"accepted\").length === 1 ? \"\" : \"s\"} added:{\" \"}\n {inFileOrder(columnsAdded.filter((c) => c.state === \"accepted\"), source?.parsed.headers ?? []).map((c) => c.label || c.column).join(\", \")}\n {columnsAdded.some((c) => c.state === \"refused\") ? (\n <span className=\"text-muted-foreground\">\n {\" \"}· {columnsAdded.filter((c) => c.state === \"refused\").map((c) => `${c.column} — ${c.reason ?? \"could not be added\"}`).join(\"; \")}\n </span>\n ) : null}\n </p>\n ) : null}\n\n {alreadyRan ? <p className=\"text-muted-foreground\">{alreadyRan}</p> : null}\n\n {outcomes.length > 0 || summary || ledger ? (\n <>\n <Separator />\n <div className=\"flex flex-wrap items-center gap-2\">\n {/* FIX-11B F2: THE STORE'S NUMBERS, FOR THE WHOLE RUN.\n This sentence used to be a tally of the `outcomes` array, which\n is a sample of one call's answers — so a 400-row file that landed\n 312 and refused 88 printed \"196 landed · 0 already here · 54\n refused\" and 88 rows went missing without a word. It is the\n ledger now: what the store counted, over every call. */}\n <span>\n {ledger\n ? `${ledger.written} landed · ${ledger.duplicate} already here · ${ledger.refused} refused, of ${ledger.seen} row${ledger.seen === 1 ? \"\" : \"s\"} offered`\n : `${counts.landed} landed · ${counts.duplicate} already here · ${counts.refused} refused`}\n </span>\n {ledger && !ledger.final && phase !== \"writing\" ? (\n <span className=\"text-destructive\">\n The run stopped here, so the rest of the file was never offered — these are the rows\n that were dealt with before it stopped, not the whole file.\n </span>\n ) : null}\n {(ledger ? ledger.refused + ledger.duplicate : counts.refused + counts.duplicate) > 0 ? (\n <>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"all\" && \"font-medium\")} onClick={() => setShow(\"all\")}>\n everything that did not land\n </button>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"refused\" && \"font-medium\")} onClick={() => setShow(\"refused\")}>\n refused\n </button>\n <button type=\"button\" className={cn(\"underline underline-offset-2\", show === \"duplicate\" && \"font-medium\")} onClick={() => setShow(\"duplicate\")}>\n already here\n </button>\n </>\n ) : null}\n </div>\n {summary ? <p className=\"text-muted-foreground\">{summary}</p> : null}\n {/* VISION-REACH lane 5: THE ROWS THAT WERE NOT ADDED, SAID AS ONE LOUD LINE WITH ITS\n REASONS AND A FILE. \"43 refused\" at the end of a sentence was read as done; 43 near-\n identical rows below it were not read at all. The notice the table page keeps\n (`ImportNotice`) says the same thing until it is dismissed. */}\n {ledger && ledger.final && ledger.refused > 0 ? (\n <div data-import-refused-summary=\"\">\n <RefusalNotice\n error={refusalOf(\n \"refused_by_rule\",\n `${ledger.refused} of ${ledger.seen} rows were not added.`,\n \"Download them, fix the file or the names, and import again.\",\n )}\n actions={\n <div className=\"flex flex-col gap-1 pt-0.5\">\n <ul className=\"flex flex-col gap-0.5\" data-import-refused-reasons=\"\">\n {groupReasons(outcomes.filter((o) => o.outcome === \"refused\").map((o) => (o.outcome === \"refused\" ? o.reason : \"\"))).map((g) => (\n <li key={g.reason}>\n {g.count} row{g.count === 1 ? \"\" : \"s\"}: {g.example}\n </li>\n ))}\n </ul>\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"self-start\"\n onClick={() =>\n offerDownload(\n refusedFileName(fileName),\n refusedRowsCsv(\n outcomes.flatMap((o) => (o.outcome === \"refused\" ? [{ row: o.row, reason: o.reason, source: o.source }] : [])),\n (n) => (source ? sentLines?.[n - 1] ?? n : lineInYourFile(sentLines?.[n - 1] ?? n)),\n ),\n )\n }\n >\n Download the rows not added\n </Button>\n </div>\n }\n />\n </div>\n ) : null}\n {afterWrite && keptAside.length > 0 ? (\n <div data-import-kept-aside=\"\" className=\"flex flex-col gap-0.5\">\n <p>\n {keptAside.length} cell{keptAside.length === 1 ? \" was\" : \"s were\"} kept aside and left empty; every other value in those rows was written.\n </p>\n <ul className=\"flex flex-col gap-0.5 text-muted-foreground\">\n {keptAside.map((c) => (\n <li key={`${c.header}:${c.line}`}>\n {c.header}, {source ? `row ${c.line}` : `line ${lineInYourFile(c.line)}`}: {c.raw} — {c.why}\n </li>\n ))}\n </ul>\n </div>\n ) : null}\n {repeatsSkipped > 0 ? (\n <p className=\"text-muted-foreground\" data-import-repeats-skipped=\"\">\n {repeatsSkipped} repeated row{repeatsSkipped === 1 ? \"\" : \"s\"} skipped\n </p>\n ) : null}\n\n {/* THE ROWS THAT DID NOT LAND, WITH THE ROW ITSELF. A count nobody can\n act on is the thing the store now refuses to hand back, and this\n is where that matters: the line of the spreadsheet is right here. */}\n {/* FIX-11B F2: A SHORT LIST NEVER READS AS THE WHOLE STORY. The door\n caps the rows it hands back, and this table caps them again at 200.\n When either cap bites, the screen says so with the number it is\n short by, rather than letting a person count the lines and believe\n that is all there was. */}\n {ledger && show === \"all\" && ledger.refused + ledger.duplicate > interesting.length ? (\n <p className=\"text-muted-foreground\">\n {interesting.length} of the {ledger.refused + ledger.duplicate} row\n {ledger.refused + ledger.duplicate === 1 ? \" that\" : \"s that\"} did not land\n {interesting.length === 1 ? \" is\" : \" are\"} listed below by their {source ? \"row\" : \"line in your file\"} —\n the rest stay with this run and are not all shown at once.\n </p>\n ) : null}\n {interesting.length > 0 ? (\n <div className=\"max-h-64 overflow-auto rounded border\">\n <table className=\"w-full\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"Row\" : \"Line in your file\"}</th>\n <th className=\"px-2 py-1 text-left font-medium\">What happened</th>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"The row\" : \"The row in your file\"}</th>\n </tr>\n </thead>\n <tbody>\n {interesting.slice(0, 200).map((o) => (\n <tr key={`${o.outcome}-${o.row}`} className=\"border-t align-top\">\n <td className=\"px-2 py-1\">{source ? (sentLines?.[o.row - 1] ?? o.row) : lineInYourFile(sentLines?.[o.row - 1] ?? o.row)}</td>\n <td className=\"px-2 py-1\">\n {o.outcome === \"refused\" ? (\n <RefusalLine\n error={refusalOf(\"refused_by_rule\", o.reason, source ? \"Fix this row where it came from and save it again.\" : \"Fix this line in your file and import it again.\")}\n />\n ) : o.outcome === \"duplicate\" ? (\n <span className=\"text-muted-foreground\">{o.reason}</span>\n ) : (\n \"written\"\n )}\n </td>\n <td className=\"max-w-96 px-2 py-1 text-muted-foreground\">\n {o.outcome === \"refused\"\n ? Object.entries(o.source)\n .map(([k, v]) => `${k}: ${String(v ?? \"\")}`)\n .join(\" · \")\n : \"\"}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : null}\n\n {proposals.length > 0 ? (\n <ul className=\"flex flex-col gap-0.5\">\n {proposals.map((p) => (\n <li key={p.column} className=\"text-muted-foreground\">\n <span className=\"font-medium text-foreground\">{p.column}</span>\n {p.state === \"waiting\"\n ? \" is waiting in the approvals inbox.\"\n : p.state === \"accepted\"\n ? \" was added as a column.\"\n : p.state === \"ignored\"\n ? \" was left out.\"\n : p.state === \"refused\"\n ? ` could not be added: ${p.reason ?? \"\"}`\n : ` — ${p.state}`}\n </li>\n ))}\n </ul>\n ) : null}\n\n {/* FIX-12 F2: THE REPORT IS READ, THEN DISMISSED — IN THAT ORDER.\n The run used to close the panel itself the instant the last row\n landed, so this whole block existed for less than a paint on any\n file small enough to finish in one call. Nothing closes it now but\n this button, and the sentence beside it says where the refused rows\n live once it is pressed: on the run itself, in the list below. */}\n {phase === \"done\" ? (\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button size=\"sm\" onClick={() => onDone?.(ledger?.written ?? 0)}>\n Done\n </Button>\n {(ledger?.refused ?? 0) > 0 ? (\n <span className=\"text-muted-foreground\">\n The {ledger?.refused} row{ledger?.refused === 1 ? \"\" : \"s\"} that {ledger?.refused === 1 ? \"was\" : \"were\"} refused\n {ledger?.refused === 1 ? \" is\" : \" are\"} kept with this import — open {ledger?.refused === 1 ? \"it\" : \"them\"} again from the list of imports below, with the\n reason and the line from your file on each.\n </span>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null}\n\n {/* ── FIX-12 F2: THE RUNS THIS TABLE ALREADY HAD. ─────────────────────\n A refusal a person did not catch in the moment was unreachable: no\n screen asked the store for it, and the store had it the whole time.\n Every run this table has had is here, newest first, and one with\n refused rows opens them — the store's own sentence and the line of the\n file, the same two things the live report shows. */}\n {runsProblem ? <RefusalNotice error={runsProblem} /> : null}\n {runs && runs.length > 0 ? (\n <>\n <Separator />\n <p className=\"font-medium\">Imports into this table</p>\n <ul className=\"flex flex-col gap-1\">\n {runs.map((r) => (\n <li key={r.import_id} className=\"flex flex-col gap-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium\">{r.source_name ?? \"a file\"}</span>\n <span className=\"text-muted-foreground\">\n {new Date(r.opened_at).toLocaleString()} · {r.rows_written} landed ·{\" \"}\n {r.rows_duplicate} already here · {r.rows_refused} refused, of {r.rows_seen} row\n {r.rows_seen === 1 ? \"\" : \"s\"} offered\n </span>\n {r.rows_refused > 0 ? (\n <button\n type=\"button\"\n className=\"underline underline-offset-2\"\n aria-expanded={openRun === r.import_id}\n onClick={() => void openRefusals(r.import_id)}\n >\n {openRun === r.import_id\n ? \"hide the rows it refused\"\n : `see the ${r.rows_refused} row${r.rows_refused === 1 ? \"\" : \"s\"} it refused`}\n </button>\n ) : null}\n </div>\n {openRun === r.import_id ? (\n runProblem ? (\n <RefusalNotice error={runProblem} />\n ) : runRows ? (\n <>\n {runRows.note ? <p className=\"text-muted-foreground\">{runRows.note}</p> : null}\n <div className=\"max-h-64 overflow-auto rounded border\">\n <table className=\"w-full\">\n <thead className=\"sticky top-0 bg-muted\">\n <tr>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"Row\" : \"Line in your file\"}</th>\n <th className=\"px-2 py-1 text-left font-medium\">What happened</th>\n <th className=\"px-2 py-1 text-left font-medium\">{source ? \"The row\" : \"The row in your file\"}</th>\n </tr>\n </thead>\n <tbody>\n {runRows.rows.map((row, i) => {\n const refusedRowSource = (row.source ?? {}) as Record<string, unknown>;\n return (\n <tr key={`${r.import_id}-${String(row.row ?? i)}`} className=\"border-t align-top\">\n <td className=\"px-2 py-1\">{typeof row.row === \"number\" ? lineInYourFile(row.row) : String(row.row ?? \"\")}</td>\n <td className=\"px-2 py-1\">\n <RefusalLine\n error={refusalOf(\n \"refused_by_rule\",\n String(row.reason ?? \"This row was refused.\"),\n \"Fix this line in your file and import it again.\",\n )}\n />\n </td>\n <td className=\"max-w-96 px-2 py-1 text-muted-foreground\">\n {Object.entries(refusedRowSource)\n .map(([k, v]) => `${k}: ${String(v ?? \"\")}`)\n .join(\" · \")}\n </td>\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n </>\n ) : (\n <p className=\"text-muted-foreground\">Reading the rows this import refused…</p>\n )\n ) : null}\n </li>\n ))}\n </ul>\n </>\n ) : null}\n\n {table.error ? <RefusalNotice error={table.error} onRetry={table.reload} /> : null}\n </div>\n );\n}\n","// src/importRuleCheck.ts — @ai-matrx/records-ui · lane REFUSAL-SWEEP (2026-09-23)\n//\n// THE IMPORT ASKS THE COLUMN RULES BEFORE IT WRITES.\n//\n// Until this file the wizard mapped a file's columns, pressed Import, and learnt\n// what each column's rules thought of the file from the store — row by row,\n// AFTER the write, as a list of refusals to go and fix. The bulk paste already\n// asked first (`pasteValues.ts`); this is the same question asked over a whole\n// file, through the SAME two bodies, so an import, a paste and a typed answer can\n// never disagree about one value:\n//\n// · `valueFromPastedText` — `@ai-matrx/records`' `coerceTypedAnswer`: does this\n// text mean a value of this column's kind at all?\n// · `predictValueRefusals` — `custom.validate_values` mirrored: would the\n// column's declared rules (min, max, length, pattern…) refuse it?\n//\n// Only the MAPPED column is judged for each cell. A required column the file\n// never mentions is not this column's refusal, and the wizard says that\n// elsewhere (the title column line).\n\nimport type { Field, RelationNameIndex } from \"@ai-matrx/records\";\nimport { predictValueRefusals } from \"@ai-matrx/records/core\";\n\nimport { valueFromPastedText, type ChoiceOptions } from \"./pasteValues\";\nimport { editorKindFor } from \"./parity\";\n\nexport interface ImportColumnVerdict {\n /** The column's header in the file. */\n header: string;\n /** The table's column it goes to. */\n field: Field;\n /** How many of the file's rows this column's rules would refuse. */\n refused: number;\n /** How many rows carried a value in this column at all. */\n judged: number;\n /** The first refusal, in the store's own words. */\n firstWhy: string;\n /** The line in the file (1 = first data row) and the text it carried. */\n firstLine: number;\n firstRaw: string;\n}\n\n/**\n * Every mapped column whose rules would refuse at least one row of the file.\n * An empty answer means the rules have nothing to say — never \"unchecked\".\n */\nexport interface ImportRefusedCell {\n /** The cell's column header in the file, its data row (1 = first data row) and the text it carried. */\n header: string;\n line: number;\n raw: string;\n /** The reason, in the store's own words. */\n why: string;\n}\n\n/** Every cell of the mapped columns the rules would refuse, in file order. The one judge. */\nexport function refusedCellsOf(\n fields: Field[],\n rows: Array<Record<string, string>>,\n mapping: Record<string, string>,\n choiceOptions?: ReadonlyMap<string, ChoiceOptions>,\n relationNames?: ReadonlyMap<string, RelationNameIndex>,\n): Array<ImportRefusedCell & { judged: number; field: Field }> {\n const byKey = new Map(fields.map((f) => [f.key, f]));\n const cells: Array<ImportRefusedCell & { judged: number; field: Field }> = [];\n for (const [header, key] of Object.entries(mapping)) {\n const field = byKey.get(key);\n if (!field) continue;\n const kind = String(editorKindFor(field));\n const isChoice = kind === \"select\" || kind === \"multi_select\";\n const options = choiceOptions?.get(key);\n if (isChoice && !options) continue;\n const named = relationNames?.get(key);\n if (kind === \"relation\" && !named) continue;\n let judged = 0;\n const mine: ImportRefusedCell[] = [];\n rows.forEach((row, i) => {\n const raw = String(row[header] ?? \"\").trim();\n if (raw === \"\") return;\n judged += 1;\n const meant = valueFromPastedText(field, raw, options, named);\n let why: string | null = null;\n if (\"unmatched\" in meant) return; // the enum ask names these words, with Add\n if (\"unmatchedNames\" in meant) return; // the relation ask names these, with its choices\n if (\"refusal\" in meant) why = meant.refusal;\n else {\n const predicted = predictValueRefusals([field], { [key]: meant.value }).filter(\n (p) => p.field_key === undefined || p.field_key === key,\n );\n if (predicted.length > 0) why = predicted[0]!.message;\n }\n if (why !== null) mine.push({ header, line: i + 1, raw, why });\n });\n for (const c of mine) cells.push({ ...c, judged, field });\n }\n return cells;\n}\n\nexport function checkImportRules(\n fields: Field[],\n rows: Array<Record<string, string>>,\n mapping: Record<string, string>,\n /**\n * A choice column's options, by field key (SAVE-AS-TABLE-EVERYWHERE). Without them a choice word\n * cannot be judged at all, and this used to say \"3 of 3 rows would be refused … its options have\n * not been read yet\" over rows whose words WERE choices — so a choice column is judged only once\n * its options are in hand, and a word it does not know is the enum ask's to raise, not this.\n */\n choiceOptions?: ReadonlyMap<string, ChoiceOptions>,\n /**\n * VISION-REACH G1: a relation column's target indexed by the file's names. A relation column is\n * judged only once its index is in hand, and a name matching nothing (or two records) is the\n * relation ask's to raise, with its choices — never a rule refusal.\n */\n relationNames?: ReadonlyMap<string, RelationNameIndex>,\n): ImportColumnVerdict[] {\n const verdicts = new Map<string, ImportColumnVerdict>();\n for (const c of refusedCellsOf(fields, rows, mapping, choiceOptions, relationNames)) {\n const have = verdicts.get(c.header);\n if (have) have.refused += 1;\n else verdicts.set(c.header, { header: c.header, field: c.field, refused: 1, judged: c.judged, firstWhy: c.why, firstLine: c.line, firstRaw: c.raw });\n }\n return [...verdicts.values()];\n}\n","// src/pasteValues.ts — @ai-matrx/records-ui\n//\n// WHAT A BLOCK OF SPREADSHEET TEXT MEANS TO THIS TABLE, WORKED OUT BEFORE ANY\n// OF IT IS WRITTEN.\n//\n// The clipboard hands over STRINGS. A column does not take strings — it takes a\n// number, a date, a tick, a document — and until a string has been turned into\n// one of those, nobody can say whether the store would accept it. Crew C, on\n// 2026-09-21, had fifty US airports in a spreadsheet and no way to get them in\n// but two hundred and fifty double-clicks; the grid had no paste at all. This\n// is the half that makes a paste answerable in advance: every cell is coerced\n// the way that column's own editor would coerce it, and then judged by the\n// store's OWN mirror of `custom.validate_values`, so the sentence a person\n// reads in the preview is the sentence the door would have said.\n//\n// THE COERCION IS `@ai-matrx/records`' `coerceTypedAnswer`, NOT A SECOND\n// OPINION. A column drawn as money must read a pasted \"$1,250.50\" as money; a\n// file that classified fields its own way would let a paste and a typed value\n// disagree about the same column, which is the class of defect the grid spent\n// September closing — and which the public booking page was still paying for\n// in September (\"Vehicle Year takes a number, and it was given a string\")\n// because the coercion lived in the grid and nowhere else.\n//\n// A CELL THAT CANNOT BE COERCED IS REFUSED, NEVER GUESSED. Writing 0 for\n// \"about twelve\" or today's date for \"soon\" is how a spreadsheet quietly\n// corrupts a table. The cell is left alone and the person is told, in words,\n// what that column takes.\n\nimport { predictValueRefusals } from \"@ai-matrx/records/core\";\nimport type { ChoiceOptions, Field, RelationNameIndex, StoredRecord, Uuid } from \"@ai-matrx/records\";\nimport { coerceTypedAnswer, optionKey } from \"@ai-matrx/records\";\nimport { calendarDayOf, hasTimePart, isDateField } from \"./dates\";\nimport { editorKindFor } from \"./parity\";\nimport { recordName } from \"./names\";\nimport { fieldName } from \"./names\";\n\n/** One pasted cell, after its column has had a look at it. */\nexport interface PastedCell {\n key: string;\n /**\n * The column's NAME, the way the grid's own header writes it. The preview\n * used to draw `key` in its header row, so the one screen that promises\n * \"exactly what will be stored\" printed `job_number` and `scheduled_date`\n * over columns the grid calls Job Number and Scheduled Date (FIX-10C F8,\n * 2026-09-22). One resolver, `fieldName`, everywhere a label is shown.\n */\n column: string;\n /** Exactly what was on the clipboard, kept so a refusal can quote it. */\n raw: string;\n /** What would be written. Meaningless when `refusal` is set. */\n value: unknown;\n /** The sentence that says why it will not be written, or null. */\n refusal: string | null;\n /**\n * WHAT THE PERSON WILL SEE IN THAT CELL once it is written — never the\n * machine id that is stored underneath it.\n *\n * 🚨 THIS IS THE OTHER HALF OF THE SAME DEFECT. A choice column stores the\n * OPTION RECORD'S ID (FLD-5/FLD-6), so the preview that says \"the values\n * below are exactly what will be stored\" printed\n * `530808bf-9f2d-4062-bc09-b8cc3b162f2a` where the person had pasted *Drain\n * Cleaning*. Both sentences were true and the screen was still lying, because\n * a person reads a screen to recognize their own data. So the plan carries\n * the WORDS beside the value: the id is what lands, the word is what is\n * shown, and `custom._words_for`'s display arm is the rule both obey.\n * `null` means the value shows itself (a number, a date, a piece of text).\n */\n display: string | null;\n}\n\n/** One row of the pasted block, and where it would land. */\nexport interface PastedRow {\n /** The record this row writes over, or null when a record would be created. */\n recordId: Uuid | null;\n /** 1-based, as a person counts rows in the thing they copied. */\n fromLine: number;\n cells: PastedCell[];\n}\n\n/** What the whole paste would do — the thing the preview draws. */\nexport interface PastePreviewPlan {\n rows: PastedRow[];\n /** Records that already exist and would be updated. */\n updates: number;\n /** Records that do not exist yet and would be created. */\n creates: number;\n /** Cells that would actually be written. */\n cells: number;\n /** Every cell that will be left alone, with its sentence. */\n refusals: Array<{ fromLine: number; column: string; raw: string; why: string }>;\n /** Cells with no column to land in — the block was wider than the table. */\n pastRightEdge: number;\n /**\n * Words a choice column did not recognize, per column, deduplicated and in\n * the order they were first pasted. The preview offers these back as ONE\n * explicit \"add these N options\" action; nothing here is ever created on its\n * own, because a typo turned into a lifecycle stage is a column nobody chose.\n */\n unmatchedOptions: Array<{ fieldKey: string; column: string; words: string[] }>;\n /**\n * Set when the pasted block's first line named this table's columns: it was read as a header\n * (matched BY NAME, as the Sheet does) and left out of the rows. `unmatched` are the pasted\n * columns whose name no column here answers to — they are not written, and the preview names them.\n */\n header?: { unmatched: string[] };\n /** Lines the person chose to drop (\"fill only the existing rows\"): how many were left out. */\n droppedLines?: number;\n}\n\n/**\n * A choice column's own options, ready to be matched against a pasted WORD.\n *\n * WHY THIS EXISTS. Until 2026-09-21 a word pasted into a choice column was\n * refused outright — \"a pasted word is not one of its options\" — which is true\n * of a raw string and useless to the person holding a spreadsheet whose Status\n * column says \"Completed\" fifty times. Airtable, the champion here, matches the\n * word to the option labeled Completed, and so does this. What it will NOT do\n * is invent an option: a typo would silently become a new lifecycle stage, and\n * every board, filter and rollup built on that column would quietly grow a\n * column nobody chose. Unmatched words are REFUSED, named, and offered back as\n * one explicit \"add these\" action in the preview.\n */\n/**\n * 🚨 THE CORE'S TYPE, RE-EXPORTED (TAILS-3, 2026-09-21). It was declared here\n * and the coercion that reads it now lives in `@ai-matrx/records`, so there is\n * one shape, not two that drift. `choiceOptionsOf` stays here because building\n * the index needs `recordName`, which is a screen concern.\n */\nexport type { ChoiceOptions };\n\n/** Index one field's option records the way a paste needs to read them. */\n/**\n * The WORD a stored choice value shows, out of the same index the coercion\n * matched against. `ChoiceOptions` is keyed word → id (that is the direction a\n * paste needs), so this walks the labels it already carries and answers the one\n * whose id matches. Deliberately not a second index: two maps that can disagree\n * about what an option is called is the class this whole file exists to avoid.\n */\nexport function wordForStoredChoice(options: ChoiceOptions | undefined, value: unknown): string | null {\n if (options === undefined || typeof value !== \"string\" || value === \"\") return null;\n for (const label of options.labels) {\n if (options.byWord.get(label.toLowerCase()) === value) return label;\n }\n return null;\n}\n\nexport function choiceOptionsOf(options: StoredRecord[]): ChoiceOptions {\n const byWord = new Map<string, string>();\n const labels: string[] = [];\n for (const option of options) {\n // WHAT IS STORED IS THE OPTION RECORD'S ID. FLD-5/FLD-6: every pick-list is\n // already a Table, so a list field holds the id of the option's record —\n // and `predictValueRefusals`, which is the store's own validator mirrored,\n // refuses anything that is not a uuid by name. Writing the option's slug\n // here would make the preview promise a write the door then refuses.\n const id = option.id as string;\n const key = optionKey(option);\n const label = recordName(option.data as never, null, \"\");\n if (label) {\n labels.push(label);\n // First one wins: two options with the same label are a data problem in\n // the choices Table, and silently preferring the later one would make a\n // paste land somewhere the person cannot see.\n if (!byWord.has(label.toLowerCase())) byWord.set(label.toLowerCase(), id);\n }\n // The KEY and the ID are matched too, because an export of this table\n // writes one of them and a round trip through a spreadsheet has to come\n // back in.\n if (key && !byWord.has(String(key).toLowerCase())) byWord.set(String(key).toLowerCase(), id);\n if (id && !byWord.has(id.toLowerCase())) byWord.set(id.toLowerCase(), id);\n }\n return { byWord, labels };\n}\n\n/**\n * Turn one clipboard string into the value this Field holds — or say, in a\n * sentence a person can act on, why it is not one.\n *\n * 🚨 IT IS ONE CALL NOW, AND THAT IS THE FIX (TAILS-3, 2026-09-21). This\n * function's body used to BE the coercion — a good one, and the only one,\n * while the two doors a STRANGER uses carried none. AGENT-BUILDS-2's closing\n * walk found Ironclad Mobile Mechanic's public booking page unbookable over\n * any table with a number field: \"Vehicle Year takes a number, and it was\n * given a string\". A capability scoped to the feature that surfaced it.\n *\n * So the body moved to `@ai-matrx/records`' `coerceTypedAnswer`, which the\n * public form, the public booking, a portal edit, a CSV import and this paste\n * all call. A clipboard cell and a typed-in answer are the same thing — a\n * string a person means as a value — and there is now ONE body that says what\n * they mean. The label stays this package's, so a refusal names the column the\n * way the grid's own header does.\n */\nexport function valueFromPastedText(\n field: Field,\n raw: string,\n /** This column's options, when the caller has loaded them. */\n options?: ChoiceOptions,\n /**\n * VISION-REACH G1: a relation column's target, indexed by the names the paste or file carries\n * (`client.relationNamesMatch` → `relationNameIndexOf`). Without it a name is refused.\n */\n relationNames?: RelationNameIndex,\n): ReturnType<typeof coerceTypedAnswer> {\n return coerceTypedAnswer(field, raw, {\n label: fieldName(field),\n ...(options ? { options } : {}),\n ...(relationNames ? { relationNames } : {}),\n });\n}\n\n/**\n * The whole plan, ready to be shown.\n *\n * `existingRowIds` are the rows the paste lands on, in the grid's order from\n * the anchor down; `overflow` are the block's remaining rows, which become new\n * records. `columnKeys` is the grid's column order from the anchor rightwards.\n */\nexport function planPastedBlock(args: {\n fields: Field[];\n /** This table's choice options, by field key. A choice column with no entry\n * here has not been read yet, and the planner says so rather than guessing. */\n options?: Map<string, ChoiceOptions>;\n /** Relation columns' targets indexed by name, by field key (VISION-REACH G1). */\n relationNames?: Map<string, RelationNameIndex>;\n /** Field key per pasted column, in order. A null means there is no column. */\n columnKeys: Array<string | null>;\n /** Rows landing on records that exist: recordId plus that row's raw cells. */\n onExisting: Array<{ recordId: Uuid; raw: Array<string | undefined> }>;\n /** Rows past the last row of the grid — each becomes a record. */\n onNew: Array<Array<string | undefined>>;\n /** Cells the grid already said have no column to land in. */\n pastRightEdge?: number;\n /** Carried onto the plan when the block's first line was read as a header. */\n header?: { unmatched: string[] };\n droppedLines?: number;\n}): PastePreviewPlan {\n const byKey = new Map(args.fields.map((f) => [f.key, f]));\n const rows: PastedRow[] = [];\n const refusals: PastePreviewPlan[\"refusals\"] = [];\n const unmatched = new Map<string, { column: string; words: string[] }>();\n let cells = 0;\n\n const lines: Array<{ recordId: Uuid | null; raw: Array<string | undefined> }> = [\n ...args.onExisting.map((r) => ({ recordId: r.recordId as Uuid | null, raw: r.raw })),\n ...args.onNew.map((raw) => ({ recordId: null, raw })),\n ];\n\n lines.forEach((line, index) => {\n const fromLine = index + 1;\n const built: PastedCell[] = [];\n const accepted: Record<string, unknown> = {};\n for (let c = 0; c < args.columnKeys.length; c += 1) {\n const key = args.columnKeys[c];\n if (key == null) continue;\n const field = byKey.get(key);\n const raw = line.raw[c];\n if (field === undefined || raw === undefined) continue;\n const judged = valueFromPastedText(field, raw, args.options?.get(key), args.relationNames?.get(key));\n if (\"refusal\" in judged) {\n if (\"unmatched\" in judged && judged.unmatched) {\n const seen = unmatched.get(key) ?? { column: fieldName(field), words: [] };\n for (const word of judged.unmatched) {\n if (!seen.words.some((w) => w.toLowerCase() === word.toLowerCase())) seen.words.push(word);\n }\n unmatched.set(key, seen);\n }\n built.push({ key, column: fieldName(field), raw, value: null, refusal: judged.refusal, display: null });\n refusals.push({ fromLine, column: fieldName(field), raw, why: judged.refusal });\n continue;\n }\n built.push({\n key,\n column: fieldName(field),\n raw,\n value: judged.value,\n refusal: null,\n // The words, resolved once here rather than by whichever screen draws\n // the plan — a second resolver is a second answer to \"what is this\n // called\", and the raw clipboard text is the honest fallback because it\n // is literally what the person typed for this cell.\n display: wordForStoredChoice(args.options?.get(key), judged.value) ?? (\"words\" in judged ? judged.words ?? null : null),\n });\n accepted[key] = judged.value;\n }\n\n // THE STORE'S OWN MIRROR, ASKED ONCE PER ROW. `predictValueRefusals` is\n // `custom.validate_values` reproduced in TypeScript, so a required field\n // left empty, a value outside a declared range, a pattern a format\n // enforces and a formula written into all come back HERE, in the store's\n // own words, instead of as fifty round trips that each fail.\n // These are the store rules' own sentences, mirrored here: a message and a field key, no\n // hint, details or SQLSTATE, so `.message` is the whole of what a person reads.\n const predicted = predictValueRefusals(args.fields, accepted);\n for (const refusal of predicted) {\n const key = refusal.field_key;\n if (key === undefined) continue;\n const cell = built.find((b) => b.key === key && b.refusal === null);\n if (!cell) continue;\n cell.refusal = refusal.message;\n cell.value = null;\n delete accepted[key];\n refusals.push({\n fromLine,\n column: fieldName(byKey.get(key) ?? ({ key } as Field)),\n raw: cell.raw,\n why: refusal.message,\n });\n }\n\n cells += Object.keys(accepted).length;\n rows.push({ recordId: line.recordId, fromLine, cells: built });\n });\n\n // A NEW RECORD WITH NOTHING LEFT IN IT IS NOT A RECORD. If every cell of a\n // pasted row was refused, writing a blank row would leave a person deleting\n // rows they never asked for.\n const keepers = rows.filter(\n (row) => row.recordId !== null || row.cells.some((c) => c.refusal === null),\n );\n\n return {\n rows: keepers,\n updates: keepers.filter((r) => r.recordId !== null).length,\n creates: keepers.filter((r) => r.recordId === null).length,\n cells,\n refusals,\n pastRightEdge: args.pastRightEdge ?? 0,\n ...(args.header ? { header: args.header } : {}),\n ...(args.droppedLines ? { droppedLines: args.droppedLines } : {}),\n unmatchedOptions: [...unmatched.entries()].map(([fieldKey, seen]) => ({\n fieldKey,\n column: seen.column,\n words: seen.words,\n })),\n };\n}\n\n/** What one row would actually be written as — the accepted cells only. */\nexport function documentOf(row: PastedRow): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const cell of row.cells) if (cell.refusal === null) out[cell.key] = cell.value;\n return out;\n}\n\n/** Letter case and spacing aside: \" Service ADDRESS \" reads as \"service address\". */\nconst sameWords = (text: string): string => text.trim().replace(/\\s+/g, \" \").toLowerCase();\n\n/**\n * IS THE FIRST LINE OF A PASTED BLOCK THE TABLE'S OWN COLUMN NAMES? Then it is a header, not a row.\n *\n * The Sheet's paste read the first line as headers and matched each BY NAME (case and spacing\n * blind; `paste-header-match.ts`); the grid wrote by position, so a block copied WITH its header\n * line landed the header as a record. This is the Sheet's rule, kept to what a person pasting into\n * a table that already has rows means:\n * · it takes at least two lines (a header with nothing under it is not a paste of data);\n * · at least one cell names a column, and at least half of the non-empty cells do — a data line\n * that happens to repeat one column's name is not a header;\n * · the lines are not all the same (one value tiled over a selection is not a header).\n * A name two columns share matches neither (it is ambiguous), and no column is filled twice.\n *\n * `columnKeys` are the pasted columns' landing columns in order, `lines` the raw cells aligned to\n * them. Returns null when the first line is data; otherwise the column each pasted column writes\n * to (null = unmatched), the header cells that matched nothing, and the lines without the header.\n */\nexport function readPasteHeader(args: {\n fields: Field[];\n columnKeys: string[];\n lines: Array<Array<string | undefined>>;\n}): { columnKeys: Array<string | null>; unmatched: string[]; lines: Array<Array<string | undefined>> } | null {\n const { fields, columnKeys, lines } = args;\n if (lines.length < 2 || columnKeys.length === 0) return null;\n const head = lines[0] ?? [];\n const sameAsFirst = lines.every((line) => columnKeys.every((_, c) => (line[c] ?? \"\") === (head[c] ?? \"\")));\n if (sameAsFirst) return null;\n\n const byName = new Map<string, Field[]>();\n for (const f of fields) {\n for (const name of new Set([sameWords(fieldName(f)), sameWords(f.key.replace(/_/g, \" \"))])) {\n byName.set(name, [...(byName.get(name) ?? []), f]);\n }\n }\n const taken = new Set<string>();\n const mapped: Array<string | null> = columnKeys.map(() => null);\n let named = 0;\n let filled = 0;\n columnKeys.forEach((_, c) => {\n const cell = head[c];\n if (cell === undefined || cell.trim() === \"\") return;\n filled += 1;\n const hits = [...new Set(byName.get(sameWords(cell)) ?? [])];\n // Name first: the column whose display name reads the same; a key spelled the same is the fallback.\n const named1 = hits.filter((f) => sameWords(fieldName(f)) === sameWords(cell));\n const pick = named1.length > 0 ? named1 : hits;\n if (pick.length !== 1) return;\n const only = pick[0]!;\n named += 1;\n if (taken.has(only.key)) return;\n taken.add(only.key);\n mapped[c] = only.key;\n });\n if (named === 0 || named * 2 < filled) return null;\n const unmatched = columnKeys.flatMap((_, c) => {\n const cell = head[c];\n return mapped[c] === null && cell !== undefined && cell.trim() !== \"\" ? [cell.trim()] : [];\n });\n return { columnKeys: mapped, unmatched, lines: lines.slice(1) };\n}\n\n/**\n * THE SAME PASTE, JUDGED AGAIN — after a choice column gained options, or with its new rows\n * dropped (\"fill only the existing rows\"). It reads the plan's own rows, so what was matched by\n * name, and what was left out, stays as it was.\n */\nexport function replanPastedBlock(\n plan: PastePreviewPlan,\n args: {\n fields: Field[];\n options?: Map<string, ChoiceOptions>;\n relationNames?: Map<string, RelationNameIndex>;\n },\n change: { dropNew?: boolean } = {},\n): PastePreviewPlan {\n const creating = plan.rows.filter((r) => r.recordId === null);\n const dropped = change.dropNew ? creating.length : 0;\n return planPastedBlock({\n ...args,\n columnKeys: plan.rows[0]?.cells.map((c) => c.key) ?? [],\n onExisting: plan.rows\n .filter((r) => r.recordId !== null)\n .map((r) => ({ recordId: r.recordId as Uuid, raw: r.cells.map((c) => c.raw) })),\n onNew: change.dropNew ? [] : creating.map((r) => r.cells.map((c) => c.raw)),\n pastRightEdge: plan.pastRightEdge,\n ...(plan.header ? { header: plan.header } : {}),\n droppedLines: (plan.droppedLines ?? 0) + dropped,\n });\n}\n\n/**\n * DID THE STORE KEEP WHAT WAS WRITTEN? Compared in the column's own terms, never as JSON text.\n *\n * The read-back asked the store for each pasted row again and compared `JSON.stringify` of the\n * stored value with the written one. The store normalizes on the way in — a day may come back as\n * an instant, a number as text, a choice by another spelling of the same option — so a whole\n * column of values that WERE in the table was counted \"not stored\". Each kind is read the way the\n * store holds it: a day by its calendar day (an instant by its moment), a number by its value\n * (0 is a number), a choice by the option it names (through the column's own options index), and\n * only anything else by its JSON.\n */\nexport function storedValueAgrees(\n field: Field | undefined,\n stored: unknown,\n written: unknown,\n options?: ChoiceOptions,\n): boolean {\n const empty = (v: unknown) => v === undefined || v === null || v === \"\";\n if (empty(stored) || empty(written)) return empty(stored) && empty(written);\n if (field !== undefined) {\n if (isDateField(field)) {\n if (hasTimePart(written)) {\n const a = new Date(stored as string).getTime();\n const b = new Date(written as string).getTime();\n if (!Number.isNaN(a) && !Number.isNaN(b)) return a === b;\n } else {\n // A day the store hands back as midnight UTC is still THAT day, in any viewer's zone.\n const dayOf = (v: unknown) => (typeof v === \"string\" && /^\\d{4}-\\d{2}-\\d{2}/.test(v.trim()) ? v.trim().slice(0, 10) : calendarDayOf(v));\n const a = dayOf(stored);\n const b = dayOf(written);\n if (a !== null && b !== null) return a === b;\n }\n }\n const kind = editorKindFor(field);\n if (kind === \"number\" || kind === \"currency\" || kind === \"percent\") {\n const a = typeof stored === \"number\" ? stored : Number(String(stored).trim());\n const b = typeof written === \"number\" ? written : Number(String(written).trim());\n if (Number.isFinite(a) && Number.isFinite(b)) return a === b;\n }\n if (options !== undefined && typeof stored === \"string\" && typeof written === \"string\") {\n const option = (v: string) => options.byWord.get(v.trim().toLowerCase()) ?? v.trim().toLowerCase();\n return option(stored) === option(written);\n }\n }\n return JSON.stringify(stored) === JSON.stringify(written);\n}\n\n/**\n * ONCE A HEADER LINE IS READ, NOTHING ON IT IS JUDGED OR REPORTED. The grid's per-cell check runs\n * before the header is known, so it refuses \"Qty\" for a number column and \"Ordered On\" for a date\n * column as if they were data. The header line lands on the anchor row, so every refusal on that\n * row was about a header cell; drop them. (A column-level refusal repeats on the data lines.)\n */\nexport function refusalsBeyondTheHeader<R extends { rowId: string | null }>(\n refusals: ReadonlyArray<R>,\n headerRowId: string | undefined,\n): R[] {\n return headerRowId === undefined ? [...refusals] : refusals.filter((r) => r.rowId !== headerRowId);\n}\n\n/**\n * The columns the grid turned away (they take no written value at all), said once each — but only\n * the ones THE BLOCK ACTUALLY WRITES. The grid judges a paste by position before a header line has\n * been read; once the header maps the block by name, a positional refusal for a column the block\n * no longer touches (a \"Qty holds a number\" for a Brand column that was left out) is about a cell\n * that is not being pasted, so it is dropped. `fromLine: 0` means \"no row\": a column-level answer.\n */\nexport function columnsTheGridTurnedAway(\n turnedAway: ReadonlyArray<{ columnId: string; reason: string }>,\n columnKeys: ReadonlyArray<string | null>,\n columnName: (columnId: string) => string,\n already: PastePreviewPlan[\"refusals\"],\n): PastePreviewPlan[\"refusals\"] {\n const said = new Map<string, string>();\n for (const refused of turnedAway) {\n if (!columnKeys.includes(refused.columnId)) continue;\n if (already.some((r) => r.column === columnName(refused.columnId))) continue;\n said.set(refused.columnId, refused.reason);\n }\n return [...said].map(([columnId, why]) => ({ fromLine: 0, column: columnName(columnId), raw: \"\", why }));\n}\n\n/**\n * WHAT THE SPREADSHEET PRIMITIVE'S PER-CELL CHECK MAY SAY about a pasted cell. That check holds no\n * options and no relation answers, so a choice cell or a relation cell judged there reads as\n * refused every time (\"Status is a list and its options have not been read yet\") while the write\n * stores it. Those two kinds are judged only by `planPastedBlock`, after the options and names are\n * in hand; every other kind is judged here.\n */\nexport function gridRefusalForPastedCell(field: Field, value: unknown): string | undefined {\n const kind = editorKindFor(field);\n if (kind === \"relation\" || kind === \"select\" || kind === \"multi_select\") return undefined;\n const judged = valueFromPastedText(field, value === null ? \"\" : String(value));\n return \"refusal\" in judged ? judged.refusal : undefined;\n}\n","// src/importKinds.ts — @ai-matrx/records-ui · VISION-REACH G14 (2026-10-02)\n//\n// WHAT A NEW COLUMN HOLDS, CHOSEN IN THE IMPORT PANEL, AND THE ROWS THAT REPEAT.\n//\n// THE BREAK (persona P02, an HOA treasurer, run 2): seven date columns of a dues file — Move-in,\n// Q1–Q4 paid, Submitted — were written \"2026-05-16\", \"Mar 31, 2026\", \"8.4.2026\" and \"5/2/2026\" in\n// one column. The store's plan read that mix as text, the panel offered no way to say \"these are\n// dates\", and the store's own cell reader takes only year-month-day and slashed dates — so every\n// one landed as Text and nothing could sort or count by date. The same file carried one homeowner's\n// row twice, and the import wrote it twice by default.\n//\n// Champions: Airtable's CSV import (a field type per column, unreadable cells left empty and\n// counted) and Google Sheets' import (one date reader for every common spelling; \"remove\n// duplicates\" offered as a one-click step). The ONE date reader is `readTypedDate` in\n// `@ai-matrx/records` — the same reader the grid, paste and forms use — so a date a person can type\n// into a cell is a date an import reads.\n\nimport { readTypedDate } from \"@ai-matrx/records\";\n\n/** The kinds a NEW column can be made as from the import panel. */\nexport type ImportKind = \"text\" | \"date\" | \"number\" | \"currency\" | \"checkbox\" | \"email\" | \"phone\" | \"url\";\n\nexport const IMPORT_KINDS: ReadonlyArray<{ kind: ImportKind; label: string }> = [\n { kind: \"text\", label: \"Text\" },\n { kind: \"date\", label: \"Date\" },\n { kind: \"number\", label: \"Number\" },\n { kind: \"currency\", label: \"Money\" },\n { kind: \"checkbox\", label: \"Checkbox\" },\n { kind: \"email\", label: \"Email\" },\n { kind: \"phone\", label: \"Phone\" },\n { kind: \"url\", label: \"Link\" },\n];\n\n/** The store's plan word for a column, as one of the kinds this panel offers (null: none fits). */\nexport function importKindOfPlan(type: string): ImportKind | null {\n if (type === \"text\" || type === \"long_text\") return \"text\";\n if (type === \"datetime\" || type === \"date\") return \"date\";\n if (type === \"number\" || type === \"range\" || type === \"integer\" || type === \"decimal\") return \"number\";\n if (type === \"currency\") return \"currency\";\n if (type === \"checkbox\" || type === \"boolean\") return \"checkbox\";\n if (type === \"email\" || type === \"phone\" || type === \"url\") return type;\n return null;\n}\n\n/** What `custom.field_declare` is handed for a column made as `kind`. */\nexport function declarationFor(kind: ImportKind): { type: \"text\" | \"datetime\" | \"number\" | \"currency\" | \"checkbox\" | \"email\" | \"phone\" | \"url\"; kind?: \"date\" } {\n if (kind === \"date\") return { type: \"datetime\", kind: \"date\" };\n return { type: kind };\n}\n\n/** One column's cells read as dates: the day each readable cell is, and every cell that is not. */\nexport interface ColumnDates {\n /** Row index (0-based) → the day (`YYYY-MM-DD`), or the instant when a time is kept. */\n read: Map<number, string>;\n /** Filled cells that are not a date, in file order. */\n unreadable: Array<{ row: number; raw: string }>;\n filled: number;\n}\n\nexport function datesOfColumn(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n opts: { withTime?: boolean; locale?: string } = {},\n): ColumnDates {\n const read = new Map<number, string>();\n const unreadable: Array<{ row: number; raw: string }> = [];\n let filled = 0;\n rows.forEach((r, i) => {\n const raw = String(r[header] ?? \"\").trim();\n if (raw === \"\") return;\n filled += 1;\n const got = readTypedDate(raw, { ...(opts.withTime ? { withTime: true } : {}), ...(opts.locale ? { locale: opts.locale } : {}) });\n if (got.ok) read.set(i, opts.withTime && got.instant ? got.instant : got.day);\n else unreadable.push({ row: i, raw });\n });\n return { read, unreadable, filled };\n}\n\n/**\n * Whether a column the store read as words is really dates: most of its filled cells read as one\n * (a few \"PAID\" notes in a paid-on column do not make it text). At least two cells must read.\n */\nexport function looksLikeDates(rows: ReadonlyArray<Record<string, string>>, header: string, locale?: string): boolean {\n const d = datesOfColumn(rows, header, locale ? { locale } : {});\n return d.read.size >= 2 && d.read.size / d.filled >= 0.6;\n}\n\n/**\n * Rows that repeat an EARLIER row exactly, over the columns that are sent (spacing at either end\n * ignored, nothing else). Answers the 0-based index of each repeat and the row it repeats.\n */\nexport function exactDuplicateRows(\n rows: ReadonlyArray<Record<string, string>>,\n headers: ReadonlyArray<string>,\n): Array<{ row: number; of: number }> {\n const seen = new Map<string, number>();\n const out: Array<{ row: number; of: number }> = [];\n rows.forEach((r, i) => {\n const cells = headers.map((h) => String(r[h] ?? \"\").trim());\n if (cells.every((c) => c === \"\")) return;\n const key = JSON.stringify(cells);\n const first = seen.get(key);\n if (first === undefined) seen.set(key, i);\n else out.push({ row: i, of: first });\n });\n return out;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\nconst PHONE = /^\\+?[\\d\\s().-]{7,20}$/;\nconst URLISH = /^(https?:\\/\\/|www\\.)\\S+$/i;\n\n/**\n * Whether a column the store read as words is really emails, phone numbers or web addresses: most of\n * its filled cells look like one (a few notes in the column do not make it text). Two cells at least.\n * A phone is 7-15 digits in the usual punctuation, so a plain count or a year is never one.\n */\nexport function looksLike(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n): \"email\" | \"phone\" | \"url\" | null {\n const cells = rows.map((r) => String(r[header] ?? \"\").trim()).filter((c) => c !== \"\");\n if (cells.length < 2) return null;\n const share = (test: (c: string) => boolean) => cells.filter(test).length / cells.length;\n if (share((c) => EMAIL.test(c)) >= 0.6) return \"email\";\n if (share((c) => URLISH.test(c)) >= 0.6) return \"url\";\n const isPhone = (c: string) => PHONE.test(c) && /[\\d]/.test(c) && c.replace(/\\D/g, \"\").length >= 7 && c.replace(/\\D/g, \"\").length <= 15 && /[()\\s.+-]/.test(c);\n if (share(isPhone) >= 0.6) return \"phone\";\n return null;\n}\n","// src/importCombine.ts — @ai-matrx/records-ui · VISION-REACH lane 5 (2026-10-03)\n//\n// ROWS THAT NAME THE SAME RECORD, COMBINED BEFORE THEY ARE WRITTEN.\n//\n// THE BREAK (persona P03, a PTA parent): families.csv had one row per STUDENT — a family with two\n// children is two rows with the same \"Family\" — and the import made one Families record per row, so\n// 33 families existed twice. Every pledge and volunteer row that then named one of them was refused\n// by the store as ambiguous (\"2 records called Cox family\"), 58 rows never landed, and the chat\n// answered from the rest. Google Sheets and Airtable never drop a row; and a person importing a\n// roster keyed by family name means ONE family per name.\n//\n// So the import panel counts how often the name column repeats, says so, and — when the repeating\n// rows look like the same record — combines them by default: one record per name, every other\n// column keeping every distinct value it held (\"Zoe; Max\"), joined the way the store's own list\n// cells split (`splitListCell`: `;`, `,` or `|`). Nothing is lost; the person can choose \"separate\n// records\" when each row really is its own thing (a pledge list named by family).\n\nimport { relationNameKey } from \"@ai-matrx/records\";\n\n/** How a name column repeats: distinct names against the rows that carry one. */\nexport interface TitleRepeats {\n distinct: number;\n filled: number;\n}\n\nexport function titleRepeats(rows: ReadonlyArray<Record<string, string>>, header: string): TitleRepeats {\n const seen = new Set<string>();\n let filled = 0;\n for (const r of rows) {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") continue;\n filled += 1;\n seen.add(key);\n }\n return { distinct: seen.size, filled };\n}\n\n/**\n * Whether rows sharing a name are plausibly ONE record rather than several events about it.\n *\n * The signal is an identity column: some OTHER column that never disagrees inside a group of\n * same-named rows and (mostly) differs between groups — a family's email or phone, a customer's\n * account number. A pledge list has none: amount, paid and date all vary within a family, and no\n * column pins the rows to one thing. Only groups of two or more rows are judged.\n */\nexport function sameRecordLikely(\n rows: ReadonlyArray<Record<string, string>>,\n header: string,\n /**\n * Columns that can never be what pins a row to one record: an amount or a date describes the\n * thing, it does not identify it (a supply list's unit price is the same for every row of one\n * item, and nearly every item has its own price — that is not one record). */\n notIdentity?: ReadonlySet<string>,\n): boolean {\n const groups = new Map<string, Array<Record<string, string>>>();\n for (const r of rows) {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") continue;\n const held = groups.get(key);\n if (held) held.push(r);\n else groups.set(key, [r]);\n }\n const repeating = [...groups.values()].filter((g) => g.length > 1);\n if (repeating.length === 0) return false;\n const headers = new Set<string>();\n for (const r of rows) for (const h of Object.keys(r)) if (h !== header) headers.add(h);\n for (const h of headers) {\n if (notIdentity?.has(h)) continue;\n // Agrees inside every repeating group, with a value in each …\n let agrees = true;\n for (const g of repeating) {\n const values = new Set(g.map((r) => String(r[h] ?? \"\").trim()).filter((v) => v !== \"\"));\n if (values.size !== 1) {\n agrees = false;\n break;\n }\n }\n if (!agrees) continue;\n // … and tells the groups apart (an identity, not a constant like a school name).\n const perGroup = [...groups.values()].map((g) => String(g[0]?.[h] ?? \"\").trim()).filter((v) => v !== \"\");\n if (perGroup.length < 2) continue;\n if (new Set(perGroup.map((v) => v.toLowerCase())).size >= Math.ceil(perGroup.length * 0.9)) return true;\n }\n return false;\n}\n\n/** The combined rows, and for each the 1-based file lines it was made from. */\nexport interface CombinedRows {\n rows: Array<Record<string, string>>;\n lines: number[][];\n /** Columns that held more than one distinct value in some group — list cells now. */\n multiValued: Set<string>;\n}\n\nexport const LIST_JOIN = \"; \";\n\nexport function combineRows(rows: ReadonlyArray<Record<string, string>>, header: string): CombinedRows {\n const order: string[] = [];\n const groups = new Map<string, { rows: Array<Record<string, string>>; lines: number[] }>();\n const out: Array<Record<string, string>> = [];\n const outLines: number[][] = [];\n rows.forEach((r, i) => {\n const key = relationNameKey(String(r[header] ?? \"\"));\n if (key === \"\") {\n // A row with no name cannot be combined with anything; it goes as itself.\n out.push({ ...r });\n outLines.push([i + 1]);\n return;\n }\n const held = groups.get(key);\n if (held) {\n held.rows.push(r);\n held.lines.push(i + 1);\n } else {\n groups.set(key, { rows: [r], lines: [i + 1] });\n order.push(key);\n }\n });\n const multiValued = new Set<string>();\n for (const key of order) {\n const g = groups.get(key)!;\n const first = g.rows[0]!;\n const combined: Record<string, string> = {};\n for (const h of Object.keys(first)) {\n if (h === header) {\n combined[h] = String(first[h] ?? \"\").trim();\n continue;\n }\n const values: string[] = [];\n for (const r of g.rows) {\n const v = String(r[h] ?? \"\").trim();\n if (v !== \"\" && !values.some((x) => x.toLowerCase() === v.toLowerCase())) values.push(v);\n }\n if (values.length > 1) multiValued.add(h);\n combined[h] = values.join(LIST_JOIN);\n }\n out.push(combined);\n outLines.push(g.lines);\n }\n // Rows are kept in first-seen order of their name; nameless rows were pushed where they sat,\n // which is what a person scanning the file expects. Sort by the first source line.\n const index = out.map((row, i) => ({ row, lines: outLines[i]! }));\n index.sort((a, b) => a.lines[0]! - b.lines[0]!);\n return { rows: index.map((e) => e.row), lines: index.map((e) => e.lines), multiValued };\n}\n","// src/importRefusals.ts — @ai-matrx/records-ui · VISION-REACH lane 5 (2026-10-03)\n//\n// THE ROWS AN IMPORT REFUSED, GROUPED BY WHY, AND HANDED BACK AS A FILE.\n//\n// THE BREAK (persona P03): 43 of 220 pledge rows were refused and the only trace was a line in the\n// import rail — \"175 landed · 0 already here · 43 refused\" — and a list of 43 identical sentences\n// differing only in the family's name. The person closed the rail, the table looked complete, and\n// the chat said \"no missing or unmatched data\". Airtable's and Google Sheets' importers never drop a\n// row without a loud, persistent count and a way to get the rows back.\n//\n// These two helpers are shared by the import rail (right after the write) and by the notice the\n// table page keeps until it is dismissed: the same grouping, the same file.\n\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { toDelimited, type DelimitedCell } from \"@ai-matrx/kit/delimited\";\n\n/** One kind of refusal and how many rows it took. */\nexport interface ReasonGroup {\n /** The store's sentence with the quoted words and numbers folded, so 43 names read as one reason. */\n reason: string;\n count: number;\n /** The first sentence as the store wrote it, with its own name — for the person who wants one example. */\n example: string;\n}\n\n/** Fold the parts of a refusal that vary row to row: quoted words and bare numbers. */\nexport function reasonShape(reason: string): string {\n return reason\n .replace(/\"[^\"]*\"/g, \"\\\"…\\\"\")\n .replace(/“[^”]*”/g, \"“…”\")\n .replace(/\\b\\d+(?:[.,]\\d+)*\\b/g, \"N\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nexport function groupReasons(reasons: ReadonlyArray<string>): ReasonGroup[] {\n const groups = new Map<string, ReasonGroup>();\n for (const raw of reasons) {\n const reason = String(raw ?? \"\").trim();\n if (reason === \"\") continue;\n const shape = reasonShape(reason);\n const held = groups.get(shape);\n if (held) held.count += 1;\n else groups.set(shape, { reason: shape, count: 1, example: reason });\n }\n return [...groups.values()].sort((a, b) => b.count - a.count);\n}\n\n/** A refused row as the store's report hands it back (`custom.io_import_report`). */\nexport interface RefusedRow {\n /** The data row, 1-based (the file's line is this + 1). */\n row?: number | null;\n reason?: string | null;\n source?: Record<string, unknown> | null;\n}\n\n/** One source value as a cell for THE one writer: primitives as themselves, anything else as text. */\nfunction cell(value: unknown): DelimitedCell {\n if (value === null || value === undefined) return null;\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" ? value : String(value);\n}\n\n/**\n * The refused rows as a CSV a person opens in their spreadsheet: every column the file had, in the\n * order the first row carries them, then the line it sat on and the store's reason — so the file\n * can be fixed and imported again, or the rows kept as a record of what did not land.\n */\nexport function refusedRowsCsv(rows: ReadonlyArray<RefusedRow>, lineOf: (dataRow: number) => number = (n) => n + 1): string {\n const headers: string[] = [];\n for (const r of rows) for (const h of Object.keys(r.source ?? {})) if (!headers.includes(h)) headers.push(h);\n // THE one writer (kit `toDelimited`): spreadsheet-safe, a trailing line ending as before.\n return toDelimited(\n [\n [...headers, \"Line in your file\", \"Why it was not added\"],\n ...rows.map((r) => [\n ...headers.map((h) => cell((r.source ?? {})[h])),\n typeof r.row === \"number\" ? lineOf(r.row) : \"\",\n r.reason ?? \"\",\n ]),\n ],\n { trailingNewline: true },\n );\n}\n\n/** Hand the person a file, where a browser is present. Answers false where there is none. */\nexport function offerDownload(name: string, text: string, type = \"text/csv\"): boolean {\n if (typeof document === \"undefined\" || typeof URL === \"undefined\" || typeof URL.createObjectURL !== \"function\") return false;\n downloadFile(name, text, type);\n return true;\n}\n\n/** \"Lincoln pledges.csv\" → \"Lincoln pledges — rows not added.csv\". */\nexport function refusedFileName(sourceName: string | null | undefined): string {\n const base = (sourceName ?? \"import\").replace(/\\.(csv|xlsx)$/i, \"\");\n return `${base} — rows not added.csv`;\n}\n","\"use client\";\n\n// src/TablesHome.tsx — @ai-matrx/records-ui\n//\n// THE LIST OF A PERSON'S TABLES — AND IT IS NEVER A FLAT PILE.\n//\n// Four lanes, always, in this order: mine · my organization · system ·\n// community. The lane a Table is in is read off the Table record itself and is\n// not a guess:\n//\n// · mine — Shown to \"Only me\" (`shown_to = 'only_me'`)\n// · organization — the rest of the organization's own Tables\n// · system — `is_kernel` (REC-27: the Tables the platform ships)\n// · community — Published to the web (`published_to_web`), titled in the law's words\n//\n// ACCESS LADDER (custom data adoption, 2026-10-03): the words are the law's — \"Shown to\" and\n// \"Published to the web\". A store that does not answer `shown_to` / `published_to_web` yet is read\n// through its old lane word, `visibility`.\n//\n// A lane with nothing in it SAYS SO in one sentence that tells a person how it\n// fills up. An empty heading with nothing under it reads as \"broken\"; this\n// reads as \"nothing here yet, and here is what puts something here\".\n//\n// Creating and importing are both here, because both make a Table, and they go\n// through the store's own doors — `declareTable` walks Home → table_declare →\n// Fields, and the import mounts `ImportWizard` on the Table it just declared.\n\nimport { useEffect, useState } from \"react\";\nimport type { DashboardSummary, Table, Uuid } from \"@ai-matrx/records\";\nimport { useRecordsClient, useTables } from \"@ai-matrx/records/react\";\nimport { withTableFacts, type TableFact } from \"@ai-matrx/records/core\";\nimport { withTablePlacement, type TablePlacementFact } from \"@ai-matrx/records\";\nimport { Button, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { NewTableStart } from \"./NewTableStart\";\n\nimport { RefusalNotice } from \"./Refusal\";\nimport { BookingSlots } from \"./BookingSlots\";\nimport { realPlural, tableName } from \"./names\";\nimport { WhereItLives } from \"./WhereItLives\";\n\n// Which lane a table belongs to is pure, so `/helpers` carries it (records-ui front door, 2026-10-16).\nimport { PLATFORM_TABLE_PREFIX, laneFor, platformOwned, publishedToWeb, shownToOnlyMe, type TableLane } from \"./tableLanes\";\nexport { laneFor, platformOwned, type TableLane } from \"./tableLanes\";\n\n/** The five lanes, in the order a person reads them. Never a flat list. */\nexport const TABLE_LANES: readonly TableLane[] = [\"mine\", \"organization\", \"system\", \"community\", \"app\"];\n\nexport const LANE_TITLE: Record<TableLane, string> = {\n mine: \"Only me\",\n organization: \"Everyone\",\n system: \"System\",\n community: \"Published to the web\",\n app: \"Platform tables\",\n};\n\n/**\n * THE APP'S OWN BOOKKEEPING, MARKED AS SUCH.\n *\n * A saved view, a comment, a queued action and a form are records in Tables\n * this package declares in the organization's own store (`platformTable.ts`) —\n * which is what makes them shareable, historied and agent-writable. The price\n * is that using the product creates Tables in the person's own list: the\n * verdict of 19 September watched \"Saved views · 9 fields · records_ui_view\"\n * appear among somebody's data, and then \"Comments\" appear beside it the\n * moment a record was opened.\n *\n * They are not hidden — hiding a real Table from the person who owns it is its\n * own lie, and they hold that person's comments. They get their own lane,\n * last, with a sentence that says what they are.\n */\n\n/** What fills an empty lane. A heading with nothing under it must still teach. */\nexport const LANE_EMPTY: Record<TableLane, string> = {\n // 🚨 BOTH SENTENCES USED TO DESCRIBE A PRODUCT THAT DOES NOT EXIST\n // (VERIFIER-15 M2, VERIFIER-16 M6). \"New table makes one that only you can\n // see\" — New table makes one shared with the organization, and it lands under\n // My organization. \"A table you make is yours until you change its visibility\n // to internal\" — it is internal from the start, and no screen here changes a\n // table's visibility at all. An empty lane says what is true and names only a\n // control that exists.\n mine: \"No tables kept to only you.\",\n organization: \"No tables yet.\",\n system: \"No platform tables here.\",\n community: \"Nothing published to the web.\",\n app: \"No platform tables yet.\",\n};\n\n/** The store's sentence for who keeps a kept Table (`custom.table_facts`' `keeper_says`), when it said one. */\nfunction keeperSays(table: Table): string | null {\n const said = (table as unknown as { keeper_says?: unknown }).keeper_says;\n return typeof said === \"string\" && said.trim() ? said : null;\n}\n\n/** The sentence when the store's table facts are not there, so no section can be decided. */\nexport const SECTIONS_UNKNOWN =\n \"Who can see each table, and which you made, could not be read, so every table \" +\n \"is listed under Everyone and Only me is empty. That is not their real sharing.\";\n\n/**\n * THE FOUR VISIBILITY LANES — who can see a thing: me, my organization, the\n * signed-in community, the whole world. (Arman, 2026-09-15: mine · my\n * organization · community · world; `common-docs/systems/platform/access/DECISIONS.md`.)\n *\n * They are NOT the sections of the table list above (`TABLE_LANES`), which also\n * separate the platform's own tables and the app's bookkeeping — those are about\n * WHO MADE a table, and a person filtering \"what is visible to whom\" is asking a\n * different question. A table the store keeps for itself, or a kernel table, has\n * no visibility a person chose, so `visibilityLaneFor` answers `null` and a\n * filter over these four leaves it out rather than inventing a lane for it.\n *\n * From the record's own `visibility`, the store's closed four:\n * Only me → Only me · the default → Everyone · Everyone on AI Matrx → Everyone on AI Matrx ·\n * Published to the web → Published to the web (an older store: its `visibility` word).\n *\n * 🚨 WHY `link` IS WORLD (chair ruling, 2026-09-23). A link anyone can open\n * WITHOUT signing in is reachable by the world; being unlisted does not make it\n * narrower. Community is the lane for things any SIGNED-IN account can reach,\n * and the store has no signed-in-only link yet — so today nothing is in\n * Community, and a signed-in-only link lands there the day it exists. The chip\n * stays, because a lane that is empty today is still a lane a person chooses.\n */\nexport type VisibilityLane = \"mine\" | \"organization\" | \"community\" | \"world\";\n\nexport const VISIBILITY_LANES: readonly VisibilityLane[] = [\"mine\", \"organization\", \"community\", \"world\"];\n\n/**\n * THE LAW'S WORDS (access ladder Words table), and no other lane names: \"Shown to\" Only me /\n * Everyone / Everyone on AI Matrx, and \"Published to the web\" for anyone on the internet.\n * \"Everyone on AI Matrx\" is offered only on a Public table; a store Table is Organization, so\n * nothing lands there today.\n */\nexport const VISIBILITY_LANE_TITLE: Record<VisibilityLane, string> = {\n mine: \"Only me\",\n organization: \"Everyone\",\n community: \"Everyone on AI Matrx\",\n world: \"Published to the web\",\n};\n\n/** Which visibility lane one Table is in, or `null` when no person chose one for it. */\nexport function visibilityLaneFor(table: Table): VisibilityLane | null {\n if (table.is_kernel) return null;\n if ((table.slug ?? \"\").startsWith(PLATFORM_TABLE_PREFIX) || platformOwned(table)) return null;\n // Anyone on the internet — Published to the web.\n if (publishedToWeb(table)) return \"world\";\n if (table.shown_to === \"everyone_on_ai_matrx\") return \"community\";\n if (shownToOnlyMe(table)) return \"mine\";\n return \"organization\";\n}\n\nexport interface TablesHomeProps {\n /** Where a table opens. Absent and the card is a plain row with no pretend link. */\n /**\n * Opening a Table, and — with a second argument — opening it ON one of its\n * dashboards. The second argument is optional so every existing caller is\n * unchanged; a host that ignores it lands on the records, which is what it\n * did before, rather than on a screen it does not know how to address.\n */\n onOpenTable?: ((tableId: Uuid, dashboardId?: Uuid) => void) | undefined;\n /**\n * THE ORGANIZATION EVERY ROW HERE LIVES IN, BY NAME (lane SC-1-TAILS; access-is-personal: a\n * list filtered by one organization says which). Each row carries a quiet \"Lives in <name>\"\n * chip that, pressed, asks the store where that table lives and — for its owner — where else\n * it can go. Absent: the list asks the store once, for its first table. When the store cannot\n * name it, the chips are absent rather than a row of \"unknown\".\n */\n organizationName?: string | null | undefined;\n /**\n * ONLY THE WAYS TO MAKE A TABLE — New table, Start from a template, and the import that\n * follows — and none of the lists (lane UI-FIX-18, VERIFIER-18 M3). A host page that already\n * lists the organization's tables, dashboards and booking pages (matrx-frontend's\n * organization hub) passes this, so one page never draws two full lists of the same tables.\n * Default false: the package's own home, lists and all.\n */\n makingOnly?: boolean | undefined;\n /**\n * THE HOST'S OWN BUTTONS ASK (merged-grid review 2, J6: \"New table\" sat ~1,700 px down /data,\n * then as a row of its own). A host whose page header already has an action bar puts \"New table\"\n * THERE and passes how many times it was pressed; this list then draws no button row of its own,\n * and opens the name box when asked. Absent: the list draws its own buttons, as before.\n */\n askedBy?: { create: number } | undefined;\n /**\n * WHERE \"START FROM A TEMPLATE\" LEADS (lane TEMPLATES, RETIRE-1): the host's published-template\n * gallery (matrx-frontend: /make's gallery, read through custom.templates and installed through\n * custom.template_install). The package's own example list was retired onto that one family.\n * Absent: no such button — never one that goes nowhere.\n */\n templatesHref?: string | undefined;\n /** Where a person describes a table in a sentence (matrx-frontend: /make). Absent: no such choice. */\n describeHref?: string | undefined;\n /** Where an outside database is connected as a table. Absent: no such choice. */\n connectHref?: string | undefined;\n /** The host closes its frame (the New table dialog). Absent: Cancel just closes the making screen. */\n onCancel?: (() => void) | undefined;\n className?: string | undefined;\n}\n\nexport function TablesHome({ onOpenTable, organizationName, makingOnly = false, askedBy, templatesHref, describeHref, connectHref, onCancel, className }: TablesHomeProps) {\n const client = useRecordsClient();\n const tables = useTables();\n\n const me = client.config.actor.user_id ?? null;\n /**\n * WHO CAN SEE EACH TABLE, AND WHICH ONES I MADE — `client.tableFacts()`, asked\n * HERE because this is a screen that sorts tables into sections, and folded onto\n * the list with `withTableFacts`. It is not part of `tableList()` (records 0.57.3):\n * a screen that only lists tables never pays for it. `null` = the store's\n * catalog has no such door (nothing asked, nothing said); `failed` = the store\n * HAS it and it did not answer, and then the page says so.\n */\n const [facts, setFacts] = useState<\n { phase: \"reading\" } | { phase: \"read\"; rows: TableFact[] | null } | { phase: \"failed\" }\n >({ phase: \"reading\" });\n useEffect(() => {\n let alive = true;\n void client.tableFacts().then((answered) => {\n if (!alive) return;\n setFacts(answered.ok ? { phase: \"read\", rows: answered.data } : { phase: \"failed\" });\n });\n return () => {\n alive = false;\n };\n }, [client]);\n // The placement facts ride on the same door (SC-1: `platform_owned`, `keeper_says`, …); a store\n // whose door answers only the three older columns leaves every Table as it was.\n const listed =\n facts.phase === \"read\"\n ? withTablePlacement(\n withTableFacts(tables.data ?? [], facts.rows, me),\n facts.rows as unknown as TablePlacementFact[] | null,\n )\n : (tables.data ?? []);\n /**\n * \"SHOW EVERYTHING\" (SCOPES-CONTEXT-TRANSITION SC-1', finished by SC-1-TAILS). What the app keeps\n * for itself — a column's choices, the context system's scope tables, its own bookkeeping — is\n * marked and never hidden from its owner, but it is not the organization's own data, so it sits\n * behind one control that says how many there are. The owner (2026-09-23): \"There should be\n * options for someone to see all, but not at random.\"\n */\n const [showEverything, setShowEverything] = useState(false);\n const keptCount = listed.filter((t) => laneFor(t) === \"app\").length;\n /** Where every row lives, by name: the host's, or the store's answer for the first table. */\n const [askedName, setAskedName] = useState<string | null>(null);\n const firstTableId = listed[0]?.id ?? null;\n useEffect(() => {\n if (organizationName || !firstTableId) return;\n let alive = true;\n void client.tableHome({ table_id: firstTableId }).then((answered) => {\n if (alive && answered.ok && answered.data) setAskedName(answered.data.organization.name);\n });\n return () => {\n alive = false;\n };\n }, [client, organizationName, firstTableId]);\n const livesIn = organizationName || askedName;\n /** A Table the person signed in made. `created_by` comes from `custom.table_facts`. */\n const isMine = (t: Table): boolean =>\n Boolean(me) && laneFor(t) !== \"system\" && laneFor(t) !== \"app\" && t.created_by === me;\n /**\n * WHETHER THE SECTIONS CAN BE DECIDED AT ALL. Only a door the store HAS can fail\n * to answer: without it this page behaves exactly as it did before, and says\n * nothing about a read nobody made (the door-presence pattern).\n */\n const sectionsKnown = facts.phase !== \"failed\";\n // Opened by the host's own button (a dialog): open from the FIRST paint, so the frame never\n // draws empty and then fills (zero layout shift on open).\n const [creating, setCreating] = useState(() => (askedBy?.create ?? 0) > 0);\n // The host's header pressed \"New table\" (a count, so every press opens).\n const createAsked = askedBy?.create ?? 0;\n useEffect(() => {\n if (createAsked > 0) setCreating(true);\n }, [createAsked]);\n const hostButtons = askedBy !== undefined;\n // SCR-16. THE ORGANIZATION'S DASHBOARDS, ON THE RECORDS HOME.\n //\n // A dashboard is about ONE Table, so it lives on that Table's page — but a\n // person who wants to know how the work is going does not start by\n // remembering which Table the answer is in. `custom.dashboards` with no\n // table id answers the whole organization, narrowed to the Tables this\n // person can already open, so this list can never reveal a Table.\n const [boards, setBoards] = useState<DashboardSummary[] | null>(null);\n useEffect(() => {\n // A page that draws only the ways to make a table lists no dashboards, so it asks for none.\n if (makingOnly) return;\n let cancelled = false;\n void client.dashboards({}).then((result) => {\n if (cancelled) return;\n // A REFUSAL HERE IS NOT THE PAGE'S REFUSAL. The Tables are what this\n // screen is for; a store with no dashboards door yet simply has no\n // section, and the Tables below are untouched.\n setBoards(result.ok ? result.data : []);\n });\n return () => {\n cancelled = true;\n };\n }, [client, makingOnly]);\n\n return (\n <div className={cn(\"flex min-h-0 flex-col gap-4\", className)}>\n {creating ? (\n <div className={cn(\"min-h-0\", hostButtons ? \"flex-1\" : \"h-[36rem] max-w-2xl rounded-lg border\")}>\n <NewTableStart\n templatesHref={templatesHref}\n describeHref={describeHref}\n connectHref={connectHref}\n existingTables={listed.filter((t) => laneFor(t) !== \"system\" && laneFor(t) !== \"app\")}\n onOpenTable={(id) => onOpenTable?.(id)}\n onMade={() => tables.reload()}\n onCancel={() => {\n setCreating(false);\n onCancel?.();\n }}\n />\n </div>\n ) : hostButtons ? null : (\n <div className=\"flex items-center gap-2\" data-tables-home-making=\"\">\n <Button size=\"sm\" onClick={() => setCreating(true)}>\n New table\n </Button>\n {templatesHref ? (\n <Button asChild size=\"sm\" variant=\"ghost\">\n <a href={templatesHref} data-tables-home-templates=\"\">\n Start from a template\n </a>\n </Button>\n ) : null}\n </div>\n )}\n\n {tables.error ? <RefusalNotice error={tables.error} /> : null}\n {!makingOnly && tables.loading && !tables.data ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-6 w-40\" />\n <Skeleton className=\"h-16 w-full\" />\n </div>\n ) : null}\n\n {/* PRODUCTS row 14, the owner's side. A booking page is the ONE thing on\n this store whose whole point is a link somebody else opens, so the\n organization's pages — with what is coming up, what is being held right\n now, and the link — belong on the home rather than only inside whichever\n table the appointments happen to land in. The picker a visitor uses is\n the public route's; nothing here computes an offer. Absent when this\n organization has no booking pages. */}\n {makingOnly ? null : <BookingSlots />}\n\n {!makingOnly && boards && boards.length > 0 ? (\n <section className=\"space-y-1.5\">\n <div className=\"flex items-baseline gap-2\">\n <h2 className=\"text-sm font-medium\">Dashboards</h2>\n <span className=\"text-xs opacity-60\">{boards.length}</span>\n </div>\n <ul className=\"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3\">\n {boards.map((board) => (\n <li key={board.dashboard_id}>\n <button\n type=\"button\"\n disabled={!board.table_id}\n onClick={() =>\n board.table_id ? onOpenTable?.(board.table_id, board.dashboard_id) : undefined\n }\n className={cn(\n \"w-full rounded-md border px-3 py-2 text-left transition-colors\",\n onOpenTable && board.table_id ? \"hover:bg-accent\" : \"cursor-default\",\n )}\n >\n <span className=\"block truncate text-sm\">{board.name}</span>\n <span className=\"block truncate text-xs opacity-60\">\n {board.block_count} block{board.block_count === 1 ? \"\" : \"s\"}\n {\" · \"}\n {(() => {\n const owner = tables.data?.find((t) => t.id === board.table_id);\n return owner ? tableName(owner) : \"its table\";\n })()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </section>\n ) : null}\n\n {!makingOnly && tables.data && !sectionsKnown ? (\n <p className=\"text-xs text-muted-foreground\">{SECTIONS_UNKNOWN}</p>\n ) : null}\n\n {!makingOnly && tables.data && keptCount > 0 ? (\n <div data-tables-show-everything={showEverything ? \"on\" : \"off\"} className=\"flex items-center text-xs\">\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-2 text-xs\"\n aria-pressed={showEverything}\n onClick={() => setShowEverything((on) => !on)}\n >\n {showEverything ? \"✓ \" : \"\"}Include system tables ({keptCount})\n </Button>\n </div>\n ) : null}\n\n {!makingOnly && tables.data\n ? TABLE_LANES.filter((lane) => lane !== \"app\" || showEverything).map((lane) => {\n // MINE IS WHAT I MADE (chair ruling, 2026-09-23), whatever its\n // visibility — so a new internal table is under Mine AND under My\n // organization. Every other section is still one visibility.\n const rows = listed.filter((t) =>\n lane === \"mine\" ? laneFor(t) === \"mine\" || isMine(t) : laneFor(t) === lane,\n );\n return (\n <section key={lane} className=\"space-y-1.5\">\n <div className=\"flex items-baseline gap-2\">\n <h2 className=\"text-sm font-medium\">{LANE_TITLE[lane]}</h2>\n <span className=\"text-xs opacity-60\">{rows.length}</span>\n </div>\n {rows.length === 0 ? (\n <p className=\"text-xs opacity-70\">{LANE_EMPTY[lane]}</p>\n ) : (\n <ul className=\"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3\">\n {rows.map((table) => (\n <li key={table.id} className=\"flex flex-col rounded-md border\">\n <button\n type=\"button\"\n onClick={() => onOpenTable?.(table.id)}\n className={cn(\n \"w-full rounded-md px-3 py-2 text-left transition-colors\",\n onOpenTable ? \"hover:bg-accent\" : \"cursor-default\",\n )}\n >\n {/* The Table's NAME, never its token: `records_ui_view`\n and `v78_widget2` are machine names and no product\n a person judges puts one on a card. */}\n <span className=\"block truncate text-sm\">{tableName(table)}</span>\n <span className=\"block truncate text-xs opacity-60\">\n {table.fields.length} field{table.fields.length === 1 ? \"\" : \"s\"}\n {realPlural(table) && realPlural(table) !== table.name\n ? ` · ${realPlural(table)}`\n : \"\"}\n </span>\n {/* WHO KEEPS IT, in the store's own sentence — a kept table is marked, never a mystery. */}\n {lane === \"app\" && keeperSays(table) ? (\n <span className=\"mt-0.5 block text-xs text-muted-foreground\">{keeperSays(table)}</span>\n ) : null}\n </button>\n {livesIn ? (\n <div className=\"px-2 pb-1.5\">\n <WhereItLives\n variant=\"row\"\n tableId={table.id}\n knownOrganizationName={livesIn}\n onMoved={() => tables.reload()}\n />\n </div>\n ) : null}\n </li>\n ))}\n </ul>\n )}\n </section>\n );\n })\n : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/NewTableStart.tsx — @ai-matrx/records-ui\n//\n// THE NEW TABLE SCREEN: every way to make a table, each one a clear choice (Arman, 2026-10-10:\n// \"quality, standards, elegant AND DO NOT LOSE MY FEATURES\").\n//\n// · Blank — a name, and optionally every column at once (typed chips, changeable).\n// · Import a file — CSV, TSV or Excel, picked or DROPPED ANYWHERE on this screen, or pasted.\n// It never asks for a name first: the name comes from the file and stays editable. The\n// separator and \"First row is column names\" are guessed and changeable, the rows are shown\n// back, and the rows can go into a NEW table or one that already exists. Then `ImportWizard`\n// takes them as its `source` — column kinds, mapping onto existing columns, the write and the\n// report are the one importer's, never a second pipeline.\n// · Start from a template · Describe it · Connect a database — the host's doors, when it has them.\n//\n// Layout: a scrolling body and a pinned footer holding the one primary action, enabled the moment\n// it is valid. The host gives this a fixed height (a dialog, a sheet), so moving between steps\n// never resizes the frame.\n\nimport { useCallback, useMemo, useRef, useState, type DragEvent, type ReactNode } from \"react\";\nimport type { Table, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsError } from \"@ai-matrx/records\";\nimport { tableShapeChanged, useRecordsClient } from \"@ai-matrx/records/react\";\nimport {\n BasicInput,\n Button,\n Label,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n Switch,\n Textarea,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { Tile } from \"@ai-matrx/design-system/controls\";\nimport { NEW_COLUMN_TYPES, columnsFrom, fieldsForNewColumns, type NewColumn, type NewColumnType } from \"./newTableColumns\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { refusalFromThrown } from \"./refusals\";\nimport { ImportWizard, type ImportSource } from \"./ImportWizard\";\nimport { declareTable, tokenFor } from \"./createTable\";\nimport { tableName } from \"./names\";\nimport {\n IMPORT_ACCEPT,\n IMPORT_SEPARATORS,\n firstRowLooksLikeHeader,\n gridFromFile,\n gridFromText,\n importFromGrid,\n importText,\n separatorWords,\n tableNameFromFile,\n type ImportSeparator,\n type ReadGrid,\n} from \"./importFileRead\";\n\nexport interface NewTableStartProps {\n /** The host's template gallery. Absent: no template choice. */\n templatesHref?: string | undefined;\n /** Where a person describes the table in a sentence (the host's /make). Absent: no such choice. */\n describeHref?: string | undefined;\n /** Where an outside database is connected. Absent: no such choice. */\n connectHref?: string | undefined;\n /** Tables an import can go into instead of a new one. */\n existingTables?: readonly Table[] | undefined;\n onOpenTable?: ((tableId: Uuid) => void) | undefined;\n /** A table was made (refresh any list behind this screen). */\n onMade?: (() => void) | undefined;\n onCancel: () => void;\n className?: string | undefined;\n}\n\ntype Step =\n | { at: \"choose\" }\n | { at: \"import\" }\n | { at: \"wizard\"; tableId: Uuid; source: ImportSource; made: boolean };\n\nconst NEW_TABLE = \"__new__\";\nconst PREVIEW_ROWS = 6;\n\n/**\n * THE TITLE COLUMN OF AN IMPORTED TABLE keeps the first pasted header's name (CD-IO-03 walk 2026-10-21: \"Zeta\" became\n * \"Title\", so the person's own column name was lost). The first column fills the title, so it is born with that name.\n */\nexport function importTitleField(headers: readonly string[]) {\n const label = headers[0]?.trim() || \"Title\";\n return { key: \"title\", label, type: \"text\" as const, sort: 10, required: false };\n}\n\nexport function NewTableStart({\n templatesHref,\n describeHref,\n connectHref,\n existingTables,\n onOpenTable,\n onMade,\n onCancel,\n className,\n}: NewTableStartProps) {\n const client = useRecordsClient();\n const [step, setStep] = useState<Step>({ at: \"choose\" });\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<RecordsError | null>(null);\n\n // Blank\n const [name, setName] = useState(\"\");\n const nameTyped = useRef(\"\");\n nameTyped.current = name;\n const [columnWords, setColumnWords] = useState(\"\");\n const [columns, setColumns] = useState<NewColumn[]>([]);\n\n // Import\n const [fileName, setFileName] = useState<string | null>(null);\n const [file, setFile] = useState<File | null>(null);\n const [pasted, setPasted] = useState<string | null>(null);\n const [read, setRead] = useState<ReadGrid | null>(null);\n const [separator, setSeparator] = useState<ImportSeparator>(\"auto\");\n const [headerRow, setHeaderRow] = useState(true);\n const [importName, setImportName] = useState(\"\");\n const [target, setTarget] = useState<string>(NEW_TABLE);\n const [dragging, setDragging] = useState(false);\n const fileInput = useRef<HTMLInputElement | null>(null);\n\n const parsed = useMemo(() => (read ? importFromGrid(read.grid, headerRow) : null), [read, headerRow]);\n const intoTables = useMemo(\n () => (existingTables ?? []).filter((t) => !t.is_kernel).slice().sort((a, b) => tableName(a).localeCompare(tableName(b))),\n [existingTables],\n );\n\n const readFile = useCallback(async (picked: File, sep: ImportSeparator) => {\n setError(null);\n try {\n const grid = await gridFromFile(picked, sep);\n setRead(grid);\n return grid;\n } catch (thrown) {\n setRead(null);\n setError(refusalFromThrown(thrown, \"That file could not be read.\", \"Save it again as CSV or Excel and pick it again.\", \"invalid_argument\"));\n return null;\n }\n }, []);\n\n const takeFile = useCallback(\n async (picked: File | null | undefined) => {\n if (!picked) return;\n setFile(picked);\n setPasted(null);\n setFileName(picked.name);\n setSeparator(\"auto\");\n setImportName((was) => was || nameTyped.current.trim() || tableNameFromFile(picked.name));\n setStep({ at: \"import\" });\n const grid = await readFile(picked, \"auto\");\n if (grid) setHeaderRow(firstRowLooksLikeHeader(grid.grid));\n },\n [readFile],\n );\n\n const takePaste = useCallback((text: string, sep: ImportSeparator) => {\n setPasted(text);\n if (!text.trim()) {\n setRead(null);\n return;\n }\n const grid = gridFromText(text, sep);\n setRead(grid);\n setHeaderRow(firstRowLooksLikeHeader(grid.grid));\n }, []);\n\n const changeSeparator = useCallback(\n (sep: ImportSeparator) => {\n setSeparator(sep);\n if (file) void readFile(file, sep);\n else if (pasted !== null) takePaste(pasted, sep);\n },\n [file, pasted, readFile, takePaste],\n );\n\n const onDrop = useCallback(\n (e: DragEvent<HTMLDivElement>) => {\n if (!e.dataTransfer?.types?.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(false);\n if (step.at === \"wizard\") return;\n void takeFile(e.dataTransfer.files?.[0]);\n },\n [step.at, takeFile],\n );\n\n const createBlank = useCallback(async () => {\n const trimmed = name.trim();\n if (!trimmed || busy) return;\n setBusy(true);\n setError(null);\n const result = await declareTable(client, {\n name: trimmed,\n slug: tokenFor(trimmed),\n ...(columns.length > 0 ? { fields: fieldsForNewColumns(columns) } : {}),\n });\n setBusy(false);\n if (!result.ok) {\n setError(result.error);\n return;\n }\n onMade?.();\n onOpenTable?.(result.data);\n }, [busy, client, columns, name, onMade, onOpenTable]);\n\n const importReady = Boolean(parsed && parsed.rows.length > 0 && parsed.headers.length > 0 && (target !== NEW_TABLE || importName.trim()));\n\n const continueImport = useCallback(async () => {\n if (!parsed || !importReady || busy) return;\n const source: ImportSource = { name: fileName ?? \"Pasted rows\", parsed, text: importText(parsed) };\n if (target !== NEW_TABLE) {\n setStep({ at: \"wizard\", tableId: target as Uuid, source, made: false });\n return;\n }\n const trimmed = importName.trim();\n setBusy(true);\n setError(null);\n const result = await declareTable(client, { name: trimmed, slug: tokenFor(trimmed), fields: [importTitleField(parsed.headers)] });\n setBusy(false);\n if (!result.ok) {\n setError(result.error);\n return;\n }\n onMade?.();\n setStep({ at: \"wizard\", tableId: result.data, source, made: true });\n }, [busy, client, fileName, importName, importReady, onMade, parsed, target]);\n\n /** The import made this table's columns after the table was first read: open it on what it holds now. */\n const openImported = (tableId: Uuid) => {\n tableShapeChanged(tableId);\n onOpenTable?.(tableId);\n };\n\n const back = () => {\n setError(null);\n setStep({ at: \"choose\" });\n };\n\n let body: ReactNode;\n let footer: ReactNode;\n if (step.at === \"choose\") {\n body = (\n <div className=\"flex flex-col gap-5\" data-tables-home-making=\"\">\n <section className=\"flex flex-col gap-2\" aria-label=\"Blank table\">\n <Label htmlFor=\"new-table-name\" className=\"text-xs font-medium text-muted-foreground\">\n Name\n </Label>\n <BasicInput\n id=\"new-table-name\"\n autoFocus\n value={name}\n placeholder=\"Table name\"\n onChange={(e) => setName(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") void createBlank();\n }}\n className=\"h-9 text-base sm:text-sm\"\n />\n <NewTableColumns\n words={columnWords}\n columns={columns}\n onWords={(text) => {\n setColumnWords(text);\n setColumns((was) =>\n columnsFrom(text).map((c) => was.find((w) => w.label.toLowerCase() === c.label.toLowerCase()) ?? c),\n );\n }}\n onType={(index, type) =>\n setColumns((was) =>\n was.map((c, i) =>\n i === index ? { label: c.label, type, ...(type === \"select\" || type === \"multi_select\" ? { options: c.options ?? [] } : {}) } : c,\n ),\n )\n }\n onCreate={() => void createBlank()}\n />\n </section>\n\n <div className=\"flex items-center gap-3 text-xs text-muted-foreground\" aria-hidden>\n <span className=\"h-px flex-1 bg-border\" />\n or\n <span className=\"h-px flex-1 bg-border\" />\n </div>\n\n <Tile\n data-new-table-import=\"\"\n onClick={() => fileInput.current?.click()}\n icon={<Icon d={ICON.upload} />}\n title=\"Import a file\"\n line=\"CSV, Excel or TSV · drop it here\"\n {...(dragging ? { selected: true } : {})}\n />\n <input\n ref={fileInput}\n type=\"file\"\n accept={IMPORT_ACCEPT}\n aria-label=\"Choose a file to import\"\n tabIndex={-1}\n className=\"sr-only\"\n onChange={(e) => {\n void takeFile(e.target.files?.[0]);\n e.target.value = \"\";\n }}\n />\n\n <div className=\"grid grid-cols-1 gap-2 sm:grid-cols-2\">\n <ChoiceCard\n icon={ICON.paste}\n title=\"Paste rows\"\n words=\"From a spreadsheet\"\n onClick={() => {\n setFile(null);\n setFileName(null);\n setRead(null);\n setPasted(\"\");\n setSeparator(\"auto\");\n // A name already typed on the first step is the table's name here too, never lost on the way.\n setImportName((was) => was || name.trim());\n setStep({ at: \"import\" });\n }}\n />\n {templatesHref ? (\n <ChoiceCard icon={ICON.template} title=\"Start from a template\" words=\"Ready-made tables\" href={templatesHref} data-tables-home-templates=\"\" />\n ) : null}\n {describeHref ? <ChoiceCard icon={ICON.spark} title=\"Describe it\" words=\"Say what it tracks\" href={describeHref} /> : null}\n {connectHref ? <ChoiceCard icon={ICON.database} title=\"Connect a database\" words=\"Sync a Postgres table\" href={connectHref} /> : null}\n </div>\n </div>\n );\n footer = (\n <>\n <Button variant=\"ghost\" onClick={onCancel}>\n Cancel\n </Button>\n <Button disabled={busy || name.trim().length === 0} onClick={() => void createBlank()} data-new-table-create=\"\">\n {busy ? \"Creating…\" : \"Create table\"}\n </Button>\n </>\n );\n } else if (step.at === \"import\") {\n const pasteMode = pasted !== null;\n body = (\n <div className=\"flex flex-col gap-4\" data-new-table-import-step=\"\">\n {pasteMode ? (\n <Textarea\n autoFocus\n value={pasted}\n rows={5}\n placeholder=\"Paste rows copied from a spreadsheet\"\n aria-label=\"Pasted rows\"\n onChange={(e) => takePaste(e.target.value, separator)}\n className=\"font-mono text-xs\"\n />\n ) : (\n <div className=\"flex min-w-0 items-center gap-3 rounded-lg border px-3 py-2.5\">\n <span className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary\">\n <Icon d={ICON.file} />\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-sm font-medium\" data-new-table-file=\"\">\n {fileName}\n </span>\n <span className=\"block text-xs text-muted-foreground\" data-new-table-counts=\"\">\n {parsed ? `${parsed.rows.length} ${parsed.rows.length === 1 ? \"row\" : \"rows\"} · ${parsed.headers.length} columns` : \"Reading…\"}\n </span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => fileInput.current?.click()}>\n Change\n </Button>\n <input\n ref={fileInput}\n type=\"file\"\n accept={IMPORT_ACCEPT}\n aria-label=\"Choose a file to import\"\n tabIndex={-1}\n className=\"sr-only\"\n onChange={(e) => {\n void takeFile(e.target.files?.[0]);\n e.target.value = \"\";\n }}\n />\n </div>\n )}\n\n <div className=\"grid grid-cols-1 gap-3 sm:grid-cols-2\">\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium text-muted-foreground\">Add to</Label>\n <Select value={target} onValueChange={setTarget}>\n <SelectTrigger aria-label=\"Add to\" className=\"h-9\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NEW_TABLE}>A new table</SelectItem>\n {intoTables.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {tableName(t)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n {target === NEW_TABLE ? (\n <div className=\"flex flex-col gap-1.5\">\n <Label htmlFor=\"new-table-import-name\" className=\"text-xs font-medium text-muted-foreground\">\n Table name\n </Label>\n <BasicInput\n id=\"new-table-import-name\"\n value={importName}\n placeholder=\"Table name\"\n onChange={(e) => setImportName(e.target.value)}\n className=\"h-9 text-base sm:text-sm\"\n />\n </div>\n ) : null}\n </div>\n\n <div className=\"flex flex-wrap items-center gap-x-5 gap-y-2\">\n <label className=\"flex items-center gap-2 text-sm\">\n <Switch checked={headerRow} onCheckedChange={setHeaderRow} aria-label=\"First row is column names\" size=\"sm\" />\n First row is column names\n </label>\n {read && read.format === \"csv\" ? (\n <div className=\"flex items-center gap-2 text-sm\">\n <span className=\"text-muted-foreground\">Separator</span>\n <Select value={separator} onValueChange={(v) => changeSeparator(v as ImportSeparator)}>\n <SelectTrigger size=\"sm\" aria-label=\"Separator\" className=\"h-8 w-[9.5rem]\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {IMPORT_SEPARATORS.map((s) => (\n <SelectItem key={s.value} value={s.value}>\n {s.value === \"auto\" ? `Detect (${separatorWords(read.separator)})` : s.words}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ) : null}\n </div>\n\n {parsed && parsed.headers.length > 0 ? (\n <div className=\"min-w-0 overflow-x-auto rounded-lg border\" data-new-table-preview=\"\">\n <table className=\"w-full border-collapse text-xs\">\n <thead className=\"bg-muted/50\">\n <tr>\n {parsed.headers.map((h) => (\n <th key={h} className=\"whitespace-nowrap border-b px-2.5 py-1.5 text-left font-medium\">\n {h}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {parsed.rows.slice(0, PREVIEW_ROWS).map((row, i) => (\n <tr key={i} className=\"border-b last:border-b-0\">\n {parsed.headers.map((h) => (\n <td key={h} className=\"max-w-[14rem] truncate whitespace-nowrap px-2.5 py-1.5 text-muted-foreground\">\n {row[h] || \" \"}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n {parsed.rows.length > PREVIEW_ROWS ? (\n <p className=\"border-t px-2.5 py-1.5 text-xs text-muted-foreground\">\n +{parsed.rows.length - PREVIEW_ROWS} more {parsed.rows.length - PREVIEW_ROWS === 1 ? \"row\" : \"rows\"}\n </p>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n footer = (\n <>\n <Button variant=\"ghost\" className=\"mr-auto\" onClick={back}>\n Back\n </Button>\n <Button variant=\"ghost\" onClick={onCancel}>\n Cancel\n </Button>\n <Button disabled={!importReady || busy} onClick={() => void continueImport()} data-new-table-continue=\"\">\n {busy ? \"Creating…\" : \"Next: columns\"}\n </Button>\n </>\n );\n } else {\n body = (\n <div data-new-table-wizard=\"\">\n <ImportWizard tableId={step.tableId} source={step.source} autoRun={step.made} onWrote={() => tableShapeChanged(step.tableId)} onDone={() => openImported(step.tableId)} />\n </div>\n );\n footer = (\n <>\n {!step.made ? (\n <Button variant=\"ghost\" className=\"mr-auto\" onClick={() => setStep({ at: \"import\" })}>\n Back\n </Button>\n ) : null}\n <Button variant=\"outline\" onClick={() => openImported(step.tableId)} data-new-table-open=\"\">\n Open the table\n </Button>\n </>\n );\n }\n\n return (\n <div\n className={cn(\"relative flex h-full min-h-0 flex-col\", className)}\n data-new-table-start={step.at}\n onDragOver={(e) => {\n if (step.at === \"wizard\" || !e.dataTransfer?.types?.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(true);\n }}\n onDragLeave={(e) => {\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;\n setDragging(false);\n }}\n onDrop={onDrop}\n >\n <div className=\"min-h-0 flex-1 overflow-y-auto px-5 py-4\">\n {body}\n {error ? <RefusalNotice error={error} className=\"mt-3\" /> : null}\n </div>\n <div className=\"flex shrink-0 items-center justify-end gap-2 border-t px-5 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\">{footer}</div>\n {dragging && step.at !== \"wizard\" ? (\n <div className=\"pointer-events-none absolute inset-2 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-background/90 text-sm font-medium text-primary\">\n Drop to import\n </div>\n ) : null}\n </div>\n );\n}\n\nfunction ChoiceCard({\n icon,\n title,\n words,\n href,\n onClick,\n ...rest\n}: {\n icon: string;\n title: string;\n words: string;\n href?: string;\n onClick?: () => void;\n [data: `data-${string}`]: string;\n}) {\n return href ? (\n <Tile asChild icon={<Icon d={icon} />} title={title} line={words} {...rest}>\n <a href={href} />\n </Tile>\n ) : (\n <Tile icon={<Icon d={icon} />} title={title} line={words} onClick={onClick} {...rest} />\n );\n}\n\nconst ICON = {\n upload: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12\",\n file: \"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h8\",\n paste: \"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2M9 2h6v4H9z\",\n template: \"M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z\",\n spark: \"M12 3l1.9 5.8L20 10l-6.1 1.2L12 17l-1.9-5.8L4 10l6.1-1.2zM19 17l.8 2.2L22 20l-2.2.8L19 23l-.8-2.2L16 20l2.2-.8z\",\n database: \"M12 8c4.97 0 9-1.34 9-3s-4.03-3-9-3-9 1.34-9 3 4.03 3 9 3zM3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5M3 12c0 1.66 4 3 9 3s9-1.34 9-3\",\n} as const;\n\nfunction Icon({ d }: { d: string }) {\n return (\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={d} />\n </svg>\n );\n}\n\n/**\n * THE NEW TABLE'S COLUMNS, ALL AT ONCE (v7 item 2). Paste a header row, a list, or write a sentence;\n * each column shows as a chip with its type, which can be changed before the one press that makes it.\n */\nexport function NewTableColumns({\n words,\n columns,\n onWords,\n onType,\n onCreate,\n}: {\n words: string;\n columns: readonly NewColumn[];\n onWords: (text: string) => void;\n onType: (index: number, type: NewColumnType) => void;\n onCreate: () => void;\n}) {\n return (\n <div className=\"flex flex-col gap-2\" data-new-table-columns=\"\">\n <Textarea\n value={words}\n rows={2}\n placeholder=\"Columns (optional): name, email, phone, start date, status\"\n aria-label=\"Columns\"\n onChange={(e) => onWords(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && (e.metaKey || e.ctrlKey)) onCreate();\n }}\n className=\"min-h-[3.5rem] text-base sm:text-sm\"\n />\n {columns.length > 0 ? (\n <ul className=\"flex flex-wrap gap-1.5\" data-new-table-column-chips=\"\">\n {columns.map((column, i) => (\n <li\n key={`${column.label}-${i}`}\n className=\"flex items-center gap-1 rounded-md border border-border py-0.5 pl-2 pr-0.5 text-xs\"\n data-new-table-column={column.type}\n >\n <span className=\"max-w-[12rem] truncate\">{column.label}</span>\n <Select value={column.type} onValueChange={(v) => onType(i, v as NewColumnType)}>\n <SelectTrigger size=\"sm\" aria-label={`${column.label} holds`} className=\"h-6 border-0 px-1.5 text-[11px] text-muted-foreground shadow-none\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {NEW_COLUMN_TYPES.map((t) => (\n <SelectItem key={t.type} value={t.type}>\n {t.words}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n}\n","// src/newTableColumns.ts — @ai-matrx/records-ui · lane TABLE-EXPERIENCE (v7 item 2)\n//\n// A NEW TABLE TAKES ALL ITS COLUMNS AT ONCE. Before this, five columns meant five Add-column dialogs\n// (70–80 s). Now the New table box takes a header row pasted from a spreadsheet, a list (one column a\n// line), or a sentence (\"clients with name, email, phone, start date and status\") and reads it into\n// typed columns, which the person sees as chips and makes with ONE press.\n//\n// The type comes from the column's NAME — a header row has no values to read yet — by the same\n// words a person would use. It is a proposal: every chip's type can be changed before the press.\n\nimport { RESOLVABLE_FIELD_TYPE_WORDS } from \"@ai-matrx/records/templates\";\nimport { tokenFor, type NewFieldSpec } from \"./createTable\";\nimport { parseDelimited } from \"@ai-matrx/kit/delimited\";\nimport { uniqueLabels } from \"./tableShape\";\n\n/** The types a new column can be given from the New table box, in the words the chip shows. */\nexport const NEW_COLUMN_TYPES = [\n { type: \"text\", words: \"Text\" },\n { type: \"rich_text\", words: \"Formatted text\" },\n { type: \"number\", words: \"Number\" },\n { type: \"currency\", words: \"Money\" },\n { type: \"percent\", words: \"Percent\" },\n { type: \"date\", words: \"Date\" },\n { type: \"datetime\", words: \"Date and time\" },\n { type: \"checkbox\", words: \"Yes / no\" },\n { type: \"select\", words: \"Choice\" },\n { type: \"multi_select\", words: \"Several choices\" },\n { type: \"email\", words: \"Email\" },\n { type: \"phone\", words: \"Phone\" },\n { type: \"url\", words: \"Link\" },\n] as const;\n\nexport type NewColumnType = (typeof NEW_COLUMN_TYPES)[number][\"type\"];\n\nexport interface NewColumn {\n label: string;\n type: NewColumnType;\n /** A choice column's starting choices (a Status starts as Notion's three). */\n options?: string[];\n}\n\n/** The most columns one box makes — a paste of a whole sheet's header stays a table, not a wall. */\nexport const MOST_NEW_COLUMNS = 40;\n\nconst BULLET = /^\\s*(?:[-*•]|\\d+[.)])\\s+/;\n\n/** What a person types in the brackets, in their words, for the store's own type words. */\nconst TYPE_WORD_ALIASES: Record<string, NewColumnType> = {\n choice: \"select\",\n dropdown: \"select\",\n status: \"select\",\n list: \"select\",\n choices: \"multi_select\",\n tags: \"multi_select\",\n money: \"currency\",\n boolean: \"checkbox\",\n bool: \"checkbox\",\n \"yes/no\": \"checkbox\",\n \"yes / no\": \"checkbox\",\n link: \"url\",\n integer: \"number\",\n decimal: \"number\",\n float: \"number\",\n string: \"text\",\n long_text: \"rich_text\",\n \"formatted text\": \"rich_text\",\n \"date and time\": \"datetime\",\n \"date time\": \"datetime\",\n};\n\n/** The column type a bracketed word names, or undefined. Only words the store resolves count. */\nfunction typeFromWord(raw: string): NewColumnType | undefined {\n const word = raw.trim().toLowerCase();\n if (word === \"\") return undefined;\n const type = TYPE_WORD_ALIASES[word] ?? NEW_COLUMN_TYPES.find((t) => t.type === word.replace(/[\\s-]+/g, \"_\"))?.type;\n if (!type) return undefined;\n // The store's one date word is \"datetime\" (a date is its kind); the rest are its own words.\n return RESOLVABLE_FIELD_TYPE_WORDS.includes(type === \"date\" ? \"datetime\" : type) ? type : undefined;\n}\n\n/** The text with everything inside (...) or [...] blanked, same length — so a split can ignore it. */\nfunction maskBrackets(text: string): string {\n let depth = 0;\n let out = \"\";\n for (const ch of text) {\n if (ch === \"(\" || ch === \"[\") {\n depth++;\n out += depth === 1 ? ch : \"\\u0000\";\n } else if ((ch === \")\" || ch === \"]\") && depth > 0) {\n depth--;\n out += depth === 0 ? ch : \"\\u0000\";\n } else out += depth > 0 ? \"\\u0000\" : ch;\n }\n return out;\n}\n\n/** Split `text` on `sep` only where it sits outside every bracket. */\nfunction splitOutsideBrackets(text: string, sep: RegExp): string[] {\n const masked = maskBrackets(text);\n const parts: string[] = [];\n let from = 0;\n const re = new RegExp(sep.source, sep.flags.includes(\"g\") ? sep.flags : sep.flags + \"g\");\n for (const m of masked.matchAll(re)) {\n if (m[0] === \"\") continue;\n parts.push(text.slice(from, m.index));\n from = m.index! + m[0].length;\n }\n parts.push(text.slice(from));\n return parts;\n}\n\ninterface ColumnSpec {\n label: string;\n type?: NewColumnType;\n options?: string[];\n}\n\n/** One column part: `Name`, `Name (type)`, `Name (choice: a, b, c)`. A stray bracket never stays in a name. */\nfunction specFromPart(part: string): ColumnSpec {\n const clean = (t: string) => t.replace(/^[\"'\\s]+|[\"'.\\s]+$/g, \"\").replace(/\\s+/g, \" \");\n const m = /^(.*?)\\s*[(\\[]([^()\\[\\]]*)[)\\]]\\s*$/.exec(part.trim());\n if (m) {\n const inner = m[2]!;\n const colon = inner.indexOf(\":\");\n const type = typeFromWord(colon >= 0 ? inner.slice(0, colon) : inner);\n const name = clean(m[1]!);\n if (type && name !== \"\") {\n const options =\n colon >= 0\n ? [...new Set(inner.slice(colon + 1).split(/\\s*[,;|]\\s*/).map(clean).filter((o) => o !== \"\"))]\n : undefined;\n return { label: name, type, ...(options && options.length > 0 && (type === \"select\" || type === \"multi_select\") ? { options } : {}) };\n }\n }\n // Not a type: a balanced note like \"Cost (USD)\" stays; an unbalanced bracket never does.\n const withoutPairs = part.replace(/\\([^()\\[\\]]*\\)|\\[[^()\\[\\]]*\\]/g, \"\");\n const label = /[()\\[\\]]/.test(withoutPairs) ? part.replace(/[()\\[\\]]/g, \" \") : part;\n return { label: clean(label) };\n}\n\nfunction specsFrom(text: string): ColumnSpec[] {\n const trimmed = text.trim();\n if (trimmed === \"\") return [];\n let parts: string[];\n const firstLine = trimmed.split(/\\r?\\n/)[0]!;\n if (firstLine.includes(\"\\t\")) {\n // A header row pasted from a spreadsheet or one of our exports: THE one reader (quotes, guard).\n parts = parseDelimited(trimmed, { delimiter: \"\\t\", strayQuotes: \"literal\" }).data[0] ?? [];\n } else if (/\\r?\\n/.test(trimmed)) {\n parts = trimmed.split(/\\r?\\n/).map((line) => line.replace(BULLET, \"\"));\n } else {\n let line = trimmed;\n const masked = maskBrackets(line);\n const colon = masked.indexOf(\":\");\n if (colon >= 0) line = line.slice(colon + 1);\n else {\n const withAt = masked.toLowerCase().lastIndexOf(\" with \");\n if (withAt >= 0) line = line.slice(withAt + \" with \".length);\n }\n parts = splitOutsideBrackets(line, /\\s*[,;|]\\s*|\\s+and\\s+|\\s*&\\s*/i);\n }\n const specs = parts\n .map(specFromPart)\n .filter((c) => c.label !== \"\")\n .map((c) => (c.label === c.label.toLowerCase() ? { ...c, label: c.label[0]!.toUpperCase() + c.label.slice(1) } : c));\n const seen = new Set<string>();\n const once = specs.filter((c) => {\n const k = c.label.toLowerCase();\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n const labels = uniqueLabels(once.map((c) => c.label));\n return once.map((c, i) => ({ ...c, label: labels[i]! })).slice(0, MOST_NEW_COLUMNS);\n}\n\n/**\n * The column NAMES a person typed or pasted, in order, each once. Empty when there are none.\n * A tab means a spreadsheet header row; several lines mean a list; otherwise one line split on\n * commas, semicolons, pipes and a last \"and\" — after \"with\" or a colon when it is a sentence.\n * Only OUTSIDE brackets: \"Status (choice: a, b)\" is one column.\n */\nexport function columnNamesFrom(text: string): string[] {\n return specsFrom(text).map((c) => c.label);\n}\n\nconst STATUS_CHOICES = [\"Not started\", \"In progress\", \"Done\"];\nconst PRIORITY_CHOICES = [\"Low\", \"Medium\", \"High\"];\n\n/** What a column of this NAME most likely holds. Text when nothing in the name says otherwise. */\nexport function columnFromName(label: string): NewColumn {\n const w = label.toLowerCase();\n const has = (re: RegExp) => re.test(w);\n if (has(/^(is|has|can|did|was)\\b|\\?$/)) return { label, type: \"checkbox\" };\n if (has(/\\be-?mail/)) return { label, type: \"email\" };\n if (has(/\\b(phone|mobile|cell|tel|telephone|whatsapp)\\b/)) return { label, type: \"phone\" };\n if (has(/\\b(url|website|web site|site|link|linkedin|instagram|tiktok|youtube)\\b/)) return { label, type: \"url\" };\n if (has(/\\b(status|stage)\\b/)) return { label, type: \"select\", options: STATUS_CHOICES };\n if (has(/\\bpriority\\b/)) return { label, type: \"select\", options: PRIORITY_CHOICES };\n if (has(/\\b(tags|labels|platforms|channels|skills)\\b/)) return { label, type: \"multi_select\" };\n if (has(/\\b(type|category|kind|tier|plan|platform|channel|source|level)\\b/)) return { label, type: \"select\" };\n if (has(/\\b(time|at|scheduled|starts|ends|appointment)\\b/) && !has(/\\b(date|day)\\b/)) return { label, type: \"datetime\" };\n if (has(/\\b(date|day|birthday|deadline|due|dob|born|joined|since|until|start|end|published|posted)\\b/)) return { label, type: \"date\" };\n if (has(/\\b(price|cost|amount|revenue|budget|fee|fees|salary|paid|total|spend|value|rate card|mrr|arr)\\b|\\$/)) return { label, type: \"currency\" };\n if (has(/%|\\b(percent|percentage|rate|ratio|margin|completion)\\b/)) return { label, type: \"percent\" };\n if (has(/\\b(count|qty|quantity|number of|age|score|hours|minutes|units|followers|views|likes|stars|rating|points|#)\\b|^#|^no\\.? /)) return { label, type: \"number\" };\n if (has(/\\b(done|completed|approved|active|signed|confirmed)\\b/)) return { label, type: \"checkbox\" };\n if (has(/\\b(notes?|description|details|comments?|summary|bio|brief|body|content|caption|script)\\b/)) return { label, type: \"rich_text\" };\n return { label, type: \"text\" };\n}\n\n/** Every column the words name, typed. */\nexport function columnsFrom(text: string): NewColumn[] {\n return specsFrom(text).map((c) =>\n c.type ? { label: c.label, type: c.type, ...(c.options && c.options.length > 0 ? { options: c.options } : {}) } : columnFromName(c.label),\n );\n}\n\n/** The columns as the table's own declaration (`declareTable`'s `fields`). */\nexport function fieldsForNewColumns(columns: readonly NewColumn[]): NewFieldSpec[] {\n const keys = new Set<string>();\n return columns.map((column, i) => {\n let key = tokenFor(column.label) || `column_${i + 1}`;\n while (keys.has(key)) key = `${key}_${i + 1}`;\n keys.add(key);\n const base = { key, label: column.label, sort: (i + 1) * 10, required: false };\n switch (column.type) {\n case \"date\":\n return { ...base, type: \"datetime\", kind: \"date\" as const };\n case \"datetime\":\n return { ...base, type: \"datetime\", kind: \"datetime\" as const };\n case \"currency\":\n return { ...base, type: \"currency\", unit: \"$\" };\n case \"select\":\n case \"multi_select\":\n return { ...base, type: column.type, multi: column.type === \"multi_select\", options: column.options ?? [] };\n default:\n return { ...base, type: column.type };\n }\n });\n}\n","// src/importFileRead.ts — @ai-matrx/records-ui\n//\n// READING A FILE INTO ROWS, WITH THE TWO QUESTIONS A FILE CAN GET WRONG ASKED OUT LOUD.\n//\n// The New table dialog's import reads the file HERE, shows it back as a preview, and hands the\n// result to `ImportWizard` as its `source` — so the plan, the column kinds, the mapping and the\n// write all stay the wizard's (one importer). What this adds is what the old table system had\n// and the bare parse never did:\n//\n// · the separator — guessed (comma, tab, semicolon, pipe) and changeable;\n// · \"First row is column names\" — guessed, and changeable;\n// · headers made usable — trimmed, a blank one named \"Column 3\", and a repeated one kept as\n// \"Notes 2\" instead of silently overwriting the first \"Notes\" column's values.\n\nimport { parseDelimited, toDelimited } from \"@ai-matrx/kit/delimited\";\nimport type { ParsedImport } from \"@ai-matrx/records/core\";\n\n/** What separates the cells of a text file. `auto` = guessed from the text. */\nexport type ImportSeparator = \"auto\" | \",\" | \"\\t\" | \";\" | \"|\";\n\nexport const IMPORT_SEPARATORS: ReadonlyArray<{ value: ImportSeparator; words: string }> = [\n { value: \"auto\", words: \"Detect\" },\n { value: \",\", words: \"Comma\" },\n { value: \"\\t\", words: \"Tab\" },\n { value: \";\", words: \"Semicolon\" },\n { value: \"|\", words: \"Pipe\" },\n];\n\n/** The words for a separator the reader settled on. */\nexport function separatorWords(separator: string | null): string {\n return IMPORT_SEPARATORS.find((s) => s.value === separator)?.words ?? \"Comma\";\n}\n\n/** The file types the import takes, as the native input's `accept`. */\nexport const IMPORT_ACCEPT = \".csv,.tsv,.txt,.xlsx,.xls\";\n\nexport interface ReadGrid {\n /** Every non-empty line as cells, header row included. */\n grid: string[][];\n /** The separator used; null for a workbook. */\n separator: string | null;\n format: \"csv\" | \"xlsx\";\n}\n\n/** Text as a grid of cells. A leading byte-order mark is dropped. */\nexport function gridFromText(text: string, separator: ImportSeparator = \"auto\"): ReadGrid {\n const clean = text.replace(/^/, \"\");\n const parsed = parseDelimited(clean, {\n ...(separator === \"auto\" ? {} : { delimiter: separator }),\n skipEmptyLines: \"greedy\",\n });\n const grid = (parsed.data as unknown[][]).map((line) => line.map((cell) => (cell == null ? \"\" : String(cell))));\n return { grid, separator: parsed.meta.delimiter ?? \",\", format: \"csv\" };\n}\n\n/** Whether a file name is a workbook rather than text. */\nexport function isWorkbook(name: string): boolean {\n return /\\.xlsx?$/i.test(name);\n}\n\n/** A file as a grid: text files through `gridFromText`, workbooks through the one workbook reader (first sheet). */\nexport async function gridFromFile(file: File, separator: ImportSeparator = \"auto\"): Promise<ReadGrid> {\n if (isWorkbook(file.name)) {\n const { readWorkbookBytes } = await import(\"@ai-matrx/print/xlsx\");\n const sheet = (await readWorkbookBytes(await file.arrayBuffer())).sheets[0];\n const raw = sheet ? (sheet.grid({ raw: false, defval: \"\" }) as unknown[][]) : [];\n const grid = raw\n .map((line) => line.map((cell) => (cell == null ? \"\" : String(cell))))\n .filter((line) => line.some((cell) => cell.trim().length > 0));\n return { grid, separator: null, format: \"xlsx\" };\n }\n return gridFromText(await file.text(), separator);\n}\n\nconst NUMERIC = /^\\s*[-+]?[$€£]?\\s*\\d[\\d,]*(\\.\\d+)?\\s*%?\\s*$/;\nconst DATEISH = /^\\s*(\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}|\\d{1,2}[-/]\\d{1,2}[-/]\\d{2,4})\\b/;\nconst EMAILISH = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/**\n * Whether the first line reads as column names: every cell filled, none repeated, and none that\n * looks like a value (a number, a date, an email). Two lines that look alike = no header.\n */\nexport function firstRowLooksLikeHeader(grid: readonly string[][]): boolean {\n const first = grid[0];\n if (!first || first.length === 0) return true;\n const filled = first.filter((c) => c.trim().length > 0);\n if (filled.length === 0) return false;\n if (filled.some((c) => NUMERIC.test(c) || DATEISH.test(c) || EMAILISH.test(c.trim()))) return false;\n return true;\n}\n\n/** Headers a person can map: trimmed, blanks named by position, repeats numbered. */\nexport function usableHeaders(raw: readonly string[], width: number): string[] {\n const taken = new Set<string>();\n const out: string[] = [];\n for (let i = 0; i < width; i++) {\n const base = String(raw[i] ?? \"\").replace(/\\s+/g, \" \").trim() || `Column ${i + 1}`;\n let name = base;\n for (let n = 2; taken.has(name.toLowerCase()); n++) name = `${base} ${n}`;\n taken.add(name.toLowerCase());\n out.push(name);\n }\n return out;\n}\n\n/** The grid as the wizard's rows. With no header row, every line is a row and columns are \"Column 1\"…. */\nexport function importFromGrid(grid: readonly string[][], firstRowIsHeader: boolean): ParsedImport {\n const width = grid.reduce((w, line) => Math.max(w, line.length), 0);\n const headers = usableHeaders(firstRowIsHeader ? (grid[0] ?? []) : [], width);\n const body = firstRowIsHeader ? grid.slice(1) : grid;\n const rows = body\n .filter((line) => line.some((cell) => cell.trim().length > 0))\n .map((line) => {\n const row: Record<string, string> = {};\n headers.forEach((h, i) => {\n row[h] = String(line[i] ?? \"\");\n });\n return row;\n });\n return { headers, rows };\n}\n\n/** The rows as CSV text — the import's identity (the same rows twice write nothing). */\nexport function importText(parsed: ParsedImport): string {\n return toDelimited([parsed.headers, ...parsed.rows.map((r) => parsed.headers.map((h) => r[h] ?? \"\"))]);\n}\n\n/** A table name from a file name: `clinic-patient_intake 2026.csv` → \"Clinic patient intake 2026\". */\nexport function tableNameFromFile(fileName: string): string {\n const stem = fileName.replace(/\\.[^.]+$/, \"\").replace(/[-_.]+/g, \" \").replace(/\\s+/g, \" \").trim();\n if (!stem) return \"\";\n return stem.charAt(0).toUpperCase() + stem.slice(1);\n}\n","\"use client\";\n\n// src/BookingSlots.tsx — @ai-matrx/records-ui · PRODUCTS row 14, THE OWNER'S SIDE\n//\n// A BOOKING PAGE IS AN `anon_form`, SO THIS IS `FormsPanel` FOR BOOKINGS.\n// It lists the booking pages this organization has, with the four numbers that\n// make the list worth opening, copies the visitor's link, and opens or closes a\n// page. That is the whole job.\n//\n// 🚨 WHAT THIS REPLACED, AND WHY IT HAD TO (lane SCREENS-2, 2026-09-20).\n// The first version of this component was a SLOT PICKER for a signed-in person,\n// and every one of its assumptions was wrong for the product it was named after:\n//\n// · It called `tableList`, `personKernelId`, `recordWrite`, `workSlotsDeclare`,\n// `workSlotHolds`, `workSlotHold` and `workSlotRelease` — seven doors granted\n// to `authenticated`. THE VISITOR IT WAS DESIGNED FOR HAS NO ACCOUNT and can\n// reach none of them.\n// · It built its OWN slot grid in the browser from an `availability` prop — a\n// second idea of what is on offer. A visitor with a wrong clock, or a console,\n// could hold a time the organization never offered.\n// · It declared its own slots Table under the slug `records_ui_slots_<tableId>`,\n// a THIRD slots Table beside the `booking_slots_<tableId>` one\n// `custom.booking_declare` finds-or-makes — so a page opened through the\n// component and a page opened through the link protected different indexes.\n//\n// THE PICKER ALREADY EXISTS AND IS CORRECT: `app/(link)/b/[bookingId]/BookingPicker.tsx`\n// in matrx-frontend, server-fed and server-lane, holding through `custom.booking_hold`.\n// The offer is `custom.booking_public`'s and the browser never computes it.\n//\n// ABSENT, NEVER DEAD. Opening or closing a booking page decides whether strangers\n// may take an organization's time, so it needs `admin` on the Table the\n// appointments land in. Someone without it sees the pages, the numbers and the\n// links, and NO open/close control at all — not a grayed one. The levels come\n// from the store in ONE call (`custom.my_levels`), never guessed here.\n\nimport { copyText } from \"@ai-matrx/kit/clipboard\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useRecordsClient, useMyLevels, type Uuid } from \"@ai-matrx/records/react\";\nimport { bookingPath, type BookingSummary, type RecordsError } from \"@ai-matrx/records\";\nimport { Badge, Button, Skeleton, cn } from \"@ai-matrx/design-system\";\n\nimport { BookingBuilder } from \"./BookingBuilder\";\nimport { BuildOrAsk } from \"./BuildOrAsk\";\nimport { ArchiveItemMenu } from \"./BuiltOnArchive\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { useRecordsUi } from \"./host\";\nimport { BOOKING_PAGE_STATE_LABEL } from \"./enumLabels\";\n\nexport interface BookingSlotsProps {\n /**\n * One Table's booking pages. Omitted — on the Records home — it is every\n * booking page in this organization, which is the same door asked the wider\n * question, never a second list.\n */\n tableId?: Uuid | null | undefined;\n /**\n * THE BOOKING PAGE A LINK NAMED (`?rail=bookings&item=<page>`, lane HUB-FIX,\n * VERIFIER-16 M4). It is marked and scrolled to. A page this rail does not\n * list is said out loud, never swapped for another.\n */\n activeBookingId?: Uuid | null | undefined;\n className?: string | undefined;\n}\n\n/** The sentence when a link named a booking page this rail does not list. */\nexport const BOOKING_NOT_HERE_LINE =\n \"The link named a booking page this table does not have — it may have been closed for good, or \" +\n \"it writes into another table. The booking pages this table does have are listed here.\";\n\n/**\n * THERE USED TO BE NO WAY TO MAKE A BOOKING PAGE FROM THIS SCREEN.\n *\n * The reasoning was `FormsPanel`'s: a person says \"let clients book a 30-minute\n * consult with me on Tuesday and Thursday afternoons\", the agent writes the\n * Table, the availability and the page in one call (`booking_propose`) and hands\n * back the link, and a builder button would make the slow path the obvious one.\n * That is still the recommendation and it is still named first.\n *\n * But the product walk of 2026-09-21 found this rail saying exactly that, on a\n * real table, with nothing to press. A person who did not know what to say had\n * no way to a booking page at all. `BookingBuilder` is the other way: four\n * decisions, in place, in this rail, through the same `custom.booking_declare`\n * door the agent calls.\n */\nconst WHAT_A_BOOKING_PAGE_IS =\n \"A booking page offers times you are free and writes each appointment into this table as an \" +\n \"ordinary record.\";\n\n/**\n * The sentence this package would put in a person's mouth.\n *\n * 🚨 IT READS AS ENGLISH (lane RECORDS-UI-FIX, guide re-walk 2026-09-23). With no table\n * name it read \"a 30-minute appointments slot\" — a plural noun where an adjective goes.\n * A table's name is a plural collection (\"Jobs\", \"Appointments\"), so it is never glued in\n * front of \"slot\"; the table is named after it, when there is one.\n */\nexport function bookingSuggestion(tableName: string | null | undefined): string {\n const name = tableName?.trim();\n return name\n ? `Let clients book a 30-minute appointment on Tuesday and Thursday afternoons, and put each one in ${name}.`\n : \"Let clients book a 30-minute appointment on Tuesday and Thursday afternoons.\";\n}\n\nconst NO_ADMIN =\n \"Opening a booking page lets people with no account take time in your calendar, so it needs \" +\n \"Full access on the table the appointments land in.\";\n\n/** The store's own word for the page's state, said the way a person would. THE one map — see `enumLabels.ts`. */\nexport const STATE_WORDS: Record<string, string> = BOOKING_PAGE_STATE_LABEL;\n\nexport function BookingSlots({ tableId, activeBookingId, className }: BookingSlotsProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const [pages, setPages] = useState<BookingSummary[] | null>(null);\n const [error, setError] = useState<RecordsError | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [copied, setCopied] = useState<string | null>(null);\n const [shown, setShown] = useState<string | null>(null);\n // BUILDING IS A MODE OF THIS RAIL: the list a person is looking at is where\n // the new page appears, so nothing has to be found again afterwards.\n const [building, setBuilding] = useState(false);\n /** The store's own sentence after an archive (MAKE-HOME 6a). */\n const [archivedSaid, setArchivedSaid] = useState<string | null>(null);\n // A PAGE THAT EXISTS CAN BE CHANGED (lane HANDOVER, 2026-09-29). Cedar Ridge's booking page had\n // been saved with its hours in UTC (2 AM slots for a clinic), and its card offered only \"Copy link\"\n // and \"Close\": nothing on the screen could change its hours, time zone or title. \"Change it\"\n // opens the same builder on that page, which re-states it rather than making a second one.\n const [changing, setChanging] = useState<{ formId: string; tableId: string } | null>(null);\n\n const load = useCallback(async () => {\n const answered = await client.bookings(tableId ? { table_id: tableId } : {});\n if (!answered.ok) {\n setError(answered.error);\n setPages([]);\n return;\n }\n setError(null);\n setPages(answered.data);\n }, [client, tableId]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n /**\n * ONE call for every page's level, not one per row. The question is \"may I\n * open this?\", and the store answers it about the TABLE the appointments land\n * in — which is the thing publishing actually exposes.\n */\n const subjectIds = useMemo(\n () =>\n Array.from(\n new Set([\n ...(pages ?? []).map((p) => p.table_id as Uuid),\n // THE EMPTY STATE ASKS THE SAME QUESTION. There is no page to read a\n // table off yet, and the empty state's two buttons need the answer\n // about the table this rail is standing in — otherwise the rail\n // offers a viewer both ways into an act the door will refuse.\n ...(tableId ? [tableId] : []),\n ]),\n ),\n [pages, tableId],\n );\n const levels = useMyLevels(subjectIds);\n\n /**\n * MAY THIS PERSON OPEN A BOOKING PAGE ON THIS TABLE? The store's word, never\n * this screen's guess, and `false` while the answer is still in flight — the\n * empty state stays quiet rather than blinking a refusal on and off.\n */\n const levelsKnown = !levels.loading && Boolean(levels.data);\n const mayBuildHere = levelsKnown && Boolean(tableId) && levels.data?.[tableId as Uuid] === \"admin\";\n\n const toggle = useCallback(\n async (page: BookingSummary) => {\n setBusy(page.form_id);\n const wanted = page.published_at === null || page.closed_at !== null;\n const answered = await client.anonPublish({ form_id: page.form_id as Uuid, published: wanted });\n setBusy(null);\n if (!answered.ok) {\n setError(answered.error);\n return;\n }\n await load();\n },\n [client, load],\n );\n\n // THE LINK IS THE PRODUCT. A clipboard that is unavailable (an insecure\n // origin, a locked-down browser) shows the address rather than failing quietly.\n const copy = useCallback(async (url: string, formId: string) => {\n if (await copyText(url)) {\n setCopied(formId);\n setShown(null);\n window.setTimeout(() => setCopied(null), 1600);\n } else {\n setShown(url);\n }\n }, []);\n\n if (pages === null) return <Skeleton className={cn(\"h-32 w-full\", className)} />;\n\n // ABSENT, NOT EMPTY. On the Records home this is a list of what the\n // organization HAS; an organization with no booking pages gets no heading and\n // no explanation it did not ask for. Asked about ONE table, the same emptiness\n // is worth a sentence — that is the screen where somebody came looking.\n if (pages.length === 0 && !tableId && !error && !building) return null;\n\n const origin = host.publicOrigin ?? (typeof window === \"undefined\" ? \"\" : window.location.origin);\n\n return (\n <section className={cn(\"flex flex-col gap-3\", className)} data-testid=\"booking-slots\">\n <header className=\"flex items-center gap-2\">\n <h3 className=\"text-sm font-medium\">Bookings</h3>\n <span className=\"text-xs text-muted-foreground\">\n {pages.length === 0 ? \"none yet\" : `${pages.length}`}\n </span>\n <div className=\"flex-1\" />\n {/* ONE-ROW HEADER. The act that makes a booking page lives beside the\n count, so the second one is as easy to make as the first. */}\n {tableId && pages.length > 0 ? (\n <Button size=\"sm\" variant={building ? \"secondary\" : \"ghost\"} onClick={() => setBuilding((b) => !b)}>\n {building ? \"Done building\" : \"Build a booking page\"}\n </Button>\n ) : null}\n </header>\n\n {error ? <RefusalNotice error={error} /> : null}\n {archivedSaid ? (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"booking-archived-said\">\n {archivedSaid}\n </p>\n ) : null}\n {activeBookingId && !pages.some((p) => p.form_id === activeBookingId) ? (\n <p className=\"rounded-md border border-amber-600/40 bg-amber-500/5 px-3 py-2 text-xs leading-relaxed text-amber-700 dark:border-amber-400/40 dark:text-amber-300\">\n {BOOKING_NOT_HERE_LINE}\n </p>\n ) : null}\n\n {changing ? (\n <BookingBuilder\n tableId={changing.tableId as Uuid}\n bookingId={changing.formId as Uuid}\n onSaved={() => {\n void load();\n }}\n onClose={() => setChanging(null)}\n />\n ) : null}\n\n {building && tableId ? (\n <BookingBuilder\n tableId={tableId}\n onSaved={() => {\n void load();\n }}\n onClose={() => setBuilding(false)}\n />\n ) : null}\n\n {pages.length === 0 && !building ? (\n tableId ? (\n <BuildOrAsk\n mayBuild={mayBuildHere}\n whyNot={mayBuildHere ? null : levelsKnown ? NO_ADMIN : null}\n onBuild={() => setBuilding(true)}\n {...(host.onAskForOne\n ? {\n onAsk: () =>\n host.onAskForOne?.({\n kind: \"booking\",\n tableId,\n suggestion: bookingSuggestion(null),\n }),\n }\n : {})}\n suggestion={bookingSuggestion(null)}\n buildLabel=\"Build the booking page\"\n >\n {WHAT_A_BOOKING_PAGE_IS}\n </BuildOrAsk>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {WHAT_A_BOOKING_PAGE_IS} Open the table the appointments should land in to make one.\n </p>\n )\n ) : null}\n\n <ul className=\"flex flex-col gap-2\">\n {pages.map((page) => {\n const url = `${origin}${bookingPath(page.form_id)}`;\n const mayOpen = levels.data?.[page.table_id] === \"admin\";\n const open = page.published_at !== null && page.closed_at === null;\n return (\n <li\n key={page.form_id}\n data-testid=\"booking-page\"\n data-linked={page.form_id === activeBookingId ? \"true\" : undefined}\n ref={page.form_id === activeBookingId ? (el) => el?.scrollIntoView({ block: \"nearest\" }) : undefined}\n className={cn(\n \"rounded-md border p-2.5\",\n page.form_id === activeBookingId && \"border-primary ring-1 ring-primary\",\n )}\n >\n <div className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium\">\n {page.title ?? page.slug}\n </span>\n <Badge variant={page.state === \"open\" ? \"default\" : \"secondary\"}>{page.state}</Badge>\n <ArchiveItemMenu\n kind=\"booking\"\n id={page.form_id as Uuid}\n title={page.title ?? page.slug}\n mayArchive={mayOpen}\n onArchived={(sentence) => {\n setArchivedSaid(sentence);\n void load();\n }}\n onRefused={setError}\n />\n </div>\n\n <p className=\"mt-0.5 text-xs text-muted-foreground\">\n {STATE_WORDS[page.state] ?? page.state}\n </p>\n\n {/* THE NUMBERS ARE THE STORE'S. A screen that counted appointments\n in the browser would drift from the index that protects a slot\n — and it would drift in the comfortable direction. */}\n <p className=\"mt-1.5 text-xs\">\n <span className=\"font-medium\">{page.upcoming}</span> coming up\n {\" · \"}\n <span className=\"font-medium\">{page.booked}</span> booked in all\n {page.held > 0 ? (\n <>\n {\" · \"}\n <span className=\"font-medium\">{page.held}</span> being held right now\n </>\n ) : null}\n {page.cancelled > 0 ? (\n <>\n {\" · \"}\n <span className=\"font-medium\">{page.cancelled}</span> canceled\n </>\n ) : null}\n <span className=\"text-muted-foreground\"> · {page.slot_minutes} minutes each</span>\n </p>\n\n {/* THE NEXT APPOINTMENT, IN WORDS, in the organization's own zone —\n which is the zone the visitor was offered times in. A time drawn\n in the reader's zone would quietly disagree with the page. */}\n <p className=\"mt-1 text-xs text-muted-foreground\">{nextInWords(page)}</p>\n\n <div className=\"mt-2 flex flex-wrap items-center gap-1.5\">\n <Button size=\"sm\" variant=\"outline\" onClick={() => void copy(url, page.form_id)}>\n {copied === page.form_id ? \"Copied\" : \"Copy link\"}\n </Button>\n {mayOpen ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => setChanging({ formId: page.form_id, tableId: page.table_id })}\n >\n Change it\n </Button>\n ) : null}\n {mayOpen ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n disabled={busy === page.form_id}\n onClick={() => void toggle(page)}\n >\n {busy === page.form_id ? \"…\" : open ? \"Close\" : \"Open\"}\n </Button>\n ) : null}\n </div>\n\n {shown && shown === url ? (\n <p className=\"mt-1.5 break-all rounded border border-dashed px-2 py-1 text-xs\">\n This browser would not let the page copy for you, so here it is to copy by hand: {url}\n </p>\n ) : null}\n </li>\n );\n })}\n </ul>\n\n {/* ONLY ONCE THE STORE HAS ANSWERED. While `custom.my_levels` is still in\n flight nothing is claimed in either direction — a sentence that said\n \"you are not an admin\" for one render and then took it back is the\n screen guessing out loud. */}\n {pages.length > 0 && !levels.loading && levels.data && subjectIds.every((id) => levels.data?.[id] !== \"admin\") ? (\n <p className=\"text-xs text-muted-foreground\">{NO_ADMIN}</p>\n ) : null}\n </section>\n );\n}\n\n/**\n * The next appointment, as a sentence. `next_at` is the store's answer over\n * every appointment this person may see — not over the page this screen loaded.\n */\nexport function nextInWords(page: Pick<BookingSummary, \"next_at\" | \"timezone\" | \"state\">): string {\n if (!page.next_at) {\n return page.state === \"open\"\n ? \"Nothing booked yet.\"\n : \"Nothing booked.\";\n }\n const at = new Date(page.next_at);\n if (Number.isNaN(at.getTime())) return \"Nothing booked yet.\";\n let said: string;\n try {\n said = at.toLocaleString(undefined, {\n timeZone: page.timezone,\n weekday: \"long\",\n month: \"long\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n } catch {\n // An unknown zone is a fact about the page, not a reason to draw nothing.\n said = at.toLocaleString(undefined, {\n weekday: \"long\",\n month: \"long\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n }\n return `Next: ${said} (${page.timezone}).`;\n}\n","\"use client\";\n\n// src/BookingBuilder.tsx — @ai-matrx/records-ui · PRODUCTS row 14, the builder\n//\n// \"LET CLIENTS BOOK A 30-MINUTE CONSULT\" — BUILT BY HAND, IN UNDER TWO MINUTES.\n//\n// The champion is Calendly, and the thing Calendly gets right is that the whole\n// page is four decisions: how long a meeting is, which hours of the week you are\n// free, how much room you want between appointments, and what the person sees\n// after they book. Everything else is a default somebody can change later. So\n// that is this screen, in that order, and nothing more.\n//\n// WHAT IT IS NOT. It is not a second booking system and it is not a slot picker:\n// the visitor's picker is `app/(link)/b/[bookingId]/BookingPicker.tsx`, which is\n// server-fed and holds through `custom.booking_hold`. This screen never computes\n// a slot. It declares the page (`custom.booking_declare`), shows what the STORE\n// normalized the offer to, and opens the link (`custom.anon_publish`) — the same\n// one act that opens a form, because a booking page IS an `anon_form`.\n//\n// THE THREE QUESTIONS A PERSON MAY NOT ASK. `slot`, `status` and `booked_with`\n// are the store's to fill in, and `custom.booking_declare` refuses a payload\n// naming any of them BY NAME. So this screen offers the Table's OTHER fields as\n// the questions a visitor answers, and never draws the three it would be refused\n// for — an offered control that is always refused is the dead control law 4\n// forbids, and hiding the refusal instead of the control would be worse.\n//\n// IT SHOWS WHAT CAME BACK, NEVER WHAT IT SENT. The store owns every default: a\n// page declared with an empty availability comes back in the organization's own\n// timezone, Monday to Friday, nine to five, thirty minutes. The offer under the\n// Save button is `availability` as the door answered it, so the screen and the\n// visitor's page cannot hold two ideas of what is free.\n//\n// PUBLISHING IS A SEPARATE ACT and it says so. `booking_declare` writes the page\n// and does NOT open it; a person who saved and walked away has a draft, not an\n// open calendar. The publish row is the same component the Forms rail uses.\n\nimport { copyText } from \"@ai-matrx/kit/clipboard\";\nimport { ErrorBox } from \"@ai-matrx/design-system\";\nimport { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useFields, useRecordsClient, useTable, type Uuid } from \"@ai-matrx/records/react\";\n\nimport { formatDurationMinutes } from \"@ai-matrx/kit/format\";\nimport {\n bookingPath,\n type BookingAvailability,\n type BookingSummary,\n type BookingWindow,\n type Field,\n type RecordsError,\n} from \"@ai-matrx/records\";\nimport { BasicInput, BasicTextarea, Button, Checkbox, Label, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { Select } from \"@ai-matrx/design-system/controls\";\n\nimport {\n BOOKING_TOKENS,\n DEFAULT_REMINDER_OFFSETS,\n REMINDER_CHOICES,\n messagesFromPresentation,\n messagesToPresentation,\n type BookingMessageNotice,\n type BookingMessages,\n} from \"./bookingMessages\";\nimport { askableFields, requiredLeftUnasked, whyNotAskable } from \"./publicQuestions\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { TimeZoneInput, ownTimeZone } from \"./TimeZoneInput\";\nimport { useRecordsUi, useTableRights } from \"./host\";\nimport { fieldName, singularNoun } from \"./names\";\nimport { editorKindFor } from \"./parity\";\n\n/**\n * THE THREE THE STORE FILLS IN. Named here so this screen never offers them —\n * `custom.booking_declare` refuses a question naming any of the three, and a\n * control that is always refused is a dead control.\n */\nexport const STORE_ANSWERS_THESE = [\"slot\", \"status\", \"booked_with\"] as const;\n\n/** Monday first, because a working week is what a person is describing. */\nconst DAYS: Array<{ weekday: number; label: string }> = [\n { weekday: 1, label: \"Mon\" },\n { weekday: 2, label: \"Tue\" },\n { weekday: 3, label: \"Wed\" },\n { weekday: 4, label: \"Thu\" },\n { weekday: 5, label: \"Fri\" },\n { weekday: 6, label: \"Sat\" },\n { weekday: 0, label: \"Sun\" },\n];\n\n/** The lengths a consultation actually is. The store takes any number; these are the ones people pick. */\nconst LENGTHS = [15, 20, 30, 45, 60, 90, 120];\n\nexport interface BookingBuilderProps {\n /** The Table the appointments land in. An appointment is an ordinary record in it. */\n tableId: Uuid;\n /** Re-state an existing page rather than making a second one over the same Table. */\n bookingId?: Uuid | null | undefined;\n /** Called after a save, so the list this opened from re-reads the store. */\n onSaved?: ((page: { form_id: string }) => void) | undefined;\n onClose?: (() => void) | undefined;\n /**\n * A NEW PAGE, whatever the table already has (lane MAKE-HOME, 2026-10-02). Without it and without\n * `bookingId` the builder opens the table's first page; a host whose person pressed \"make a\n * booking page\" (the /make hub) passes this, and the first Save makes a second page beside the\n * old one. After that Save the builder keeps editing the page it just made.\n */\n startNew?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** One window a person is describing, before the store has normalized it. */\ninterface DraftWindow extends BookingWindow {\n on: boolean;\n}\n\n/**\n * THE SCREEN STARTS WHERE THE STORE STARTS (walk 2, 2026-09-21).\n *\n * `custom._booking_availability` substitutes Monday-to-Friday, nine to five,\n * for an empty window list, on purpose — its own comment says a booking page\n * that offered nothing \"would look broken rather than unconfigured\". This\n * screen started with every day OFF and every row reading \"not taking\n * bookings\", so a person who saved without touching the days was told the page\n * offered nothing and got a page offering the whole working week. The screen\n * and the store now start from the same place, and an EXISTING page is drawn\n * from what it actually holds.\n */\nconst WORKING_WEEK = new Set([1, 2, 3, 4, 5]);\n\nfunction draftWindows(availability: BookingAvailability | null): DraftWindow[] {\n return DAYS.map((day) => {\n const found = availability?.windows.find((w) => w.weekday === day.weekday);\n return {\n weekday: day.weekday,\n from: found?.from ?? \"09:00\",\n to: found?.to ?? \"17:00\",\n on: availability ? Boolean(found) : WORKING_WEEK.has(day.weekday),\n };\n });\n}\n\nexport function BookingBuilder({ tableId, bookingId, onSaved, onClose, startNew, className }: BookingBuilderProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const table = useTable(tableId);\n const rights = useTableRights(table.data);\n const fields = useFields(tableId);\n\n const [existing, setExisting] = useState<BookingSummary | null>(null);\n const [loaded, setLoaded] = useState(false);\n const [error, setError] = useState<RecordsError | null>(null);\n const [saving, setSaving] = useState(false);\n const [publishing, setPublishing] = useState(false);\n const [copied, setCopied] = useState(false);\n\n const [title, setTitle] = useState(\"\");\n const [minutes, setMinutes] = useState(30);\n const [buffer, setBuffer] = useState(0);\n const [lead, setLead] = useState(120);\n const [perDay, setPerDay] = useState(8);\n const [days, setDays] = useState(30);\n // THE CLOCK THE HOURS ARE IN (lane HANDOVER, 2026-09-28). An organization with no time zone\n // of its own got a page \"in UTC\", so a clinic's 9-to-5 opened at 2 AM its own time. A new page\n // starts in the owner's own zone (Calendly's default), a saved one in the zone it was saved in,\n // and the zone is on the screen to change.\n const [timezone, setTimezone] = useState<string>(() => ownTimeZone());\n const [windows, setWindows] = useState<DraftWindow[]>(() => draftWindows(null));\n const [asked, setAsked] = useState<string[]>([]);\n const [confirmation, setConfirmation] = useState(\"\");\n // WHAT THE BOOKER IS EMAILED (BOOKING-NOTIFY). Held whole and sent back on every Save: Save\n // re-states the page, so a screen that dropped this would erase the owner's switches.\n const [messages, setMessages] = useState<BookingMessages>({});\n // EVERYTHING THE PAGE ALREADY HOLDS THAT THIS SCREEN DOES NOT EDIT. Save re-states the whole page\n // (the store takes absent as \"none\"), so what is not carried back is erased: the owner's intro,\n // endings and per-question wording, the cap, the accept and notify Rules, the link name.\n const [stored, setStored] = useState<{\n presentation: Record<string, unknown>;\n questions: Array<Record<string, unknown>>;\n submissionCap: number | null;\n quarantineRuleId: Uuid | null;\n notifyRuleId: Uuid | null;\n slug: string | null;\n thankYouTitle: string | null;\n } | null>(null);\n // The offer as the STORE normalized it — what the visitor's page will show.\n const [offer, setOffer] = useState<BookingAvailability | null>(null);\n const [formId, setFormId] = useState<Uuid | null>((bookingId as Uuid | null) ?? null);\n /** The page a `startNew` builder made with its first Save; it is the page from then on. */\n const madeRef = useRef<Uuid | null>(null);\n\n const publicOrigin = host.publicOrigin ?? (typeof window === \"undefined\" ? \"\" : window.location.origin);\n\n /**\n * THE QUESTIONS A VISITOR MAY BE ASKED — this Table's own Fields, minus the\n * three the store fills in. A form is a view on a real Table, so there is no\n * way on this screen to invent a question that lands nowhere.\n */\n const askable = useMemo(\n () => askableFields(fields.data ?? [], STORE_ANSWERS_THESE as readonly string[]),\n [fields.data],\n );\n /** A required column this page leaves unasked: every booking would be refused (said, never blocking). */\n const unfillable = requiredLeftUnasked(fields.data ?? [], asked, STORE_ANSWERS_THESE as readonly string[]);\n /** The Fields a visitor could never answer, named with the reason (walk 2). */\n const leftOut = useMemo(\n () => whyNotAskable(fields.data ?? [], STORE_ANSWERS_THESE as readonly string[]),\n [fields.data],\n );\n\n const load = useCallback(async () => {\n const answered = await client.bookings({ table_id: tableId });\n if (!answered.ok) {\n setError(answered.error);\n setLoaded(true);\n return;\n }\n // A new page (startNew) is the page this builder saved, once it has saved one — never the first.\n const wanted = bookingId ?? (startNew ? madeRef.current : null);\n const mine = wanted\n ? (answered.data.find((p) => p.form_id === wanted) ?? null)\n : startNew\n ? null\n : (answered.data[0] ?? null);\n setExisting(mine);\n if (mine) {\n setFormId(mine.form_id as Uuid);\n // A PAGE THAT EXISTS OPENS WITH ITS OWN QUESTIONS AND HOURS (lane HANDOVER, 2026-09-29).\n // \"Change it\" opened Cedar Ridge's booking page with its title and clock but no questions and\n // the opening guess for its hours, so saving was refused (\"has to ask the person something\")\n // and, had it gone through, would have replaced the page's real hours. The page's own\n // presentation (the forms door answers booking pages too) is what the builder starts from.\n const pages = await client.forms({ table_id: tableId });\n const page = pages.ok ? pages.data.find((f) => f.form_id === mine.form_id) : undefined;\n const presentation = (page?.presentation ?? {}) as Record<string, unknown>;\n const questions = Array.isArray(presentation[\"questions\"])\n ? (presentation[\"questions\"] as Array<{ field?: unknown; hidden?: unknown }>)\n : [];\n // The page's stored list also carries the store's own hidden columns (slot, status,\n // booked_with); those are the store's to fill, and sending them back is refused.\n const keys = questions\n .filter((q) => q.hidden !== true)\n .map((q) => (typeof q.field === \"string\" ? q.field : \"\"))\n .filter((k) => k !== \"\" && !(STORE_ANSWERS_THESE as readonly string[]).includes(k));\n if (keys.length > 0) setAsked(keys);\n setMessages(messagesFromPresentation(presentation));\n const thankYou = presentation[\"thank_you\"] as { title?: unknown; body?: unknown } | null | undefined;\n if (thankYou && typeof thankYou.body === \"string\") setConfirmation(thankYou.body);\n setStored({\n presentation,\n questions: questions as Array<Record<string, unknown>>,\n submissionCap: page?.submission_cap ?? null,\n quarantineRuleId: (page?.quarantine_rule_id as Uuid | null | undefined) ?? null,\n notifyRuleId: (page?.notify_rule_id as Uuid | null | undefined) ?? null,\n slug: page?.slug ?? null,\n thankYouTitle: typeof thankYou?.title === \"string\" ? thankYou.title : null,\n });\n const block = presentation[\"booking\"];\n if (block && typeof block === \"object\" && Array.isArray((block as { windows?: unknown }).windows)) {\n setOffer(block as BookingAvailability);\n }\n }\n setLoaded(true);\n }, [client, tableId, bookingId, startNew]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n // The name a person would give it, from the Table they are standing on — never\n // \"Booking 1\". A real business's booking page is named after the work.\n useEffect(() => {\n if (title !== \"\" || !table.data) return;\n setTitle(existing?.title ?? `Book a ${minutes}-minute ${singularNoun(table.data, \"appointment\")}`);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [table.data, existing]);\n\n useEffect(() => {\n if (!existing) return;\n setMinutes(existing.slot_minutes);\n if (existing.timezone && existing.timezone !== \"UTC\") setTimezone(existing.timezone);\n }, [existing]);\n\n // Once the store has said what a page actually offers, the day rows are ITS\n // answer — never the screen's opening guess sitting on top of a real page.\n useEffect(() => {\n if (!offer) return;\n setWindows(draftWindows(offer));\n setMinutes(offer.slot_minutes);\n setBuffer(offer.buffer_minutes);\n setLead(offer.lead_minutes);\n setPerDay(offer.max_per_day);\n setDays(offer.days);\n // A page kept in UTC before the screen sent a zone starts in the owner's own clock instead.\n if (offer.timezone && offer.timezone !== \"UTC\") setTimezone(offer.timezone);\n }, [offer]);\n\n const availability = useCallback(\n (): Partial<BookingAvailability> => ({\n timezone,\n slot_minutes: minutes,\n buffer_minutes: buffer,\n lead_minutes: lead,\n max_per_day: perDay,\n days,\n windows: windows\n .filter((w) => w.on)\n .map((w) => ({ weekday: w.weekday, from: w.from, to: w.to })),\n }),\n [timezone, minutes, buffer, lead, perDay, days, windows],\n );\n\n // A NEW PAGE SAVES ON ITS FIRST PRESS (lane MAKE-HOME 1b): it starts asking the table's required\n // columns and the ones that say who is booking (Calendly's page works with its defaults), or the\n // first askable column — never an empty list the store refuses. Once, and never over a saved page.\n const startedAsking = useRef(false);\n useEffect(() => {\n if (startedAsking.current || !loaded || existing || formId || !fields.data) return;\n startedAsking.current = true;\n if (asked.length > 0) return;\n const keys = askable.filter((f) => f.required || isWhoField(f)).map((f) => f.key);\n const first = askable[0]?.key;\n setAsked(keys.length > 0 ? keys : first ? [first] : []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaded, existing, formId, fields.data, askable]);\n\n const [addingWho, setAddingWho] = useState(false);\n /** Adds a Name and an Email column to this table and asks both on the page. */\n async function addWho() {\n setAddingWho(true);\n setError(null);\n for (const spec of [\n { label: \"Name\", plain: \"text\" as const },\n { label: \"Email\", parity_type: \"email\" as const },\n ]) {\n const made = await client.fieldDeclare({ table_id: tableId, spec });\n if (!made.ok) {\n setAddingWho(false);\n setError(made.error);\n return;\n }\n }\n fields.reload();\n setAddingWho(false);\n setWhoAdded(true);\n }\n // Once the two columns are there, the page asks them — the owner pressed the button to be told\n // who booked, not to add columns and then tick them.\n const [whoAdded, setWhoAdded] = useState(false);\n useEffect(() => {\n if (!whoAdded) return;\n const who = askable.filter((f) => isWhoField(f)).map((f) => f.key);\n if (who.length === 0) return;\n setAsked((prev) => [...prev, ...who.filter((k) => !prev.includes(k))]);\n setWhoAdded(false);\n }, [whoAdded, askable]);\n\n async function save() {\n setSaving(true);\n setError(null);\n const written = await client.bookingDeclare({\n table_id: tableId,\n title: title.trim() === \"\" ? \"Book a time\" : title.trim(),\n // The Fields a visitor is asked for, in the order this screen shows them.\n // The questions as the page words them (ask / help / required), for the ones still asked.\n questions: asked.map(\n (key) => stored?.questions.find((q) => (q[\"field\"] ?? q[\"key\"]) === key) ?? { field: key },\n ),\n availability: availability(),\n presentation: {\n // Everything else the page holds, as it is. The store re-adds `questions` and `booking`.\n ...Object.fromEntries(\n Object.entries(stored?.presentation ?? {}).filter(\n ([k]) => ![\"questions\", \"booking\", \"thank_you\", \"booking_messages\"].includes(k),\n ),\n ),\n // THE SENTENCE AFTER THE BOOKING. It is the thank-you screen every other\n // public surface in this package uses, so one component renders it.\n thank_you:\n confirmation.trim() === \"\" ? null : { title: stored?.thankYouTitle ?? \"You're booked\", body: confirmation.trim() },\n ...(messagesToPresentation(messages) ? { booking_messages: messagesToPresentation(messages) } : {}),\n },\n ...(stored\n ? {\n submission_cap: stored.submissionCap,\n quarantine_rule_id: stored.quarantineRuleId,\n notify_rule_id: stored.notifyRuleId,\n slug: stored.slug,\n }\n : {}),\n ...(formId ? { form_id: formId } : {}),\n });\n setSaving(false);\n if (!written.ok) {\n setError(written.error);\n return;\n }\n // WHAT CAME BACK, not what was sent: the store owns every default.\n setOffer(written.data.availability);\n setFormId(written.data.form_id as Uuid);\n madeRef.current = written.data.form_id as Uuid;\n onSaved?.({ form_id: written.data.form_id });\n await load();\n }\n\n async function publish(wanted: boolean) {\n if (!formId) return;\n setPublishing(true);\n const answered = await client.anonPublish({ form_id: formId, published: wanted });\n setPublishing(false);\n if (!answered.ok) {\n setError(answered.error);\n return;\n }\n await load();\n onSaved?.({ form_id: formId });\n }\n\n if (!loaded || (fields.loading && !fields.data)) return <Skeleton className={cn(\"h-64 w-full\", className)} />;\n\n // ABSENT, NEVER DEAD. A booking page lets people with no account take time in\n // this organization's calendar, so the store asks for `admin` on the Table —\n // and when a person does not hold it there is no builder at all, with the\n // store's own reason in its place.\n if (!rights.structure) {\n return (\n <p className={cn(\"text-xs text-muted-foreground\", className)}>\n {rights.why(\"structure\") ??\n \"Making a booking page needs Full access on this table, because it lets people with no account take time in your calendar.\"}\n </p>\n );\n }\n\n const url = formId ? `${publicOrigin}${bookingPath(formId)}` : null;\n const shown = offer ?? null;\n\n return (\n // THE RAIL IS 384px WIDE AND THE VIEWPORT IS NOT (walk 1, 2026-09-21):\n // every split below is a CONTAINER query, so this screen is the same\n // screen in a rail, a dialog and a full page.\n <section className={cn(\"@container flex flex-col gap-3\", className)}>\n {/* ONE-ROW HEADER. No repeated name, no second title bar. */}\n <header className=\"flex items-center gap-2\">\n <h3 className=\"text-sm font-medium\">{existing ? \"Booking page\" : \"New booking page\"}</h3>\n <div className=\"flex-1\" />\n <Button size=\"sm\" disabled={saving} onClick={() => void save()}>\n {saving ? \"Saving…\" : \"Save\"}\n </Button>\n {onClose ? (\n <Button size=\"sm\" variant=\"ghost\" onClick={onClose}>\n Close\n </Button>\n ) : null}\n </header>\n {!existing && !formId && fields.data && STORE_ANSWERS_THESE.some((k) => !fields.data!.some((f) => f.key === k)) ? (\n <p className=\"text-xs text-muted-foreground\" data-booking-adds-columns=\"\">\n Saving adds three columns to this table: Appointment, Status, With\n </p>\n ) : null}\n\n {error ? <RefusalNotice error={error} /> : null}\n\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">What it is called</Label>\n <BasicInput value={title} onChange={(e) => setTitle(e.target.value)} />\n </label>\n\n <div className=\"grid grid-cols-1 gap-2 @md:grid-cols-2\">\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">How long one appointment is</Label>\n <Select\n aria-label=\"How long one appointment is\"\n value={String(minutes)}\n onValueChange={(v) => setMinutes(Number(v))}\n options={LENGTHS.map((n) => ({ value: String(n), label: `${n} minutes` }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Gap kept after each one</Label>\n <Select\n aria-label=\"Gap kept after each one\"\n value={String(buffer)}\n onValueChange={(v) => setBuffer(Number(v))}\n options={[0, 5, 10, 15, 30].map((n) => ({ value: String(n), label: n === 0 ? \"No gap — back to back\" : `${n} minutes` }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Earliest somebody may book</Label>\n <Select\n aria-label=\"Earliest somebody may book\"\n value={String(lead)}\n onValueChange={(v) => setLead(Number(v))}\n options={[0, 60, 120, 240, 1440].map((n) => ({\n value: String(n),\n label: n === 0 ? \"Right away\" : n === 1440 ? \"A day from now\" : `${formatDurationMinutes(n, { style: \"long\" })} from now`,\n }))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">Most in one day</Label>\n <BasicInput\n type=\"number\"\n min={1}\n value={perDay}\n onChange={(e) => setPerDay(Math.max(1, Number(e.target.value) || 1))}\n />\n </label>\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">How far ahead the page offers</Label>\n <Select\n aria-label=\"How far ahead the page offers\"\n value={String(days)}\n onValueChange={(v) => setDays(Number(v))}\n options={[7, 14, 30, 60, 90].map((n) => ({ value: String(n), label: `${n} days` }))}\n />\n </label>\n {/* Type to find a zone: four hundred of them are a search, not a list to scroll. */}\n <TimeZoneInput label=\"Time zone the hours are in\" value={timezone} onChange={setTimezone} />\n </div>\n\n {/* THE HOURS OF THE WEEK. One row per day, the day itself the switch — the\n shape a person already knows from every calendar they have used. */}\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium\">Hours you are free</Label>\n {windows.map((w, i) => (\n <div key={w.weekday} className=\"flex items-center gap-2\">\n <label className=\"flex w-20 items-center gap-1.5 text-xs\">\n <Checkbox\n checked={w.on}\n onCheckedChange={(on) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, on: Boolean(on) } : x)))\n }\n />\n {DAYS[i]?.label}\n </label>\n {w.on ? (\n <>\n <BasicInput\n type=\"time\"\n className=\"h-8 w-28\"\n value={w.from}\n onChange={(e) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, from: e.target.value } : x)))\n }\n />\n <span className=\"text-xs text-muted-foreground\">to</span>\n <BasicInput\n type=\"time\"\n className=\"h-8 w-28\"\n value={w.to}\n onChange={(e) =>\n setWindows((prev) => prev.map((x, j) => (i === j ? { ...x, to: e.target.value } : x)))\n }\n />\n </>\n ) : (\n <span className=\"text-xs text-muted-foreground\">not taking bookings</span>\n )}\n </div>\n ))}\n </div>\n\n {/* WHAT THE PERSON BOOKING IS ASKED. This Table's own Fields, minus the\n three the store fills in — so an appointment is a record, complete. */}\n <div className=\"flex flex-col gap-1.5\">\n <Label className=\"text-xs font-medium\">What to ask the person booking</Label>\n {askable.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">\n This table has no fields yet, so there is nothing a booking page could ask for. Add a\n field first — every question is one of this table&apos;s own fields.\n </p>\n ) : (\n <div className=\"flex flex-wrap gap-x-4 gap-y-1.5\">\n {askable.map((f) => (\n <label key={f.key} className=\"flex items-center gap-1.5 text-xs\">\n <Checkbox\n checked={asked.includes(f.key)}\n onCheckedChange={(on) =>\n setAsked((prev) => (on ? [...prev, f.key] : prev.filter((k) => k !== f.key)))\n }\n />\n {fieldName(f)}\n </label>\n ))}\n </div>\n )}\n {/* WHO IS BOOKING (lane HANDOVER, 2026-09-28). Cedar Ridge's Visits names its patient by a\n link a stranger cannot follow, so its page asked nobody who they were and an appointment\n arrived with no one to call. Calendly always asks a name and an email; a table with\n neither gets them in one press, and the page asks them. */}\n {!asksWhoTheyAre(askable) ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded border border-dashed px-2 py-1.5\" data-booking-who=\"\">\n <p className=\"text-xs text-muted-foreground\">\n Nobody booking is asked who they are, so you would not know who booked or how to reach them.\n </p>\n <Button size=\"sm\" variant=\"outline\" disabled={addingWho} onClick={() => void addWho()}>\n {addingWho ? \"Adding…\" : \"Ask their name and email\"}\n </Button>\n </div>\n ) : null}\n <p className=\"text-xs text-muted-foreground\">\n The time, whether it is booked or canceled, and who it is with are filled in for you\n — a booking page cannot ask a visitor for any of the three.\n </p>\n {leftOut ? <p className=\"text-xs text-muted-foreground\">{leftOut}</p> : null}\n {unfillable ? (\n <ErrorBox\n className=\"rounded border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive\"\n message={unfillable}\n operation=\"Build a booking page\"\n origin=\"records-ui/BookingBuilder\"\n />\n ) : null}\n </div>\n\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs font-medium\">What they see after booking</Label>\n <BasicTextarea\n rows={2}\n value={confirmation}\n placeholder=\"You're booked. We'll send a reminder the day before — reply to that message to move it.\"\n onChange={(e) => setConfirmation(e.target.value)}\n />\n </label>\n\n\n {/* WHAT THE BOOKER IS EMAILED. Every notice is on until it is switched off; an empty box\n means the default words. The store sends them (custom.booking_messages). */}\n <div className=\"flex flex-col gap-2\" data-booking-messages=\"\">\n <Label className=\"text-xs font-medium\">Emails to the person who books</Label>\n {(\n [\n [\"confirmation\", \"Confirmation, with a calendar file\"],\n [\"changed\", \"When they move it\"],\n [\"cancelled\", \"When they cancel\"],\n ] as const\n ).map(([key, label]) => (\n <MessageRow\n key={key}\n label={label}\n value={messages[key]}\n onChange={(n) => setMessages((m) => ({ ...m, [key]: n }))}\n />\n ))}\n <MessageRow\n label=\"Reminders\"\n value={messages.reminders}\n onChange={(n) => setMessages((m) => ({ ...m, reminders: { ...m.reminders, ...n } }))}\n >\n <div className=\"flex flex-wrap gap-x-3 gap-y-1\">\n {REMINDER_CHOICES.map((c) => {\n const offsets = messages.reminders?.offsets ?? [...DEFAULT_REMINDER_OFFSETS];\n return (\n <label key={c.minutes} className=\"flex items-center gap-1.5 text-xs\">\n <Checkbox\n checked={offsets.includes(c.minutes)}\n onCheckedChange={(on) =>\n setMessages((m) => ({\n ...m,\n reminders: {\n ...m.reminders,\n offsets: on === true ? [...offsets, c.minutes] : offsets.filter((o) => o !== c.minutes),\n },\n }))\n }\n />\n {c.label}\n </label>\n );\n })}\n </div>\n </MessageRow>\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={messages.host?.on !== false}\n onCheckedChange={(on) => setMessages((m) => ({ ...m, host: { on: on === true } }))}\n />\n Tell me when someone books, moves or cancels\n </label>\n <label className=\"flex items-center gap-2 text-xs\">\n <Checkbox\n checked={messages.sms?.on === true}\n onCheckedChange={(on) => setMessages((m) => ({ ...m, sms: { on: on === true } }))}\n />\n Offer text reminders (booker ticks Text me reminders)\n </label>\n <p className=\"text-xs text-muted-foreground\">Words can use {BOOKING_TOKENS.join(\" \")}</p>\n </div>\n\n {/* THE OFFER, AS THE STORE NORMALIZED IT. Shown only after a save, because\n before one there is nothing the store has agreed to. */}\n {shown ? (\n <p className=\"rounded-md border bg-muted/40 p-2.5 text-xs\">\n Saved. The page offers {shown.slot_minutes}-minute appointments in {shown.timezone}, up to{\" \"}\n {shown.max_per_day} a day, {shown.days} days ahead\n {shown.buffer_minutes > 0 ? `, with ${shown.buffer_minutes} minutes between them` : \"\"}:{\" \"}\n {shown.windows\n .map(\n (w) => `${DAYS.find((d) => d.weekday === w.weekday)?.label ?? w.weekday} ${w.from}–${w.to}`,\n )\n .join(\", \")}\n .\n </p>\n ) : null}\n\n {/* PUBLISHING IS ITS OWN ACT, and until it happens the link does not\n answer. Saying so is the difference between a draft and an open\n calendar somebody thinks they have. */}\n {url ? (\n <div className=\"flex flex-wrap items-center gap-2 rounded-md border p-2.5\">\n <span className=\"min-w-0 flex-1 break-all text-xs\">{url}</span>\n <Button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n void copyText(url).then((landed) => {\n setCopied(landed);\n if (landed) window.setTimeout(() => setCopied(false), 1600);\n });\n }}\n >\n {copied ? \"Copied\" : \"Copy link\"}\n </Button>\n <Button\n size=\"sm\"\n disabled={publishing}\n onClick={() => void publish(!(existing?.published_at && !existing.closed_at))}\n >\n {publishing\n ? \"…\"\n : existing?.published_at && !existing.closed_at\n ? \"Unpublish\"\n : \"Publish\"}\n </Button>\n <p className=\"w-full text-xs text-muted-foreground\">\n {existing?.published_at && !existing.closed_at\n ? \"Open. Anyone with this link can book a time.\"\n : \"Not open yet — the link does not take bookings until you publish it.\"}\n </p>\n </div>\n ) : null}\n </section>\n );\n}\n\n/** One notice: a switch, and its words when it is on. An empty box is the default words. */\nfunction MessageRow({\n label,\n value,\n onChange,\n children,\n}: {\n label: string;\n value: BookingMessageNotice | undefined;\n onChange: (next: BookingMessageNotice) => void;\n children?: ReactNode;\n}) {\n const on = value?.on !== false;\n return (\n <div className=\"flex flex-col gap-1.5 rounded-md border p-2\">\n <label className=\"flex items-center gap-2 text-xs font-medium\">\n <Checkbox checked={on} onCheckedChange={(next) => onChange({ ...value, on: next === true })} />\n {label}\n </label>\n {on ? (\n <>\n {children}\n <BasicInput\n aria-label={`${label}: subject`}\n placeholder=\"Subject (blank = the default)\"\n value={value?.subject ?? \"\"}\n onChange={(e) => onChange({ ...value, subject: e.target.value })}\n />\n <BasicTextarea\n aria-label={`${label}: message`}\n rows={2}\n placeholder=\"Message (blank = the default)\"\n value={value?.body ?? \"\"}\n onChange={(e) => onChange({ ...value, body: e.target.value })}\n />\n </>\n ) : null}\n </div>\n );\n}\n\n/** A column that says who somebody is: a name, an email or a phone. */\nfunction isWhoField(field: Field): boolean {\n const kind = editorKindFor(field);\n return kind === \"email\" || kind === \"phone\" || /\\bname\\b/i.test(fieldName(field));\n}\n\n/** Whether the page can already ask who is booking: an email or a phone column it may ask. */\nfunction asksWhoTheyAre(askable: readonly Field[]): boolean {\n return askable.some((f) => {\n const kind = editorKindFor(f);\n return kind === \"email\" || kind === \"phone\";\n });\n}\n","// src/bookingMessages.ts — @ai-matrx/records-ui · what a booking page says to the person who booked.\n//\n// BOOKING-NOTIFY. The words and switches live on the page as `presentation.booking_messages`; the\n// SENDER is the store (`custom.booking_messages`, called by the confirm, reschedule and cancel\n// doors), so the screen only edits this one object and hands it back whole on every Save.\n// 🚨 Save re-states the whole page, so a screen that did not read this object and send it back\n// would silently erase an owner's switches and wording the next time anyone pressed Save.\n//\n// Every notice is ON until an owner switches it off, and an empty word box means \"use the default\".\n\nexport interface BookingMessageNotice {\n on?: boolean;\n subject?: string;\n body?: string;\n}\n\nexport interface BookingMessages {\n confirmation?: BookingMessageNotice;\n changed?: BookingMessageNotice;\n cancelled?: BookingMessageNotice;\n reminders?: BookingMessageNotice & { offsets?: number[] };\n host?: { on?: boolean };\n /** Offer \"Text me reminders\" on the public page. OFF until an owner switches it on (it spends their texting number). */\n sms?: { on?: boolean };\n}\n\n/** The reminders a new page sends: the day before and the hour before (minutes before the start). */\nexport const DEFAULT_REMINDER_OFFSETS: readonly number[] = [1440, 60];\n\n/** The offsets an owner can pick from, in minutes before the start. */\nexport const REMINDER_CHOICES: ReadonlyArray<{ minutes: number; label: string }> = [\n { minutes: 10080, label: \"1 week before\" },\n { minutes: 2880, label: \"2 days before\" },\n { minutes: 1440, label: \"1 day before\" },\n { minutes: 180, label: \"3 hours before\" },\n { minutes: 60, label: \"1 hour before\" },\n { minutes: 15, label: \"15 minutes before\" },\n];\n\n/** The merge fields a message may use, exactly the ones the store fills. */\nexport const BOOKING_TOKENS: readonly string[] = [\n \"{{booker.name}}\",\n \"{{time}}\",\n \"{{title}}\",\n \"{{calendar.google}}\",\n \"{{calendar.outlook}}\",\n];\n\nfunction notice(raw: unknown): BookingMessageNotice | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const r = raw as Record<string, unknown>;\n const out: BookingMessageNotice = {};\n if (typeof r[\"on\"] === \"boolean\") out.on = r[\"on\"];\n if (typeof r[\"subject\"] === \"string\" && r[\"subject\"].trim() !== \"\") out.subject = r[\"subject\"];\n if (typeof r[\"body\"] === \"string\" && r[\"body\"].trim() !== \"\") out.body = r[\"body\"];\n return out;\n}\n\n/** `presentation.booking_messages` back into the screen's words; unknown keys are kept as they are not ours to drop. */\nexport function messagesFromPresentation(presentation: unknown): BookingMessages {\n const raw = presentation && typeof presentation === \"object\" ? (presentation as Record<string, unknown>)[\"booking_messages\"] : null;\n if (!raw || typeof raw !== \"object\") return {};\n const r = raw as Record<string, unknown>;\n const out: BookingMessages = {};\n for (const k of [\"confirmation\", \"changed\", \"cancelled\"] as const) {\n const n = notice(r[k]);\n if (n) out[k] = n;\n }\n const rem = notice(r[\"reminders\"]);\n const offsets = (r[\"reminders\"] as { offsets?: unknown } | undefined)?.offsets;\n if (rem || Array.isArray(offsets)) {\n out.reminders = {\n ...(rem ?? {}),\n ...(Array.isArray(offsets)\n ? { offsets: offsets.map(Number).filter((n) => Number.isInteger(n) && n > 0) }\n : {}),\n };\n }\n const host = r[\"host\"] as { on?: unknown } | undefined;\n if (host && typeof host.on === \"boolean\") out.host = { on: host.on };\n const sms = r[\"sms\"] as { on?: unknown } | undefined;\n if (sms && typeof sms.on === \"boolean\") out.sms = { on: sms.on };\n return out;\n}\n\n/** The screen's words as the store reads them. Empty means \"use the default\", so it is not sent. */\nexport function messagesToPresentation(m: BookingMessages): BookingMessages | null {\n const out: BookingMessages = {};\n for (const k of [\"confirmation\", \"changed\", \"cancelled\"] as const) {\n const n = m[k];\n if (n && (n.on === false || n.subject?.trim() || n.body?.trim())) {\n out[k] = {\n ...(n.on === false ? { on: false } : {}),\n ...(n.subject?.trim() ? { subject: n.subject.trim() } : {}),\n ...(n.body?.trim() ? { body: n.body.trim() } : {}),\n };\n }\n }\n const rem = m.reminders;\n if (rem) {\n const offsets = rem.offsets && rem.offsets.length > 0 ? [...new Set(rem.offsets)].sort((a, b) => b - a) : null;\n const custom = offsets && (offsets.length !== DEFAULT_REMINDER_OFFSETS.length || offsets.some((o, i) => o !== DEFAULT_REMINDER_OFFSETS[i]));\n if (rem.on === false || custom || rem.subject?.trim() || rem.body?.trim()) {\n out.reminders = {\n ...(rem.on === false ? { on: false } : {}),\n ...(custom && offsets ? { offsets } : {}),\n ...(rem.subject?.trim() ? { subject: rem.subject.trim() } : {}),\n ...(rem.body?.trim() ? { body: rem.body.trim() } : {}),\n };\n }\n }\n if (m.host?.on === false) out.host = { on: false };\n if (m.sms?.on === true) out.sms = { on: true };\n return Object.keys(out).length > 0 ? out : null;\n}\n","\"use client\";\n\n// src/publicQuestions.ts — @ai-matrx/records-ui\n//\n// WHAT A STRANGER CAN ACTUALLY ANSWER.\n//\n// WHAT WALK 2 FOUND (lane BUILDERS, 2026-09-21). Ironclad Mobile Mechanic built\n// a booking page over his `Service Calls` table and ticked \"Customer\", because\n// of course the page should ask who is booking. `Customer` is a RELATION Field\n// pointing at his Customers table. A visitor typed her name, the page sent it,\n// and the store refused at the last step with\n//\n// Customer points at something that is not there\n//\n// — correctly: a relation holds the IDENTITY of a record, and a stranger with\n// no account cannot see that Table, cannot search it, and has no id to give.\n// Her slot stayed held and she lost the booking.\n//\n// THE CONTROL WAS THE DEFECT, not the refusal. A tick that can only ever end in\n// a refusal is the dead control law 4 forbids, and the builder was offering\n// several of them on every real Table. So the question list is now the Fields a\n// person with NO ACCOUNT can answer, and the ones left out are NAMED with the\n// reason rather than silently missing — a manager who wonders where \"Customer\"\n// went is told, in the same place she would have ticked it.\n//\n// IT IS NOT A DENY-LIST OF TYPES SOMEBODY WILL FORGET TO EXTEND. The question it\n// asks is the one that matters: does answering this need something only a\n// signed-in member of this organization has?\n//\n// · `relation` — the id of a record in a Table the visitor cannot open.\n// · `member` — a person in an organization the visitor does not belong to.\n// · `attachment` — a file in the organization's own store; a public upload\n// door is a real feature, not a checkbox, and until it exists a stranger\n// has nowhere to put the bytes.\n// · `formula`, `lookup`, `rollup` — computed. Nobody answers them, including\n// the owner; asking would write into something the store derives.\n//\n// Everything else — text, number, money, percent, date, email, phone, url, a\n// choice from a list — is answerable by anybody with the link, which is why the\n// class-signup form in walk 1 worked on its first try.\n\nimport type { Field } from \"@ai-matrx/records\";\n\n/** Why a Field cannot be asked of somebody with no account, in a person's words. */\nconst CANNOT_ASK: Record<string, string> = {\n relation:\n \"points at a record in another table, and somebody with no account cannot see that table to pick from it\",\n member:\n \"is a person in this organization, and somebody outside it has no way to choose one\",\n attachment:\n \"holds a file in your own files, and a public page has nowhere to put one yet\",\n formula: \"is calculated, so there is nothing for anybody to answer\",\n lookup: \"is read through a relation, so it fills in by itself\",\n rollup: \"is added up, so there is nothing for anybody to answer\",\n};\n\n/** Can somebody with no account and no membership answer this question? */\nexport function publiclyAnswerable(field: Field): boolean {\n return !(field.type in CANNOT_ASK);\n}\n\n/** The Fields a public page may ask for, in the Table's own order. */\nexport function askableFields(fields: readonly Field[], hidden: readonly string[] = []): Field[] {\n return fields.filter((f) => publiclyAnswerable(f) && !hidden.includes(f.key));\n}\n\n/**\n * THE ONES LEFT OUT, NAMED. Absent is fine; absent and unexplained is the dead\n * end this package does not ship. Returns null when nothing was left out.\n */\nexport function whyNotAskable(\n fields: readonly Field[],\n hidden: readonly string[] = [],\n): string | null {\n const left = fields.filter((f) => !publiclyAnswerable(f) && !hidden.includes(f.key));\n if (left.length === 0) return null;\n const said = left.map((f) => `${f.label || f.key} ${CANNOT_ASK[f.type]}`);\n return said.length === 1\n ? `${said[0]}, so it is not offered here.`\n : `These are not offered here: ${said.join(\"; \")}.`;\n}\n\n/**\n * A REQUIRED COLUMN THE PAGE LEAVES UNASKED MEANS EVERY ANSWER IS REFUSED (lane HANDOVER, 2026-09-29).\n *\n * Cedar Ridge Physical Therapy's booking page over Visits: a front-desk member picked a time,\n * answered, pressed Book it and read \"Patient is required\". Visits requires a Patient (a link to\n * another record), which no public page can ask, so no booking could ever be made — and nothing on\n * the builder said so. This is said while the page is being made, with the remedy; it offers, it\n * does not stop the save (validation offers, never blocks). `storeFills` are the columns the store\n * writes itself (a booking page's slot, status and who it is with).\n */\nexport function requiredLeftUnasked(\n fields: readonly Field[],\n asked: readonly string[],\n storeFills: readonly string[] = [],\n): string | null {\n const missing = fields.filter(\n (f) => f.required === true && !asked.includes(f.key) && !storeFills.includes(f.key) && !COMPUTED.has(f.type),\n );\n if (missing.length === 0) return null;\n const said = missing.map((f) => {\n const name = f.label || f.key;\n return publiclyAnswerable(f)\n ? `${name} is required — tick it so this page asks it`\n : `${name} is required and this page cannot ask it (${SHORT_WHY[f.type] ?? \"a stranger cannot answer it\"}) — make it optional in this table's settings`;\n });\n return `Every answer would be refused as this page stands: ${said.join(\"; \")}.`;\n}\n\n/** Why a stranger cannot answer it, in a few words for a sentence. */\nconst SHORT_WHY: Record<string, string> = {\n relation: \"it points at a record in another table\",\n member: \"it is a person in this organization\",\n attachment: \"it holds a file\",\n};\n\n/** Columns the store works out itself: never asked, never \"missing\". */\nconst COMPUTED = new Set([\"formula\", \"lookup\", \"rollup\"]);\n","// THE CLOCK A TIME IS READ IN — one control for every screen that asks a time of day\n// (lane HANDOVER, 2026-09-28).\n//\n// A booking page's hours and a summary's \"every Monday at 8\" are both read by the store in a\n// named zone and fall back to UTC when none is given. Both screens start at the zone of the\n// person at the keyboard and let them type to find another (four hundred zones are a search,\n// not a list to scroll). One control, so the next screen that asks a time inherits it.\n\nimport { useId } from \"react\";\nimport { BasicInput, Label } from \"@ai-matrx/design-system\";\n\n/** The zone of the person at the keyboard, which is where a new schedule's hours start. */\nexport function ownTimeZone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n } catch {\n return \"UTC\";\n }\n}\n\nconst TIME_ZONES: readonly string[] = (() => {\n try {\n return (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.(\"timeZone\") ?? [];\n } catch {\n return [];\n }\n})();\n\nexport function TimeZoneInput({\n label,\n value,\n onChange,\n className,\n}: {\n /** What the zone is for, in the screen's words (\"Time zone the hours are in\"). */\n label: string;\n value: string;\n onChange: (zone: string) => void;\n className?: string | undefined;\n}) {\n const listId = useId();\n return (\n <label className={className ?? \"flex flex-col gap-1\"}>\n <Label className=\"text-xs font-medium\">{label}</Label>\n <BasicInput\n list={listId}\n value={value}\n onChange={(e) => onChange(e.target.value)}\n className=\"h-9 text-sm\"\n aria-label={label}\n />\n <datalist id={listId}>\n {TIME_ZONES.map((zone) => (\n <option key={zone} value={zone} />\n ))}\n </datalist>\n </label>\n );\n}\n","\"use client\";\n\n// src/BuildOrAsk.tsx — @ai-matrx/records-ui · the empty state of every builder\n//\n// THE PRODUCT WALK THAT MADE THIS FILE (2026-09-21). A non-technical expert\n// opened a real table she had just filled with her own business's records, and\n// the Forms, Bookings and Portals rails each said the same thing: none yet, ask\n// an agent for one in a sentence. There was no other way in. Four screens of\n// this package could make the thing and none of them was reachable, so the\n// agent was not the FASTER path — it was the ONLY path, and a person who did\n// not know what to say to it was finished.\n//\n// THE RULING THIS ENCODES: the agent path stays, and it stays FIRST in the\n// sentence, because saying it out loud really is faster. But a person may\n// always build the thing by hand, in under two minutes, without leaving the\n// rail they are standing in. Two buttons, one row, every rail identical — so\n// somebody who learns it on forms already knows it on portals.\n//\n// ABSENT, NEVER DEAD (law 4). \"Ask an agent\" is a HOST port: only a server can\n// honestly speak as an agent, and a browser that stamped itself one would be\n// claiming to be one. A host that has not bound the port gets no button at all\n// — not a grayed one — and the sentence says plainly that asking in words needs\n// an agent this screen cannot reach. \"Build it\" is absent the same way when the\n// store says this person does not hold the level the act needs, and the store's\n// own reason is shown in its place.\n//\n// AND THE SAME LAW BINDS THE AGENT HALF (chair ruling, 2026-09-21). Measured on\n// Ironclad Mobile Mechanic's Service Calls table: a dispatcher at VIEWER read\n// the rail's true sentence — \"Making one needs the admin level on it\" — and\n// then pressed the fully live \"Ask an agent\" button beside it. The composer\n// opened, \"make me a signup form\" was accepted, the agent read the table and\n// worked for about five minutes. It created nothing and never said why; the\n// rail was identical before and after. That is a control that is neither absent\n// nor honest, and an agent burning money answering nothing.\n//\n// So `mayBuild` gates BOTH ways in, not just the button on the right. Asking an\n// agent is not a lesser act than building by hand — it is the SAME act, said\n// out loud, through the same doors, and it hits the same refusal. A door the\n// store has shut shows no way through it and one sentence saying why. This is\n// gated HERE, in the one component every rail mounts, so forms, bookings,\n// portals, dashboards and every rail added after this inherit it rather than\n// each re-deciding it.\n\nimport type { ReactNode } from \"react\";\nimport { Button, cn } from \"@ai-matrx/design-system\";\n\n/** What a person is asking to have made, in the store's own word for it. */\nexport type BuildableKind = \"form\" | \"booking\" | \"portal\" | \"digest\";\n\nexport interface BuildOrAskProps {\n /**\n * The sentence that says what this thing IS, in a practitioner's words —\n * never \"You have no forms.\" A person who does not already know what a\n * booking page does is not helped by being told they have none.\n */\n children: ReactNode;\n /** Pressed, the builder opens in place. Absent when `mayBuild` is false. */\n onBuild: () => void;\n /** The store's answer, never a guess on this screen. */\n mayBuild: boolean;\n /**\n * WHY NOT, in the store's words, shown where the button would have been.\n * A missing control with no explanation is the same dead end as a dead one.\n */\n whyNot?: string | null | undefined;\n /**\n * The host's agent port. Unbound, the second button is absent and the\n * sentence below names what is missing. Bound but `mayBuild` false, it is\n * absent too: an agent asked to do what this person may not do gets refused\n * by the same doors, five minutes later, with nothing to show for it.\n */\n onAsk?: (() => void) | undefined;\n /** The words a person would actually say, offered as the starting sentence. */\n suggestion: string;\n /** \"Build the form\", \"Build the booking page\" — the act, never \"New\". */\n buildLabel: string;\n /** The agent button's words. Default \"Ask an agent\"; a layout's empty state says \"Ask AI\". */\n askLabel?: string | undefined;\n /**\n * What the person may change before pressing — a column's name and its choices (`ViewNeeds`).\n * Drawn between the sentence and the buttons, and only when they may build.\n */\n editor?: ReactNode;\n /** What to say when no agent is bound. Default `NO_AGENT_PORT`. */\n noAgentSentence?: string | undefined;\n /** The build is in flight: the button says so and does not take a second press. */\n building?: boolean | undefined;\n className?: string | undefined;\n}\n\n/** What this package tells a host that has bound no agent. One sentence, one remedy. */\nexport const NO_AGENT_PORT =\n \"Asking for one in words needs an agent, which this screen reaches through its host's \" +\n \"`onAskForOne` port — it is not bound here, so build it below instead.\";\n\nexport function BuildOrAsk({\n children,\n onBuild,\n mayBuild,\n whyNot,\n onAsk,\n suggestion,\n buildLabel,\n askLabel = \"Ask an agent\",\n editor,\n building = false,\n noAgentSentence = NO_AGENT_PORT,\n className,\n}: BuildOrAskProps) {\n /**\n * THE ONE GATE ON BOTH WAYS IN. Saying it out loud and building it by hand\n * are the same act through the same doors, so the store's answer decides\n * both. `mayBuild` first, deliberately: a person who may not build is offered\n * nothing at all, whether or not the host bound an agent.\n */\n const mayAsk = mayBuild && Boolean(onAsk);\n\n return (\n <div className={cn(\"rounded-md border border-dashed p-3\", className)}>\n <p className=\"text-xs text-muted-foreground\">{children}</p>\n\n {/* TWO WAYS, ONE ROW. The agent is named first because it is faster; the\n builder is a button of equal weight beside it because it is the one\n that always works. When the store has shut the door, this row is empty\n and the sentence underneath carries the whole answer. */}\n {mayBuild && editor ? <div className=\"mt-2.5\">{editor}</div> : null}\n {mayBuild ? (\n <div className=\"mt-2.5 flex flex-wrap items-center gap-2\">\n {mayAsk ? (\n <Button size=\"sm\" variant=\"outline\" onClick={onAsk}>\n {askLabel}\n </Button>\n ) : null}\n <Button size=\"sm\" onClick={onBuild} disabled={building} aria-busy={building || undefined}>\n {buildLabel}\n </Button>\n </div>\n ) : null}\n\n {/* WHAT THE SENTENCE UNDER THE ROW SAYS, in the only three states there\n are. A shut door says the store's own reason and NOTHING else — the\n unbound-port sentence ends \"build it below instead\", which is a lie to\n somebody who may not build, and the suggested wording is an invitation\n to an act that cannot happen. */}\n {!mayBuild ? (\n whyNot ? (\n <p className=\"mt-2 text-xs text-muted-foreground\">{whyNot}</p>\n ) : null\n ) : mayAsk ? (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n You would say something like: “{suggestion}”\n </p>\n ) : (\n <p className=\"mt-2 text-xs text-muted-foreground\">{noAgentSentence}</p>\n )}\n </div>\n );\n}\n","\"use client\";\n\n// src/BuiltOnArchive.tsx — @ai-matrx/records-ui · lane MAKE-HOME wave 6a (2026-10-03)\n//\n// THE WAY OUT AND THE WAY BACK FOR WHAT IS BUILT ON A TABLE: its forms, its booking pages and its\n// checklists. Before this, none of the three had any way out — an old intake form stayed in the\n// rail forever — because the store had no door. CHAIR-DOORS-3B landed `custom.form_archive` /\n// `form_restore` / `forms_archived` and `checklist_templates_archived` (a checklist template is a\n// record: `record_delete` archives it, `record_restore` brings it back).\n//\n// ONE PRIMITIVE EACH, REUSED:\n// · `ArchiveItemMenu` — the ⋯ on one item of the Forms, Bookings and Checklists rails. It is the\n// platform's own row menu: a design-system DropdownMenu drawing an `ObjectAction` list through\n// `ObjectActionMenuItems`, the renderer every table menu uses. No new chrome row.\n// · `ArchivedBuiltOn` — the archived ones, in the table's Archived view beside its archived\n// rows and columns, each with Restore (the archived-items law: every archive has a way back).\n//\n// ABSENT OR HONEST, NEVER DEAD. Archive is drawn disabled with its reason for somebody below the\n// rung the door asks (admin on the table); Restore is absent with the store's reason when the store\n// says it cannot come back (`can_restore` false — its table is archived).\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport {\n archivedWhen,\n BUILT_KIND_WORD,\n type ArchivedChecklistTemplate,\n type ArchivedForm,\n type RecordsError,\n} from \"@ai-matrx/records\";\nimport { useRecordsClient, type Uuid } from \"@ai-matrx/records/react\";\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuTrigger,\n} from \"@ai-matrx/design-system\";\n\nimport { ObjectActionMenuItems } from \"./ObjectActionMenuItems\";\nimport type { ObjectAction } from \"./objectActions\";\nimport { RefusalNotice } from \"./Refusal\";\n\nexport type BuiltKind = \"form\" | \"booking\" | \"checklist\";\n\n/** The one action this menu carries today, in the shape every table menu draws. */\nexport function archiveItemActions(args: {\n kind: BuiltKind;\n whyNot?: string | null | undefined;\n run: () => void | Promise<void>;\n}): ObjectAction[] {\n return [\n {\n id: \"archive\",\n label: \"Archive\",\n icon: \"archive\",\n group: \"danger\",\n verb: \"archive\",\n destructive: true,\n ...(args.whyNot ? { disabledReason: args.whyNot } : {}),\n run: args.run,\n },\n ];\n}\n\n/** Why a person below the door's rung may not archive it (≤ 60 chars, the menu's reason line). */\nexport const ARCHIVE_NEEDS_ADMIN = \"Needs Full access on this table\";\n\nexport interface ArchiveItemMenuProps {\n kind: BuiltKind;\n /** The form's or booking page's form id, or the checklist template's record id. */\n id: Uuid;\n title: string;\n /** False → the action is drawn disabled with `ARCHIVE_NEEDS_ADMIN`. */\n mayArchive: boolean;\n /** The store's own sentence after it archived; the rail shows it and re-reads its list. */\n onArchived: (sentence: string) => void;\n onRefused: (error: RecordsError) => void;\n}\n\n/** THE ⋯ ON ONE ITEM. Archiving is reversible, so it acts at once and says what happened. */\nexport function ArchiveItemMenu({ kind, id, title, mayArchive, onArchived, onRefused }: ArchiveItemMenuProps) {\n const client = useRecordsClient();\n const run = async () => {\n if (kind === \"checklist\") {\n const done = await client.recordDelete({ record_id: id });\n if (!done.ok) return onRefused(done.error);\n onArchived(`The checklist \"${title}\" is archived. It waits in this table's Archived view.`);\n return;\n }\n const done = await client.formArchive({ form_id: id });\n if (!done.ok) return onRefused(done.error);\n onArchived(done.data.sentence);\n };\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-7 w-7 p-0\"\n aria-label={`More for ${title}`}\n title=\"More\"\n data-built-item-menu={kind}\n >\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"currentColor\" aria-hidden=\"true\">\n <circle cx=\"5\" cy=\"12\" r=\"1.75\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.75\" />\n <circle cx=\"19\" cy=\"12\" r=\"1.75\" />\n </svg>\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-56\">\n <ObjectActionMenuItems\n actions={archiveItemActions({ kind, whyNot: mayArchive ? null : ARCHIVE_NEEDS_ADMIN, run })}\n />\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n\n/** One archived thing, whichever door listed it. */\ninterface ArchivedThing {\n kind: BuiltKind;\n id: Uuid;\n title: string;\n archivedAt: string;\n /** Null = may be restored; a sentence = why not, said in place of the button. */\n whyNot: string | null;\n}\n\nexport function archivedThings(forms: ArchivedForm[], checklists: ArchivedChecklistTemplate[]): ArchivedThing[] {\n const fromForms = forms.map<ArchivedThing>((f) => ({\n kind: f.kind === \"booking\" ? \"booking\" : \"form\",\n id: f.form_id,\n title: f.title?.trim() || f.slug,\n archivedAt: f.archived_at,\n whyNot: f.can_restore ? null : f.table_archived ? \"Its table is archived\" : \"Needs Full access on this table\",\n }));\n const fromChecklists = checklists.map<ArchivedThing>((c) => ({\n kind: \"checklist\",\n id: c.template_id,\n title: c.name?.trim() || \"A checklist with no name\",\n archivedAt: c.archived_at,\n whyNot: c.table_archived ? \"Its table is archived\" : null,\n }));\n return [...fromForms, ...fromChecklists].sort((a, b) => (a.archivedAt < b.archivedAt ? 1 : -1));\n}\n\n/**\n * THE ARCHIVED FORMS, BOOKING PAGES AND CHECKLISTS OF ONE TABLE, each with Restore. Drawn in the\n * table's Archived view; nothing at all while there are none (the view's own rows say \"empty\").\n */\nexport function ArchivedBuiltOn({ tableId, onRestored }: { tableId: Uuid; onRestored?: (() => void) | undefined }) {\n const client = useRecordsClient();\n const [things, setThings] = useState<ArchivedThing[] | null>(null);\n const [error, setError] = useState<RecordsError | null>(null);\n const [restoring, setRestoring] = useState<Uuid | null>(null);\n const [refusal, setRefusal] = useState<{ id: Uuid; error: RecordsError } | null>(null);\n const [said, setSaid] = useState<string | null>(null);\n\n const read = useCallback(async () => {\n const [forms, checklists] = await Promise.all([\n client.formsArchived({ table_id: tableId }),\n client.checklistTemplatesArchived({ about_table_id: tableId }),\n ]);\n if (!forms.ok) return setError(forms.error);\n if (!checklists.ok) return setError(checklists.error);\n setError(null);\n setThings(archivedThings(forms.data, checklists.data));\n }, [client, tableId]);\n\n useEffect(() => {\n void read();\n }, [read]);\n\n const restore = async (thing: ArchivedThing) => {\n setRestoring(thing.id);\n setRefusal(null);\n setSaid(null);\n if (thing.kind === \"checklist\") {\n const done = await client.recordRestore({ record_id: thing.id });\n setRestoring(null);\n if (!done.ok) return setRefusal({ id: thing.id, error: done.error });\n setSaid(`The checklist \"${thing.title}\" is back.`);\n } else {\n const done = await client.formRestore({ form_id: thing.id });\n setRestoring(null);\n if (!done.ok) return setRefusal({ id: thing.id, error: done.error });\n setSaid(done.data.sentence);\n }\n await read();\n onRestored?.();\n };\n\n if (error) return <RefusalNotice error={error} />;\n if (!things || (things.length === 0 && !said)) return null;\n return (\n <section className=\"flex flex-col gap-1\" data-testid=\"archived-built-on\">\n <span className=\"text-sm font-medium\">Forms, bookings and checklists</span>\n {said ? (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"archived-built-on-said\">\n {said}\n </p>\n ) : null}\n <ul className=\"flex flex-col gap-1\">\n {things.map((thing) => (\n <li\n key={thing.id}\n data-testid=\"archived-built-thing\"\n data-kind={thing.kind}\n data-id={thing.id}\n className=\"flex flex-wrap items-center gap-2 rounded-md border px-3 py-2\"\n >\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <span className=\"truncate text-sm\">{thing.title}</span>\n <span className=\"truncate text-xs text-muted-foreground\">\n {BUILT_KIND_WORD[thing.kind]} · archived {archivedWhen(thing.archivedAt)}\n </span>\n {refusal && refusal.id === thing.id ? <RefusalNotice error={refusal.error} className=\"mt-2\" /> : null}\n </div>\n {thing.whyNot ? (\n <span className=\"text-xs text-muted-foreground\">{thing.whyNot}</span>\n ) : (\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={restoring === thing.id}\n data-testid=\"archived-built-restore\"\n onClick={() => void restore(thing)}\n >\n {restoring === thing.id ? \"Bringing it back…\" : \"Restore\"}\n </Button>\n )}\n </li>\n ))}\n </ul>\n </section>\n );\n}\n","// src/ObjectActionMenuItems.tsx — @ai-matrx/records-ui\n//\n// The header ⋯ renderer of the ONE action list (`objectActions.ts`). It draws\n// `toDropdownEntries(actions)` inside a design-system `DropdownMenuContent` and\n// nothing else: no item of its own, no filter, no reorder — G1 holds it to the\n// same ids in the same order as every other renderer.\n//\n// Each entry draws its glyph (`objectActionIcons.tsx`). A disabled action shows its\n// reason as a muted inline line, because a disabled Radix item takes no hover and a\n// `title` alone is unreachable on a phone.\n\nimport {\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n} from \"@ai-matrx/design-system\";\nimport { toDropdownEntries, type ObjectAction } from \"./objectActions\";\nimport { ObjectActionGlyph } from \"./objectActionIcons\";\n\nfunction ActionItem({ action }: { action: ObjectAction }) {\n const disabled = action.disabledReason !== undefined;\n return (\n <DropdownMenuItem\n disabled={disabled}\n onSelect={() => {\n if (!disabled) void action.run();\n }}\n title={action.disabledReason}\n data-object-action={action.id}\n className={action.destructive ? \"text-destructive focus:text-destructive\" : undefined}\n >\n <ObjectActionGlyph name={action.icon} className=\"mr-2 h-4 w-4 shrink-0\" />\n <span className=\"flex min-w-0 flex-col\">\n <span>{action.label}</span>\n {disabled ? (\n <span className=\"truncate text-xs text-muted-foreground\" data-object-action-reason=\"\">\n {action.disabledReason}\n </span>\n ) : null}\n </span>\n {action.shortcut ? <DropdownMenuShortcut>{action.shortcut}</DropdownMenuShortcut> : null}\n </DropdownMenuItem>\n );\n}\n\nexport interface ObjectActionMenuItemsProps {\n actions: readonly ObjectAction[];\n}\n\nexport function ObjectActionMenuItems({ actions }: ObjectActionMenuItemsProps) {\n return (\n <>\n {toDropdownEntries(actions).map((entry) => {\n if (entry.kind === \"separator\") return <DropdownMenuSeparator key={entry.id} />;\n if (entry.kind === \"item\") return <ActionItem key={entry.action.id} action={entry.action} />;\n return (\n <DropdownMenuSub key={entry.id}>\n <DropdownMenuSubTrigger data-object-action-group={entry.id}>\n {entry.icon ? <ObjectActionGlyph name={entry.icon} className=\"mr-2 h-4 w-4 shrink-0\" /> : null}\n {entry.label}\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n {entry.actions.map((a) => (\n <ActionItem key={a.id} action={a} />\n ))}\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n );\n })}\n </>\n );\n}\n","// src/objectActionIcons.tsx — @ai-matrx/records-ui\n//\n// The glyphs of the ONE action list (`ObjectActionIcon`). Each name maps to the glyph\n// `@ai-matrx/design-system/icons` draws (the one lucide-free glyph home, lucide v1.48 geometry; \"history\" is\n// its alias rotate-ccw-clock): this package holds no path data. Exhaustive by type: a new name fails\n// typecheck here until it is mapped.\n\nimport type { SVGAttributes } from \"react\";\nimport {\n ArchiveIcon,\n ArchiveRestoreIcon,\n ArrowUpFromLineIcon,\n BellIcon,\n BlocksIcon,\n CalendarClockIcon,\n Columns3Icon,\n CopyIcon,\n CornerDownRightIcon,\n DoorOpenIcon,\n DownloadIcon,\n EraserIcon,\n ExternalLinkIcon,\n FileTextIcon,\n FolderInputIcon,\n FolderOpenIcon,\n GitMergeIcon,\n HistoryIcon,\n InboxIcon,\n LayoutDashboardIcon,\n LayoutGridIcon,\n Link2Icon,\n LinkIcon,\n ListChecksIcon,\n LockIcon,\n LockOpenIcon,\n PencilIcon,\n PrinterIcon,\n SettingsIcon,\n Share2Icon,\n SplitIcon,\n StarIcon,\n StarOffIcon,\n UploadIcon,\n} from \"@ai-matrx/design-system/icons\";\nimport type { GlyphComponent } from \"@ai-matrx/design-system/icons\";\nimport type { ObjectActionIcon } from \"./objectActions\";\n\nconst GLYPHS: Record<ObjectActionIcon, GlyphComponent> = {\n \"folder-open\": FolderOpenIcon,\n \"external-link\": ExternalLinkIcon,\n \"link\": LinkIcon,\n \"pencil\": PencilIcon,\n \"copy\": CopyIcon,\n \"folder-input\": FolderInputIcon,\n \"star\": StarIcon,\n \"star-off\": StarOffIcon,\n \"share-2\": Share2Icon,\n \"download\": DownloadIcon,\n \"upload\": UploadIcon,\n \"columns-3\": Columns3Icon,\n \"settings\": SettingsIcon,\n \"history\": HistoryIcon,\n \"blocks\": BlocksIcon,\n \"file-text\": FileTextIcon,\n \"calendar-clock\": CalendarClockIcon,\n \"list-checks\": ListChecksIcon,\n \"bell\": BellIcon,\n \"door-open\": DoorOpenIcon,\n \"inbox\": InboxIcon,\n \"layout-dashboard\": LayoutDashboardIcon,\n \"archive-restore\": ArchiveRestoreIcon,\n \"archive\": ArchiveIcon,\n \"link-2\": Link2Icon,\n \"layout-grid\": LayoutGridIcon,\n \"git-merge\": GitMergeIcon,\n \"split\": SplitIcon,\n \"arrow-up-from-line\": ArrowUpFromLineIcon,\n \"corner-down-right\": CornerDownRightIcon,\n \"lock\": LockIcon,\n \"lock-open\": LockOpenIcon,\n \"eraser\": EraserIcon,\n \"printer\": PrinterIcon,\n};\n\nexport function ObjectActionGlyph({ name, ...props }: { name: ObjectActionIcon } & SVGAttributes<SVGSVGElement>) {\n const Glyph = GLYPHS[name];\n return <Glyph data-object-action-icon={name} {...props} />;\n}\n","\"use client\";\n\n// src/WhereItLives.tsx — @ai-matrx/records-ui (lanes SC-1' / SC-1-TAILS)\n//\n// THE ONE UI BUILDER FOR \"WHICH ORGANIZATION IS THIS IN, AND MOVE IT\".\n//\n// The owner, 2026-09-23: \"I am not seeing how I can see what org this data is in. Is there an easy\n// way to see that or do we need to add something that makes it easy to see and set the org for\n// something?\" A chip that names the organization a Table lives in — read FROM THE TABLE through\n// `client.tableHome` (custom.table_home), never from the organization the screen is bound to —\n// and, on press, says what the store says: who may move it, what holds it where it is, and each\n// of the person's other organizations with either a Move button or the sentence why it cannot go\n// there. Picking one says the consequence first (what rides along, who stops seeing it) in the\n// same panel, and only \"Move it\" asks `client.tableMove`, which moves it or hands back the store's\n// one sentence, shown as it came.\n//\n// It lived in matrx-frontend first (features/unified-data/where-it-lives). It is here because the\n// package's own screens (TablesHome) list tables too, and a package screen cannot reach a host\n// component: one builder, in the one place every host can mount it.\n//\n// Champion: Notion's \"Move to\" (every page names its workspace in the breadcrumb and moves from the\n// same place) and Linear's \"Move to team\" (the consequence is said before the move).\n\nimport { useEffect, useState } from \"react\";\nimport type { TableHome, TableHomeDestination, Uuid } from \"@ai-matrx/records\";\nimport { moveConsequence } from \"@ai-matrx/records\";\nimport { useRecordsClient } from \"@ai-matrx/records/react\";\nimport { useRecordsUi } from \"./host\";\nimport { hintForAPerson } from \"./Refusal\";\nimport { Button, ErrorBox, Popover, PopoverContent, PopoverTrigger, displayId } from \"@ai-matrx/design-system\";\nimport { refusalSaid } from \"./refusalSaid\";\n\ntype Answer =\n | { state: \"found\"; home: TableHome }\n /** Not given to this person — or not there. The store says the same for both, on purpose. */\n | { state: \"not-given\" }\n /** The door is not on this database yet. Said, never a pretend organization. */\n | { state: \"door-absent\" }\n /** We could not ask. NOT an answer about the person's access. */\n | { state: \"unavailable\"; why: string };\n\nexport interface WhereItLivesProps {\n tableId: Uuid;\n /**\n * The name the screen already holds (a list whose rows all live in one organization), shown\n * until the store answers — and, on a row, instead of asking at all until the chip is pressed:\n * forty rows are not forty reads.\n */\n knownOrganizationName?: string | null | undefined;\n /** After a move lands: the host re-reads (the list, its rows, the page). */\n onMoved?: ((to: { id: Uuid; name: string }) => void) | undefined;\n /**\n * `row` is quieter, for a list; `header` for an object page's own row; `title` rides the page\n * header beside the object's name (Linear's team beside the issue title) — no frame, muted.\n */\n /**\n * `anchor` draws no chip at all: the panel opens over the place it is mounted when `openAsked`\n * increases — the table menu's \"Move to…\" (lane TABLE-ACTIONS) opens this same panel.\n */\n variant?: \"header\" | \"row\" | \"title\" | \"anchor\" | undefined;\n /** Each increase opens the panel (the menu's \"Move to…\"). */\n openAsked?: number | undefined;\n}\n\nexport function WhereItLives({ tableId, knownOrganizationName, onMoved, variant = \"header\", openAsked = 0 }: WhereItLivesProps) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const [answer, setAnswer] = useState<Answer | null>(null);\n const [attempt, setAttempt] = useState(0);\n const [open, setOpen] = useState(false);\n const [armed, setArmed] = useState(variant === \"anchor\" ? false : variant !== \"row\" || !knownOrganizationName);\n useEffect(() => {\n if (openAsked <= 0) return;\n setArmed(true);\n setOpen(true);\n }, [openAsked]);\n const [choosing, setChoosing] = useState<TableHomeDestination | null>(null);\n const [moving, setMoving] = useState(false);\n const [said, setSaid] = useState<{ tone: \"done\" | \"refused\"; text: string } | null>(null);\n\n useEffect(() => {\n if (!armed) return;\n let alive = true;\n setAnswer(null);\n void client.tableHome({ table_id: tableId }).then((answered) => {\n if (!alive) return;\n if (answered.ok) {\n setAnswer(answered.data ? { state: \"found\", home: answered.data } : { state: \"not-given\" });\n } else if (answered.error.code === \"door_absent\") {\n setAnswer({ state: \"door-absent\" });\n } else {\n setAnswer({ state: \"unavailable\", why: refusalSaid(answered.error) });\n }\n });\n return () => {\n alive = false;\n };\n }, [client, tableId, attempt, armed]);\n\n const home = answer?.state === \"found\" ? answer.home : null;\n const name = home?.organization.name ?? knownOrganizationName ?? null;\n // Absent, never a blank or a guess.\n const label =\n name ??\n (answer === null || !armed\n ? \"Reading where this lives…\"\n : answer.state === \"not-given\"\n ? \"Not shared with you\"\n : answer.state === \"door-absent\"\n ? \"Its organization is not named here yet\"\n : \"Could not ask where this lives\");\n\n async function move(to: TableHomeDestination) {\n if (!home) return;\n setMoving(true);\n const moved = await client.tableMove({\n table_id: home.table.id,\n to_organization_id: to.id,\n expected_version: home.table.version,\n });\n setMoving(false);\n if (!moved.ok) {\n // A REFUSAL IS SAID WHERE SHE PRESSED, AND THE PANEL STAYS (MOVE-AND-OUTSIDER, VERIFIER-19\n // finding 1: the panel closed and the screen said nothing). The store's own sentence, then\n // its remedy when it gave one, on the same confirm — so \"Try again\" and \"Cancel\" are right\n // there. Nothing is re-read: a re-read would swap the panel for \"Asking…\" under her.\n // A hint written for an engineer (a lane codename, a SQLSTATE) is never shown (UI-FIX-19).\n const hint = hintForAPerson(moved.error.hint);\n const sentence = refusalSaid(moved.error);\n setSaid({ tone: \"refused\", text: `Nothing moved. ${sentence}${hint && !sentence.includes(hint) ? ` ${hint}` : \"\"}` });\n return;\n }\n setChoosing(null);\n const done = `${moved.data.tableName} now lives in ${moved.data.to.name}.`;\n // THE CONFIRMATION OUTLIVES THE HOST'S RE-READ (UI-FIX-19, MOVE-AND-OUTSIDER). `onMoved` makes\n // a host re-read, and an object page re-mounts its header — this chip with it — so a sentence\n // held in this chip's state died unread: the person saw the new organization's name and no\n // \"it moved\". The host's toasts live outside the page, so when the host binds them the\n // sentence is said THERE, and only there (one home per sentence); unbound, it is said here.\n if (host.notify) host.notify.success(done);\n else setSaid({ tone: \"done\", text: done });\n setAttempt((n) => n + 1);\n onMoved?.(moved.data.to);\n }\n\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n if (next) setArmed(true);\n if (!next) {\n setChoosing(null);\n setSaid(null);\n }\n setOpen(next);\n }}\n >\n <PopoverTrigger asChild>\n {variant === \"anchor\" ? (\n <span aria-hidden className=\"pointer-events-none inline-block h-0 w-0\" data-where-it-lives-anchor={tableId} />\n ) : (\n <button\n type=\"button\"\n data-where-it-lives={tableId}\n data-where-it-lives-organization={home?.organization.id ?? \"\"}\n onClick={(e) => e.stopPropagation()}\n className={\n variant === \"row\"\n ? \"inline-flex max-w-[14rem] items-center gap-1 rounded px-1 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground\"\n : variant === \"title\"\n ? \"inline-flex min-w-0 max-w-full items-center gap-1 rounded px-1 text-[11px] font-normal text-muted-foreground hover:bg-muted hover:text-foreground sm:text-xs\"\n : \"inline-flex max-w-[28rem] items-center gap-1 rounded-md border border-border bg-muted/40 px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground\"\n }\n title={name ? `Lives in ${name}` : label}\n >\n <svg aria-hidden viewBox=\"0 0 24 24\" className=\"h-3 w-3 shrink-0\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n <rect x=\"4\" y=\"2\" width=\"16\" height=\"20\" rx=\"2\" />\n <path d=\"M9 22v-4h6v4M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01\" />\n </svg>\n <span className=\"truncate\">{label}</span>\n </button>\n )}\n </PopoverTrigger>\n <PopoverContent\n align=\"start\"\n className=\"w-80 p-3 text-xs\"\n onClick={(e) => e.stopPropagation()}\n // Only the person closes it (a press outside, Escape). Focus moving elsewhere — a toast,\n // the error pill, the grid re-rendering behind it — is not her closing it, and must never\n // take the store's answer off the screen.\n onFocusOutside={(e) => e.preventDefault()}\n >\n {answer === null ? (\n <p className=\"text-muted-foreground\">Finding where this table lives&hellip;</p>\n ) : answer.state === \"not-given\" ? (\n <p className=\"text-muted-foreground\">This table has not been shared with you, so where it lives is not yours to see.</p>\n ) : answer.state === \"door-absent\" || answer.state === \"unavailable\" ? (\n <div className=\"space-y-2\">\n {knownOrganizationName ? (\n <p>\n Lives in <span className=\"font-medium text-foreground\">{knownOrganizationName}</span>.\n </p>\n ) : null}\n <p className=\"text-muted-foreground\">\n {answer.state === \"door-absent\"\n ? \"Moving it to another organization is not available on this database yet.\"\n : `Where this lives could not be found, so nothing here says anything about your access. ${answer.why}`}\n </p>\n {answer.state === \"unavailable\" ? (\n <Button size=\"sm\" variant=\"outline\" className=\"h-7 text-xs\" onClick={() => setAttempt((n) => n + 1)}>\n Ask again\n </Button>\n ) : null}\n </div>\n ) : (\n <div className=\"space-y-2\" data-where-it-lives-panel={answer.home.table.id}>\n <p>\n <span className=\"text-muted-foreground\">{answer.home.table.name} lives in </span>\n <span className=\"font-medium text-foreground\">{answer.home.organization.name}</span>.\n </p>\n {said && !(said.tone === \"refused\" && choosing) ? (\n <p data-where-it-lives-said={said.tone} className={said.tone === \"refused\" ? \"text-destructive\" : \"text-foreground\"}>\n {said.text}\n </p>\n ) : null}\n {choosing ? (\n // THE CONSEQUENCE, SAID BEFORE THE MOVE, in the same panel — no second dialog.\n <div className=\"space-y-2\" data-where-it-lives-confirm={choosing.id}>\n <p className=\"font-medium text-foreground\">\n Move {answer.home.table.name} to {choosing.name}\n <SharedNameAddress to={choosing} all={answer.home.destinations} />?\n </p>\n <p className=\"text-muted-foreground\">{moveConsequence(answer.home, choosing)}</p>\n {said?.tone === \"refused\" ? (\n <ErrorBox\n data-where-it-lives-said=\"refused\"\n className=\"text-destructive\"\n message={said.text}\n operation={`Move ${answer.home.table.name} to ${choosing.name}`}\n origin=\"records-ui/WhereItLives\"\n />\n ) : null}\n <div className=\"flex gap-2\">\n <Button size=\"sm\" className=\"h-7 text-xs\" disabled={moving} onClick={() => void move(choosing)}>\n {moving ? `Moving to ${choosing.name}…` : said?.tone === \"refused\" ? \"Try again\" : \"Move it\"}\n </Button>\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-7 text-xs\"\n disabled={moving}\n onClick={() => {\n // Back to the list, re-read: what the store says now may differ from before.\n const wasRefused = said?.tone === \"refused\";\n setChoosing(null);\n setSaid(null);\n if (wasRefused) setAttempt((n) => n + 1);\n }}\n >\n Cancel\n </Button>\n </div>\n </div>\n ) : !answer.home.mayMove ? (\n <p className=\"text-muted-foreground\">{answer.home.whyNot}</p>\n ) : answer.home.heldBy.length > 0 ? (\n <div className=\"space-y-1\">\n <p className=\"font-medium text-foreground\">It cannot move yet:</p>\n <ul className=\"list-disc space-y-1 pl-4 text-muted-foreground\">\n {answer.home.heldBy.map((line) => (\n <li key={line}>{line}</li>\n ))}\n </ul>\n </div>\n ) : answer.home.destinations.length === 0 ? (\n <p className=\"text-muted-foreground\">You are not a member of any other organization, so there is nowhere else to move it.</p>\n ) : (\n <div className=\"space-y-1\">\n <p className=\"font-medium text-foreground\">Move it to</p>\n <ul className=\"max-h-64 space-y-1 overflow-y-auto pr-1\">\n {answer.home.destinations.map((to) => (\n <li key={to.id}>\n {to.ok ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"h-7 w-full justify-start text-xs\"\n data-where-it-lives-move={to.id}\n onClick={() => {\n setSaid(null);\n setChoosing(to);\n }}\n >\n {to.name}\n <SharedNameAddress to={to} all={answer.home.destinations} />\n </Button>\n ) : (\n <p className=\"text-muted-foreground\">\n <span className=\"text-foreground\">{to.name}</span>\n <SharedNameAddress to={to} all={answer.home.destinations} /> &mdash; {to.why}\n </p>\n )}\n </li>\n ))}\n </ul>\n </div>\n )}\n </div>\n )}\n </PopoverContent>\n </Popover>\n );\n}\n\n/**\n * THE SAME NAME, TOLD APART (UI-FIX-19, VERIFIER-19 #9). A destination whose name another\n * destination also carries is drawn with its web address — the way GitHub shows owner/name — so\n * three organizations called \"Ironclad Mobile Mechanic\" are three rows a person can tell apart.\n * A list of distinct names is unchanged.\n */\nexport function sharedNameAddress(\n to: Pick<TableHomeDestination, \"id\" | \"name\" | \"slug\">,\n all: ReadonlyArray<Pick<TableHomeDestination, \"id\" | \"name\">>,\n): string | null {\n const name = to.name.trim();\n if (!all.some((other) => other.id !== to.id && other.name.trim() === name)) return null;\n return to.slug ?? displayId(to.id);\n}\n\nfunction SharedNameAddress({\n to,\n all,\n}: {\n to: Pick<TableHomeDestination, \"id\" | \"name\" | \"slug\">;\n all: ReadonlyArray<Pick<TableHomeDestination, \"id\" | \"name\">>;\n}) {\n const address = sharedNameAddress(to, all);\n return address ? (\n <span className=\"ml-1.5 font-normal text-muted-foreground\" data-where-it-lives-address=\"\">\n {address}\n </span>\n ) : 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/writeOnTheWinningVersion.ts — @ai-matrx/records-ui · moved whole to @ai-matrx/records/versions (2026-10-08); one instance (askOnce's cache) for both packages.\nexport * from \"@ai-matrx/records/versions\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,aAAAA,YAAW,WAAAC,UAAS,UAAAC,SAAQ,YAAAC,iBAAgB;AACrD,SAAS,oBAAAC,mBAAkB,eAAAC,cAAa,aAAAC,kBAA4B;AAEpE;AAAA,EACE,UAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA,iBAAAC;AAAA,EACA,cAAAC;AAAA,EACA,iBAAAC;AAAA,EACA,eAAAC;AAAA,EACA,MAAAC;AAAA,OACK;;;ACnBA,IAAM,uBAAuB,KAAK,KAAK,KAAK;AAM5C,IAAM,mBAAmB,KAAK,KAAK;AAQ1C,eAAsB,oBACpB,QACA,YACA,YAEA,YACA,MAAc,KAAK,IAAI,GACU;AACjC,QAAM,OAAO,WAAW,KAAK,EAAE,YAAY;AAC3C,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,SAAS,MAAM,OAAO,UAAU;AACtC,MAAI,CAAC,OAAO,GAAI,QAAO;AACvB,QAAM,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AO,cAAc,YAAY,OAAe,IAAI,UAAU;AAAA;AAAA,UAJjE,GAAG,OAAO,IAAI,KAAK,IAAI,KAAK;AAAA,QAKnC,IACE;AAAA,SACN;AAAA,OAEJ;AAAA,KAEJ;AAEJ;","names":["useEffect","useMemo","useRef","useState","useRecordsClient","useMyLevels","useTables","Button","Checkbox","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","relationNameKey","predictValueRefusals","cell","predictValueRefusals","best","titleKey","titleTakesWords","relationNameKey","at","inFileOrder","take","refusalOf","table","useEffect","useState","useRecordsClient","Button","Skeleton","cn","useCallback","useMemo","useState","useRecordsClient","Button","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","parseDelimited","toDelimited","cell","Fragment","jsx","jsxs","useRecordsClient","useState","useMemo","useCallback","Button","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","cn","copyText","useCallback","useEffect","useMemo","useState","useRecordsClient","bookingPath","Badge","Button","Skeleton","cn","useCallback","useEffect","useMemo","useRef","useState","useFields","useRecordsClient","useTable","BasicInput","Button","Label","cn","Select","BasicInput","Label","jsx","jsxs","Fragment","jsx","jsxs","useRecordsClient","useTable","useFields","useState","useRef","useMemo","useCallback","useEffect","cn","Button","Label","BasicInput","Select","Button","cn","jsx","jsxs","useCallback","useEffect","useState","useRecordsClient","Button","jsx","Fragment","jsx","jsxs","jsx","jsxs","useRecordsClient","done","Button","useState","useCallback","useEffect","Fragment","jsx","jsxs","tableName","useRecordsClient","useState","useCallback","useEffect","useMemo","copyText","Skeleton","cn","Button","bookingPath","Badge","useEffect","useState","useRecordsClient","Button","ErrorBox","jsx","jsxs","useRecordsClient","useState","useEffect","Button","ErrorBox","jsx","jsxs","useRecordsClient","useState","useEffect","cn","Button","Skeleton","Fragment","jsx","jsxs","typeWord","useRecordsClient","useMemo","useState","useTables","useMyLevels","useRef","useEffect","cn","refusalOf","tableName","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Button","Checkbox"]}