@ai-matrx/agents 0.43.9 → 0.43.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/content-transfer/index.cjs.map +1 -1
- package/dist/content-transfer/index.js.map +1 -1
- package/dist/content-transfer/react/index.cjs.map +1 -1
- package/dist/content-transfer/react/index.js.map +1 -1
- package/dist/context/react/index.cjs +41 -23
- package/dist/context/react/index.cjs.map +1 -1
- package/dist/context/react/index.d.cts +4 -3
- package/dist/context/react/index.d.ts +4 -3
- package/dist/context/react/index.js +42 -24
- package/dist/context/react/index.js.map +1 -1
- package/dist/generated/api-types.cjs.map +1 -1
- package/dist/generated/api-types.d.cts +117 -7
- package/dist/generated/api-types.d.ts +117 -7
- package/dist/generated/stream-events.cjs +296 -0
- package/dist/generated/stream-events.cjs.map +1 -1
- package/dist/generated/stream-events.d.cts +34 -2
- package/dist/generated/stream-events.d.ts +34 -2
- package/dist/generated/stream-events.js +296 -0
- package/dist/generated/stream-events.js.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{keys.generated-Dfy6RITs.d.cts → keys.generated-5CeTgBps.d.cts} +4 -4
- package/dist/{keys.generated-Dfy6RITs.d.ts → keys.generated-5CeTgBps.d.ts} +4 -4
- package/dist/mandates/index.cjs +2 -2
- package/dist/mandates/index.cjs.map +1 -1
- package/dist/mandates/index.d.cts +2 -2
- package/dist/mandates/index.d.ts +2 -2
- package/dist/mandates/index.js +2 -2
- package/dist/mandates/index.js.map +1 -1
- package/dist/matrx/index.d.cts +1 -1
- package/dist/matrx/index.d.ts +1 -1
- package/generated/api-types.ts +117 -7
- package/generated/stream-events.ts +333 -0
- package/mandates/snapshots/keys.0.43.10.json +653 -0
- package/mandates/snapshots/keys.0.43.11.json +653 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../context/react/index.ts","../../../context/react/ContextRulesTable.tsx","../../../context/index.ts","../../../context/react/icons.tsx","../../../context/react/hierarchy.ts","../../../context/react/FrozenInclude.tsx","../../../context/react/InlineMaxInput.tsx","../../../context/react/shared.ts","../../../context/react/summary.ts","../../../context/react/ContextRulesChip.tsx","../../../context/react/ContextRulesPanelBody.tsx","../../../context/react/ContextDeliveredValue.tsx","../../../context/react/ContextReceiptBlocks.tsx"],"sourcesContent":["/**\n * @ai-matrx/agents/context/react — presentational, state-agnostic context\n * rules UI. Every edit leaves through `onChange`; the host owns persistence\n * (RULES.md §3: optimistic write, no debounce). SSR-safe: no window access at\n * import. Built on @ai-matrx/design-system primitives; glyphs are inlined\n * Lucide shapes (C19).\n */\nexport { ContextRulesTable, type ContextRulesTableProps, type ContextRulesDensity } from \"./ContextRulesTable\";\nexport { ContextRulesChip, summarizeContextRows, type ContextRulesChipProps } from \"./ContextRulesChip\";\nexport { ContextRulesPanelBody, type ContextRulesPanelBodyProps } from \"./ContextRulesPanelBody\";\nexport {\n AI_MATRX_LEVEL,\n ATTACHED_LEVEL,\n PAGE_LEVEL,\n buildContextLevels,\n includeChanges,\n inheritedInclude,\n levelRows,\n placeByOrigin,\n type ContextGroupNode,\n type ContextGroupRef,\n type ContextHierarchy,\n type ContextLevelMaster,\n type ContextLevelNode,\n type ContextLevelRef,\n type ContextRowPlace,\n type ContextRuleChange,\n} from \"./hierarchy\";\nexport { InlineMaxInput, type InlineMaxInputProps } from \"./InlineMaxInput\";\nexport { ContextDeliveredValue, DeliveredSection } from \"./ContextDeliveredValue\";\nexport {\n ContextReceiptBlocks,\n ContextReceiptBlockDetail,\n type ContextReceiptBlocksProps,\n} from \"./ContextReceiptBlocks\";\n","import * as React from \"react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n Switch,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n formatChars,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ArrowDownToLineIcon, TriangleAlertIcon } from \"./icons\";\nimport {\n buildContextLevels,\n includeChanges,\n levelRows,\n type ContextHierarchy,\n type ContextLevelNode,\n type ContextRuleChange,\n} from \"./hierarchy\";\nimport { FrozenInclude } from \"./FrozenInclude\";\nimport { InlineMaxInput } from \"./InlineMaxInput\";\nimport { summarizeContextRows } from \"./summary\";\nimport {\n LAYER_LABEL,\n describeMismatches,\n formatLimit,\n SELF_CHECK_TOOLTIP,\n SERVER_RESOLVED_TOOLTIP,\n inheritedLimit,\n limitPlaceholder,\n onRequestReason,\n rowId,\n withInclude,\n withLimit,\n} from \"./shared\";\n\nexport type ContextRulesDensity = \"compact\" | \"comfortable\";\n\nexport interface ContextRulesTableProps {\n rows: readonly ResolvedContextRow[];\n cap: number;\n readOnly?: boolean | undefined;\n /** From `compareReceipt` — rows with a mismatch get an amber marker. */\n mismatches?: readonly ContextReceiptMismatch[];\n /** `next === null` resets the person's rule for that key. */\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n onOpenRow?: (key: string) => void;\n /** `comfortable` = 44px touch rows (the deciding layer stays in the row tooltip). Default `compact`. */\n density?: ContextRulesDensity;\n /** Highlights the open row (master/detail). */\n selectedKey?: string | null;\n /**\n * Where each row sits (level → group) and the host's level switches. Omit:\n * rows sit under their origin (\"Page\", \"Attached\", \"AI Matrx\").\n */\n hierarchy?: ContextHierarchy | null | undefined;\n /**\n * A level or group switch: the person's per-value rules for every value in\n * it, at once. Omit: level and group switches are hidden (a host master\n * switch still shows).\n */\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /**\n * Host slots inside a row's Item cell, never a second renderer: `renderRowLead`\n * before the label (a status mark), `renderRowTrail` after it (an admin's\n * machine name). Each renders inline and truncates with the label.\n */\n renderRowLead?: ((row: ResolvedContextRow) => React.ReactNode) | undefined;\n renderRowTrail?: ((row: ResolvedContextRow) => React.ReactNode) | undefined;\n className?: string;\n}\n\nexport const CONTEXT_RULES_GRID = {\n compact: \"grid grid-cols-[minmax(0,1fr)_2.75rem_4rem_6.5rem] items-center gap-x-2 px-2\",\n comfortable: \"grid grid-cols-[minmax(0,1fr)_2.75rem_3.5rem_6.75rem] items-center gap-x-1.5 px-3\",\n} as const;\n\n/**\n * Narrow (a window sidebar, a phone): the name takes the whole row; Include,\n * Chars and Inline max shrink to their content and Inline max collapses to a\n * button that opens its field — names stay readable, never \"Bra…\".\n */\nconst NARROW_GRID = {\n compact: \"grid grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-1.5 px-2\",\n comfortable: \"grid grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-1.5 px-3\",\n} as const;\n\n/** Below this width the table lays out narrow. */\nexport const CONTEXT_RULES_NARROW_BELOW = 400;\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\n/** Narrow when the table's own width is under `CONTEXT_RULES_NARROW_BELOW`, measured on every resize. */\nfunction useNarrow(ref: React.RefObject<HTMLDivElement | null>): boolean {\n const [narrow, setNarrow] = React.useState(false);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const fit = () => {\n const width = el.clientWidth;\n if (width > 0) setNarrow(width < CONTEXT_RULES_NARROW_BELOW);\n };\n fit();\n if (typeof ResizeObserver === \"undefined\") return undefined;\n const observer = new ResizeObserver(fit);\n observer.observe(el);\n return () => observer.disconnect();\n }, [ref]);\n return narrow;\n}\n\n/** One indent step per depth (ui-dense: small). */\nconst INDENT = [\"\", \"pl-2\", \"pl-4\", \"pl-6\"] as const;\nconst indent = (depth: number) => INDENT[Math.min(depth, INDENT.length - 1)];\n\n/** Levels that share a section (\"Marketing\") sit under one section row. */\ninterface SectionNode {\n id: string;\n label: string | null;\n levels: ContextLevelNode[];\n}\n\nfunction sectionsOf(levels: readonly ContextLevelNode[]): SectionNode[] {\n const out: SectionNode[] = [];\n for (const level of levels) {\n const label = level.ref.path.length > 1 ? level.ref.path[0]! : null;\n const last = out[out.length - 1];\n if (label !== null && last && last.label === label) last.levels.push(level);\n else out.push({ id: label === null ? `level:${level.ref.id}` : `section:${label}`, label, levels: [level] });\n }\n return out;\n}\n\n/**\n * The context rules table: Item | Include | Chars | Inline max, under nested\n * heading rows — section (\"Marketing\"), page (\"Marketing Brand Cockpit\"), the\n * page's own groups — each heading full width with its switch. Presentational\n * and state-agnostic — every edit goes out through `onChange`.\n */\nexport function ContextRulesTable({\n rows,\n cap,\n readOnly,\n mismatches,\n onChange,\n onOpenRow,\n density = \"compact\",\n selectedKey,\n hierarchy,\n onSetInclude,\n renderRowLead,\n renderRowTrail,\n className,\n}: ContextRulesTableProps) {\n const comfortable = density === \"comfortable\";\n const rootRef = React.useRef<HTMLDivElement>(null);\n const narrow = useNarrow(rootRef);\n const grid = narrow ? NARROW_GRID[density] : CONTEXT_RULES_GRID[density];\n const levels = buildContextLevels(rows, hierarchy);\n // One origin and no host hierarchy: the heading would only repeat the chip.\n const headed = Boolean(hierarchy) || levels.length > 1;\n const bulkChanges = (list: readonly ResolvedContextRow[], next: boolean) => includeChanges(list, next, cap);\n const bulk = (list: readonly ResolvedContextRow[]) =>\n onSetInclude && !readOnly\n ? (next: boolean) => {\n const changes = bulkChanges(list, next);\n if (changes.length > 0) onSetInclude(changes);\n }\n : undefined;\n const renderRow = (row: ResolvedContextRow, depth: number) => (\n <ContextRuleRow\n key={rowId(row)}\n row={row}\n cap={cap}\n grid={grid}\n narrow={narrow}\n depth={headed ? depth : 0}\n readOnly={readOnly}\n selected={selectedKey === row.key}\n mismatches={mismatches?.filter((m) => m.key === row.key) ?? []}\n onChange={onChange}\n onOpenRow={onOpenRow}\n comfortable={comfortable}\n lead={renderRowLead?.(row)}\n trail={renderRowTrail?.(row)}\n />\n );\n const heading = (props: Omit<HeadingProps, \"grid\" | \"narrow\" | \"comfortable\" | \"readOnly\">) => (\n <Heading key={props.id} {...props} grid={grid} narrow={narrow} comfortable={comfortable} readOnly={readOnly} />\n );\n const renderLevel = (level: ContextLevelNode, depth: number) => {\n const all = levelRows(level);\n const name = level.ref.path[level.ref.path.length - 1] ?? \"\";\n return (\n <div role=\"rowgroup\" key={level.ref.id} aria-label={headed ? level.ref.path.join(\" › \") : undefined} data-level={level.ref.id}>\n {headed\n ? heading({\n id: `h:${level.ref.id}`,\n kind: \"level\",\n label: name,\n switchName: level.ref.path.join(\" › \"),\n depth,\n rows: all,\n ...levelSwitch(level, bulk(all)),\n })\n : null}\n {level.rows.map((row) => renderRow(row, depth + 1))}\n {level.groups.map((group) => (\n <div role=\"rowgroup\" key={group.ref.id} aria-label={group.ref.label} data-group={group.ref.id}>\n {heading({\n id: `h:${group.ref.id}`,\n kind: \"group\",\n label: group.ref.label,\n switchName: group.ref.label,\n depth: depth + 1,\n rows: group.rows,\n checked: group.rows.some((r) => r.include),\n onToggle: bulk(group.rows),\n })}\n {group.rows.map((row) => renderRow(row, depth + 2))}\n </div>\n ))}\n </div>\n );\n };\n\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <div\n ref={rootRef}\n role=\"table\"\n aria-label=\"Values\"\n data-density={density}\n data-layout={narrow ? \"narrow\" : \"wide\"}\n className={cn(\"text-xs\", className)}\n >\n {/* Narrow: the columns are self-evident from their controls; no header row. */}\n {narrow ? null : (\n <div\n role=\"row\"\n className={cn(grid, \"sticky top-0 z-10 h-7 border-b border-border bg-card font-medium text-muted-foreground\")}\n >\n <span role=\"columnheader\">Item</span>\n <span role=\"columnheader\" className=\"text-center\">\n Include\n </span>\n <span role=\"columnheader\" className=\"text-right\">\n Chars\n </span>\n <span role=\"columnheader\" className=\"pr-6 text-right\">\n Inline max\n </span>\n </div>\n )}\n {levels.length === 0 ? (\n <div className=\"px-2 py-3 text-center text-muted-foreground\">None</div>\n ) : (\n sectionsOf(levels).map((section) => {\n if (section.label === null || !headed) return renderLevel(section.levels[0]!, 0);\n const all = section.levels.flatMap(levelRows);\n // A section switch only where it governs more than one page.\n const several = section.levels.length > 1;\n const toggleSection =\n several && !readOnly\n ? (next: boolean) => {\n const changes: ContextRuleChange[] = [];\n for (const level of section.levels) {\n if (level.master) level.master.onToggle?.(next);\n else changes.push(...bulkChanges(levelRows(level), next));\n }\n if (changes.length > 0) onSetInclude?.(changes);\n }\n : undefined;\n return (\n <div role=\"rowgroup\" key={section.id} aria-label={section.label} data-section={section.label}>\n {heading({\n id: `h:${section.id}`,\n kind: \"section\",\n label: section.label,\n switchName: section.label,\n depth: 0,\n rows: all,\n checked: section.levels.some((l) => (l.master ? l.master.on : levelRows(l).some((r) => r.include))),\n onToggle: toggleSection,\n noSwitch: !several,\n })}\n {section.levels.map((level) => renderLevel(level, 1))}\n </div>\n );\n })\n )}\n </div>\n </TooltipProvider>\n );\n}\n\n/** A level's switch: the host's master when it has one, else its values' rules. */\nfunction levelSwitch(\n level: ContextLevelNode,\n bulk: ((next: boolean) => void) | undefined,\n): { checked: boolean; onToggle: ((next: boolean) => void) | undefined } {\n if (level.master) return { checked: level.master.on, onToggle: level.master.onToggle };\n return { checked: levelRows(level).some((r) => r.include), onToggle: bulk };\n}\n\ninterface HeadingProps {\n id: string;\n kind: \"section\" | \"level\" | \"group\";\n label: string;\n /** The switch's accessible name: the full path for a page. */\n switchName: string;\n depth: number;\n rows: readonly ResolvedContextRow[];\n checked: boolean;\n onToggle: ((next: boolean) => void) | undefined;\n /** A section over one page: no switch at all (the page's row has it). */\n noSwitch?: boolean;\n grid: string;\n narrow: boolean;\n comfortable: boolean;\n readOnly: boolean | undefined;\n}\n\nfunction Heading({\n kind,\n label,\n switchName,\n depth,\n rows,\n checked,\n onToggle,\n noSwitch,\n grid,\n narrow,\n comfortable,\n readOnly,\n}: HeadingProps) {\n const { count, charsLabel } = summarizeContextRows(rows);\n const total = rows.length;\n // A switch shows where something can be switched, or where a read-only view\n // states the same fact its rows state — never a dead control.\n const showSwitch = !noSwitch && (Boolean(onToggle) || (readOnly && total > 0));\n const countLabel = total > 0 ? (count === total ? String(total) : `${count}/${total}`) : null;\n const toggle = showSwitch ? (\n readOnly ? (\n <FrozenInclude name={switchName} checked={checked} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${switchName}`}\n checked={checked}\n disabled={!onToggle}\n onCheckedChange={(next) => onToggle?.(next)}\n />\n )\n ) : null;\n // The name is never cut: it wraps to a second line before it truncates.\n // Wide: the switch sits in the Include column and the size in Chars, so\n // every switch in the table lines up. Narrow: the switch is the row's last\n // cell, at the far right, like every value's.\n return (\n <div\n role=\"row\"\n data-heading={kind}\n className={cn(\n grid,\n \"border-b border-border/50 font-medium\",\n comfortable ? \"min-h-11 py-1\" : \"min-h-7 py-0.5\",\n kind === \"group\" ? \"bg-muted/25 text-muted-foreground\" : \"bg-muted/60 text-foreground\",\n )}\n >\n <div role=\"cell\" className={cn(\"flex min-w-0 items-baseline gap-1.5\", indent(depth))}>\n <span className=\"min-w-0 whitespace-normal break-words\" title={label}>\n {label}\n </span>\n {countLabel ? (\n <span className=\"shrink-0 font-normal tabular-nums text-muted-foreground\">{countLabel}</span>\n ) : null}\n </div>\n <div role=\"cell\" className={cn(\"flex justify-center\", narrow && \"order-last\")}>\n {toggle}\n </div>\n <div role=\"cell\" className=\"text-right font-normal tabular-nums text-muted-foreground\">\n {total > 0 ? charsLabel : null}\n </div>\n <div role=\"cell\" />\n </div>\n );\n}\n\ninterface RowProps {\n row: ResolvedContextRow;\n cap: number;\n grid: string;\n narrow: boolean;\n /** Indent depth (nested headings above it). */\n depth: number;\n comfortable: boolean;\n readOnly: boolean | undefined;\n selected: boolean;\n mismatches: ContextReceiptMismatch[];\n onChange: ContextRulesTableProps[\"onChange\"];\n onOpenRow: ContextRulesTableProps[\"onOpenRow\"];\n lead?: React.ReactNode;\n trail?: React.ReactNode;\n}\n\nfunction ContextRuleRow({\n row,\n cap,\n grid,\n narrow,\n depth,\n comfortable,\n readOnly,\n selected,\n mismatches,\n onChange,\n onOpenRow,\n lead,\n trail,\n}: RowProps) {\n const selfChecked =\n row.blockedBy === \"self_check\" || mismatches.some((m) => m.reason === \"self_check\");\n const decided = selfChecked\n ? SELF_CHECK_TOOLTIP\n : row.serverResolved\n ? SERVER_RESOLVED_TOOLTIP\n : `Include: ${LAYER_LABEL[row.decided_by.include]} · Limit: ${LAYER_LABEL[row.decided_by.max_inline_chars]}`;\n const labelNode = onOpenRow ? (\n <button\n type=\"button\"\n onClick={() => onOpenRow(row.key)}\n className=\"block min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {row.label}\n </button>\n ) : (\n <span className=\"block min-w-0 flex-1 truncate\">{row.label}</span>\n );\n\n return (\n <div\n role=\"row\"\n data-key={row.key}\n data-server-resolved={row.serverResolved ? \"true\" : undefined}\n data-self-check={selfChecked ? \"true\" : undefined}\n data-included={row.include ? \"true\" : \"false\"}\n data-mismatch={mismatches.length > 0 ? \"true\" : undefined}\n aria-selected={selected || undefined}\n className={cn(\n grid,\n \"border-b border-border/50\",\n comfortable ? \"min-h-11\" : \"h-7\",\n selected && \"bg-accent\",\n )}\n >\n <div\n role=\"cell\"\n className={cn(\n \"flex min-w-0 items-center gap-1.5\",\n indent(depth),\n !row.include && \"opacity-50\",\n )}\n >\n {mismatches.length > 0 ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <span\n role=\"img\"\n aria-label=\"Mismatch\"\n className=\"inline-flex shrink-0 text-warning\"\n >\n <TriangleAlertIcon className=\"h-3.5 w-3.5\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{describeMismatches(mismatches)}</TooltipContent>\n </Tooltip>\n ) : null}\n {lead ? <span className=\"inline-flex shrink-0 items-center\">{lead}</span> : null}\n <Tooltip>\n <TooltipTrigger asChild>{labelNode}</TooltipTrigger>\n <TooltipContent>\n <div>{row.label}</div>\n <div className=\"font-normal text-muted-foreground\">{decided}</div>\n </TooltipContent>\n </Tooltip>\n {trail ? <span className=\"min-w-0 max-w-[45%] shrink truncate text-muted-foreground\">{trail}</span> : null}\n </div>\n <div role=\"cell\" className={cn(\"flex justify-center\", narrow && \"order-last\")}>\n {readOnly ? (\n <FrozenInclude name={row.label} checked={row.include} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${row.label}`}\n checked={row.include}\n onCheckedChange={(next) => onChange(row.key, row.surfaceKey, withInclude(row, next))}\n />\n )}\n </div>\n <div\n role=\"cell\"\n className={cn(\"flex items-center justify-end gap-1 tabular-nums\", !row.include && \"opacity-50\")}\n >\n {row.include && row.delivery === \"on_request\" ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <span role=\"img\" aria-label=\"On request\" className=\"inline-flex text-muted-foreground\">\n <ArrowDownToLineIcon className=\"h-3 w-3\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{onRequestReason(row)}</TooltipContent>\n </Tooltip>\n ) : null}\n <span>{formatChars(row.chars)}</span>\n </div>\n <div role=\"cell\">\n {narrow ? (\n <InlineMaxButton row={row} cap={cap} readOnly={readOnly} comfortable={comfortable} onChange={onChange} />\n ) : (\n <InlineMaxInput\n label={row.label}\n value={row.userRule?.max_inline_chars ?? null}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n )}\n </div>\n </div>\n );\n}\n\n/**\n * Narrow layout's Inline max: the limit as a compact button (its value, muted\n * when inherited, a dot when the person set it) that opens the same field.\n */\nfunction InlineMaxButton({\n row,\n cap,\n readOnly,\n comfortable,\n onChange,\n}: {\n row: ResolvedContextRow;\n cap: number;\n readOnly: boolean | undefined;\n comfortable: boolean;\n onChange: ContextRulesTableProps[\"onChange\"];\n}) {\n const [open, setOpen] = React.useState(false);\n const own = row.userRule?.max_inline_chars ?? null;\n const text = own !== null ? formatLimit(own) : limitPlaceholder(row, cap);\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n aria-label={`Inline max ${row.label}: ${text}`}\n disabled={readOnly}\n className={cn(\n \"relative inline-flex min-w-[2.25rem] items-center justify-end gap-1 rounded px-1 tabular-nums hover:bg-accent disabled:opacity-60\",\n comfortable ? \"h-8 after:absolute after:-inset-y-1.5 after:inset-x-0 after:content-['']\" : \"h-6\",\n own === null ? \"text-muted-foreground\" : \"text-foreground\",\n )}\n >\n {own !== null ? <span aria-hidden className=\"h-1 w-1 rounded-full bg-primary\" /> : null}\n {text}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"end\" className=\"w-auto p-2\">\n <div className=\"flex items-center gap-2 text-xs\">\n <span className=\"text-muted-foreground\">Inline max</span>\n <InlineMaxInput\n label={row.label}\n value={own}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n","/**\n * @ai-matrx/agents/context — the context value rules, headless.\n *\n * Contract: common-docs/systems/scopes-context/context-delivery/RULES.md.\n * Parity corpus: ./rules-corpus.json (run here by rules.test.ts and by aidream's\n * pytest against the Python twin `resolve_context_rule`). Every function here\n * is pure, zero-React, and safe to import on a server.\n *\n * The one flow a client runs per turn:\n * rows = values.map(v => resolveContextRow(v, savedRows, cap)) // what the table shows\n * context = buildContextWire(rows) // what the request sends\n * …on `context_receipt`: compareReceipt(rows, receipt) // screen vs server\n */\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** `users.user_surface_state.feature` for the person's saved rules. */\nexport const CONTEXT_RULES_FEATURE = \"context_rules\";\n/** Surface key for values no surface emitted (attachments, server-added values). */\nexport const DEFAULT_SURFACE_KEY = \"_default\";\n/** The server's default inline threshold when no layer sets one. */\nexport const DEFAULT_INLINE_MAX_CHARS = 200;\n/** The default ceiling every resolved limit is clamped to (a server knob). */\nexport const DEFAULT_INLINE_CAP = 50000;\n/** A lazy document's server default (RULES.md §2: \"a small lazy document 6000\"). */\nexport const LAZY_SOURCE_DEFAULT_MAX = 6000;\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** Which layer decided a field — lowest to highest. */\nexport type ContextLayer = \"default\" | \"page\" | \"agent\" | \"you\";\nexport type ContextDelivery = \"inline\" | \"on_request\" | \"off\";\n/**\n * A client row's delivery: the server's three, plus `\"server\"` — an included\n * value the server resolves itself (`isServerResolved`), whose delivery the\n * client does not claim. Never on the wire or in a receipt.\n */\nexport type ContextRowDelivery = ContextDelivery | \"server\";\n\n/** One saved per-person rule (one key on one surface). Both fields optional. */\nexport interface SavedContextRule {\n include?: boolean;\n max_inline_chars?: number;\n}\n\n/** `{ [surface_key]: { [context key]: SavedContextRule } }` — the person's rows. */\nexport type SavedContextRuleRows = Record<string, Record<string, SavedContextRule>>;\n\n/** The agent layer for one key (RULES.md §2). */\nexport interface ContextAgentLayer {\n /** The agent's Context Policy declares this key (or the value is the agent's own seed). */\n declared?: boolean;\n /** The policy's ceiling; only read when `declared`. */\n max_inline_chars?: number | null;\n /** `auto_context_disabled` — closes every undeclared key. */\n kill_switch?: boolean;\n}\n\n/** The page layer for one key: the surface that emitted the value. */\nexport interface ContextSurfaceLayer {\n /** The surface declares this value (a `ui_surface_value` row / manifest entry). */\n declared?: boolean;\n /** `false` drops the value unless the agent declares it. */\n auto_context?: boolean | null;\n /** `inlineUpTo` / envelope `max_inline_chars` / DB column. */\n max_inline_chars?: number | null;\n}\n\n/** The non-person layers for one value — what the table's layer breakdown shows. */\nexport interface ContextRuleLayers {\n /** The server's per-key default limit; `null`/absent = 200. */\n default_max?: number | null;\n agent?: ContextAgentLayer | null;\n surface?: ContextSurfaceLayer | null;\n}\n\n/**\n * Input to `resolveContextRule`. Snake case on purpose: it is the corpus shape\n * and the Python twin's shape. `user` is typed loosely because invalid saved\n * values (non-boolean include, non-integer or negative limit) must be ignored,\n * not trusted.\n */\nexport interface ContextRuleInput extends ContextRuleLayers {\n /** Size in code points; `null` = an unresolved lazy source. */\n chars: number | null;\n user?: { include?: unknown; max_inline_chars?: unknown } | null;\n /** Ceiling; default `DEFAULT_INLINE_CAP`. */\n cap?: number;\n /**\n * A server-authoritative value (`SERVER_AUTHORITATIVE_KEYS`, RULES.md §5a):\n * identity is not page or ambient context, so neither the page's switch nor\n * the agent's or mandate's kill switch closes it — only the person's own rule.\n */\n identity?: boolean;\n}\n\nexport interface ContextRuleResult {\n include: boolean;\n /** Effective limit, after the clamp. */\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n clamped: boolean;\n}\n\n/** One receipt row — RULES.md §5, wire fields exactly. */\nexport interface ContextReceiptRow {\n key: string;\n label: string;\n surface_key: string;\n origin: \"client\" | \"server\" | \"surroundings\" | \"rule\";\n chars: number | null;\n include: boolean;\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n user_rule: { include?: boolean; max_inline_chars?: number } | null;\n clamped: boolean;\n /** The CLIENT itself sent a value the person turned off. */\n client_sent_excluded: boolean;\n /**\n * `\"model\"`: nothing reached a model that reads no context. `\"self_check\"`:\n * the server's post-render safety check stripped it (RULES.md §4/§5) —\n * the row stays, `delivery: \"off\"`.\n */\n blocked_by: ContextBlockedBy | null;\n /**\n * Set when the server did not keep the value under its own key — still a\n * row, never missing (RULES.md §5): `\"expanded\"` (a surroundings envelope\n * became one row per part), `\"directive\"` (a reserved directive the server\n * acted on), `\"renamed\"` (an earlier key spelling, held under the stable\n * key), `\"unaccounted\"` (a server path removed it with no reason — filed as\n * a defect). Absent from an older server.\n */\n consumed_as?: ContextConsumedAs | null;\n /** The keys (each with its own row) that now carry what this value held. */\n consumed_into?: string[];\n /**\n * What the model READ for this value, verbatim from the rendered context\n * block (its own element: the whole value inline, or its on-request entry;\n * for a server-authoritative value, the server's own statement of it).\n * Absent/null when it reached no block (off, consumed) or from an older server.\n */\n delivered?: ContextDeliveredRef | null;\n /** On-request values the server holds as text: what the `context` tool returns (size + hash). */\n on_request?: ContextDeliveredRef | null;\n}\n\n/**\n * What the model read for one value or block, by SIZE and HASH only — never\n * the text (RULES.md §5b: a server-shaped value is fetched on demand, never\n * pushed). The text comes from the viewer (`ContextViewLoader`).\n */\nexport interface ContextDeliveredRef {\n /** Code-point length of the whole text the model read. */\n chars: number;\n /** SHA-256 hex of that text (UTF-8). */\n sha256: string;\n}\n\n/**\n * What to view: a value's `delivered` element, its `on_request` text, a\n * `block`, or what the agent can `fetchable` for a value through a tool (the\n * Organization: its selected scopes' values via `scope_system` — rendered when\n * opened, never on the receipt; `source: \"fetched_now\"`).\n */\nexport type ContextViewKind = \"delivered\" | \"on_request\" | \"block\" | \"fetchable\";\n\nexport interface ContextViewTarget {\n kind: ContextViewKind;\n /** The value's key, or the block's id. */\n key: string;\n}\n\n/**\n * The exact text the model received (a sent turn: `GET /ai/context/delivered`)\n * or will receive (the next turn: `POST /ai/context/preview` with `view`).\n */\nexport interface ContextViewedText {\n kind: ContextViewKind;\n key: string;\n text: string;\n chars: number;\n sha256: string;\n /**\n * `fetched_now`: read at request time — a `fetchable` text (what the agent\n * gets if it asks now) or a lazy `on_request` value the agent never read.\n * `tool_result`: exactly what the `context` tool returned to the agent.\n */\n source: \"preview\" | \"wire\" | \"conversation_prompt\" | \"turn_record\" | \"fetched_now\" | \"tool_result\";\n /**\n * `fetchable` only: `false` when the turn's agent cannot call the tool that\n * returns it (tools off, excluded, a structured-output turn). `text` is then\n * `\"\"`; the screen says so with state, never shows content as fetchable.\n */\n available?: boolean;\n /**\n * A lazy `on_request` value of a SENT turn only (a document, a file family,\n * a scope — the turn never reads one): `true` — the agent called `context`\n * for it and `text` is what the tool returned; `false` — the agent never\n * read it and `text` is what it returns now (the screen says so).\n */\n fetched?: boolean | null;\n}\n\n/** The host's door to the viewer API — called only when a person opens a value. */\nexport type ContextViewLoader = (target: ContextViewTarget) => Promise<ContextViewedText>;\n\n/**\n * The blocks a value's detail shows beneath its own text, because the model\n * received them as part of that value: the Organization is its live statement\n * AND the organization catalog (owner ruling 2026-10-01). Such a block is\n * counted in the value's chars and is not listed again under \"Also sent\".\n */\nexport const CONTEXT_ROW_BLOCKS: Readonly<Record<string, readonly string[]>> = {\n organization: [\"organization_catalog\"],\n};\n\n/**\n * Values whose content the agent READS THROUGH A TOOL rather than receiving it,\n * keyed to that tool: the Organization's selected scopes' values are returned\n * by `scope_system` (by design, never inline). Their detail shows \"Agent can\n * fetch\" — the viewer's `fetchable` text, loaded when opened (RULES.md §5b).\n */\nexport const CONTEXT_FETCHABLE_ROWS: Readonly<Record<string, string>> = {\n organization: \"scope_system\",\n};\n\n/** The receipt blocks shown under `key`'s detail (`CONTEXT_ROW_BLOCKS`). */\nexport function blocksForRow(\n key: string,\n blocks: readonly ContextReceiptBlock[] | null | undefined,\n): ContextReceiptBlock[] {\n const ids = CONTEXT_ROW_BLOCKS[key] ?? [];\n return (blocks ?? []).filter((b) => ids.includes(b.id));\n}\n\n/** The receipt blocks not shown under any value present in `rowKeys`. */\nexport function unclaimedBlocks(\n blocks: readonly ContextReceiptBlock[] | null | undefined,\n rowKeys: Iterable<string>,\n): ContextReceiptBlock[] {\n const claimed = new Set<string>();\n for (const key of rowKeys) for (const id of CONTEXT_ROW_BLOCKS[key] ?? []) claimed.add(id);\n return (blocks ?? []).filter((b) => !claimed.has(b.id));\n}\n\n/** How the server consumed a value it did not keep under its own key (receipt `consumed_as`). */\nexport type ContextConsumedAs = \"expanded\" | \"directive\" | \"renamed\" | \"unaccounted\";\n\n/**\n * The reserved keys the server never keeps under their own name, and what it\n * does with each — the receipt rows say so (`consumed_as`). The same table is\n * the parity corpus's `consumed_key_cases` (aidream `RESERVED_CONSUMED_KEYS`).\n */\nexport const RESERVED_CONSUMED_KEYS: Readonly<Record<string, ContextConsumedAs>> = {\n surface_chain: \"expanded\",\n window_forms: \"expanded\",\n __table_access: \"directive\",\n __google_files: \"directive\",\n};\n\n/**\n * Where the server states each SERVER-AUTHORITATIVE value (RULES.md §5a, owner\n * ruling 2026-10-01: identity is the server's truth, never the page's claim).\n * The server drops the client's copy of these keys and the model reads the\n * server's own value, every turn: `\"active_context\"` — its `<active_context>`\n * block (the conversation's organization, the scopes it admitted);\n * `\"manifest\"` — a server-built value (the authenticated person, the server's\n * clock). A screen never shows the client's copy of one as what will be sent.\n * The same table is the parity corpus's `server_authoritative_keys` (aidream\n * `SERVER_AUTHORITATIVE_KEYS`).\n */\nexport const SERVER_AUTHORITATIVE_KEYS: Readonly<Record<string, \"manifest\" | \"active_context\">> = {\n user: \"manifest\",\n client: \"manifest\",\n organization: \"active_context\",\n active_scopes: \"active_context\",\n};\n\n/** True for a key whose value the server states itself (`SERVER_AUTHORITATIVE_KEYS`). */\nexport function isServerAuthoritativeKey(key: string): boolean {\n return Object.prototype.hasOwnProperty.call(SERVER_AUTHORITATIVE_KEYS, key);\n}\n\n/**\n * One block of server text the model received this turn that is not a single\n * value — the turn's `<active_context>`, earlier-turn context, the sandbox\n * briefing, skills, memory, the organization catalog… (receipt `blocks`,\n * RULES.md §5). `delivered` is its exact text, cut at the receipt's cap.\n */\nexport interface ContextReceiptBlock {\n /** Stable id: the per-turn slot it rode in, or the system-prompt addition's name. */\n id: string;\n /** The id in words (`humanizeIdentifier`, `@ai-matrx/kit/text-case`). */\n label: string;\n /** Size and hash; the text comes from the viewer (`kind: \"block\"`). */\n delivered: ContextDeliveredRef;\n}\n\n/** The per-turn receipt the server streams as `context_receipt` — RULES.md §5. */\nexport interface ContextReceipt {\n version: 1;\n surface: string | null;\n cap: number;\n /** False: this turn's model cannot read context at all (every row `blocked_by: \"model\"`). */\n model_reads_context: boolean;\n /** The person's saved rules could not be read; the turn ran without them. */\n rules_error: string | null;\n rows: ContextReceiptRow[];\n /** Every other block of server text the model received, in render order (absent: older server). */\n blocks?: ContextReceiptBlock[];\n}\n\nexport type ContextRowOrigin = \"page\" | \"attached\" | \"system\";\n\n/** Why the server kept a value from the model on this turn (receipt `blocked_by`). */\nexport type ContextBlockedBy = \"model\" | \"self_check\";\n\n/** A client's resolved row: what its table renders and what `buildContextWire` sends. */\nexport interface ResolvedContextRow extends Omit<ContextRuleResult, \"delivery\"> {\n delivery: ContextRowDelivery;\n /**\n * The server resolves this value (a resource reference, a `*_id` UUID): size\n * and delivery are unknown (`chars: null`, `delivery: \"server\"` when\n * included), and its default limit is not predicted. Include and the\n * person's own rule still resolve normally.\n */\n serverResolved?: boolean;\n /** Display-only: chars / limit / delivery were filled from a receipt (`applyReceiptToRows`). */\n fromReceipt?: boolean;\n /** From a receipt: why the server kept this value from the model this turn. */\n blockedBy?: ContextBlockedBy;\n /**\n * Display-only, from a receipt: what the model read for this value. When set,\n * a detail view shows THIS — never `value`, the client's pre-send copy.\n */\n delivered?: ContextDeliveredRef;\n /** Display-only, from a receipt: what the `context` tool returns for it (size + hash). */\n onRequest?: ContextDeliveredRef;\n /** Display-only, from a receipt: blocks the model received as part of this value. */\n deliveredBlocks?: ContextReceiptBlock[];\n key: string;\n label: string;\n surfaceKey: string;\n origin: ContextRowOrigin;\n /** The raw value, or an already-rich envelope (`{ content, type, … }`). */\n value: unknown;\n chars: number | null;\n /** The saved rule that was applied (merged `_default` + surface row), or null. */\n userRule: SavedContextRule | null;\n description?: string;\n /** Context object type for the wire envelope (`text`, `json`, …). */\n type?: string;\n /** The non-person layers the rule was resolved from. Absent = default only. */\n layers?: ContextRuleLayers;\n}\n\n/** What a client knows about one value before resolution. */\nexport interface ContextRowSource {\n key: string;\n label: string;\n surfaceKey?: string;\n origin: ContextRowOrigin;\n value: unknown;\n /** Override the measured size (e.g. `null` for an unresolved lazy source). */\n chars?: number | null;\n description?: string;\n type?: string;\n layers?: ContextRuleLayers;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nconst isNum = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v);\nconst isValidLimit = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isInteger(v) && v >= 0;\n\n// ── resolveContextRule — RULES.md §2, line for line ─────────────────────────\n\nexport function resolveContextRule(input: ContextRuleInput): ContextRuleResult {\n const agent = input.agent ?? null;\n const surface = input.surface ?? null;\n const user = input.user ?? null;\n const cap = isNum(input.cap) ? input.cap : DEFAULT_INLINE_CAP;\n const agentDeclared = agent?.declared === true;\n\n const identity = input.identity === true;\n\n let include = true;\n let includeBy: ContextLayer = \"default\";\n if (!identity && surface?.declared === true && surface.auto_context === false) {\n if (agentDeclared) {\n include = true;\n includeBy = \"agent\";\n } else {\n include = false;\n includeBy = \"page\";\n }\n }\n if (!identity && agent?.kill_switch === true && !agentDeclared) {\n include = false;\n includeBy = \"agent\";\n }\n if (user && typeof user.include === \"boolean\") {\n include = user.include;\n includeBy = \"you\";\n }\n\n let limit = isNum(input.default_max) ? input.default_max : DEFAULT_INLINE_MAX_CHARS;\n let limitBy: ContextLayer = \"default\";\n const a = agentDeclared && isNum(agent?.max_inline_chars) ? agent.max_inline_chars : null;\n const s = isNum(surface?.max_inline_chars) ? surface.max_inline_chars : null;\n if (a !== null && s !== null) {\n if (s < a) {\n limit = s;\n limitBy = \"page\";\n } else {\n limit = a;\n limitBy = \"agent\";\n }\n } else if (a !== null) {\n limit = a;\n limitBy = \"agent\";\n } else if (s !== null) {\n limit = s;\n limitBy = \"page\";\n }\n if (user && isValidLimit(user.max_inline_chars)) {\n limit = user.max_inline_chars;\n limitBy = \"you\";\n }\n const clamped = limit > cap;\n limit = Math.min(limit, cap);\n\n const chars = input.chars;\n const delivery: ContextDelivery = !include\n ? \"off\"\n : chars === null || chars === undefined || limit === 0 || chars > limit\n ? \"on_request\"\n : \"inline\";\n\n return {\n include,\n max_inline_chars: limit,\n delivery,\n decided_by: { include: includeBy, max_inline_chars: limitBy },\n clamped,\n };\n}\n\n// ── contextValueChars — RULES.md §1 ─────────────────────────────────────────\n\n/** Count Unicode code points (never UTF-16 units: `\"😀\".length` is 2). */\nfunction codePoints(s: string): number {\n let n = 0;\n for (const _ of s) n += 1;\n return n;\n}\n\n/**\n * Size of a value in code points, exactly as the server's `content_as_str()`:\n * a string is itself; anything else is `JSON.stringify(value, null, 2)`\n * (Python `json.dumps(value, ensure_ascii=False, indent=2)`). `undefined` → 0.\n */\nexport function contextValueChars(value: unknown): number {\n if (value === undefined) return 0;\n if (typeof value === \"string\") return codePoints(value);\n let text: string | undefined;\n try {\n text = JSON.stringify(value, null, 2);\n } catch {\n text = String(value);\n }\n return text === undefined ? 0 : codePoints(text);\n}\n\n// ── lookupSavedRule — RULES.md §3 ───────────────────────────────────────────\n\nfunction sanitizeRule(raw: unknown): SavedContextRule {\n const out: SavedContextRule = {};\n if (!raw || typeof raw !== \"object\") return out;\n const r = raw as Record<string, unknown>;\n if (typeof r.include === \"boolean\") out.include = r.include;\n if (isValidLimit(r.max_inline_chars)) out.max_inline_chars = r.max_inline_chars;\n return out;\n}\n\n/**\n * The person's rule for one key on one surface: `_default[key]` merged per\n * field under `rows[surfaceKey][key]`, invalid fields stripped. `null` when\n * nothing valid is saved.\n */\nexport function lookupSavedRule(\n rows: SavedContextRuleRows | null | undefined,\n surfaceKey: string,\n key: string,\n): SavedContextRule | null {\n if (!rows || typeof rows !== \"object\") return null;\n const base = sanitizeRule(rows[DEFAULT_SURFACE_KEY]?.[key]);\n const own = surfaceKey === DEFAULT_SURFACE_KEY ? {} : sanitizeRule(rows[surfaceKey]?.[key]);\n const merged: SavedContextRule = { ...base, ...own };\n return Object.keys(merged).length === 0 ? null : merged;\n}\n\n/**\n * The person's rule for one key, drift-proof (identical to aidream's\n * `lookup_user_rule_for`). While a primary surface P is in play, every key\n * filed under `_default` OR under P resolves to the same per-field merge\n * `{ ..._default[key], ...rows[P][key] }` (P wins) — whichever surface the\n * client's or the server's manifest says \"declares\" the key. A code manifest\n * and the DB manifest can disagree (sync drift); this makes the person's rule\n * land the same on both sides anyway. A surroundings key (any other surface)\n * keeps its own surface: `{ ..._default[key], ...rows[surfaceKey][key] }`.\n * With no primary surface this is exactly `lookupSavedRule`.\n *\n * Saving is unchanged: page values save to P, everything else to `_default`.\n */\nexport function lookupSavedRuleFor(\n rows: SavedContextRuleRows | null | undefined,\n primarySurface: string | null | undefined,\n surfaceKey: string,\n key: string,\n): SavedContextRule | null {\n const primary = primarySurface && primarySurface !== DEFAULT_SURFACE_KEY ? primarySurface : null;\n if (primary && (surfaceKey === DEFAULT_SURFACE_KEY || surfaceKey === primary)) {\n return lookupSavedRule(rows, primary, key);\n }\n return lookupSavedRule(rows, surfaceKey, key);\n}\n\n// ── serverDefaultMax — the server's per-key default, read from the wire value ─\n\n/**\n * The keys that make a dict the rich envelope form — exactly aidream\n * `context_objects._RICH_FORM_KEYS`. A dict with ANY other key is raw content\n * on the server, `content` key or not.\n */\nexport const RICH_ENVELOPE_KEYS: ReadonlySet<string> = new Set([\n \"content\",\n \"mutable\",\n \"persist\",\n \"source\",\n \"type\",\n \"label\",\n \"description\",\n \"max_inline_chars\",\n \"default_max_inline_chars\",\n \"summary_agent_id\",\n]);\n\n/**\n * A UUID as the server's `_uuid` (Python `UUID(value.strip())`) accepts it:\n * hyphens optional, `{…}` braces and `urn:uuid:` prefixes allowed.\n */\nfunction isUuidLike(value: string): boolean {\n const hex = value\n .trim()\n .replace(/urn:/gi, \"\")\n .replace(/uuid:/gi, \"\")\n .replace(/^\\{+|\\}+$/g, \"\")\n .replace(/-/g, \"\");\n return /^[0-9a-f]{32}$/i.test(hex);\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/** A canonical resource reference the server promotes (aidream `parse_resource_reference`). */\nfunction isResourceRef(v: Record<string, unknown>): boolean {\n if (v.__kind !== \"resource_ref\") return false;\n const type = v.resource_type || v.type;\n const id = v.resource_id || v.id;\n return (\n typeof type === \"string\" &&\n type.trim() !== \"\" &&\n typeof id === \"string\" &&\n isUuidLike(id)\n );\n}\n\nfunction hasOwn(o: Record<string, unknown>, k: string): boolean {\n return Object.prototype.hasOwnProperty.call(o, k);\n}\n\nfunction onlyRichKeys(o: Record<string, unknown>): boolean {\n return Object.keys(o).every((k) => RICH_ENVELOPE_KEYS.has(k));\n}\n\nfunction hasLazySource(o: Record<string, unknown>): boolean {\n return isPlainObject(o.source) && typeof o.source.kind === \"string\";\n}\n\n/**\n * A rich envelope exactly as the server reads one (aidream\n * `_split_rich_context_value`): a plain object with its own `content` whose\n * every key is in `RICH_ENVELOPE_KEYS`. A record that merely HAS `content`\n * (a note `{ id, title, content }`) is raw content, not an envelope.\n */\nexport function isRichEnvelope(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value) && hasOwn(value, \"content\") && onlyRichKeys(value);\n}\n\n/** The source-only lazy pointer form: rich keys only, no `content`, a `source` with a `kind`. */\nfunction isLazyPointer(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value) && !hasOwn(value, \"content\") && onlyRichKeys(value) && hasLazySource(value);\n}\n\n/**\n * Split one wire value into `{ content, overrides }` exactly as aidream\n * `_split_rich_context_value`: a rich envelope or lazy pointer → its `content`\n * (null when absent) and every other key; anything else → the whole value as\n * content, no overrides.\n */\nexport function splitContextValue(value: unknown): {\n content: unknown;\n overrides: Record<string, unknown>;\n} {\n if (isRichEnvelope(value) || isLazyPointer(value)) {\n const { content = null, ...overrides } = value;\n return { content, overrides };\n }\n return { content: value, overrides: {} };\n}\n\n/**\n * The server's default inline limit for one wire value — the `default` layer\n * the server will use, before page/agent/you. Mirrors aidream\n * `context_rules._server_default_max` over the object `ContextManifest.build`\n * makes from the value (after `normalize_resource_context`):\n *\n * - a rich envelope (every key in the rich-form set, and `content` present or a\n * lazy `source` with a string `kind`) carrying a whole-number, non-negative\n * `default_max_inline_chars` → that;\n * - a top-level resource reference (`__kind: \"resource_ref\"` with a type and a\n * UUID id), or a lazy source whose `extra.resource_type` is set → 0\n * (descriptor-first);\n * - a lazy source (a `source` and null/absent `content`) → 6000;\n * - anything else → null (the server's 200).\n *\n * A resource reference nested as an envelope's `content` is NOT promoted by the\n * server (it reads top-level values only), so it is plain JSON content → null.\n */\nexport function serverDefaultMax(value: unknown): number | null {\n if (!isPlainObject(value)) return null;\n if (isResourceRef(value)) return 0;\n if (!isRichEnvelope(value) && !isLazyPointer(value)) return null;\n if (isValidLimit(value.default_max_inline_chars)) return value.default_max_inline_chars;\n if (hasLazySource(value) && (value.content === null || value.content === undefined)) {\n const src = value.source as Record<string, unknown>;\n const extra = isPlainObject(src.extra) ? src.extra : {};\n return extra.resource_type ? 0 : LAZY_SOURCE_DEFAULT_MAX;\n }\n return null;\n}\n\n// ── resolveContextRow — the glue a client runs per value ────────────────────\n\n/** Resolve one value into the row the table renders and the wire sends. */\nexport function resolveContextRow(\n source: ContextRowSource,\n savedRows: SavedContextRuleRows | null | undefined,\n cap: number = DEFAULT_INLINE_CAP,\n /** The page in play; makes the rule lookup drift-proof (`lookupSavedRuleFor`). */\n primarySurface?: string | null,\n): ResolvedContextRow {\n const surfaceKey = source.surfaceKey ?? DEFAULT_SURFACE_KEY;\n const serverResolved = isServerResolved(source.key, source.value);\n const chars = serverResolved\n ? null\n : source.chars !== undefined\n ? source.chars\n : unresolvedSize(source.value)\n ? null\n : contextValueChars(splitContextValue(source.value).content);\n const userRule = lookupSavedRuleFor(savedRows, primarySurface, surfaceKey, source.key);\n const layers: ContextRuleLayers = { ...(source.layers ?? {}) };\n if (!serverResolved && (layers.default_max === undefined || layers.default_max === null)) {\n const serverDefault = serverDefaultMax(source.value);\n if (serverDefault !== null) layers.default_max = serverDefault;\n }\n // Identity is decided as the server decides its own statement of it (RULES.md §5a): only the\n // person's rule closes it — never the page switch or the agent's / mandate's kill switch.\n const identity = isServerAuthoritativeKey(source.key);\n const result = resolveContextRule({ ...layers, chars, user: userRule, cap, identity });\n const row: ResolvedContextRow = {\n ...result,\n delivery: serverResolved && result.include ? \"server\" : result.delivery,\n key: source.key,\n label: source.label,\n surfaceKey,\n origin: source.origin,\n value: source.value,\n chars,\n userRule,\n };\n if (source.description !== undefined) row.description = source.description;\n if (source.type !== undefined) row.type = source.type;\n if (source.layers !== undefined || layers.default_max !== undefined) row.layers = layers;\n if (serverResolved) row.serverResolved = true;\n return row;\n}\n\n// ── buildContextWire — the ONLY producer of a request's `context` ──────────\n\n/**\n * Size the server cannot know yet: a lazy pointer (or an envelope with a lazy\n * source and null content), or a resource reference it will promote to one.\n */\nfunction unresolvedSize(value: unknown): boolean {\n if (!isPlainObject(value)) return false;\n if (isResourceRef(value)) return true;\n return (\n (isRichEnvelope(value) || isLazyPointer(value)) &&\n hasLazySource(value) &&\n (value.content === null || value.content === undefined)\n );\n}\n\nconst KIND_RESOURCE_REF = \"resource_ref\";\n\n/**\n * Values the server acts on by their top-level shape in `request.context`\n * (aidream `normalize_resource_context` → `parse_resource_reference`, which\n * reads ONLY top-level values):\n *\n * - a resource reference — any object whose `__kind` is `\"resource_ref\"`\n * (its own promote/exclude/overlay policy rides inside it);\n * - a bare UUID string under a conventional `*_id` key (`file_id`,\n * `attached_file_id`, `current_note_id`, …), which the server promotes when\n * the noun is a registered resource type. The registry lives on the server,\n * so every `*_id` key with a UUID passes through; for an unregistered noun\n * the server reads the bare string exactly as it would read it wrapped;\n * - a reserved key the server consumes by shape (`RESERVED_CONSUMED_KEYS`:\n * `surface_chain`, `window_forms`, `__table_access`, `__google_files`) —\n * wrapped, the server reads `{content, label}` instead of its list or grant\n * and drops it.\n *\n * These ship exactly as-is: no label, type, description or limit added.\n */\nexport function isWireDirective(key: string, value: unknown): boolean {\n if (Object.hasOwn(RESERVED_CONSUMED_KEYS, key)) return true;\n if (isPlainObject(value)) return value.__kind === KIND_RESOURCE_REF;\n return (\n typeof value === \"string\" &&\n isIdKey(key) &&\n isUuidLike(value)\n );\n}\n\n/** The server's key rule for promoting a bare id (`_resource_type_for_key`): a `*_id` key. */\nfunction isIdKey(key: string): boolean {\n return key.trim().toLowerCase().endsWith(\"_id\");\n}\n\n/**\n * A value whose size, default limit and delivery the SERVER decides by\n * resolving it — so the client must not predict them:\n *\n * - a top-level resource reference (`__kind: \"resource_ref\"`), bare or as a\n * rich envelope's `content`;\n * - a UUID string under a `*_id` key, bare or as a rich envelope's `content`.\n *\n * The server only promotes an id when its noun is in the resource registry\n * (aidream `_resource_type_for_key`), which the client cannot see, so every\n * `*_id` UUID counts. This is a deliberate superset: on a value the server\n * does not promote, the client only stops predicting — it never makes a wrong\n * promise.\n */\nexport function isServerResolved(key: string, value: unknown): boolean {\n const inner = isRichEnvelope(value) ? value.content : value;\n if (isPlainObject(inner)) return inner.__kind === KIND_RESOURCE_REF;\n return typeof inner === \"string\" && isIdKey(key) && isUuidLike(inner);\n}\n\n/**\n * Build the request's `context` object from the resolved rows. This is the\n * ONLY function that may produce it, so what the table shows and what the\n * request carries cannot drift apart.\n *\n * - A row whose `include` is false is omitted entirely — it never reaches the\n * wire (RULES.md §1: off means off everywhere).\n * - An included row becomes `{ content, type?, label, description?,\n * max_inline_chars? }`. An already-rich envelope (`isRichEnvelope`, e.g. a\n * working document carrying `source`/`mutable`/`persist`, or a lazy pointer)\n * keeps every non-rule field it already has; `label`/`description`/`type`\n * are only filled when missing.\n * - `max_inline_chars` on the envelope is the PAGE layer's value only\n * (`layers.surface.max_inline_chars`, else the envelope's own page value).\n * The server reads the person's saved rules itself every turn (RULES.md §3)\n * and the agent layer from its own policy, so the wire must never carry the\n * person's number or the resolved effective limit dressed up as a page rule\n * — that would make a stale client value outrank the server's fresh read.\n */\nexport function buildContextWire(rows: readonly ResolvedContextRow[]): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n for (const row of rows) {\n if (!row.include) continue;\n // A row with no value (a receipt-built display row) has nothing to send.\n if (row.value === undefined) continue;\n // Rich: an envelope with `content`, or a source-only lazy pointer. Every\n // non-rule field survives — including `default_max_inline_chars`, the\n // server's per-key default (not a person's or a page's number).\n // A record that merely has `content` is NOT rich: it is wrapped whole, or\n // the server would read it as raw content and drop the envelope fields.\n // A top-level directive the server acts on by SHAPE ships exactly as-is:\n // wrapped, it becomes plain JSON and silently stops resolving.\n if (isWireDirective(row.key, row.value)) {\n wire[row.key] = row.value;\n continue;\n }\n const rich = isRichEnvelope(row.value) || isLazyPointer(row.value);\n const envelope: Record<string, unknown> = rich\n ? { ...(row.value as Record<string, unknown>) }\n : { content: row.value };\n delete envelope.max_inline_chars;\n if (envelope.type === undefined && row.type !== undefined) envelope.type = row.type;\n if (envelope.label === undefined) envelope.label = row.label;\n if (envelope.description === undefined && row.description !== undefined) {\n envelope.description = row.description;\n }\n const pageLimit = row.layers?.surface?.max_inline_chars;\n const ownPageLimit = rich ? (row.value as Record<string, unknown>).max_inline_chars : undefined;\n if (isValidLimit(pageLimit)) envelope.max_inline_chars = pageLimit;\n else if (isValidLimit(ownPageLimit)) envelope.max_inline_chars = ownPageLimit;\n wire[row.key] = envelope;\n }\n return wire;\n}\n\n// ── compareReceipt — RULES.md §6 ────────────────────────────────────────────\n\nexport interface ContextReceiptMismatch {\n key: string;\n field: \"include\" | \"max_inline_chars\" | \"delivery\" | \"user_rule\" | \"missing\";\n expected: unknown;\n actual: unknown;\n /**\n * `\"self_check\"`: a real difference from what was shown — the server's\n * safety check stripped the value before the model call. Say \"removed by\n * the server's safety check\", not \"the screen was wrong\".\n */\n reason?: \"self_check\";\n}\n\nfunction normalizeUserRule(rule: SavedContextRule | null | undefined): SavedContextRule | null {\n const clean = sanitizeRule(rule);\n return Object.keys(clean).length === 0 ? null : clean;\n}\n\nfunction sameRule(a: SavedContextRule | null, b: SavedContextRule | null): boolean {\n if (a === null || b === null) return a === b;\n return a.include === b.include && a.max_inline_chars === b.max_inline_chars;\n}\n\n/**\n * Compare the rows the client resolved (and rendered, and sent) with the\n * receipt the server emitted for the same turn.\n *\n * For each expected row, the receipt row is matched by key + surface key, then\n * by key alone. Compared: `include`, `max_inline_chars`, `delivery` (only when\n * both sides know the size) and `user_rule`. An expected row absent from the\n * receipt is a `missing` mismatch — except a row the client correctly withheld\n * for a reason other than the person's own rule (page `auto_context` off, the\n * agent's kill switch): the client never sent it and the server lists only\n * the person's saved `include: false` rules as `origin: \"rule\"` rows, so its\n * absence is the truth, not a lie. Receipt rows nobody expected are returned\n * as `systemRows` — shown, never hidden. A row the server consumed\n * (`consumed_as`: expanded / directive / renamed) is compared on `include`\n * and `user_rule` only — its parts carry their own rows; an `\"unaccounted\"`\n * row, or an included envelope `\"expanded\"` into no parts, is a `missing`\n * mismatch.\n */\nexport function compareReceipt(\n expected: readonly ResolvedContextRow[],\n receipt: ContextReceipt,\n): { mismatches: ContextReceiptMismatch[]; systemRows: ContextReceiptRow[]; modelReadsContext: boolean } {\n const mismatches: ContextReceiptMismatch[] = [];\n // A turn whose model reads no context delivers nothing by design: every row\n // is `delivery: \"off\"`, `blocked_by: \"model\"`. That is not a lie about the\n // person's rules, so delivery is not compared; include / limit / rule still are.\n const modelReadsContext = receipt.model_reads_context !== false;\n const used = new Set<ContextReceiptRow>();\n const rows = receipt.rows ?? [];\n\n for (const exp of expected) {\n const actual =\n rows.find((r) => !used.has(r) && r.key === exp.key && r.surface_key === exp.surfaceKey) ??\n rows.find((r) => !used.has(r) && r.key === exp.key);\n if (!actual) {\n const withheldByOthers = !exp.include && exp.decided_by.include !== \"you\";\n if (!withheldByOthers) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: null });\n }\n continue;\n }\n used.add(actual);\n if (actual.include !== exp.include) {\n mismatches.push({ key: exp.key, field: \"include\", expected: exp.include, actual: actual.include });\n }\n // A consumed value (expanded / directive / renamed) was not delivered as\n // itself: its parts carry their own rows, limits and deliveries. Only\n // include and the person's rule are this key's own promise.\n const consumed = Boolean(actual.consumed_as);\n // A server path removed the value with no reason: kept as a row so it is\n // never silently missing, and still a broken promise on this screen.\n if (actual.consumed_as === \"unaccounted\" && exp.include) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: \"unaccounted\" });\n }\n // An envelope the screen showed as sent that the server expanded into no\n // parts delivered nothing (a window whose fields were all unreadable):\n // \"expanded\" alone would pass it silently.\n if (\n actual.consumed_as === \"expanded\" &&\n actual.include &&\n exp.include &&\n (actual.consumed_into ?? []).length === 0\n ) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: \"expanded_into_nothing\" });\n }\n // A server-resolved value's limit is only the client's to promise when the\n // person set one; its default-derived limit and delivery are the server's.\n const promisesLimit =\n !consumed && (!exp.serverResolved || exp.userRule?.max_inline_chars !== undefined);\n if (promisesLimit && actual.max_inline_chars !== exp.max_inline_chars) {\n mismatches.push({\n key: exp.key,\n field: \"max_inline_chars\",\n expected: exp.max_inline_chars,\n actual: actual.max_inline_chars,\n });\n }\n // The safety check stripped a value the person included: always a\n // mismatch (server-resolved or not), tagged with its reason.\n const selfChecked = actual.blocked_by === \"self_check\" && exp.include;\n if (selfChecked) {\n mismatches.push({\n key: exp.key,\n field: \"delivery\",\n expected: exp.delivery,\n actual: actual.delivery,\n reason: \"self_check\",\n });\n }\n if (\n !selfChecked &&\n !consumed &&\n modelReadsContext &&\n !exp.serverResolved &&\n exp.delivery !== \"server\" &&\n exp.chars !== null &&\n actual.chars !== null &&\n actual.delivery !== exp.delivery\n ) {\n mismatches.push({ key: exp.key, field: \"delivery\", expected: exp.delivery, actual: actual.delivery });\n }\n const expRule = normalizeUserRule(exp.userRule);\n const actRule = normalizeUserRule(actual.user_rule);\n if (!sameRule(expRule, actRule)) {\n mismatches.push({ key: exp.key, field: \"user_rule\", expected: expRule, actual: actRule });\n }\n }\n\n return { mismatches, systemRows: rows.filter((r) => !used.has(r)), modelReadsContext };\n}\n\n/**\n * For DISPLAY only: fill each server-resolved row's `chars`,\n * `max_inline_chars` and `delivery` from the latest receipt row for the same\n * key (key + surface key, then key), marking it `fromReceipt`. Other rows are\n * returned unchanged. Never compare these rows — `compareReceipt` takes the\n * rows the client resolved before sending.\n */\nexport function applyReceiptToRows(\n rows: readonly ResolvedContextRow[],\n receipt: ContextReceipt | null | undefined,\n): ResolvedContextRow[] {\n const receiptRows = receipt?.rows ?? [];\n return rows.map((row) => {\n const hit =\n receiptRows.find((r) => r.key === row.key && r.surface_key === row.surfaceKey) ??\n receiptRows.find((r) => r.key === row.key);\n if (!hit) return row;\n // What the model read is the server's to report for EVERY value — a value the\n // server replaced or reshaped must never show as the client's copy. A value the\n // server states itself (RULES.md §5a) is measured by what it stated, never by\n // the page's copy.\n const attached = blocksForRow(row.key, receipt?.blocks);\n const stated =\n hit.delivered && isServerAuthoritativeKey(row.key)\n ? hit.delivered.chars + attached.reduce((n, b) => n + b.delivered.chars, 0)\n : null;\n const shown = {\n ...row,\n ...deliveredFields(hit),\n ...(stated !== null ? { chars: stated } : {}),\n ...(attached.length ? { deliveredBlocks: attached } : {}),\n };\n if (!row.serverResolved) return shown;\n return {\n ...shown,\n chars: stated ?? hit.chars,\n max_inline_chars: hit.max_inline_chars,\n delivery: hit.delivery,\n fromReceipt: true,\n ...(hit.blocked_by ? { blockedBy: hit.blocked_by } : {}),\n };\n });\n}\n\n// ── receiptRowToResolved — read-only rows for a sent message ────────────────\n\n/**\n * Turn one receipt row into the row a read-only table renders (a sent\n * message's context, read back from `chat.message.model_context`). The value\n * itself is not in the receipt, so `value` is undefined.\n */\nexport function receiptRowToResolved(\n row: ContextReceiptRow,\n blocks?: readonly ContextReceiptBlock[] | null,\n): ResolvedContextRow {\n const attached = row.delivered ? blocksForRow(row.key, blocks) : [];\n const origin: ContextRowOrigin =\n row.surface_key !== DEFAULT_SURFACE_KEY ? \"page\" : row.origin === \"client\" ? \"attached\" : \"system\";\n return {\n key: row.key,\n label: row.label,\n surfaceKey: row.surface_key,\n origin,\n value: undefined,\n chars:\n row.delivered && isServerAuthoritativeKey(row.key)\n ? row.delivered.chars + attached.reduce((n, b) => n + b.delivered.chars, 0)\n : row.chars,\n userRule: normalizeUserRule(row.user_rule),\n include: row.include,\n max_inline_chars: row.max_inline_chars,\n delivery: row.delivery,\n decided_by: { include: row.decided_by.include, max_inline_chars: row.decided_by.max_inline_chars },\n clamped: row.clamped,\n layers: receiptLayers(row),\n ...(row.blocked_by ? { blockedBy: row.blocked_by } : {}),\n ...deliveredFields(row),\n ...(attached.length ? { deliveredBlocks: attached } : {}),\n };\n}\n\n/** A receipt row's `delivered` / `on_request` as display fields (absent when not sent). */\nexport function deliveredFields(\n row: Pick<ContextReceiptRow, \"delivered\" | \"on_request\">,\n): Pick<ResolvedContextRow, \"delivered\" | \"onRequest\"> {\n return {\n ...(row.delivered ? { delivered: row.delivered } : {}),\n ...(row.on_request ? { onRequest: row.on_request } : {}),\n };\n}\n\n/**\n * Rebuild the non-person layers from what the server applied, so a read-only\n * table shows the applied limit as the inherited value and marks the layer\n * that decided it. The limit goes on the layer named by\n * `decided_by.max_inline_chars` (`you` is carried by `userRule`); include is\n * rebuilt the same way for a page `auto_context` off or the agent's kill switch.\n */\n/**\n * Keys the client has a value for but is NOT sending this turn (excluded by\n * the page, the agent or the person's rule). Clients send this list as the\n * request's `context_withheld`, so the receipt's `origin: \"rule\"` rows are\n * limited to keys actually withheld on this page. Deduplicated, in row order.\n */\nexport function withheldKeys(rows: readonly ResolvedContextRow[]): string[] {\n const out: string[] = [];\n for (const row of rows) {\n if (row.include || row.value === undefined || out.includes(row.key)) continue;\n out.push(row.key);\n }\n return out;\n}\n\nconst DOCUMENT_KEY_PREFIXES = [\"attached_document_\", \"attached_file_\", \"resource_file_\"];\n\n/**\n * Receipt rows the client never sent (`compareReceipt(...).systemRows`:\n * server-seeded attachments, scope seeds, saved off-rules…) as table rows, so\n * a person can see and govern them — the normal Include switch and Inline max\n * apply. Documents (`attached_document_*`, `attached_file_*`,\n * `resource_file_*`) group as \"attached\", everything else as \"system\". The\n * server resolved them (`serverResolved`), values come from the receipt\n * (`fromReceipt`), and `surfaceKey` is the row's own `surface_key` — so a rule\n * saved for one writes to `_default` unless the server filed it under a page.\n * `value` is undefined: `buildContextWire` never sends these rows.\n */\nexport function systemRowsToResolved(systemRows: readonly ContextReceiptRow[]): ResolvedContextRow[] {\n return systemRows.map((receiptRow) => {\n const row = receiptRowToResolved(receiptRow);\n const isDocument = DOCUMENT_KEY_PREFIXES.some((p) => receiptRow.key.startsWith(p));\n return {\n ...row,\n origin: isDocument ? \"attached\" : \"system\",\n serverResolved: true,\n fromReceipt: true,\n };\n });\n}\n\nfunction receiptLayers(row: ContextReceiptRow): ContextRuleLayers {\n const layers: ContextRuleLayers = {};\n const limit = row.max_inline_chars;\n const limitBy = row.decided_by.max_inline_chars;\n const includeBy = row.decided_by.include;\n if (limitBy === \"default\") layers.default_max = limit;\n // Page auto_context off: the page dropped it, or the agent re-admitted it.\n const pageOff = (includeBy === \"page\" && !row.include) || (includeBy === \"agent\" && row.include);\n if (limitBy === \"page\" || pageOff) {\n layers.surface = {\n declared: true,\n auto_context: !pageOff,\n max_inline_chars: limitBy === \"page\" ? limit : null,\n };\n }\n if (limitBy === \"agent\") {\n // An agent limit means the key is declared; a declared key the agent decided to include\n // was re-admitted past a page auto_context off. (The kill switch never closes a declared key.)\n layers.agent = { declared: true, max_inline_chars: limit };\n } else if (includeBy === \"agent\") {\n // Off = the kill switch closing an undeclared key; on = a declaration re-admitting a\n // page auto_context-off value.\n layers.agent = row.include ? { declared: true } : { declared: false, kill_switch: true };\n }\n return layers;\n}\n\n// ── attachmentContextKey — the context key of a conversation attachment ─────\n\n/**\n * The context key the server files a conversation attachment under, derivable\n * by every client from `GET /conversations/{id}/attachments` (aidream\n * `conversation_attachments/briefing.py`; corpus `attachment_key_cases`):\n *\n * `attached_resource_` + encode(`${provider}:${resourceRef}`)\n *\n * where encode keeps ASCII letters, digits and `-`, and writes every other\n * UTF-8 byte as `_` + two lowercase hex digits (`_` itself is `_5f`). Unique\n * across providers, case-preserving (Drive ids), stable.\n */\nexport function attachmentContextKey(provider: string, resourceRef: string): string {\n const bytes = new TextEncoder().encode(`${provider}:${resourceRef}`);\n let out = \"attached_resource_\";\n for (const b of bytes) {\n const keep =\n (b >= 0x30 && b <= 0x39) || (b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a) || b === 0x2d;\n out += keep ? String.fromCharCode(b) : `_${b.toString(16).padStart(2, \"0\")}`;\n }\n return out;\n}\n\n// ── Display ─────────────────────────────────────────────────────────────────\n\n/** Compact size for a tabular column: `950`, `18.4k`, `184k`, `1.2M`, `—` for unknown. */\nexport function formatChars(n: number | null | undefined): string {\n if (n === null || n === undefined || !Number.isFinite(n)) return \"—\";\n const abs = Math.abs(n);\n const trim = (s: string) => s.replace(/\\.0$/, \"\");\n if (abs < 1000) return String(Math.round(n));\n if (abs < 100_000) return `${trim((n / 1000).toFixed(1))}k`;\n if (abs < 1_000_000) return `${Math.round(n / 1000)}k`;\n return `${trim((n / 1_000_000).toFixed(1))}M`;\n}\n\n// RULES.md §0 — what a page's own conversation (or a switched-off page) never receives.\nexport * from \"./page-context\";\n","/**\n * Inlined Lucide shapes (C19 — no icon-library dependency): same 24×24 grid,\n * 2px stroke, `currentColor` only. Names match the Lucide originals.\n */\nimport type { ReactNode, SVGProps } from \"react\";\n\nexport type ContextIconProps = SVGProps<SVGSVGElement>;\n\nfunction icon(children: ReactNode) {\n return function Icon(props: ContextIconProps) {\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 {...props}\n >\n {children}\n </svg>\n );\n };\n}\n\nexport const EyeIcon = icon(\n <>\n <path d=\"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </>,\n);\nexport const EyeOffIcon = icon(\n <>\n <path d=\"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49\" />\n <path d=\"M14.084 14.158a3 3 0 0 1-4.242-4.242\" />\n <path d=\"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143\" />\n <path d=\"m2 2 20 20\" />\n </>,\n);\nexport const RotateCcwIcon = icon(\n <>\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n </>,\n);\nexport const PanelRightIcon = icon(\n <>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </>,\n);\nexport const ChevronLeftIcon = icon(<path d=\"m15 18-6-6 6-6\" />);\nexport const TriangleAlertIcon = icon(\n <>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </>,\n);\nexport const SearchIcon = icon(\n <>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </>,\n);\n/** \"On request\" — the agent pulls the value down when it needs it. */\nexport const ArrowDownToLineIcon = icon(\n <>\n <path d=\"M12 17V3\" />\n <path d=\"m6 11 6 6 6-6\" />\n <path d=\"M19 21H5\" />\n </>,\n);\n\nexport const LockIcon = icon(\n <>\n <rect width=\"18\" height=\"11\" x=\"3\" y=\"11\" rx=\"2\" ry=\"2\" />\n <path d=\"M7 11V7a5 5 0 0 1 10 0v4\" />\n </>,\n);\n\nexport const CheckIcon = icon(<path d=\"M20 6 9 17l-5-5\" />);\n\nexport const MinusIcon = icon(<path d=\"M5 12h14\" />);\n","/**\n * THE HIERARCHY of the context rules table — where each value sits, and the\n * switch at every level (Arman, 2026-10-02: \"AI Matrx\" for the platform's own\n * values; the page by its section and real name; under it the page's own\n * declared groups; a switch per level).\n *\n * The package never knows a page's groups: the host PLACES each row (level +\n * group, both already-human labels) and may give a level a host switch (the\n * page's own on/off). Without a host placement every row is placed by its\n * origin. A level or group switch is NOT a new kind of rule: it is the\n * person's per-value include rules for every value in it, written at once\n * (`includeChanges`), so the server's gate and receipt see exactly the rules\n * they already honour.\n */\n\nimport {\n isServerAuthoritativeKey,\n resolveContextRule,\n type ContextRowOrigin,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\n\n/** A level of the table: the platform, a page, the chat's attachments. */\nexport interface ContextLevelRef {\n /** Stable id (a surface key, `ai_matrx`, `attached`). */\n id: string;\n /** Heading, root first: `[\"Marketing\", \"Marketing Brand Cockpit\"]`, `[\"AI Matrx\"]`. */\n path: readonly string[];\n /** Sort order between levels (lower first). */\n order?: number;\n}\n\n/** A group inside a level — the page's own declared group, label as declared. */\nexport interface ContextGroupRef {\n id: string;\n label: string;\n order?: number;\n}\n\n/** Where one row sits. */\nexport interface ContextRowPlace {\n level: ContextLevelRef;\n /** Null: directly under the level. */\n group?: ContextGroupRef | null;\n}\n\n/**\n * A level whose switch is the host's own (the page on/off for this\n * conversation) rather than the person's per-value rules. Shown even when the\n * level has no rows, so the switch never disappears with its values.\n */\nexport interface ContextLevelMaster {\n level: ContextLevelRef;\n on: boolean;\n onToggle?: ((next: boolean) => void) | undefined;\n}\n\nexport interface ContextHierarchy {\n place: (row: ResolvedContextRow) => ContextRowPlace;\n masters?: readonly ContextLevelMaster[];\n}\n\nexport interface ContextGroupNode {\n ref: ContextGroupRef;\n rows: ResolvedContextRow[];\n}\n\nexport interface ContextLevelNode {\n ref: ContextLevelRef;\n /** Rows directly under the level (no group). */\n rows: ResolvedContextRow[];\n groups: ContextGroupNode[];\n master: ContextLevelMaster | null;\n}\n\n/** The platform's own values: the person, their organization, the client. */\nexport const AI_MATRX_LEVEL: ContextLevelRef = { id: \"ai_matrx\", path: [\"AI Matrx\"], order: 900 };\n/** Files and documents attached to the conversation. */\nexport const ATTACHED_LEVEL: ContextLevelRef = { id: \"attached\", path: [\"Attached\"], order: 500 };\n/** A page the host has not named. */\nexport const PAGE_LEVEL: ContextLevelRef = { id: \"page\", path: [\"Page\"], order: 100 };\n\nconst ORIGIN_LEVEL: Record<ContextRowOrigin, ContextLevelRef> = {\n page: PAGE_LEVEL,\n attached: ATTACHED_LEVEL,\n system: AI_MATRX_LEVEL,\n};\n\n/** The placement a host without one gets: by origin. */\nexport function placeByOrigin(row: ResolvedContextRow): ContextRowPlace {\n return { level: ORIGIN_LEVEL[row.origin] };\n}\n\n/** Sort by `order`, keeping first-seen order among equals. */\nfunction stableSort<T>(list: readonly T[], ref: (item: T) => { order?: number }): T[] {\n return list\n .map((item, i) => ({ item, i }))\n .sort((a, b) => (ref(a.item).order ?? 0) - (ref(b.item).order ?? 0) || a.i - b.i)\n .map(({ item }) => item);\n}\n\n/** Rows → levels → groups, in the host's order (stable within equal orders). */\nexport function buildContextLevels(\n rows: readonly ResolvedContextRow[],\n hierarchy?: ContextHierarchy | null,\n): ContextLevelNode[] {\n const place = hierarchy?.place ?? placeByOrigin;\n const levels = new Map<string, ContextLevelNode>();\n const levelFor = (ref: ContextLevelRef) => {\n let node = levels.get(ref.id);\n if (!node) {\n node = { ref, rows: [], groups: [], master: null };\n levels.set(ref.id, node);\n }\n return node;\n };\n for (const master of hierarchy?.masters ?? []) levelFor(master.level).master = master;\n for (const row of rows) {\n const where = place(row);\n const level = levelFor(where.level);\n if (!where.group) {\n level.rows.push(row);\n continue;\n }\n let group = level.groups.find((g) => g.ref.id === where.group!.id);\n if (!group) {\n group = { ref: where.group, rows: [] };\n level.groups.push(group);\n }\n group.rows.push(row);\n }\n const out = [...levels.values()];\n for (const level of out) level.groups = stableSort(level.groups, (g) => g.ref);\n return stableSort(out, (level) => level.ref);\n}\n\n/** Every row of a level, groups included. */\nexport function levelRows(level: ContextLevelNode): ResolvedContextRow[] {\n return [...level.rows, ...level.groups.flatMap((g) => g.rows)];\n}\n\n/** What the row's include would be with no rule of the person's. */\nexport function inheritedInclude(row: ResolvedContextRow, cap: number): boolean {\n return resolveContextRule({\n ...(row.layers ?? {}),\n chars: row.chars,\n cap,\n user: null,\n identity: isServerAuthoritativeKey(row.key),\n }).include;\n}\n\n/** One person-rule write: `rule: null` removes the person's rule for that value. */\nexport interface ContextRuleChange {\n key: string;\n surfaceKey: string;\n rule: SavedContextRule | null;\n}\n\n/**\n * A level or group switch: the person's include rule for every value in it\n * that is not already `include`. A value whose default already gives\n * `include` loses its own include rule instead (back to the default) — the\n * saved rules stay minimal and \"Reset all\" means what it says.\n */\nexport function includeChanges(\n rows: readonly ResolvedContextRow[],\n include: boolean,\n cap: number,\n): ContextRuleChange[] {\n const changes: ContextRuleChange[] = [];\n for (const row of rows) {\n if (row.include === include) continue;\n const next: SavedContextRule = { ...(row.userRule ?? {}) };\n if (inheritedInclude(row, cap) === include) delete next.include;\n else next.include = include;\n changes.push({\n key: row.key,\n surfaceKey: row.surfaceKey,\n rule: Object.keys(next).length === 0 ? null : next,\n });\n }\n return changes;\n}\n","import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, cn } from \"@ai-matrx/design-system\";\n\nimport { CheckIcon, LockIcon, MinusIcon } from \"./icons\";\n\n/** Tooltip on a frozen include state (a sent turn's receipt). ≤140 chars. */\nexport const FROZEN_INCLUDE_TOOLTIP = \"Sent as shown\";\n\n/**\n * A sent message's include state, frozen: a static on/off mark with a lock —\n * never a switch, so nothing on a receipt looks clickable.\n */\nexport function FrozenInclude({ name, checked }: { name: string; checked: boolean }) {\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <Tooltip>\n <TooltipTrigger asChild>\n <span\n role=\"img\"\n aria-label={`${checked ? \"Included\" : \"Not included\"}: ${name}`}\n data-frozen-include={checked ? \"on\" : \"off\"}\n tabIndex={0}\n className={cn(\n \"inline-flex h-5 items-center gap-0.5 rounded px-1 text-muted-foreground\",\n checked ? \"bg-muted text-foreground\" : \"bg-transparent\",\n )}\n >\n {checked ? <CheckIcon className=\"h-3 w-3\" /> : <MinusIcon className=\"h-3 w-3\" />}\n <LockIcon className=\"h-2.5 w-2.5 opacity-70\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{FROZEN_INCLUDE_TOOLTIP}</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport {\n Input,\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport { RotateCcwIcon } from \"./icons\";\nimport { formatLimit } from \"./shared\";\n\nexport interface InlineMaxInputProps {\n /** The person's own limit, or null when inherited. */\n value: number | null;\n /** What applies without the person's number (shown muted). */\n inherited: number;\n /** Override the muted text shown when the person set no number (e.g. \"auto\"). */\n placeholder?: string | undefined;\n cap: number;\n /** Next limit, or null to drop the person's number. */\n onCommit: (next: number | null) => void;\n disabled?: boolean | undefined;\n /** Accessible name — the row's label. */\n label: string;\n comfortable?: boolean;\n}\n\n/**\n * The Inline max cell: a 6ch numeric field. Inherited value shows as muted\n * placeholder text; an override shows a dot and a reset button. `0` reads\n * \"Never\". Commits on blur/Enter, Escape reverts, above-cap is clamped on\n * commit with a brief \"Limit is {cap}\" tooltip.\n */\nexport function InlineMaxInput({\n value,\n inherited,\n cap,\n onCommit,\n disabled,\n label,\n comfortable,\n placeholder,\n}: InlineMaxInputProps) {\n const [focused, setFocused] = React.useState(false);\n const [draft, setDraft] = React.useState(\"\");\n const [notice, setNotice] = React.useState(false);\n const skip = React.useRef(false);\n\n React.useEffect(() => {\n if (!notice) return;\n const t = setTimeout(() => setNotice(false), 2000);\n return () => clearTimeout(t);\n }, [notice]);\n\n const commit = () => {\n const text = draft.trim();\n let next: number | null;\n if (text === \"\") next = null;\n else if (/^never$/i.test(text)) next = 0;\n else if (/^\\d+$/.test(text)) next = Number(text);\n else return;\n if (next !== null && next > cap) {\n next = cap;\n setNotice(true);\n }\n if (next !== value) onCommit(next);\n };\n\n const overridden = value !== null;\n\n return (\n <div className={cn(\"flex items-center justify-end\", comfortable ? \"gap-0.5\" : \"gap-1\")}>\n <span\n aria-hidden=\"true\"\n className={cn(\"h-1.5 w-1.5 shrink-0 rounded-full\", overridden ? \"bg-primary\" : \"bg-transparent\")}\n />\n <Tooltip open={notice}>\n <TooltipTrigger asChild>\n <Input\n type=\"text\"\n inputMode=\"numeric\"\n aria-label={`Inline max for ${label}`}\n disabled={disabled}\n value={focused ? draft : overridden ? formatLimit(value) : \"\"}\n placeholder={overridden ? undefined : (placeholder ?? formatLimit(inherited))}\n onFocus={() => {\n setDraft(overridden ? String(value) : \"\");\n setFocused(true);\n }}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n setFocused(false);\n if (skip.current) {\n skip.current = false;\n return;\n }\n commit();\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") e.currentTarget.blur();\n else if (e.key === \"Escape\") {\n e.stopPropagation();\n skip.current = true;\n e.currentTarget.blur();\n }\n }}\n className={cn(\n \"min-w-0 rounded px-1 py-0 text-right tabular-nums shadow-none\",\n comfortable ? \"h-8 w-[6.5ch] text-base\" : \"h-6 w-[6.5ch] text-xs\",\n )}\n />\n </TooltipTrigger>\n <TooltipContent>{`Limit is ${cap}`}</TooltipContent>\n </Tooltip>\n {overridden && !disabled ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={`Reset inline max for ${label}`}\n onClick={() => onCommit(null)}\n className={cn(\n \"inline-flex shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground\",\n comfortable ? \"h-8 w-7\" : \"h-5 w-5\",\n )}\n >\n <RotateCcwIcon className=\"h-3 w-3\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>{`Reset to ${formatLimit(inherited)}`}</TooltipContent>\n </Tooltip>\n ) : (\n <span aria-hidden=\"true\" className={cn(\"shrink-0\", comfortable ? \"w-7\" : \"w-5\")} />\n )}\n </div>\n );\n}\n","import {\n resolveContextRule,\n type ContextDelivery,\n type ContextRowDelivery,\n type ContextLayer,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\n\nexport const LAYER_LABEL: Record<ContextLayer, string> = {\n default: \"Default\",\n page: \"Page\",\n agent: \"Agent\",\n you: \"You\",\n};\n\nexport const DELIVERY_LABEL: Record<ContextRowDelivery, string> = {\n inline: \"Inline\",\n on_request: \"On request\",\n off: \"Off\",\n server: \"Server\",\n};\n\nexport const SERVER_RESOLVED_TOOLTIP = \"Resolved by the server\";\nexport const SELF_CHECK_TOOLTIP = \"Removed by the server's safety check\";\n\n/**\n * The Inline max field's muted text when the person set no number: \"auto\" for\n * a server-resolved value (the server picks its limit), the applied limit\n * once a receipt filled it, else the inherited limit.\n */\nexport function limitPlaceholder(row: ResolvedContextRow, cap: number): string {\n if (row.serverResolved && !row.fromReceipt) return \"auto\";\n if (row.fromReceipt) return formatLimit(row.max_inline_chars);\n return formatLimit(inheritedLimit(row, cap));\n}\n\n/** `0` is \"Never\"; anything else is the number as typed. */\nexport function formatLimit(n: number): string {\n return n === 0 ? \"Never\" : String(n);\n}\n\n/** The limit this row would have without the person's own number. */\nexport function inheritedLimit(row: ResolvedContextRow, cap: number): number {\n return resolveContextRule({ ...(row.layers ?? {}), chars: row.chars, cap, user: null })\n .max_inline_chars;\n}\n\nexport function hasOverride(row: ResolvedContextRow): boolean {\n return row.userRule !== null && Object.keys(row.userRule).length > 0;\n}\n\nexport function withInclude(row: ResolvedContextRow, include: boolean): SavedContextRule {\n return { ...(row.userRule ?? {}), include };\n}\n\nexport function withLimit(row: ResolvedContextRow, limit: number | null): SavedContextRule | null {\n const next: SavedContextRule = { ...(row.userRule ?? {}) };\n if (limit === null) delete next.max_inline_chars;\n else next.max_inline_chars = limit;\n return Object.keys(next).length === 0 ? null : next;\n}\n\nexport function rowId(row: ResolvedContextRow): string {\n return `${row.surfaceKey}::${row.key}`;\n}\n\nfunction show(field: ContextReceiptMismatch[\"field\"], v: unknown): string {\n if (v === null || v === undefined) return \"none\";\n if (typeof v === \"boolean\") return v ? \"On\" : \"Off\";\n if (typeof v === \"number\") return formatLimit(v);\n if (field === \"delivery\" || field === \"missing\") {\n return DELIVERY_LABEL[v as ContextDelivery] ?? String(v);\n }\n if (typeof v === \"object\") {\n const r = v as SavedContextRule;\n const parts: string[] = [];\n if (r.include !== undefined) parts.push(r.include ? \"On\" : \"Off\");\n if (r.max_inline_chars !== undefined) parts.push(formatLimit(r.max_inline_chars));\n return parts.join(\", \") || \"none\";\n }\n return String(v);\n}\n\nconst FIELD_LABEL: Record<ContextReceiptMismatch[\"field\"], string> = {\n include: \"Include\",\n max_inline_chars: \"Inline max\",\n delivery: \"Delivery\",\n user_rule: \"Your rule\",\n missing: \"Not sent\",\n};\n\n/** One line per mismatch — \"Inline max: expected 8000, got 200\". Tooltip-sized. */\nexport function describeMismatches(list: readonly ContextReceiptMismatch[]): string {\n const text = list\n .map((m) =>\n m.reason === \"self_check\"\n ? SELF_CHECK_TOOLTIP\n : m.field === \"missing\"\n ? \"Missing from the server's receipt\"\n : `${FIELD_LABEL[m.field]}: expected ${show(m.field, m.expected)}, got ${show(m.field, m.actual)}`,\n )\n .join(\" · \");\n return text.length > 140 ? `${text.slice(0, 139)}…` : text;\n}\n\n/** Tooltip for the \"on request\" marker, by why the value is not inline. */\nexport function onRequestReason(row: ResolvedContextRow): string {\n if (row.chars === null) return \"Size unknown — the agent reads it on request\";\n if (row.max_inline_chars === 0) return \"Never inline — the agent reads it on request\";\n return \"Over the limit — the agent reads it on request\";\n}\n","import { formatChars, type ResolvedContextRow } from \"../index\";\n\n/**\n * The header's \"N · chars\" total. A row whose size is not known yet (an\n * attachment the server has not measured) never counts as 0: with some sizes\n * unknown the total is a floor (\"1.2k+\"), with none known it is \"—\".\n */\nexport function summarizeContextRows(rows: readonly ResolvedContextRow[]) {\n let count = 0;\n let chars = 0;\n let known = 0;\n for (const r of rows) {\n if (!r.include) continue;\n count += 1;\n if (r.chars === null || r.chars === undefined) continue;\n chars += r.chars;\n known += 1;\n }\n const charsLabel =\n count > 0 && known === 0 ? \"—\" : known < count ? `${formatChars(chars)}+` : formatChars(chars);\n return { count, chars, charsLabel };\n}\n","import * as React from \"react\";\nimport {\n BottomSheet,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Switch,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ContextRulesTable } from \"./ContextRulesTable\";\nimport type { ContextHierarchy, ContextRuleChange } from \"./hierarchy\";\nimport { EyeIcon, EyeOffIcon, PanelRightIcon, RotateCcwIcon, TriangleAlertIcon } from \"./icons\";\nimport { hasOverride } from \"./shared\";\nimport { summarizeContextRows } from \"./summary\";\n\nexport { summarizeContextRows };\n\nexport interface ContextRulesChipProps {\n /**\n * The group's own name — \"Notes\", \"Invoice 1042\". Empty or omitted: the chip\n * shows NO text (icon + count only). Never pass a generic word such as\n * \"Context\" here — when there is no real name, there is no label (Arman,\n * 2026-10-01).\n */\n label?: string | null | undefined;\n rows: readonly ResolvedContextRow[];\n cap: number;\n /**\n * Page context on/off (the face's eye). With no `hierarchy`, also the\n * header's master switch; with one, the page's switch is its level's\n * (`hierarchy.masters`) and the header has none.\n */\n on?: boolean | undefined;\n onToggleAll?: ((next: boolean) => void) | undefined;\n /** Levels and groups with a switch each (see `ContextRulesTable`). */\n hierarchy?: ContextHierarchy | null | undefined;\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /** False: this turn's model cannot read context — muted face, no amber. */\n modelReadsContext?: boolean | undefined;\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n onResetAll: () => void;\n onOpenFullView: () => void;\n mismatchCount?: number;\n mismatches?: readonly ContextReceiptMismatch[];\n onOpenRow?: (key: string) => void;\n /** Bottom sheet instead of a popover. */\n isMobile?: boolean;\n readOnly?: boolean | undefined;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * The chip toggles a view the host shows elsewhere (a canvas tab): `true`\n * while that view is in front. Sets `aria-pressed` and the pressed face.\n * Omitted: the chip is a plain popover trigger, no pressed state.\n */\n pressed?: boolean | undefined;\n className?: string;\n}\n\nconst BLIND_TOOLTIP = \"This model can't read these values\";\nconst BLIND_LABEL = \"Not read\";\n\nfunction IconButton({\n label,\n onClick,\n comfortable,\n children,\n}: {\n label: string;\n onClick: () => void;\n comfortable: boolean;\n children: React.ReactNode;\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={label}\n onClick={onClick}\n className={cn(\n \"inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground\",\n comfortable ? \"h-11 w-11\" : \"h-7 w-7\",\n )}\n >\n {children}\n </button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n );\n}\n\n/**\n * The composer's value-group chip — far right of the composer's one row — and the surface it opens: a header (label,\n * \"N · chars\" summary, page master switch, reset-all, full view) over the\n * compact rules table. Popover on desktop, bottom sheet on mobile.\n */\nexport function ContextRulesChip({\n label,\n rows,\n cap,\n on,\n onToggleAll,\n hierarchy,\n onSetInclude,\n onChange,\n onResetAll,\n onOpenFullView,\n mismatchCount = 0,\n modelReadsContext = true,\n mismatches,\n onOpenRow,\n isMobile,\n readOnly,\n open: openProp,\n onOpenChange,\n pressed,\n className,\n}: ContextRulesChipProps) {\n const [openState, setOpenState] = React.useState(false);\n const open = openProp ?? openState;\n const setOpen = (next: boolean) => {\n if (openProp === undefined) setOpenState(next);\n onOpenChange?.(next);\n };\n const { count, charsLabel } = summarizeContextRows(rows);\n const name = label?.trim() ?? \"\";\n // The face's accessible name and tooltip — the group's name when it has one,\n // otherwise what the number counts.\n const faceName = name ? `${name} · ${count} included` : `${count} included`;\n const anyOverride = rows.some(hasOverride);\n const blind = !modelReadsContext;\n const warn = mismatchCount > 0 && !blind;\n const comfortable = !!isMobile;\n // With a hierarchy the page's name and switch sit on its own level row.\n const hasPage = on !== undefined && !hierarchy;\n const headerName = hierarchy ? \"\" : name;\n // Eye open only when context can reach the model: a page that is on (or no\n // page at all) and a model that reads context.\n const eyeOpen = !blind && on !== false;\n\n // Compact: the same height as the composer's other row pills (h-6). On touch\n // an invisible ring takes the hit area to 44px without growing the row.\n const faceButton = (\n <button\n type=\"button\"\n aria-label={faceName}\n // Full width when the row has room; it truncates only when the row's\n // attachments need the space, and the whole name stays in the title.\n title={name || undefined}\n data-mismatch={warn ? \"true\" : undefined}\n data-blind={blind ? \"true\" : undefined}\n aria-pressed={pressed}\n onClick={isMobile ? () => setOpen(true) : undefined}\n className={cn(\n \"relative inline-flex h-6 min-w-0 shrink items-center gap-1 rounded-md border border-border bg-card px-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent\",\n comfortable && \"after:absolute after:-inset-x-1.5 after:-inset-y-2.5 after:content-['']\",\n !eyeOpen && \"text-muted-foreground\",\n blind && \"border-dashed\",\n warn && \"border-warning/60 ring-1 ring-warning\",\n pressed && \"border-primary bg-primary/15 text-primary ring-1 ring-inset ring-primary/30 hover:bg-primary/20\",\n className,\n )}\n >\n {eyeOpen ? <EyeIcon className=\"h-3 w-3 shrink-0\" /> : <EyeOffIcon className=\"h-3 w-3 shrink-0\" />}\n {name ? <span className=\"min-w-0 truncate\">{name}</span> : null}\n <span className=\"shrink-0 tabular-nums text-muted-foreground\">{count}</span>\n {warn ? (\n <span className=\"inline-flex shrink-0 items-center gap-0.5 tabular-nums text-warning\">\n <TriangleAlertIcon className=\"h-3 w-3\" />\n {mismatchCount}\n </span>\n ) : null}\n </button>\n );\n\n // The blind state says why; a nameless face says what its number counts.\n const faceTip = blind ? BLIND_TOOLTIP : name ? null : faceName;\n const withBlindTip = (trigger: React.ReactElement) =>\n faceTip ? (\n <Tooltip>\n <TooltipTrigger asChild>{trigger}</TooltipTrigger>\n <TooltipContent>{faceTip}</TooltipContent>\n </Tooltip>\n ) : (\n trigger\n );\n\n const body = (\n <div className=\"flex min-h-0 flex-col\">\n <div\n className={cn(\n \"flex shrink-0 items-center gap-2 border-b border-border px-3\",\n comfortable ? \"h-12\" : \"h-10\",\n )}\n >\n {eyeOpen ? (\n <EyeIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n ) : (\n <EyeOffIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n )}\n {headerName ? <span className=\"min-w-0 truncate text-sm font-medium\">{headerName}</span> : null}\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${count} · ${charsLabel} chars`}\n </span>\n <div className=\"ml-auto flex shrink-0 items-center gap-0.5\">\n {blind ? (\n <span className=\"mr-1 text-xs text-muted-foreground\">{BLIND_LABEL}</span>\n ) : null}\n {hasPage ? (\n <Switch\n size=\"sm\"\n aria-label=\"Include this page\"\n checked={on}\n disabled={readOnly || !onToggleAll}\n onCheckedChange={(next) => onToggleAll?.(next)}\n className=\"mr-1\"\n />\n ) : null}\n {anyOverride && !readOnly ? (\n <IconButton label=\"Reset all\" onClick={onResetAll} comfortable={comfortable}>\n <RotateCcwIcon className=\"h-3.5 w-3.5\" />\n </IconButton>\n ) : null}\n <IconButton\n label=\"Open full view\"\n comfortable={comfortable}\n onClick={() => {\n setOpen(false);\n onOpenFullView();\n }}\n >\n <PanelRightIcon className=\"h-3.5 w-3.5\" />\n </IconButton>\n </div>\n </div>\n <div className={cn(\"min-h-0 overflow-y-auto\", comfortable ? \"max-h-[70dvh]\" : \"max-h-[min(24rem,60vh)]\")}>\n <ContextRulesTable\n rows={rows}\n cap={cap}\n readOnly={readOnly}\n density={comfortable ? \"comfortable\" : \"compact\"}\n onChange={onChange}\n hierarchy={hierarchy}\n onSetInclude={onSetInclude}\n {...(mismatches ? { mismatches } : {})}\n {...(onOpenRow ? { onOpenRow } : {})}\n />\n </div>\n </div>\n );\n\n if (isMobile) {\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n {withBlindTip(faceButton)}\n <BottomSheet open={open} onOpenChange={setOpen} title={name || faceName} surface=\"solid\">\n {body}\n </BottomSheet>\n </TooltipProvider>\n );\n }\n\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <Popover open={open} onOpenChange={setOpen}>\n {withBlindTip(<PopoverTrigger asChild>{faceButton}</PopoverTrigger>)}\n <PopoverContent\n align=\"end\"\n className=\"w-[30rem] max-w-[calc(100vw-1rem)] overflow-hidden p-0\"\n >\n {body}\n </PopoverContent>\n </Popover>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport {\n Input,\n Switch,\n TooltipProvider,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n DEFAULT_INLINE_MAX_CHARS,\n formatChars,\n type ContextLayer,\n type ContextReceiptBlock,\n type ContextViewLoader,\n unclaimedBlocks,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ContextRulesTable } from \"./ContextRulesTable\";\nimport type { ContextHierarchy, ContextRuleChange } from \"./hierarchy\";\nimport { ChevronLeftIcon, SearchIcon, TriangleAlertIcon } from \"./icons\";\nimport { ContextDeliveredValue } from \"./ContextDeliveredValue\";\nimport { ContextReceiptBlockDetail, ContextReceiptBlocks } from \"./ContextReceiptBlocks\";\nimport { FrozenInclude } from \"./FrozenInclude\";\nimport { InlineMaxInput } from \"./InlineMaxInput\";\nimport {\n DELIVERY_LABEL,\n LAYER_LABEL,\n describeMismatches,\n formatLimit,\n inheritedLimit,\n limitPlaceholder,\n withInclude,\n withLimit,\n} from \"./shared\";\n\nexport interface ContextRulesPanelBodyProps {\n rows: readonly ResolvedContextRow[];\n cap: number;\n mismatches?: readonly ContextReceiptMismatch[];\n /** The latest receipt's `blocks`: listed read-only under \"Also sent\". */\n blocks?: readonly ContextReceiptBlock[];\n /** The viewer door (RULES.md §5b): fetches a value's or block's exact text when it opens. */\n loadView?: ContextViewLoader;\n readOnly?: boolean | undefined;\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n /** Levels and groups with a switch each (see `ContextRulesTable`). */\n hierarchy?: ContextHierarchy | null | undefined;\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /** Host content under the built-in controls (a value preview, source link…). */\n renderDetail?: (row: ResolvedContextRow) => React.ReactNode;\n isMobile?: boolean;\n /** Controlled selection; omit for internal state. */\n selectedKey?: string | null;\n onSelectedKeyChange?: (key: string | null) => void;\n className?: string;\n}\n\ninterface LayerCell {\n include: string;\n limit: string;\n}\n\n/** What each layer says about this row; \"—\" where the layer is silent. */\nfunction layerCells(row: ResolvedContextRow): Record<ContextLayer, LayerCell> {\n const { surface, agent, default_max } = row.layers ?? {};\n const declared = agent?.declared === true;\n const pageOff = surface?.declared === true && surface.auto_context === false;\n const num = (n: number | null | undefined) => (typeof n === \"number\" ? formatLimit(n) : \"—\");\n const rule = row.userRule;\n return {\n default: { include: \"On\", limit: formatLimit(default_max ?? DEFAULT_INLINE_MAX_CHARS) },\n page: { include: pageOff ? \"Off\" : \"—\", limit: num(surface?.max_inline_chars) },\n agent: {\n include: agent?.kill_switch && !declared ? \"Off\" : declared && pageOff ? \"On\" : \"—\",\n limit: declared ? num(agent?.max_inline_chars) : \"—\",\n },\n you: {\n include: rule?.include === undefined ? \"—\" : rule.include ? \"On\" : \"Off\",\n limit: num(rule?.max_inline_chars),\n },\n };\n}\n\nconst LAYERS: ContextLayer[] = [\"default\", \"page\", \"agent\", \"you\"];\n\nfunction LayerTable({ row }: { row: ResolvedContextRow }) {\n const cells = layerCells(row);\n const cell = (text: string, winning: boolean) => (\n <span\n role=\"cell\"\n data-winning={winning ? \"true\" : undefined}\n className={cn(\n \"rounded px-1.5 py-0.5 text-right tabular-nums\",\n winning ? \"bg-primary/10 font-medium text-foreground\" : \"text-muted-foreground\",\n )}\n >\n {text}\n </span>\n );\n return (\n <div role=\"table\" aria-label=\"Layers\" className=\"text-xs\">\n <div\n role=\"row\"\n className=\"grid h-7 grid-cols-[1fr_5rem_5rem] items-center gap-x-2 border-b border-border font-medium text-muted-foreground\"\n >\n <span role=\"columnheader\">Layer</span>\n <span role=\"columnheader\" className=\"text-right\">\n Include\n </span>\n <span role=\"columnheader\" className=\"text-right\">\n Inline max\n </span>\n </div>\n {LAYERS.map((layer) => (\n <div\n role=\"row\"\n key={layer}\n className=\"grid h-7 grid-cols-[1fr_5rem_5rem] items-center gap-x-2 border-b border-border/50\"\n >\n <span role=\"cell\">{LAYER_LABEL[layer]}</span>\n {cell(cells[layer].include, row.decided_by.include === layer)}\n {cell(cells[layer].limit, row.decided_by.max_inline_chars === layer)}\n </div>\n ))}\n </div>\n );\n}\n\nfunction RowDetail({\n row,\n cap,\n readOnly,\n mismatches,\n onChange,\n renderDetail,\n comfortable,\n loadView,\n}: {\n loadView: ContextViewLoader | undefined;\n row: ResolvedContextRow;\n cap: number;\n readOnly: boolean | undefined;\n mismatches: ContextReceiptMismatch[];\n onChange: ContextRulesPanelBodyProps[\"onChange\"];\n renderDetail: ContextRulesPanelBodyProps[\"renderDetail\"];\n comfortable: boolean;\n}) {\n return (\n <div className=\"flex flex-col gap-3 p-3\">\n <div className=\"flex min-w-0 items-baseline gap-2\">\n <h3 className=\"min-w-0 truncate text-sm font-medium\">{row.label}</h3>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${formatChars(row.chars)} chars · ${DELIVERY_LABEL[row.delivery]}`}\n </span>\n </div>\n {mismatches.length > 0 ? (\n <div className=\"flex items-start gap-1.5 rounded-md border border-warning/40 bg-warning/10 px-2 py-1.5 text-xs text-warning\">\n <TriangleAlertIcon className=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\n <span>{describeMismatches(mismatches)}</span>\n </div>\n ) : null}\n <div className=\"grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2 text-xs\">\n <span className=\"text-muted-foreground\">Include</span>\n <div className={cn(\"flex items-center\", comfortable ? \"h-11\" : \"h-7\")}>\n {readOnly ? (\n <FrozenInclude name={row.label} checked={row.include} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${row.label}`}\n checked={row.include}\n onCheckedChange={(next) => onChange(row.key, row.surfaceKey, withInclude(row, next))}\n />\n )}\n </div>\n <span className=\"text-muted-foreground\">Inline max</span>\n <div className=\"flex\">\n <InlineMaxInput\n label={row.label}\n value={row.userRule?.max_inline_chars ?? null}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n </div>\n </div>\n <LayerTable row={row} />\n <ContextDeliveredValue row={row} load={loadView} />\n {renderDetail ? renderDetail(row) : null}\n </div>\n );\n}\n\n/**\n * Master/detail body for a docked context panel: search + compact table on\n * the left, the open row's controls, layer breakdown and host detail on the\n * right. On mobile: list, then detail with Back.\n */\nexport function ContextRulesPanelBody({\n rows,\n cap,\n mismatches,\n blocks,\n loadView,\n readOnly,\n onChange,\n hierarchy,\n onSetInclude,\n renderDetail,\n isMobile,\n selectedKey: selectedProp,\n onSelectedKeyChange,\n className,\n}: ContextRulesPanelBodyProps) {\n const [selectedState, setSelectedState] = React.useState<string | null>(null);\n const [query, setQuery] = React.useState(\"\");\n const [openBlockId, setOpenBlockId] = React.useState<string | null>(null);\n const selectedKey = selectedProp !== undefined ? selectedProp : selectedState;\n const select = (key: string | null) => {\n setOpenBlockId(null);\n if (selectedProp === undefined) setSelectedState(key);\n onSelectedKeyChange?.(key);\n };\n const openBlock = (id: string) => {\n select(null);\n setOpenBlockId(id);\n };\n\n const q = query.trim().toLowerCase();\n const visible = q\n ? rows.filter((r) => r.label.toLowerCase().includes(q) || r.key.toLowerCase().includes(q))\n : rows;\n // A block the model read as part of a value (the Organization's catalog) shows in that\n // value's detail and its chars — never listed twice.\n const alsoSent = unclaimedBlocks(\n blocks,\n rows.filter((r) => r.delivered).map((r) => r.key),\n );\n const visibleBlocks = q\n ? alsoSent.filter((b) => b.label.toLowerCase().includes(q) || b.id.toLowerCase().includes(q))\n : alsoSent;\n const openedBlock = openBlockId ? (blocks ?? []).find((b) => b.id === openBlockId) ?? null : null;\n const selected =\n !openedBlock && selectedKey ? rows.find((r) => r.key === selectedKey) ?? null : null;\n const comfortable = !!isMobile;\n\n const search = (\n <div className=\"relative shrink-0 border-b border-border p-2\">\n <SearchIcon className=\"pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground\" />\n <Input\n type=\"search\"\n aria-label=\"Search values\"\n placeholder=\"Search\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n className={cn(\"pl-7 shadow-none\", comfortable ? \"h-11 text-base\" : \"h-8 text-xs\")}\n />\n </div>\n );\n\n const table = (\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n <ContextRulesTable\n rows={visible}\n cap={cap}\n readOnly={readOnly}\n density={comfortable ? \"comfortable\" : \"compact\"}\n selectedKey={selectedKey}\n onChange={onChange}\n hierarchy={hierarchy}\n onSetInclude={onSetInclude}\n onOpenRow={(key) => select(key)}\n {...(mismatches ? { mismatches } : {})}\n />\n <ContextReceiptBlocks\n blocks={visibleBlocks}\n selectedId={openedBlock?.id ?? null}\n onOpenBlock={openBlock}\n density={comfortable ? \"comfortable\" : \"compact\"}\n />\n </div>\n );\n\n const detail = openedBlock ? (\n <ContextReceiptBlockDetail block={openedBlock} load={loadView} />\n ) : selected ? (\n <RowDetail\n row={selected}\n cap={cap}\n readOnly={readOnly}\n mismatches={mismatches?.filter((m) => m.key === selected.key) ?? []}\n onChange={onChange}\n renderDetail={renderDetail}\n comfortable={comfortable}\n loadView={loadView}\n />\n ) : null;\n\n if (isMobile) {\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <div className={cn(\"flex h-full min-h-0 flex-col\", className)}>\n {detail ? (\n <>\n <div className=\"flex h-12 shrink-0 items-center border-b border-border px-1\">\n <button\n type=\"button\"\n onClick={() => select(null)}\n className=\"inline-flex h-11 items-center gap-1 rounded-md px-2 text-sm text-muted-foreground hover:text-foreground\"\n >\n <ChevronLeftIcon className=\"h-4 w-4\" />\n Back\n </button>\n </div>\n <div className=\"min-h-0 flex-1 overflow-y-auto\">{detail}</div>\n </>\n ) : (\n <>\n {search}\n {table}\n </>\n )}\n </div>\n </TooltipProvider>\n );\n }\n\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <div className={cn(\"flex h-full min-h-0\", className)}>\n <aside className=\"flex w-[22rem] shrink-0 flex-col border-r border-border\">\n {search}\n {table}\n </aside>\n <section className=\"min-h-0 min-w-0 flex-1 overflow-y-auto\">\n {detail ?? (\n <div className=\"flex h-full items-center justify-center text-xs text-muted-foreground\">\n Select an item\n </div>\n )}\n </section>\n </div>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport { ErrorBox, Skeleton, cn } from \"@ai-matrx/design-system\";\n\nimport {\n CONTEXT_FETCHABLE_ROWS,\n formatChars,\n isServerAuthoritativeKey,\n type ContextDeliveredRef,\n type ContextReceiptBlock,\n type ContextViewLoader,\n type ContextViewTarget,\n type ResolvedContextRow,\n} from \"../index\";\n\n/**\n * What the model READ for one value — fetched from the viewer when the detail\n * opens, never pushed (RULES.md §5b): its own element (`delivered`), the blocks\n * it rode with (`deliveredBlocks` — the Organization's catalog), and for an\n * on-request value what the `context` tool returns (`onRequest`), and for a\n * value the agent reads through a tool (`CONTEXT_FETCHABLE_ROWS`) what that tool\n * returns now (`fetchable`, sized once loaded). Verbatim;\n * never the client's copy. With no receipt yet: a server-authoritative value\n * says the server fills it; anything else renders nothing (the host may show\n * the value the page will send, labelled so).\n */\nexport function ContextDeliveredValue({\n row,\n load,\n className,\n}: {\n row: Pick<ResolvedContextRow, \"key\" | \"delivered\" | \"onRequest\" | \"deliveredBlocks\"> &\n Partial<Pick<ResolvedContextRow, \"delivery\">>;\n /** The host's viewer door; without one, sizes show and the text reads \"—\". */\n load?: ContextViewLoader | undefined;\n className?: string;\n}) {\n const blocks = row.deliveredBlocks ?? [];\n if (!row.delivered && !row.onRequest && blocks.length === 0) {\n return isServerAuthoritativeKey(row.key) ? (\n <p data-testid=\"context-server-fills\" className={cn(\"text-xs text-muted-foreground\", className)}>\n Filled in by the server\n </p>\n ) : null;\n }\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n {row.delivered ? (\n <DeliveredSection\n title=\"Agent received\"\n target={{ kind: \"delivered\", key: row.key }}\n ref_={row.delivered}\n load={load}\n />\n ) : null}\n {blocks.map((block: ContextReceiptBlock) => (\n <DeliveredSection\n key={block.id}\n title={block.label}\n target={{ kind: \"block\", key: block.id }}\n ref_={block.delivered}\n load={load}\n />\n ))}\n {row.onRequest || (row.delivery === \"on_request\" && row.delivered) ? (\n // A lazy value (a document, a file family …) carries no ref: the turn never reads\n // it. It is fetched — and sized — when opened.\n <DeliveredSection\n title=\"Returned on request\"\n target={{ kind: \"on_request\", key: row.key }}\n ref_={row.onRequest}\n load={load}\n />\n ) : null}\n {row.delivered && CONTEXT_FETCHABLE_ROWS[row.key] ? (\n <DeliveredSection\n title=\"Agent can fetch\"\n target={{ kind: \"fetchable\", key: row.key }}\n load={load}\n />\n ) : null}\n </div>\n );\n}\n\ntype Loaded =\n | { state: \"loading\" }\n | { state: \"error\"; message: string }\n | { state: \"done\"; text: string; chars: number; available: boolean; fetched: boolean | null };\n\n/** One viewed text: its title and size, then the exact text, fetched on mount. */\nexport function DeliveredSection({\n title,\n target,\n ref_,\n load,\n}: {\n title: string;\n target: ContextViewTarget;\n /** The receipt's size; absent for a `fetchable` text, sized once it loads. */\n ref_?: ContextDeliveredRef | undefined;\n load?: ContextViewLoader | undefined;\n}) {\n const [loaded, setLoaded] = React.useState<Loaded>({ state: \"loading\" });\n const [attempt, setAttempt] = React.useState(0);\n const { kind, key } = target;\n React.useEffect(() => {\n if (!load) return;\n let live = true;\n setLoaded({ state: \"loading\" });\n load({ kind, key }).then(\n (viewed) => {\n if (live)\n setLoaded({\n state: \"done\",\n text: viewed.text,\n chars: viewed.chars,\n available: viewed.available !== false,\n fetched: viewed.fetched ?? null,\n });\n },\n (error: unknown) => {\n if (live)\n setLoaded({\n state: \"error\",\n message: error instanceof Error && error.message ? error.message : \"Couldn't load\",\n });\n },\n );\n return () => {\n live = false;\n };\n }, [load, kind, key, attempt]);\n\n const unavailable = loaded.state === \"done\" && !loaded.available;\n return (\n <section className=\"flex flex-col gap-1\" aria-label={title} data-view-kind={kind} data-view-key={key}>\n <div className=\"flex items-baseline gap-2 text-xs\">\n <span className=\"font-medium\">{title}</span>\n {unavailable ? (\n <span\n data-testid=\"context-delivered-unavailable\"\n className=\"rounded border border-border px-1.5 text-[11px] text-muted-foreground\"\n >\n Not available to this agent\n </span>\n ) : ref_ || loaded.state === \"done\" ? (\n <span className=\"tabular-nums text-muted-foreground\">\n {`${formatChars(ref_ ? ref_.chars : loaded.state === \"done\" ? loaded.chars : 0)} chars`}\n </span>\n ) : null}\n {loaded.state === \"done\" && loaded.fetched === false ? (\n <span\n data-testid=\"context-delivered-not-read\"\n className=\"rounded border border-border px-1.5 text-[11px] text-muted-foreground\"\n >\n Not read by the agent\n </span>\n ) : null}\n </div>\n {unavailable ? null : !load ? (\n <span className=\"text-xs text-muted-foreground\">—</span>\n ) : loaded.state === \"loading\" ? (\n <Skeleton data-testid=\"context-delivered-loading\" className=\"h-16 w-full\" />\n ) : loaded.state === \"error\" ? (\n <ErrorBox as=\"div\" message={loaded.message} className=\"flex items-center gap-2 text-xs text-destructive\">\n <span className=\"min-w-0 truncate\" title={loaded.message}>\n {loaded.message}\n </span>\n <button\n type=\"button\"\n onClick={() => setAttempt((n) => n + 1)}\n className=\"shrink-0 rounded px-1.5 py-0.5 text-foreground hover:bg-accent\"\n >\n Retry\n </button>\n </ErrorBox>\n ) : loaded.text === \"\" ? (\n <span data-testid=\"context-delivered-empty\" className=\"text-xs text-muted-foreground\">\n None\n </span>\n ) : (\n <pre\n data-testid=\"context-delivered-text\"\n className={cn(\n \"max-h-[min(50dvh,22rem)] cursor-text select-text overflow-auto\",\n \"whitespace-pre-wrap break-words rounded border border-border\",\n \"bg-muted/40 p-2 font-mono text-[11px] text-foreground\",\n )}\n >\n {loaded.text}\n </pre>\n )}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"@ai-matrx/design-system\";\n\nimport { formatChars, type ContextReceiptBlock, type ContextViewLoader } from \"../index\";\nimport { DeliveredSection } from \"./ContextDeliveredValue\";\nimport { DELIVERY_LABEL } from \"./shared\";\nimport { CONTEXT_RULES_GRID, type ContextRulesDensity } from \"./ContextRulesTable\";\n\nexport interface ContextReceiptBlocksProps {\n blocks: readonly ContextReceiptBlock[];\n /** The open block (master/detail). */\n selectedId?: string | null;\n onOpenBlock?: (id: string) => void;\n density?: ContextRulesDensity;\n className?: string;\n}\n\n/**\n * \"Also sent\" — every block of server text the model received that is not a\n * single value (receipt `blocks`, RULES.md §5): read-only rows, label + chars,\n * aligned to the context table's Chars column. Renders nothing when empty.\n */\nexport function ContextReceiptBlocks({\n blocks,\n selectedId,\n onOpenBlock,\n density = \"compact\",\n className,\n}: ContextReceiptBlocksProps) {\n if (blocks.length === 0) return null;\n const comfortable = density === \"comfortable\";\n return (\n <div role=\"table\" aria-label=\"Also sent\" className={cn(\"text-xs\", className)}>\n <div role=\"rowgroup\">\n <div\n role=\"row\"\n className=\"flex h-6 items-center bg-muted/40 px-2 font-medium text-muted-foreground\"\n >\n <span role=\"cell\">Also sent</span>\n </div>\n {blocks.map((block) => (\n <div\n role=\"row\"\n key={block.id}\n data-block-id={block.id}\n aria-selected={selectedId === block.id || undefined}\n className={cn(\n CONTEXT_RULES_GRID[density],\n \"border-b border-border/50\",\n comfortable ? \"min-h-11\" : \"h-7\",\n selectedId === block.id && \"bg-accent\",\n )}\n >\n <div role=\"cell\" className=\"col-span-2 flex min-w-0 items-center\">\n {onOpenBlock ? (\n <button\n type=\"button\"\n title={block.label}\n onClick={() => onOpenBlock(block.id)}\n className=\"block min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {block.label}\n </button>\n ) : (\n <span title={block.label} className=\"block min-w-0 flex-1 truncate\">\n {block.label}\n </span>\n )}\n </div>\n <div role=\"cell\" className=\"text-right tabular-nums\">\n {formatChars(block.delivered.chars)}\n </div>\n <div role=\"cell\" />\n </div>\n ))}\n </div>\n </div>\n );\n}\n\n/** One block's detail: its name, its size, and exactly what the agent received (on demand). */\nexport function ContextReceiptBlockDetail({\n block,\n load,\n className,\n}: {\n block: ContextReceiptBlock;\n load?: ContextViewLoader | undefined;\n className?: string;\n}) {\n return (\n <div className={cn(\"flex flex-col gap-3 p-3\", className)}>\n <div className=\"flex min-w-0 items-baseline gap-2\">\n <h3 className=\"min-w-0 truncate text-sm font-medium\">{block.label}</h3>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${formatChars(block.delivered.chars)} chars · ${DELIVERY_LABEL.inline}`}\n </span>\n </div>\n <DeliveredSection\n title=\"Agent received\"\n target={{ kind: \"block\", key: block.id }}\n ref_={block.delivered}\n load={load}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,SAAuB;AACvB,IAAAC,wBAUO;;;ACUA,IAAM,2BAA2B;AAEjC,IAAM,qBAAqB;AA+L3B,IAAM,qBAAkE;AAAA,EAC7E,cAAc,CAAC,sBAAsB;AACvC;AAQO,IAAM,yBAA2D;AAAA,EACtE,cAAc;AAChB;AAYO,SAAS,gBACd,QACA,SACuB;AACvB,QAAM,UAAU,oBAAI,IAAY;AAChC,aAAW,OAAO,QAAS,YAAW,MAAM,mBAAmB,GAAG,KAAK,CAAC,EAAG,SAAQ,IAAI,EAAE;AACzF,UAAQ,UAAU,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,IAAI,EAAE,EAAE,CAAC;AACxD;AA4BO,IAAM,4BAAqF;AAAA,EAChG,MAAM;AAAA,EACN,Q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AAAA,MACC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,YAAY,YAAY,OAAO,CAAC,MAAM,EAAE,QAAQ,SAAS,GAAG,KAAK,CAAC;AAAA,MAClE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA;AAAA,EACF,IACE;AAEJ,MAAI,UAAU;AACZ,WACE,6CAAC,yCAAgB,eAAe,KAAK,eAAe,OAClD,uDAAC,SAAI,eAAW,0BAAG,gCAAgC,SAAS,GACzD,mBACC,8EACE;AAAA,mDAAC,SAAI,WAAU,+DACb;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAS,MAAM,OAAO,IAAI;AAAA,UAC1B,WAAU;AAAA,UAEV;AAAA,yDAAC,mBAAgB,WAAU,WAAU;AAAA,YAAE;AAAA;AAAA;AAAA,MAEzC,GACF;AAAA,MACA,6CAAC,SAAI,WAAU,kCAAkC,kBAAO;AAAA,OAC1D,IAEA,8EACG;AAAA;AAAA,MACA;AAAA,OACH,GAEJ,GACF;AAAA,EAEJ;AAEA,SACE,6CAAC,yCAAgB,eAAe,KAAK,eAAe,OAClD,wDAAC,SAAI,eAAW,0BAAG,uBAAuB,SAAS,GACjD;AAAA,kDAAC,WAAM,WAAU,2DACd;AAAA;AAAA,MACA;AAAA,OACH;AAAA,IACA,6CAAC,aAAQ,WAAU,0CAChB,oBACC,6CAAC,SAAI,WAAU,yEAAwE,4BAEvF,GAEJ;AAAA,KACF,GACF;AAEJ;","names":["React","import_design_system","import_jsx_runtime","import_design_system","import_jsx_runtime","import_jsx_runtime","React","import_design_system","import_jsx_runtime","React","import_design_system","React","import_design_system","import_jsx_runtime","import_design_system","import_jsx_runtime","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../../../context/react/index.ts","../../../context/react/ContextRulesTable.tsx","../../../context/index.ts","../../../context/react/icons.tsx","../../../context/react/hierarchy.ts","../../../context/react/FrozenInclude.tsx","../../../context/react/InlineMaxInput.tsx","../../../context/react/shared.ts","../../../context/react/summary.ts","../../../context/react/ContextRulesChip.tsx","../../../context/react/ContextRulesPanelBody.tsx","../../../context/react/ContextDeliveredValue.tsx","../../../context/react/ContextReceiptBlocks.tsx"],"sourcesContent":["/**\n * @ai-matrx/agents/context/react — presentational, state-agnostic context\n * rules UI. Every edit leaves through `onChange`; the host owns persistence\n * (RULES.md §3: optimistic write, no debounce). SSR-safe: no window access at\n * import. Built on @ai-matrx/design-system primitives; glyphs are inlined\n * Lucide shapes (C19).\n */\nexport { ContextRulesTable, type ContextRulesTableProps, type ContextRulesDensity } from \"./ContextRulesTable\";\nexport { ContextRulesChip, summarizeContextRows, type ContextRulesChipProps } from \"./ContextRulesChip\";\nexport { ContextRulesPanelBody, type ContextRulesPanelBodyProps } from \"./ContextRulesPanelBody\";\nexport {\n AI_MATRX_LEVEL,\n ATTACHED_LEVEL,\n PAGE_LEVEL,\n buildContextLevels,\n includeChanges,\n inheritedInclude,\n levelRows,\n placeByOrigin,\n type ContextGroupNode,\n type ContextGroupRef,\n type ContextHierarchy,\n type ContextLevelMaster,\n type ContextLevelNode,\n type ContextLevelRef,\n type ContextRowPlace,\n type ContextRuleChange,\n} from \"./hierarchy\";\nexport { InlineMaxInput, type InlineMaxInputProps } from \"./InlineMaxInput\";\nexport { ContextDeliveredValue, DeliveredSection } from \"./ContextDeliveredValue\";\nexport {\n ContextReceiptBlocks,\n ContextReceiptBlockDetail,\n type ContextReceiptBlocksProps,\n} from \"./ContextReceiptBlocks\";\n","import * as React from \"react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n Switch,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n formatChars,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ArrowDownToLineIcon, TriangleAlertIcon } from \"./icons\";\nimport {\n buildContextLevels,\n includeChanges,\n levelRows,\n type ContextHierarchy,\n type ContextLevelNode,\n type ContextRuleChange,\n} from \"./hierarchy\";\nimport { FrozenInclude } from \"./FrozenInclude\";\nimport { InlineMaxInput } from \"./InlineMaxInput\";\nimport { summarizeContextRows } from \"./summary\";\nimport {\n LAYER_LABEL,\n describeMismatches,\n formatLimit,\n SELF_CHECK_TOOLTIP,\n SERVER_RESOLVED_TOOLTIP,\n inheritedLimit,\n limitPlaceholder,\n onRequestReason,\n rowId,\n withInclude,\n withLimit,\n} from \"./shared\";\n\nexport type ContextRulesDensity = \"compact\" | \"comfortable\";\n\nexport interface ContextRulesTableProps {\n rows: readonly ResolvedContextRow[];\n cap: number;\n readOnly?: boolean | undefined;\n /** From `compareReceipt` — rows with a mismatch get an amber marker. */\n mismatches?: readonly ContextReceiptMismatch[];\n /** `next === null` resets the person's rule for that key. */\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n onOpenRow?: (key: string) => void;\n /** `comfortable` = 44px touch rows (the deciding layer stays in the row tooltip). Default `compact`. */\n density?: ContextRulesDensity;\n /** Highlights the open row (master/detail). */\n selectedKey?: string | null;\n /**\n * Where each row sits (level → group) and the host's level switches. Omit:\n * rows sit under their origin (\"Page\", \"Attached\", \"AI Matrx\").\n */\n hierarchy?: ContextHierarchy | null | undefined;\n /**\n * A level or group switch: the person's per-value rules for every value in\n * it, at once. Omit: level and group switches are hidden (a host master\n * switch still shows).\n */\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /**\n * Host slots inside a row's Item cell, never a second renderer: `renderRowLead`\n * before the label (a status mark), `renderRowTrail` after it (an admin's\n * machine name). Each renders inline and truncates with the label.\n */\n renderRowLead?: ((row: ResolvedContextRow) => React.ReactNode) | undefined;\n renderRowTrail?: ((row: ResolvedContextRow) => React.ReactNode) | undefined;\n className?: string;\n}\n\nexport const CONTEXT_RULES_GRID = {\n compact: \"grid grid-cols-[minmax(0,1fr)_2.75rem_4rem_6.5rem] items-center gap-x-2 px-2\",\n comfortable: \"grid grid-cols-[minmax(0,1fr)_2.75rem_3.5rem_6.75rem] items-center gap-x-1.5 px-3\",\n} as const;\n\n/**\n * Narrow (a window sidebar, a phone): the name takes the whole row; Include,\n * Chars and Inline max shrink to their content and Inline max collapses to a\n * button that opens its field — names stay readable, never \"Bra…\".\n */\nconst NARROW_GRID = {\n compact: \"grid grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-1.5 px-2\",\n comfortable: \"grid grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-1.5 px-3\",\n} as const;\n\n/** Below this width the table lays out narrow. */\nexport const CONTEXT_RULES_NARROW_BELOW = 400;\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\n/** Narrow when the table's own width is under `CONTEXT_RULES_NARROW_BELOW`, measured on every resize. */\nfunction useNarrow(ref: React.RefObject<HTMLDivElement | null>): boolean {\n const [narrow, setNarrow] = React.useState(false);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const fit = () => {\n const width = el.clientWidth;\n if (width > 0) setNarrow(width < CONTEXT_RULES_NARROW_BELOW);\n };\n fit();\n if (typeof ResizeObserver === \"undefined\") return undefined;\n const observer = new ResizeObserver(fit);\n observer.observe(el);\n return () => observer.disconnect();\n }, [ref]);\n return narrow;\n}\n\n/** One indent step per depth (ui-dense: small). */\nconst INDENT = [\"\", \"pl-2\", \"pl-4\", \"pl-6\"] as const;\nconst indent = (depth: number) => INDENT[Math.min(depth, INDENT.length - 1)];\n\n/** Levels that share a section (\"Marketing\") sit under one section row. */\ninterface SectionNode {\n id: string;\n label: string | null;\n levels: ContextLevelNode[];\n}\n\nfunction sectionsOf(levels: readonly ContextLevelNode[]): SectionNode[] {\n const out: SectionNode[] = [];\n for (const level of levels) {\n const label = level.ref.path.length > 1 ? level.ref.path[0]! : null;\n const last = out[out.length - 1];\n if (label !== null && last && last.label === label) last.levels.push(level);\n else out.push({ id: label === null ? `level:${level.ref.id}` : `section:${label}`, label, levels: [level] });\n }\n return out;\n}\n\n/**\n * The context rules table: Item | Include | Chars | Inline max, under nested\n * heading rows — section (\"Marketing\"), page (\"Marketing Brand Cockpit\"), the\n * page's own groups — each heading full width with its switch. Presentational\n * and state-agnostic — every edit goes out through `onChange`.\n */\nexport function ContextRulesTable({\n rows,\n cap,\n readOnly,\n mismatches,\n onChange,\n onOpenRow,\n density = \"compact\",\n selectedKey,\n hierarchy,\n onSetInclude,\n renderRowLead,\n renderRowTrail,\n className,\n}: ContextRulesTableProps) {\n const comfortable = density === \"comfortable\";\n const rootRef = React.useRef<HTMLDivElement>(null);\n const narrow = useNarrow(rootRef);\n const grid = narrow ? NARROW_GRID[density] : CONTEXT_RULES_GRID[density];\n const levels = buildContextLevels(rows, hierarchy);\n // One origin and no host hierarchy: the heading would only repeat the chip.\n const headed = Boolean(hierarchy) || levels.length > 1;\n const bulkChanges = (list: readonly ResolvedContextRow[], next: boolean) => includeChanges(list, next, cap);\n const bulk = (list: readonly ResolvedContextRow[]) =>\n onSetInclude && !readOnly\n ? (next: boolean) => {\n const changes = bulkChanges(list, next);\n if (changes.length > 0) onSetInclude(changes);\n }\n : undefined;\n const renderRow = (row: ResolvedContextRow, depth: number) => (\n <ContextRuleRow\n key={rowId(row)}\n row={row}\n cap={cap}\n grid={grid}\n narrow={narrow}\n depth={headed ? depth : 0}\n readOnly={readOnly}\n selected={selectedKey === row.key}\n mismatches={mismatches?.filter((m) => m.key === row.key) ?? []}\n onChange={onChange}\n onOpenRow={onOpenRow}\n comfortable={comfortable}\n lead={renderRowLead?.(row)}\n trail={renderRowTrail?.(row)}\n />\n );\n const heading = (props: Omit<HeadingProps, \"grid\" | \"narrow\" | \"comfortable\" | \"readOnly\">) => (\n <Heading key={props.id} {...props} grid={grid} narrow={narrow} comfortable={comfortable} readOnly={readOnly} />\n );\n const renderLevel = (level: ContextLevelNode, depth: number) => {\n const all = levelRows(level);\n const name = level.ref.path[level.ref.path.length - 1] ?? \"\";\n return (\n <div role=\"rowgroup\" key={level.ref.id} aria-label={headed ? level.ref.path.join(\" › \") : undefined} data-level={level.ref.id}>\n {headed\n ? heading({\n id: `h:${level.ref.id}`,\n kind: \"level\",\n label: name,\n switchName: level.ref.path.join(\" › \"),\n depth,\n rows: all,\n ...levelSwitch(level, bulk(all)),\n })\n : null}\n {level.rows.map((row) => renderRow(row, depth + 1))}\n {level.groups.map((group) => (\n <div role=\"rowgroup\" key={group.ref.id} aria-label={group.ref.label} data-group={group.ref.id}>\n {heading({\n id: `h:${group.ref.id}`,\n kind: \"group\",\n label: group.ref.label,\n switchName: group.ref.label,\n depth: depth + 1,\n rows: group.rows,\n checked: group.rows.some((r) => r.include),\n onToggle: bulk(group.rows),\n })}\n {group.rows.map((row) => renderRow(row, depth + 2))}\n </div>\n ))}\n </div>\n );\n };\n\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <div\n ref={rootRef}\n role=\"table\"\n aria-label=\"Values\"\n data-density={density}\n data-layout={narrow ? \"narrow\" : \"wide\"}\n className={cn(\"text-xs\", className)}\n >\n {/* Narrow: the columns are self-evident from their controls; no header row. */}\n {narrow ? null : (\n <div\n role=\"row\"\n className={cn(grid, \"sticky top-0 z-10 h-7 border-b border-border bg-card font-medium text-muted-foreground\")}\n >\n <span role=\"columnheader\">Item</span>\n <span role=\"columnheader\" className=\"text-center\">\n Include\n </span>\n <span role=\"columnheader\" className=\"text-right\">\n Chars\n </span>\n <span role=\"columnheader\" className=\"pr-6 text-right\">\n Inline max\n </span>\n </div>\n )}\n {levels.length === 0 ? (\n <div className=\"px-2 py-3 text-center text-muted-foreground\">None</div>\n ) : (\n sectionsOf(levels).map((section) => {\n if (section.label === null || !headed) return renderLevel(section.levels[0]!, 0);\n const all = section.levels.flatMap(levelRows);\n // A section switch only where it governs more than one page.\n const several = section.levels.length > 1;\n const toggleSection =\n several && !readOnly\n ? (next: boolean) => {\n const changes: ContextRuleChange[] = [];\n for (const level of section.levels) {\n if (level.master) level.master.onToggle?.(next);\n else changes.push(...bulkChanges(levelRows(level), next));\n }\n if (changes.length > 0) onSetInclude?.(changes);\n }\n : undefined;\n return (\n <div role=\"rowgroup\" key={section.id} aria-label={section.label} data-section={section.label}>\n {heading({\n id: `h:${section.id}`,\n kind: \"section\",\n label: section.label,\n switchName: section.label,\n depth: 0,\n rows: all,\n checked: section.levels.some((l) => (l.master ? l.master.on : levelRows(l).some((r) => r.include))),\n onToggle: toggleSection,\n noSwitch: !several,\n })}\n {section.levels.map((level) => renderLevel(level, 1))}\n </div>\n );\n })\n )}\n </div>\n </TooltipProvider>\n );\n}\n\n/** A level's switch: the host's master when it has one, else its values' rules. */\nfunction levelSwitch(\n level: ContextLevelNode,\n bulk: ((next: boolean) => void) | undefined,\n): { checked: boolean; onToggle: ((next: boolean) => void) | undefined } {\n if (level.master) return { checked: level.master.on, onToggle: level.master.onToggle };\n return { checked: levelRows(level).some((r) => r.include), onToggle: bulk };\n}\n\ninterface HeadingProps {\n id: string;\n kind: \"section\" | \"level\" | \"group\";\n label: string;\n /** The switch's accessible name: the full path for a page. */\n switchName: string;\n depth: number;\n rows: readonly ResolvedContextRow[];\n checked: boolean;\n onToggle: ((next: boolean) => void) | undefined;\n /** A section over one page: no switch at all (the page's row has it). */\n noSwitch?: boolean;\n grid: string;\n narrow: boolean;\n comfortable: boolean;\n readOnly: boolean | undefined;\n}\n\nfunction Heading({\n kind,\n label,\n switchName,\n depth,\n rows,\n checked,\n onToggle,\n noSwitch,\n grid,\n narrow,\n comfortable,\n readOnly,\n}: HeadingProps) {\n const { count, charsLabel } = summarizeContextRows(rows);\n const total = rows.length;\n // A switch shows where something can be switched, or where a read-only view\n // states the same fact its rows state — never a dead control.\n const showSwitch = !noSwitch && (Boolean(onToggle) || (readOnly && total > 0));\n const countLabel = total > 0 ? (count === total ? String(total) : `${count}/${total}`) : null;\n const toggle = showSwitch ? (\n readOnly ? (\n <FrozenInclude name={switchName} checked={checked} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${switchName}`}\n checked={checked}\n disabled={!onToggle}\n onCheckedChange={(next) => onToggle?.(next)}\n />\n )\n ) : null;\n // The name is never cut: it wraps to a second line before it truncates.\n // Wide: the switch sits in the Include column and the size in Chars, so\n // every switch in the table lines up. Narrow: the switch is the row's last\n // cell, at the far right, like every value's.\n return (\n <div\n role=\"row\"\n data-heading={kind}\n className={cn(\n grid,\n \"border-b border-border/50 font-medium\",\n comfortable ? \"min-h-11 py-1\" : \"min-h-7 py-0.5\",\n kind === \"group\" ? \"bg-muted/25 text-muted-foreground\" : \"bg-muted/60 text-foreground\",\n )}\n >\n <div role=\"cell\" className={cn(\"flex min-w-0 items-baseline gap-1.5\", indent(depth))}>\n <span className=\"min-w-0 whitespace-normal break-words\" title={label}>\n {label}\n </span>\n {countLabel ? (\n <span className=\"shrink-0 font-normal tabular-nums text-muted-foreground\">{countLabel}</span>\n ) : null}\n </div>\n <div role=\"cell\" className={cn(\"flex justify-center\", narrow && \"order-last\")}>\n {toggle}\n </div>\n <div role=\"cell\" className=\"text-right font-normal tabular-nums text-muted-foreground\">\n {total > 0 ? charsLabel : null}\n </div>\n <div role=\"cell\" />\n </div>\n );\n}\n\ninterface RowProps {\n row: ResolvedContextRow;\n cap: number;\n grid: string;\n narrow: boolean;\n /** Indent depth (nested headings above it). */\n depth: number;\n comfortable: boolean;\n readOnly: boolean | undefined;\n selected: boolean;\n mismatches: ContextReceiptMismatch[];\n onChange: ContextRulesTableProps[\"onChange\"];\n onOpenRow: ContextRulesTableProps[\"onOpenRow\"];\n lead?: React.ReactNode;\n trail?: React.ReactNode;\n}\n\nfunction ContextRuleRow({\n row,\n cap,\n grid,\n narrow,\n depth,\n comfortable,\n readOnly,\n selected,\n mismatches,\n onChange,\n onOpenRow,\n lead,\n trail,\n}: RowProps) {\n const selfChecked =\n row.blockedBy === \"self_check\" || mismatches.some((m) => m.reason === \"self_check\");\n const decided = selfChecked\n ? SELF_CHECK_TOOLTIP\n : row.serverResolved\n ? SERVER_RESOLVED_TOOLTIP\n : `Include: ${LAYER_LABEL[row.decided_by.include]} · Limit: ${LAYER_LABEL[row.decided_by.max_inline_chars]}`;\n const labelNode = onOpenRow ? (\n <button\n type=\"button\"\n onClick={() => onOpenRow(row.key)}\n className=\"block min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {row.label}\n </button>\n ) : (\n <span className=\"block min-w-0 flex-1 truncate\">{row.label}</span>\n );\n\n return (\n <div\n role=\"row\"\n data-key={row.key}\n data-server-resolved={row.serverResolved ? \"true\" : undefined}\n data-self-check={selfChecked ? \"true\" : undefined}\n data-included={row.include ? \"true\" : \"false\"}\n data-mismatch={mismatches.length > 0 ? \"true\" : undefined}\n aria-selected={selected || undefined}\n className={cn(\n grid,\n \"border-b border-border/50\",\n comfortable ? \"min-h-11\" : \"h-7\",\n selected && \"bg-accent\",\n )}\n >\n <div\n role=\"cell\"\n className={cn(\n \"flex min-w-0 items-center gap-1.5\",\n indent(depth),\n !row.include && \"opacity-50\",\n )}\n >\n {mismatches.length > 0 ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <span\n role=\"img\"\n aria-label=\"Mismatch\"\n className=\"inline-flex shrink-0 text-warning\"\n >\n <TriangleAlertIcon className=\"h-3.5 w-3.5\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{describeMismatches(mismatches)}</TooltipContent>\n </Tooltip>\n ) : null}\n {lead ? <span className=\"inline-flex shrink-0 items-center\">{lead}</span> : null}\n <Tooltip>\n <TooltipTrigger asChild>{labelNode}</TooltipTrigger>\n <TooltipContent>\n <div>{row.label}</div>\n <div className=\"font-normal text-muted-foreground\">{decided}</div>\n </TooltipContent>\n </Tooltip>\n {trail ? <span className=\"min-w-0 max-w-[45%] shrink truncate text-muted-foreground\">{trail}</span> : null}\n </div>\n <div role=\"cell\" className={cn(\"flex justify-center\", narrow && \"order-last\")}>\n {readOnly ? (\n <FrozenInclude name={row.label} checked={row.include} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${row.label}`}\n checked={row.include}\n onCheckedChange={(next) => onChange(row.key, row.surfaceKey, withInclude(row, next))}\n />\n )}\n </div>\n <div\n role=\"cell\"\n className={cn(\"flex items-center justify-end gap-1 tabular-nums\", !row.include && \"opacity-50\")}\n >\n {row.include && row.delivery === \"on_request\" ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <span role=\"img\" aria-label=\"On request\" className=\"inline-flex text-muted-foreground\">\n <ArrowDownToLineIcon className=\"h-3 w-3\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{onRequestReason(row)}</TooltipContent>\n </Tooltip>\n ) : null}\n <span>{formatChars(row.chars)}</span>\n </div>\n <div role=\"cell\">\n {narrow ? (\n <InlineMaxButton row={row} cap={cap} readOnly={readOnly} comfortable={comfortable} onChange={onChange} />\n ) : (\n <InlineMaxInput\n label={row.label}\n value={row.userRule?.max_inline_chars ?? null}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n )}\n </div>\n </div>\n );\n}\n\n/**\n * Narrow layout's Inline max: the limit as a compact button (its value, muted\n * when inherited, a dot when the person set it) that opens the same field.\n */\nfunction InlineMaxButton({\n row,\n cap,\n readOnly,\n comfortable,\n onChange,\n}: {\n row: ResolvedContextRow;\n cap: number;\n readOnly: boolean | undefined;\n comfortable: boolean;\n onChange: ContextRulesTableProps[\"onChange\"];\n}) {\n const [open, setOpen] = React.useState(false);\n const own = row.userRule?.max_inline_chars ?? null;\n const text = own !== null ? formatLimit(own) : limitPlaceholder(row, cap);\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n aria-label={`Inline max ${row.label}: ${text}`}\n disabled={readOnly}\n className={cn(\n \"relative inline-flex min-w-[2.25rem] items-center justify-end gap-1 rounded px-1 tabular-nums hover:bg-accent disabled:opacity-60\",\n comfortable ? \"h-8 after:absolute after:-inset-y-1.5 after:inset-x-0 after:content-['']\" : \"h-6\",\n own === null ? \"text-muted-foreground\" : \"text-foreground\",\n )}\n >\n {own !== null ? <span aria-hidden className=\"h-1 w-1 rounded-full bg-primary\" /> : null}\n {text}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"end\" className=\"w-auto p-2\">\n <div className=\"flex items-center gap-2 text-xs\">\n <span className=\"text-muted-foreground\">Inline max</span>\n <InlineMaxInput\n label={row.label}\n value={own}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n","/**\n * @ai-matrx/agents/context — the context value rules, headless.\n *\n * Contract: common-docs/systems/scopes-context/context-delivery/RULES.md.\n * Parity corpus: ./rules-corpus.json (run here by rules.test.ts and by aidream's\n * pytest against the Python twin `resolve_context_rule`). Every function here\n * is pure, zero-React, and safe to import on a server.\n *\n * The one flow a client runs per turn:\n * rows = values.map(v => resolveContextRow(v, savedRows, cap)) // what the table shows\n * context = buildContextWire(rows) // what the request sends\n * …on `context_receipt`: compareReceipt(rows, receipt) // screen vs server\n */\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** `users.user_surface_state.feature` for the person's saved rules. */\nexport const CONTEXT_RULES_FEATURE = \"context_rules\";\n/** Surface key for values no surface emitted (attachments, server-added values). */\nexport const DEFAULT_SURFACE_KEY = \"_default\";\n/** The server's default inline threshold when no layer sets one. */\nexport const DEFAULT_INLINE_MAX_CHARS = 200;\n/** The default ceiling every resolved limit is clamped to (a server knob). */\nexport const DEFAULT_INLINE_CAP = 50000;\n/** A lazy document's server default (RULES.md §2: \"a small lazy document 6000\"). */\nexport const LAZY_SOURCE_DEFAULT_MAX = 6000;\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** Which layer decided a field — lowest to highest. */\nexport type ContextLayer = \"default\" | \"page\" | \"agent\" | \"you\";\nexport type ContextDelivery = \"inline\" | \"on_request\" | \"off\";\n/**\n * A client row's delivery: the server's three, plus `\"server\"` — an included\n * value the server resolves itself (`isServerResolved`), whose delivery the\n * client does not claim. Never on the wire or in a receipt.\n */\nexport type ContextRowDelivery = ContextDelivery | \"server\";\n\n/** One saved per-person rule (one key on one surface). Both fields optional. */\nexport interface SavedContextRule {\n include?: boolean;\n max_inline_chars?: number;\n}\n\n/** `{ [surface_key]: { [context key]: SavedContextRule } }` — the person's rows. */\nexport type SavedContextRuleRows = Record<string, Record<string, SavedContextRule>>;\n\n/** The agent layer for one key (RULES.md §2). */\nexport interface ContextAgentLayer {\n /** The agent's Context Policy declares this key (or the value is the agent's own seed). */\n declared?: boolean;\n /** The policy's ceiling; only read when `declared`. */\n max_inline_chars?: number | null;\n /** `auto_context_disabled` — closes every undeclared key. */\n kill_switch?: boolean;\n}\n\n/** The page layer for one key: the surface that emitted the value. */\nexport interface ContextSurfaceLayer {\n /** The surface declares this value (a `ui_surface_value` row / manifest entry). */\n declared?: boolean;\n /** `false` drops the value unless the agent declares it. */\n auto_context?: boolean | null;\n /** `inlineUpTo` / envelope `max_inline_chars` / DB column. */\n max_inline_chars?: number | null;\n}\n\n/** The non-person layers for one value — what the table's layer breakdown shows. */\nexport interface ContextRuleLayers {\n /** The server's per-key default limit; `null`/absent = 200. */\n default_max?: number | null;\n agent?: ContextAgentLayer | null;\n surface?: ContextSurfaceLayer | null;\n}\n\n/**\n * Input to `resolveContextRule`. Snake case on purpose: it is the corpus shape\n * and the Python twin's shape. `user` is typed loosely because invalid saved\n * values (non-boolean include, non-integer or negative limit) must be ignored,\n * not trusted.\n */\nexport interface ContextRuleInput extends ContextRuleLayers {\n /** Size in code points; `null` = an unresolved lazy source. */\n chars: number | null;\n user?: { include?: unknown; max_inline_chars?: unknown } | null;\n /** Ceiling; default `DEFAULT_INLINE_CAP`. */\n cap?: number;\n /**\n * A server-authoritative value (`SERVER_AUTHORITATIVE_KEYS`, RULES.md §5a):\n * identity is not page or ambient context, so neither the page's switch nor\n * the agent's or mandate's kill switch closes it — only the person's own rule.\n */\n identity?: boolean;\n}\n\nexport interface ContextRuleResult {\n include: boolean;\n /** Effective limit, after the clamp. */\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n clamped: boolean;\n}\n\n/** One receipt row — RULES.md §5, wire fields exactly. */\nexport interface ContextReceiptRow {\n key: string;\n label: string;\n surface_key: string;\n origin: \"client\" | \"server\" | \"surroundings\" | \"rule\";\n chars: number | null;\n include: boolean;\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n user_rule: { include?: boolean; max_inline_chars?: number } | null;\n clamped: boolean;\n /** The CLIENT itself sent a value the person turned off. */\n client_sent_excluded: boolean;\n /**\n * `\"model\"`: nothing reached a model that reads no context. `\"self_check\"`:\n * the server's post-render safety check stripped it (RULES.md §4/§5) —\n * the row stays, `delivery: \"off\"`.\n */\n blocked_by: ContextBlockedBy | null;\n /**\n * Set when the server did not keep the value under its own key — still a\n * row, never missing (RULES.md §5): `\"expanded\"` (a surroundings envelope\n * became one row per part), `\"directive\"` (a reserved directive the server\n * acted on), `\"renamed\"` (an earlier key spelling, held under the stable\n * key), `\"unaccounted\"` (a server path removed it with no reason — filed as\n * a defect). Absent from an older server.\n */\n consumed_as?: ContextConsumedAs | null;\n /** The keys (each with its own row) that now carry what this value held. */\n consumed_into?: string[];\n /**\n * What the model READ for this value, verbatim from the rendered context\n * block (its own element: the whole value inline, or its on-request entry;\n * for a server-authoritative value, the server's own statement of it).\n * Absent/null when it reached no block (off, consumed) or from an older server.\n */\n delivered?: ContextDeliveredRef | null;\n /** On-request values the server holds as text: what the `context` tool returns (size + hash). */\n on_request?: ContextDeliveredRef | null;\n}\n\n/**\n * What the model read for one value or block, by SIZE and HASH only — never\n * the text (RULES.md §5b: a server-shaped value is fetched on demand, never\n * pushed). The text comes from the viewer (`ContextViewLoader`).\n */\nexport interface ContextDeliveredRef {\n /** Code-point length of the whole text the model read. */\n chars: number;\n /** SHA-256 hex of that text (UTF-8). */\n sha256: string;\n}\n\n/**\n * What to view: a value's `delivered` element, its `on_request` text, a\n * `block`, or what the agent can `fetchable` for a value through a tool (the\n * Organization: its selected scopes' values via `scope_system` — rendered when\n * opened, never on the receipt; `source: \"fetched_now\"`).\n */\nexport type ContextViewKind = \"delivered\" | \"on_request\" | \"block\" | \"fetchable\";\n\nexport interface ContextViewTarget {\n kind: ContextViewKind;\n /** The value's key, or the block's id. */\n key: string;\n}\n\n/**\n * The exact text the model received (a sent turn: `GET /ai/context/delivered`)\n * or will receive (the next turn: `POST /ai/context/preview` with `view`).\n */\nexport interface ContextViewedText {\n kind: ContextViewKind;\n key: string;\n text: string;\n chars: number;\n sha256: string;\n /**\n * `fetched_now`: read at request time — a `fetchable` text (what the agent\n * gets if it asks now) or a lazy `on_request` value the agent never read.\n * `tool_result`: exactly what the `context` tool returned to the agent.\n */\n source: \"preview\" | \"wire\" | \"conversation_prompt\" | \"turn_record\" | \"fetched_now\" | \"tool_result\";\n /**\n * `fetchable` only: `false` when the turn's agent cannot call the tool that\n * returns it (tools off, excluded, a structured-output turn). `text` is then\n * `\"\"`; the screen says so with state, never shows content as fetchable.\n */\n available?: boolean;\n /**\n * A lazy `on_request` value of a SENT turn only (a document, a file family,\n * a scope — the turn never reads one): `true` — the agent called `context`\n * for it and `text` is what the tool returned; `false` — the agent never\n * read it and `text` is what it returns now (the screen says so).\n */\n fetched?: boolean | null;\n}\n\n/** The host's door to the viewer API — called only when a person opens a value. */\nexport type ContextViewLoader = (target: ContextViewTarget) => Promise<ContextViewedText>;\n\n/**\n * The blocks a value's detail shows beneath its own text, because the model\n * received them as part of that value: the Organization is its live statement\n * AND the organization catalog (owner ruling 2026-10-01). Such a block is\n * counted in the value's chars and is not listed again under \"Also sent\".\n */\nexport const CONTEXT_ROW_BLOCKS: Readonly<Record<string, readonly string[]>> = {\n organization: [\"organization_catalog\"],\n};\n\n/**\n * Values whose content the agent READS THROUGH A TOOL rather than receiving it,\n * keyed to that tool: the Organization's selected scopes' values are returned\n * by `scope_system` (by design, never inline). Their detail shows \"Agent can\n * fetch\" — the viewer's `fetchable` text, loaded when opened (RULES.md §5b).\n */\nexport const CONTEXT_FETCHABLE_ROWS: Readonly<Record<string, string>> = {\n organization: \"scope_system\",\n};\n\n/** The receipt blocks shown under `key`'s detail (`CONTEXT_ROW_BLOCKS`). */\nexport function blocksForRow(\n key: string,\n blocks: readonly ContextReceiptBlock[] | null | undefined,\n): ContextReceiptBlock[] {\n const ids = CONTEXT_ROW_BLOCKS[key] ?? [];\n return (blocks ?? []).filter((b) => ids.includes(b.id));\n}\n\n/** The receipt blocks not shown under any value present in `rowKeys`. */\nexport function unclaimedBlocks(\n blocks: readonly ContextReceiptBlock[] | null | undefined,\n rowKeys: Iterable<string>,\n): ContextReceiptBlock[] {\n const claimed = new Set<string>();\n for (const key of rowKeys) for (const id of CONTEXT_ROW_BLOCKS[key] ?? []) claimed.add(id);\n return (blocks ?? []).filter((b) => !claimed.has(b.id));\n}\n\n/** How the server consumed a value it did not keep under its own key (receipt `consumed_as`). */\nexport type ContextConsumedAs = \"expanded\" | \"directive\" | \"renamed\" | \"unaccounted\";\n\n/**\n * The reserved keys the server never keeps under their own name, and what it\n * does with each — the receipt rows say so (`consumed_as`). The same table is\n * the parity corpus's `consumed_key_cases` (aidream `RESERVED_CONSUMED_KEYS`).\n */\nexport const RESERVED_CONSUMED_KEYS: Readonly<Record<string, ContextConsumedAs>> = {\n surface_chain: \"expanded\",\n window_forms: \"expanded\",\n __table_access: \"directive\",\n __google_files: \"directive\",\n};\n\n/**\n * Where the server states each SERVER-AUTHORITATIVE value (RULES.md §5a, owner\n * ruling 2026-10-01: identity is the server's truth, never the page's claim).\n * The server drops the client's copy of these keys and the model reads the\n * server's own value, every turn: `\"active_context\"` — its `<active_context>`\n * block (the conversation's organization, the scopes it admitted);\n * `\"manifest\"` — a server-built value (the authenticated person, the server's\n * clock). A screen never shows the client's copy of one as what will be sent.\n * The same table is the parity corpus's `server_authoritative_keys` (aidream\n * `SERVER_AUTHORITATIVE_KEYS`).\n */\nexport const SERVER_AUTHORITATIVE_KEYS: Readonly<Record<string, \"manifest\" | \"active_context\">> = {\n user: \"manifest\",\n client: \"manifest\",\n organization: \"active_context\",\n active_scopes: \"active_context\",\n};\n\n/** True for a key whose value the server states itself (`SERVER_AUTHORITATIVE_KEYS`). */\nexport function isServerAuthoritativeKey(key: string): boolean {\n return Object.prototype.hasOwnProperty.call(SERVER_AUTHORITATIVE_KEYS, key);\n}\n\n/**\n * One block of server text the model received this turn that is not a single\n * value — the turn's `<active_context>`, earlier-turn context, the sandbox\n * briefing, skills, memory, the organization catalog… (receipt `blocks`,\n * RULES.md §5). `delivered` is its exact text, cut at the receipt's cap.\n */\nexport interface ContextReceiptBlock {\n /** Stable id: the per-turn slot it rode in, or the system-prompt addition's name. */\n id: string;\n /** The id in words (`humanizeIdentifier`, `@ai-matrx/kit/text-case`). */\n label: string;\n /** Size and hash; the text comes from the viewer (`kind: \"block\"`). */\n delivered: ContextDeliveredRef;\n}\n\n/** The per-turn receipt the server streams as `context_receipt` — RULES.md §5. */\nexport interface ContextReceipt {\n version: 1;\n surface: string | null;\n cap: number;\n /** False: this turn's model cannot read context at all (every row `blocked_by: \"model\"`). */\n model_reads_context: boolean;\n /** The person's saved rules could not be read; the turn ran without them. */\n rules_error: string | null;\n rows: ContextReceiptRow[];\n /** Every other block of server text the model received, in render order (absent: older server). */\n blocks?: ContextReceiptBlock[];\n}\n\nexport type ContextRowOrigin = \"page\" | \"attached\" | \"system\";\n\n/** Why the server kept a value from the model on this turn (receipt `blocked_by`). */\nexport type ContextBlockedBy = \"model\" | \"self_check\";\n\n/** A client's resolved row: what its table renders and what `buildContextWire` sends. */\nexport interface ResolvedContextRow extends Omit<ContextRuleResult, \"delivery\"> {\n delivery: ContextRowDelivery;\n /**\n * The server resolves this value (a resource reference, a `*_id` UUID): size\n * and delivery are unknown (`chars: null`, `delivery: \"server\"` when\n * included), and its default limit is not predicted. Include and the\n * person's own rule still resolve normally.\n */\n serverResolved?: boolean;\n /** Display-only: chars / limit / delivery were filled from a receipt (`applyReceiptToRows`). */\n fromReceipt?: boolean;\n /** From a receipt: why the server kept this value from the model this turn. */\n blockedBy?: ContextBlockedBy;\n /**\n * Display-only, from a receipt: what the model read for this value. When set,\n * a detail view shows THIS — never `value`, the client's pre-send copy.\n */\n delivered?: ContextDeliveredRef;\n /** Display-only, from a receipt: what the `context` tool returns for it (size + hash). */\n onRequest?: ContextDeliveredRef;\n /** Display-only, from a receipt: blocks the model received as part of this value. */\n deliveredBlocks?: ContextReceiptBlock[];\n key: string;\n label: string;\n surfaceKey: string;\n origin: ContextRowOrigin;\n /** The raw value, or an already-rich envelope (`{ content, type, … }`). */\n value: unknown;\n chars: number | null;\n /** The saved rule that was applied (merged `_default` + surface row), or null. */\n userRule: SavedContextRule | null;\n description?: string;\n /** Context object type for the wire envelope (`text`, `json`, …). */\n type?: string;\n /** The non-person layers the rule was resolved from. Absent = default only. */\n layers?: ContextRuleLayers;\n}\n\n/** What a client knows about one value before resolution. */\nexport interface ContextRowSource {\n key: string;\n label: string;\n surfaceKey?: string;\n origin: ContextRowOrigin;\n value: unknown;\n /** Override the measured size (e.g. `null` for an unresolved lazy source). */\n chars?: number | null;\n description?: string;\n type?: string;\n layers?: ContextRuleLayers;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nconst isNum = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v);\nconst isValidLimit = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isInteger(v) && v >= 0;\n\n// ── resolveContextRule — RULES.md §2, line for line ─────────────────────────\n\nexport function resolveContextRule(input: ContextRuleInput): ContextRuleResult {\n const agent = input.agent ?? null;\n const surface = input.surface ?? null;\n const user = input.user ?? null;\n const cap = isNum(input.cap) ? input.cap : DEFAULT_INLINE_CAP;\n const agentDeclared = agent?.declared === true;\n\n const identity = input.identity === true;\n\n let include = true;\n let includeBy: ContextLayer = \"default\";\n if (!identity && surface?.declared === true && surface.auto_context === false) {\n if (agentDeclared) {\n include = true;\n includeBy = \"agent\";\n } else {\n include = false;\n includeBy = \"page\";\n }\n }\n if (!identity && agent?.kill_switch === true && !agentDeclared) {\n include = false;\n includeBy = \"agent\";\n }\n if (user && typeof user.include === \"boolean\") {\n include = user.include;\n includeBy = \"you\";\n }\n\n let limit = isNum(input.default_max) ? input.default_max : DEFAULT_INLINE_MAX_CHARS;\n let limitBy: ContextLayer = \"default\";\n const a = agentDeclared && isNum(agent?.max_inline_chars) ? agent.max_inline_chars : null;\n const s = isNum(surface?.max_inline_chars) ? surface.max_inline_chars : null;\n if (a !== null && s !== null) {\n if (s < a) {\n limit = s;\n limitBy = \"page\";\n } else {\n limit = a;\n limitBy = \"agent\";\n }\n } else if (a !== null) {\n limit = a;\n limitBy = \"agent\";\n } else if (s !== null) {\n limit = s;\n limitBy = \"page\";\n }\n if (user && isValidLimit(user.max_inline_chars)) {\n limit = user.max_inline_chars;\n limitBy = \"you\";\n }\n const clamped = limit > cap;\n limit = Math.min(limit, cap);\n\n const chars = input.chars;\n const delivery: ContextDelivery = !include\n ? \"off\"\n : chars === null || chars === undefined || limit === 0 || chars > limit\n ? \"on_request\"\n : \"inline\";\n\n return {\n include,\n max_inline_chars: limit,\n delivery,\n decided_by: { include: includeBy, max_inline_chars: limitBy },\n clamped,\n };\n}\n\n// ── contextValueChars — RULES.md §1 ─────────────────────────────────────────\n\n/** Count Unicode code points (never UTF-16 units: `\"😀\".length` is 2). */\nfunction codePoints(s: string): number {\n let n = 0;\n for (const _ of s) n += 1;\n return n;\n}\n\n/**\n * Size of a value in code points, exactly as the server's `content_as_str()`:\n * a string is itself; anything else is `JSON.stringify(value, null, 2)`\n * (Python `json.dumps(value, ensure_ascii=False, indent=2)`). `undefined` → 0.\n */\nexport function contextValueChars(value: unknown): number {\n if (value === undefined) return 0;\n if (typeof value === \"string\") return codePoints(value);\n let text: string | undefined;\n try {\n text = JSON.stringify(value, null, 2);\n } catch {\n text = String(value);\n }\n return text === undefined ? 0 : codePoints(text);\n}\n\n// ── lookupSavedRule — RULES.md §3 ───────────────────────────────────────────\n\nfunction sanitizeRule(raw: unknown): SavedContextRule {\n const out: SavedContextRule = {};\n if (!raw || typeof raw !== \"object\") return out;\n const r = raw as Record<string, unknown>;\n if (typeof r.include === \"boolean\") out.include = r.include;\n if (isValidLimit(r.max_inline_chars)) out.max_inline_chars = r.max_inline_chars;\n return out;\n}\n\n/**\n * The person's rule for one key on one surface: `_default[key]` merged per\n * field under `rows[surfaceKey][key]`, invalid fields stripped. `null` when\n * nothing valid is saved.\n */\nexport function lookupSavedRule(\n rows: SavedContextRuleRows | null | undefined,\n surfaceKey: string,\n key: string,\n): SavedContextRule | null {\n if (!rows || typeof rows !== \"object\") return null;\n const base = sanitizeRule(rows[DEFAULT_SURFACE_KEY]?.[key]);\n const own = surfaceKey === DEFAULT_SURFACE_KEY ? {} : sanitizeRule(rows[surfaceKey]?.[key]);\n const merged: SavedContextRule = { ...base, ...own };\n return Object.keys(merged).length === 0 ? null : merged;\n}\n\n/**\n * The person's rule for one key, drift-proof (identical to aidream's\n * `lookup_user_rule_for`). While a primary surface P is in play, every key\n * filed under `_default` OR under P resolves to the same per-field merge\n * `{ ..._default[key], ...rows[P][key] }` (P wins) — whichever surface the\n * client's or the server's manifest says \"declares\" the key. A code manifest\n * and the DB manifest can disagree (sync drift); this makes the person's rule\n * land the same on both sides anyway. A surroundings key (any other surface)\n * keeps its own surface: `{ ..._default[key], ...rows[surfaceKey][key] }`.\n * With no primary surface this is exactly `lookupSavedRule`.\n *\n * Saving is unchanged: page values save to P, everything else to `_default`.\n */\nexport function lookupSavedRuleFor(\n rows: SavedContextRuleRows | null | undefined,\n primarySurface: string | null | undefined,\n surfaceKey: string,\n key: string,\n): SavedContextRule | null {\n const primary = primarySurface && primarySurface !== DEFAULT_SURFACE_KEY ? primarySurface : null;\n if (primary && (surfaceKey === DEFAULT_SURFACE_KEY || surfaceKey === primary)) {\n return lookupSavedRule(rows, primary, key);\n }\n return lookupSavedRule(rows, surfaceKey, key);\n}\n\n// ── serverDefaultMax — the server's per-key default, read from the wire value ─\n\n/**\n * The keys that make a dict the rich envelope form — exactly aidream\n * `context_objects._RICH_FORM_KEYS`. A dict with ANY other key is raw content\n * on the server, `content` key or not.\n */\nexport const RICH_ENVELOPE_KEYS: ReadonlySet<string> = new Set([\n \"content\",\n \"mutable\",\n \"persist\",\n \"source\",\n \"type\",\n \"label\",\n \"description\",\n \"max_inline_chars\",\n \"default_max_inline_chars\",\n \"summary_agent_id\",\n]);\n\n/**\n * A UUID as the server's `_uuid` (Python `UUID(value.strip())`) accepts it:\n * hyphens optional, `{…}` braces and `urn:uuid:` prefixes allowed.\n */\nfunction isUuidLike(value: string): boolean {\n const hex = value\n .trim()\n .replace(/urn:/gi, \"\")\n .replace(/uuid:/gi, \"\")\n .replace(/^\\{+|\\}+$/g, \"\")\n .replace(/-/g, \"\");\n return /^[0-9a-f]{32}$/i.test(hex);\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/** A canonical resource reference the server promotes (aidream `parse_resource_reference`). */\nfunction isResourceRef(v: Record<string, unknown>): boolean {\n if (v.__kind !== \"resource_ref\") return false;\n const type = v.resource_type || v.type;\n const id = v.resource_id || v.id;\n return (\n typeof type === \"string\" &&\n type.trim() !== \"\" &&\n typeof id === \"string\" &&\n isUuidLike(id)\n );\n}\n\nfunction hasOwn(o: Record<string, unknown>, k: string): boolean {\n return Object.prototype.hasOwnProperty.call(o, k);\n}\n\nfunction onlyRichKeys(o: Record<string, unknown>): boolean {\n return Object.keys(o).every((k) => RICH_ENVELOPE_KEYS.has(k));\n}\n\nfunction hasLazySource(o: Record<string, unknown>): boolean {\n return isPlainObject(o.source) && typeof o.source.kind === \"string\";\n}\n\n/**\n * A rich envelope exactly as the server reads one (aidream\n * `_split_rich_context_value`): a plain object with its own `content` whose\n * every key is in `RICH_ENVELOPE_KEYS`. A record that merely HAS `content`\n * (a note `{ id, title, content }`) is raw content, not an envelope.\n */\nexport function isRichEnvelope(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value) && hasOwn(value, \"content\") && onlyRichKeys(value);\n}\n\n/** The source-only lazy pointer form: rich keys only, no `content`, a `source` with a `kind`. */\nfunction isLazyPointer(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value) && !hasOwn(value, \"content\") && onlyRichKeys(value) && hasLazySource(value);\n}\n\n/**\n * Split one wire value into `{ content, overrides }` exactly as aidream\n * `_split_rich_context_value`: a rich envelope or lazy pointer → its `content`\n * (null when absent) and every other key; anything else → the whole value as\n * content, no overrides.\n */\nexport function splitContextValue(value: unknown): {\n content: unknown;\n overrides: Record<string, unknown>;\n} {\n if (isRichEnvelope(value) || isLazyPointer(value)) {\n const { content = null, ...overrides } = value;\n return { content, overrides };\n }\n return { content: value, overrides: {} };\n}\n\n/**\n * The server's default inline limit for one wire value — the `default` layer\n * the server will use, before page/agent/you. Mirrors aidream\n * `context_rules._server_default_max` over the object `ContextManifest.build`\n * makes from the value (after `normalize_resource_context`):\n *\n * - a rich envelope (every key in the rich-form set, and `content` present or a\n * lazy `source` with a string `kind`) carrying a whole-number, non-negative\n * `default_max_inline_chars` → that;\n * - a top-level resource reference (`__kind: \"resource_ref\"` with a type and a\n * UUID id), or a lazy source whose `extra.resource_type` is set → 0\n * (descriptor-first);\n * - a lazy source (a `source` and null/absent `content`) → 6000;\n * - anything else → null (the server's 200).\n *\n * A resource reference nested as an envelope's `content` is NOT promoted by the\n * server (it reads top-level values only), so it is plain JSON content → null.\n */\nexport function serverDefaultMax(value: unknown): number | null {\n if (!isPlainObject(value)) return null;\n if (isResourceRef(value)) return 0;\n if (!isRichEnvelope(value) && !isLazyPointer(value)) return null;\n if (isValidLimit(value.default_max_inline_chars)) return value.default_max_inline_chars;\n if (hasLazySource(value) && (value.content === null || value.content === undefined)) {\n const src = value.source as Record<string, unknown>;\n const extra = isPlainObject(src.extra) ? src.extra : {};\n return extra.resource_type ? 0 : LAZY_SOURCE_DEFAULT_MAX;\n }\n return null;\n}\n\n// ── resolveContextRow — the glue a client runs per value ────────────────────\n\n/** Resolve one value into the row the table renders and the wire sends. */\nexport function resolveContextRow(\n source: ContextRowSource,\n savedRows: SavedContextRuleRows | null | undefined,\n cap: number = DEFAULT_INLINE_CAP,\n /** The page in play; makes the rule lookup drift-proof (`lookupSavedRuleFor`). */\n primarySurface?: string | null,\n): ResolvedContextRow {\n const surfaceKey = source.surfaceKey ?? DEFAULT_SURFACE_KEY;\n const serverResolved = isServerResolved(source.key, source.value);\n const chars = serverResolved\n ? null\n : source.chars !== undefined\n ? source.chars\n : unresolvedSize(source.value)\n ? null\n : contextValueChars(splitContextValue(source.value).content);\n const userRule = lookupSavedRuleFor(savedRows, primarySurface, surfaceKey, source.key);\n const layers: ContextRuleLayers = { ...(source.layers ?? {}) };\n if (!serverResolved && (layers.default_max === undefined || layers.default_max === null)) {\n const serverDefault = serverDefaultMax(source.value);\n if (serverDefault !== null) layers.default_max = serverDefault;\n }\n // Identity is decided as the server decides its own statement of it (RULES.md §5a): only the\n // person's rule closes it — never the page switch or the agent's / mandate's kill switch.\n const identity = isServerAuthoritativeKey(source.key);\n const result = resolveContextRule({ ...layers, chars, user: userRule, cap, identity });\n const row: ResolvedContextRow = {\n ...result,\n delivery: serverResolved && result.include ? \"server\" : result.delivery,\n key: source.key,\n label: source.label,\n surfaceKey,\n origin: source.origin,\n value: source.value,\n chars,\n userRule,\n };\n if (source.description !== undefined) row.description = source.description;\n if (source.type !== undefined) row.type = source.type;\n if (source.layers !== undefined || layers.default_max !== undefined) row.layers = layers;\n if (serverResolved) row.serverResolved = true;\n return row;\n}\n\n// ── buildContextWire — the ONLY producer of a request's `context` ──────────\n\n/**\n * Size the server cannot know yet: a lazy pointer (or an envelope with a lazy\n * source and null content), or a resource reference it will promote to one.\n */\nfunction unresolvedSize(value: unknown): boolean {\n if (!isPlainObject(value)) return false;\n if (isResourceRef(value)) return true;\n return (\n (isRichEnvelope(value) || isLazyPointer(value)) &&\n hasLazySource(value) &&\n (value.content === null || value.content === undefined)\n );\n}\n\nconst KIND_RESOURCE_REF = \"resource_ref\";\n\n/**\n * Values the server acts on by their top-level shape in `request.context`\n * (aidream `normalize_resource_context` → `parse_resource_reference`, which\n * reads ONLY top-level values):\n *\n * - a resource reference — any object whose `__kind` is `\"resource_ref\"`\n * (its own promote/exclude/overlay policy rides inside it);\n * - a bare UUID string under a conventional `*_id` key (`file_id`,\n * `attached_file_id`, `current_note_id`, …), which the server promotes when\n * the noun is a registered resource type. The registry lives on the server,\n * so every `*_id` key with a UUID passes through; for an unregistered noun\n * the server reads the bare string exactly as it would read it wrapped;\n * - a reserved key the server consumes by shape (`RESERVED_CONSUMED_KEYS`:\n * `surface_chain`, `window_forms`, `__table_access`, `__google_files`) —\n * wrapped, the server reads `{content, label}` instead of its list or grant\n * and drops it.\n *\n * These ship exactly as-is: no label, type, description or limit added.\n */\nexport function isWireDirective(key: string, value: unknown): boolean {\n if (Object.hasOwn(RESERVED_CONSUMED_KEYS, key)) return true;\n if (isPlainObject(value)) return value.__kind === KIND_RESOURCE_REF;\n return (\n typeof value === \"string\" &&\n isIdKey(key) &&\n isUuidLike(value)\n );\n}\n\n/** The server's key rule for promoting a bare id (`_resource_type_for_key`): a `*_id` key. */\nfunction isIdKey(key: string): boolean {\n return key.trim().toLowerCase().endsWith(\"_id\");\n}\n\n/**\n * A value whose size, default limit and delivery the SERVER decides by\n * resolving it — so the client must not predict them:\n *\n * - a top-level resource reference (`__kind: \"resource_ref\"`), bare or as a\n * rich envelope's `content`;\n * - a UUID string under a `*_id` key, bare or as a rich envelope's `content`.\n *\n * The server only promotes an id when its noun is in the resource registry\n * (aidream `_resource_type_for_key`), which the client cannot see, so every\n * `*_id` UUID counts. This is a deliberate superset: on a value the server\n * does not promote, the client only stops predicting — it never makes a wrong\n * promise.\n */\nexport function isServerResolved(key: string, value: unknown): boolean {\n const inner = isRichEnvelope(value) ? value.content : value;\n if (isPlainObject(inner)) return inner.__kind === KIND_RESOURCE_REF;\n return typeof inner === \"string\" && isIdKey(key) && isUuidLike(inner);\n}\n\n/**\n * Build the request's `context` object from the resolved rows. This is the\n * ONLY function that may produce it, so what the table shows and what the\n * request carries cannot drift apart.\n *\n * - A row whose `include` is false is omitted entirely — it never reaches the\n * wire (RULES.md §1: off means off everywhere).\n * - An included row becomes `{ content, type?, label, description?,\n * max_inline_chars? }`. An already-rich envelope (`isRichEnvelope`, e.g. a\n * working document carrying `source`/`mutable`/`persist`, or a lazy pointer)\n * keeps every non-rule field it already has; `label`/`description`/`type`\n * are only filled when missing.\n * - `max_inline_chars` on the envelope is the PAGE layer's value only\n * (`layers.surface.max_inline_chars`, else the envelope's own page value).\n * The server reads the person's saved rules itself every turn (RULES.md §3)\n * and the agent layer from its own policy, so the wire must never carry the\n * person's number or the resolved effective limit dressed up as a page rule\n * — that would make a stale client value outrank the server's fresh read.\n */\nexport function buildContextWire(rows: readonly ResolvedContextRow[]): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n for (const row of rows) {\n if (!row.include) continue;\n // A row with no value (a receipt-built display row) has nothing to send.\n if (row.value === undefined) continue;\n // Rich: an envelope with `content`, or a source-only lazy pointer. Every\n // non-rule field survives — including `default_max_inline_chars`, the\n // server's per-key default (not a person's or a page's number).\n // A record that merely has `content` is NOT rich: it is wrapped whole, or\n // the server would read it as raw content and drop the envelope fields.\n // A top-level directive the server acts on by SHAPE ships exactly as-is:\n // wrapped, it becomes plain JSON and silently stops resolving.\n if (isWireDirective(row.key, row.value)) {\n wire[row.key] = row.value;\n continue;\n }\n const rich = isRichEnvelope(row.value) || isLazyPointer(row.value);\n const envelope: Record<string, unknown> = rich\n ? { ...(row.value as Record<string, unknown>) }\n : { content: row.value };\n delete envelope.max_inline_chars;\n if (envelope.type === undefined && row.type !== undefined) envelope.type = row.type;\n if (envelope.label === undefined) envelope.label = row.label;\n if (envelope.description === undefined && row.description !== undefined) {\n envelope.description = row.description;\n }\n const pageLimit = row.layers?.surface?.max_inline_chars;\n const ownPageLimit = rich ? (row.value as Record<string, unknown>).max_inline_chars : undefined;\n if (isValidLimit(pageLimit)) envelope.max_inline_chars = pageLimit;\n else if (isValidLimit(ownPageLimit)) envelope.max_inline_chars = ownPageLimit;\n wire[row.key] = envelope;\n }\n return wire;\n}\n\n// ── compareReceipt — RULES.md §6 ────────────────────────────────────────────\n\nexport interface ContextReceiptMismatch {\n key: string;\n field: \"include\" | \"max_inline_chars\" | \"delivery\" | \"user_rule\" | \"missing\";\n expected: unknown;\n actual: unknown;\n /**\n * `\"self_check\"`: a real difference from what was shown — the server's\n * safety check stripped the value before the model call. Say \"removed by\n * the server's safety check\", not \"the screen was wrong\".\n */\n reason?: \"self_check\";\n}\n\nfunction normalizeUserRule(rule: SavedContextRule | null | undefined): SavedContextRule | null {\n const clean = sanitizeRule(rule);\n return Object.keys(clean).length === 0 ? null : clean;\n}\n\nfunction sameRule(a: SavedContextRule | null, b: SavedContextRule | null): boolean {\n if (a === null || b === null) return a === b;\n return a.include === b.include && a.max_inline_chars === b.max_inline_chars;\n}\n\n/**\n * Compare the rows the client resolved (and rendered, and sent) with the\n * receipt the server emitted for the same turn.\n *\n * For each expected row, the receipt row is matched by key + surface key, then\n * by key alone. Compared: `include`, `max_inline_chars`, `delivery` (only when\n * both sides know the size) and `user_rule`. An expected row absent from the\n * receipt is a `missing` mismatch — except a row the client correctly withheld\n * for a reason other than the person's own rule (page `auto_context` off, the\n * agent's kill switch): the client never sent it and the server lists only\n * the person's saved `include: false` rules as `origin: \"rule\"` rows, so its\n * absence is the truth, not a lie. Receipt rows nobody expected are returned\n * as `systemRows` — shown, never hidden. A row the server consumed\n * (`consumed_as`: expanded / directive / renamed) is compared on `include`\n * and `user_rule` only — its parts carry their own rows; an `\"unaccounted\"`\n * row, or an included envelope `\"expanded\"` into no parts, is a `missing`\n * mismatch.\n */\nexport function compareReceipt(\n expected: readonly ResolvedContextRow[],\n receipt: ContextReceipt,\n): { mismatches: ContextReceiptMismatch[]; systemRows: ContextReceiptRow[]; modelReadsContext: boolean } {\n const mismatches: ContextReceiptMismatch[] = [];\n // A turn whose model reads no context delivers nothing by design: every row\n // is `delivery: \"off\"`, `blocked_by: \"model\"`. That is not a lie about the\n // person's rules, so delivery is not compared; include / limit / rule still are.\n const modelReadsContext = receipt.model_reads_context !== false;\n const used = new Set<ContextReceiptRow>();\n const rows = receipt.rows ?? [];\n\n for (const exp of expected) {\n const actual =\n rows.find((r) => !used.has(r) && r.key === exp.key && r.surface_key === exp.surfaceKey) ??\n rows.find((r) => !used.has(r) && r.key === exp.key);\n if (!actual) {\n const withheldByOthers = !exp.include && exp.decided_by.include !== \"you\";\n if (!withheldByOthers) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: null });\n }\n continue;\n }\n used.add(actual);\n if (actual.include !== exp.include) {\n mismatches.push({ key: exp.key, field: \"include\", expected: exp.include, actual: actual.include });\n }\n // A consumed value (expanded / directive / renamed) was not delivered as\n // itself: its parts carry their own rows, limits and deliveries. Only\n // include and the person's rule are this key's own promise.\n const consumed = Boolean(actual.consumed_as);\n // A server path removed the value with no reason: kept as a row so it is\n // never silently missing, and still a broken promise on this screen.\n if (actual.consumed_as === \"unaccounted\" && exp.include) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: \"unaccounted\" });\n }\n // An envelope the screen showed as sent that the server expanded into no\n // parts delivered nothing (a window whose fields were all unreadable):\n // \"expanded\" alone would pass it silently.\n if (\n actual.consumed_as === \"expanded\" &&\n actual.include &&\n exp.include &&\n (actual.consumed_into ?? []).length === 0\n ) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: \"expanded_into_nothing\" });\n }\n // A server-resolved value's limit is only the client's to promise when the\n // person set one; its default-derived limit and delivery are the server's.\n const promisesLimit =\n !consumed && (!exp.serverResolved || exp.userRule?.max_inline_chars !== undefined);\n if (promisesLimit && actual.max_inline_chars !== exp.max_inline_chars) {\n mismatches.push({\n key: exp.key,\n field: \"max_inline_chars\",\n expected: exp.max_inline_chars,\n actual: actual.max_inline_chars,\n });\n }\n // The safety check stripped a value the person included: always a\n // mismatch (server-resolved or not), tagged with its reason.\n const selfChecked = actual.blocked_by === \"self_check\" && exp.include;\n if (selfChecked) {\n mismatches.push({\n key: exp.key,\n field: \"delivery\",\n expected: exp.delivery,\n actual: actual.delivery,\n reason: \"self_check\",\n });\n }\n if (\n !selfChecked &&\n !consumed &&\n modelReadsContext &&\n !exp.serverResolved &&\n exp.delivery !== \"server\" &&\n exp.chars !== null &&\n actual.chars !== null &&\n actual.delivery !== exp.delivery\n ) {\n mismatches.push({ key: exp.key, field: \"delivery\", expected: exp.delivery, actual: actual.delivery });\n }\n const expRule = normalizeUserRule(exp.userRule);\n const actRule = normalizeUserRule(actual.user_rule);\n if (!sameRule(expRule, actRule)) {\n mismatches.push({ key: exp.key, field: \"user_rule\", expected: expRule, actual: actRule });\n }\n }\n\n return { mismatches, systemRows: rows.filter((r) => !used.has(r)), modelReadsContext };\n}\n\n/**\n * For DISPLAY only: fill each server-resolved row's `chars`,\n * `max_inline_chars` and `delivery` from the latest receipt row for the same\n * key (key + surface key, then key), marking it `fromReceipt`. Other rows are\n * returned unchanged. Never compare these rows — `compareReceipt` takes the\n * rows the client resolved before sending.\n */\nexport function applyReceiptToRows(\n rows: readonly ResolvedContextRow[],\n receipt: ContextReceipt | null | undefined,\n): ResolvedContextRow[] {\n const receiptRows = receipt?.rows ?? [];\n return rows.map((row) => {\n const hit =\n receiptRows.find((r) => r.key === row.key && r.surface_key === row.surfaceKey) ??\n receiptRows.find((r) => r.key === row.key);\n if (!hit) return row;\n // What the model read is the server's to report for EVERY value — a value the\n // server replaced or reshaped must never show as the client's copy. A value the\n // server states itself (RULES.md §5a) is measured by what it stated, never by\n // the page's copy.\n const attached = blocksForRow(row.key, receipt?.blocks);\n const stated =\n hit.delivered && isServerAuthoritativeKey(row.key)\n ? hit.delivered.chars + attached.reduce((n, b) => n + b.delivered.chars, 0)\n : null;\n const shown = {\n ...row,\n ...deliveredFields(hit),\n ...(stated !== null ? { chars: stated } : {}),\n ...(attached.length ? { deliveredBlocks: attached } : {}),\n };\n if (!row.serverResolved) return shown;\n return {\n ...shown,\n chars: stated ?? hit.chars,\n max_inline_chars: hit.max_inline_chars,\n delivery: hit.delivery,\n fromReceipt: true,\n ...(hit.blocked_by ? { blockedBy: hit.blocked_by } : {}),\n };\n });\n}\n\n// ── receiptRowToResolved — read-only rows for a sent message ────────────────\n\n/**\n * Turn one receipt row into the row a read-only table renders (a sent\n * message's context, read back from `chat.message.model_context`). The value\n * itself is not in the receipt, so `value` is undefined.\n */\nexport function receiptRowToResolved(\n row: ContextReceiptRow,\n blocks?: readonly ContextReceiptBlock[] | null,\n): ResolvedContextRow {\n const attached = row.delivered ? blocksForRow(row.key, blocks) : [];\n const origin: ContextRowOrigin =\n row.surface_key !== DEFAULT_SURFACE_KEY ? \"page\" : row.origin === \"client\" ? \"attached\" : \"system\";\n return {\n key: row.key,\n label: row.label,\n surfaceKey: row.surface_key,\n origin,\n value: undefined,\n chars:\n row.delivered && isServerAuthoritativeKey(row.key)\n ? row.delivered.chars + attached.reduce((n, b) => n + b.delivered.chars, 0)\n : row.chars,\n userRule: normalizeUserRule(row.user_rule),\n include: row.include,\n max_inline_chars: row.max_inline_chars,\n delivery: row.delivery,\n decided_by: { include: row.decided_by.include, max_inline_chars: row.decided_by.max_inline_chars },\n clamped: row.clamped,\n layers: receiptLayers(row),\n ...(row.blocked_by ? { blockedBy: row.blocked_by } : {}),\n ...deliveredFields(row),\n ...(attached.length ? { deliveredBlocks: attached } : {}),\n };\n}\n\n/** A receipt row's `delivered` / `on_request` as display fields (absent when not sent). */\nexport function deliveredFields(\n row: Pick<ContextReceiptRow, \"delivered\" | \"on_request\">,\n): Pick<ResolvedContextRow, \"delivered\" | \"onRequest\"> {\n return {\n ...(row.delivered ? { delivered: row.delivered } : {}),\n ...(row.on_request ? { onRequest: row.on_request } : {}),\n };\n}\n\n/**\n * Rebuild the non-person layers from what the server applied, so a read-only\n * table shows the applied limit as the inherited value and marks the layer\n * that decided it. The limit goes on the layer named by\n * `decided_by.max_inline_chars` (`you` is carried by `userRule`); include is\n * rebuilt the same way for a page `auto_context` off or the agent's kill switch.\n */\n/**\n * Keys the client has a value for but is NOT sending this turn (excluded by\n * the page, the agent or the person's rule). Clients send this list as the\n * request's `context_withheld`, so the receipt's `origin: \"rule\"` rows are\n * limited to keys actually withheld on this page. Deduplicated, in row order.\n */\nexport function withheldKeys(rows: readonly ResolvedContextRow[]): string[] {\n const out: string[] = [];\n for (const row of rows) {\n if (row.include || row.value === undefined || out.includes(row.key)) continue;\n out.push(row.key);\n }\n return out;\n}\n\nconst DOCUMENT_KEY_PREFIXES = [\"attached_document_\", \"attached_file_\", \"resource_file_\"];\n\n/**\n * Receipt rows the client never sent (`compareReceipt(...).systemRows`:\n * server-seeded attachments, scope seeds, saved off-rules…) as table rows, so\n * a person can see and govern them — the normal Include switch and Inline max\n * apply. Documents (`attached_document_*`, `attached_file_*`,\n * `resource_file_*`) group as \"attached\", everything else as \"system\". The\n * server resolved them (`serverResolved`), values come from the receipt\n * (`fromReceipt`), and `surfaceKey` is the row's own `surface_key` — so a rule\n * saved for one writes to `_default` unless the server filed it under a page.\n * `value` is undefined: `buildContextWire` never sends these rows.\n */\nexport function systemRowsToResolved(systemRows: readonly ContextReceiptRow[]): ResolvedContextRow[] {\n return systemRows.map((receiptRow) => {\n const row = receiptRowToResolved(receiptRow);\n const isDocument = DOCUMENT_KEY_PREFIXES.some((p) => receiptRow.key.startsWith(p));\n return {\n ...row,\n origin: isDocument ? \"attached\" : \"system\",\n serverResolved: true,\n fromReceipt: true,\n };\n });\n}\n\nfunction receiptLayers(row: ContextReceiptRow): ContextRuleLayers {\n const layers: ContextRuleLayers = {};\n const limit = row.max_inline_chars;\n const limitBy = row.decided_by.max_inline_chars;\n const includeBy = row.decided_by.include;\n if (limitBy === \"default\") layers.default_max = limit;\n // Page auto_context off: the page dropped it, or the agent re-admitted it.\n const pageOff = (includeBy === \"page\" && !row.include) || (includeBy === \"agent\" && row.include);\n if (limitBy === \"page\" || pageOff) {\n layers.surface = {\n declared: true,\n auto_context: !pageOff,\n max_inline_chars: limitBy === \"page\" ? limit : null,\n };\n }\n if (limitBy === \"agent\") {\n // An agent limit means the key is declared; a declared key the agent decided to include\n // was re-admitted past a page auto_context off. (The kill switch never closes a declared key.)\n layers.agent = { declared: true, max_inline_chars: limit };\n } else if (includeBy === \"agent\") {\n // Off = the kill switch closing an undeclared key; on = a declaration re-admitting a\n // page auto_context-off value.\n layers.agent = row.include ? { declared: true } : { declared: false, kill_switch: true };\n }\n return layers;\n}\n\n// ── attachmentContextKey — the context key of a conversation attachment ─────\n\n/**\n * The context key the server files a conversation attachment under, derivable\n * by every client from `GET /conversations/{id}/attachments` (aidream\n * `conversation_attachments/briefing.py`; corpus `attachment_key_cases`):\n *\n * `attached_resource_` + encode(`${provider}:${resourceRef}`)\n *\n * where encode keeps ASCII letters, digits and `-`, and writes every other\n * UTF-8 byte as `_` + two lowercase hex digits (`_` itself is `_5f`). Unique\n * across providers, case-preserving (Drive ids), stable.\n */\nexport function attachmentContextKey(provider: string, resourceRef: string): string {\n const bytes = new TextEncoder().encode(`${provider}:${resourceRef}`);\n let out = \"attached_resource_\";\n for (const b of bytes) {\n const keep =\n (b >= 0x30 && b <= 0x39) || (b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a) || b === 0x2d;\n out += keep ? String.fromCharCode(b) : `_${b.toString(16).padStart(2, \"0\")}`;\n }\n return out;\n}\n\n// ── Display ─────────────────────────────────────────────────────────────────\n\n/** Compact size for a tabular column: `950`, `18.4k`, `184k`, `1.2M`, `—` for unknown. */\nexport function formatChars(n: number | null | undefined): string {\n if (n === null || n === undefined || !Number.isFinite(n)) return \"—\";\n const abs = Math.abs(n);\n const trim = (s: string) => s.replace(/\\.0$/, \"\");\n if (abs < 1000) return String(Math.round(n));\n if (abs < 100_000) return `${trim((n / 1000).toFixed(1))}k`;\n if (abs < 1_000_000) return `${Math.round(n / 1000)}k`;\n return `${trim((n / 1_000_000).toFixed(1))}M`;\n}\n\n// RULES.md §0 — what a page's own conversation (or a switched-off page) never receives.\nexport * from \"./page-context\";\n","/**\n * Inlined Lucide shapes (C19 — no icon-library dependency): same 24×24 grid,\n * 2px stroke, `currentColor` only. Names match the Lucide originals.\n */\nimport type { ReactNode, SVGProps } from \"react\";\n\nexport type ContextIconProps = SVGProps<SVGSVGElement>;\n\nfunction icon(children: ReactNode) {\n return function Icon(props: ContextIconProps) {\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 {...props}\n >\n {children}\n </svg>\n );\n };\n}\n\nexport const EyeIcon = icon(\n <>\n <path d=\"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </>,\n);\nexport const EyeOffIcon = icon(\n <>\n <path d=\"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49\" />\n <path d=\"M14.084 14.158a3 3 0 0 1-4.242-4.242\" />\n <path d=\"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143\" />\n <path d=\"m2 2 20 20\" />\n </>,\n);\nexport const RotateCcwIcon = icon(\n <>\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n </>,\n);\nexport const PanelRightIcon = icon(\n <>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </>,\n);\nexport const ChevronLeftIcon = icon(<path d=\"m15 18-6-6 6-6\" />);\nexport const TriangleAlertIcon = icon(\n <>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </>,\n);\nexport const SearchIcon = icon(\n <>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </>,\n);\n/** \"On request\" — the agent pulls the value down when it needs it. */\nexport const ArrowDownToLineIcon = icon(\n <>\n <path d=\"M12 17V3\" />\n <path d=\"m6 11 6 6 6-6\" />\n <path d=\"M19 21H5\" />\n </>,\n);\n\nexport const LockIcon = icon(\n <>\n <rect width=\"18\" height=\"11\" x=\"3\" y=\"11\" rx=\"2\" ry=\"2\" />\n <path d=\"M7 11V7a5 5 0 0 1 10 0v4\" />\n </>,\n);\n\nexport const CheckIcon = icon(<path d=\"M20 6 9 17l-5-5\" />);\n\nexport const MinusIcon = icon(<path d=\"M5 12h14\" />);\n","/**\n * THE HIERARCHY of the context rules table — where each value sits, and the\n * switch at every level (Arman, 2026-10-02: \"AI Matrx\" for the platform's own\n * values; the page by its section and real name; under it the page's own\n * declared groups; a switch per level).\n *\n * The package never knows a page's groups: the host PLACES each row (level +\n * group, both already-human labels) and may give a level a host switch (the\n * page's own on/off). Without a host placement every row is placed by its\n * origin. A level or group switch is NOT a new kind of rule: it is the\n * person's per-value include rules for every value in it, written at once\n * (`includeChanges`), so the server's gate and receipt see exactly the rules\n * they already honour.\n */\n\nimport {\n isServerAuthoritativeKey,\n resolveContextRule,\n type ContextRowOrigin,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\n\n/** A level of the table: the platform, a page, the chat's attachments. */\nexport interface ContextLevelRef {\n /** Stable id (a surface key, `ai_matrx`, `attached`). */\n id: string;\n /** Heading, root first: `[\"Marketing\", \"Marketing Brand Cockpit\"]`, `[\"AI Matrx\"]`. */\n path: readonly string[];\n /** Sort order between levels (lower first). */\n order?: number;\n}\n\n/** A group inside a level — the page's own declared group, label as declared. */\nexport interface ContextGroupRef {\n id: string;\n label: string;\n order?: number;\n}\n\n/** Where one row sits. */\nexport interface ContextRowPlace {\n level: ContextLevelRef;\n /** Null: directly under the level. */\n group?: ContextGroupRef | null;\n}\n\n/**\n * A level whose switch is the host's own (the page on/off for this\n * conversation) rather than the person's per-value rules. Shown even when the\n * level has no rows, so the switch never disappears with its values.\n */\nexport interface ContextLevelMaster {\n level: ContextLevelRef;\n on: boolean;\n onToggle?: ((next: boolean) => void) | undefined;\n}\n\nexport interface ContextHierarchy {\n place: (row: ResolvedContextRow) => ContextRowPlace;\n masters?: readonly ContextLevelMaster[];\n}\n\nexport interface ContextGroupNode {\n ref: ContextGroupRef;\n rows: ResolvedContextRow[];\n}\n\nexport interface ContextLevelNode {\n ref: ContextLevelRef;\n /** Rows directly under the level (no group). */\n rows: ResolvedContextRow[];\n groups: ContextGroupNode[];\n master: ContextLevelMaster | null;\n}\n\n/** The platform's own values: the person, their organization, the client. */\nexport const AI_MATRX_LEVEL: ContextLevelRef = { id: \"ai_matrx\", path: [\"AI Matrx\"], order: 900 };\n/** Files and documents attached to the conversation. */\nexport const ATTACHED_LEVEL: ContextLevelRef = { id: \"attached\", path: [\"Attached\"], order: 500 };\n/** A page the host has not named. */\nexport const PAGE_LEVEL: ContextLevelRef = { id: \"page\", path: [\"Page\"], order: 100 };\n\nconst ORIGIN_LEVEL: Record<ContextRowOrigin, ContextLevelRef> = {\n page: PAGE_LEVEL,\n attached: ATTACHED_LEVEL,\n system: AI_MATRX_LEVEL,\n};\n\n/** The placement a host without one gets: by origin. */\nexport function placeByOrigin(row: ResolvedContextRow): ContextRowPlace {\n return { level: ORIGIN_LEVEL[row.origin] };\n}\n\n/** Sort by `order`, keeping first-seen order among equals. */\nfunction stableSort<T>(list: readonly T[], ref: (item: T) => { order?: number }): T[] {\n return list\n .map((item, i) => ({ item, i }))\n .sort((a, b) => (ref(a.item).order ?? 0) - (ref(b.item).order ?? 0) || a.i - b.i)\n .map(({ item }) => item);\n}\n\n/** Rows → levels → groups, in the host's order (stable within equal orders). */\nexport function buildContextLevels(\n rows: readonly ResolvedContextRow[],\n hierarchy?: ContextHierarchy | null,\n): ContextLevelNode[] {\n const place = hierarchy?.place ?? placeByOrigin;\n const levels = new Map<string, ContextLevelNode>();\n const levelFor = (ref: ContextLevelRef) => {\n let node = levels.get(ref.id);\n if (!node) {\n node = { ref, rows: [], groups: [], master: null };\n levels.set(ref.id, node);\n }\n return node;\n };\n for (const master of hierarchy?.masters ?? []) levelFor(master.level).master = master;\n for (const row of rows) {\n const where = place(row);\n const level = levelFor(where.level);\n if (!where.group) {\n level.rows.push(row);\n continue;\n }\n let group = level.groups.find((g) => g.ref.id === where.group!.id);\n if (!group) {\n group = { ref: where.group, rows: [] };\n level.groups.push(group);\n }\n group.rows.push(row);\n }\n const out = [...levels.values()];\n for (const level of out) level.groups = stableSort(level.groups, (g) => g.ref);\n return stableSort(out, (level) => level.ref);\n}\n\n/** Every row of a level, groups included. */\nexport function levelRows(level: ContextLevelNode): ResolvedContextRow[] {\n return [...level.rows, ...level.groups.flatMap((g) => g.rows)];\n}\n\n/** What the row's include would be with no rule of the person's. */\nexport function inheritedInclude(row: ResolvedContextRow, cap: number): boolean {\n return resolveContextRule({\n ...(row.layers ?? {}),\n chars: row.chars,\n cap,\n user: null,\n identity: isServerAuthoritativeKey(row.key),\n }).include;\n}\n\n/** One person-rule write: `rule: null` removes the person's rule for that value. */\nexport interface ContextRuleChange {\n key: string;\n surfaceKey: string;\n rule: SavedContextRule | null;\n}\n\n/**\n * A level or group switch: the person's include rule for every value in it\n * that is not already `include`. A value whose default already gives\n * `include` loses its own include rule instead (back to the default) — the\n * saved rules stay minimal and \"Reset all\" means what it says.\n */\nexport function includeChanges(\n rows: readonly ResolvedContextRow[],\n include: boolean,\n cap: number,\n): ContextRuleChange[] {\n const changes: ContextRuleChange[] = [];\n for (const row of rows) {\n if (row.include === include) continue;\n const next: SavedContextRule = { ...(row.userRule ?? {}) };\n if (inheritedInclude(row, cap) === include) delete next.include;\n else next.include = include;\n changes.push({\n key: row.key,\n surfaceKey: row.surfaceKey,\n rule: Object.keys(next).length === 0 ? null : next,\n });\n }\n return changes;\n}\n","import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, cn } from \"@ai-matrx/design-system\";\n\nimport { CheckIcon, LockIcon, MinusIcon } from \"./icons\";\n\n/** Tooltip on a frozen include state (a sent turn's receipt). ≤140 chars. */\nexport const FROZEN_INCLUDE_TOOLTIP = \"Sent as shown\";\n\n/**\n * A sent message's include state, frozen: a static on/off mark with a lock —\n * never a switch, so nothing on a receipt looks clickable.\n */\nexport function FrozenInclude({ name, checked }: { name: string; checked: boolean }) {\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <Tooltip>\n <TooltipTrigger asChild>\n <span\n role=\"img\"\n aria-label={`${checked ? \"Included\" : \"Not included\"}: ${name}`}\n data-frozen-include={checked ? \"on\" : \"off\"}\n tabIndex={0}\n className={cn(\n \"inline-flex h-5 items-center gap-0.5 rounded px-1 text-muted-foreground\",\n checked ? \"bg-muted text-foreground\" : \"bg-transparent\",\n )}\n >\n {checked ? <CheckIcon className=\"h-3 w-3\" /> : <MinusIcon className=\"h-3 w-3\" />}\n <LockIcon className=\"h-2.5 w-2.5 opacity-70\" />\n </span>\n </TooltipTrigger>\n <TooltipContent>{FROZEN_INCLUDE_TOOLTIP}</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport {\n Input,\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport { RotateCcwIcon } from \"./icons\";\nimport { formatLimit } from \"./shared\";\n\nexport interface InlineMaxInputProps {\n /** The person's own limit, or null when inherited. */\n value: number | null;\n /** What applies without the person's number (shown muted). */\n inherited: number;\n /** Override the muted text shown when the person set no number (e.g. \"auto\"). */\n placeholder?: string | undefined;\n cap: number;\n /** Next limit, or null to drop the person's number. */\n onCommit: (next: number | null) => void;\n disabled?: boolean | undefined;\n /** Accessible name — the row's label. */\n label: string;\n comfortable?: boolean;\n}\n\n/**\n * The Inline max cell: a 6ch numeric field. Inherited value shows as muted\n * placeholder text; an override shows a dot and a reset button. `0` reads\n * \"Never\". Commits on blur/Enter, Escape reverts, above-cap is clamped on\n * commit with a brief \"Limit is {cap}\" tooltip.\n */\nexport function InlineMaxInput({\n value,\n inherited,\n cap,\n onCommit,\n disabled,\n label,\n comfortable,\n placeholder,\n}: InlineMaxInputProps) {\n const [focused, setFocused] = React.useState(false);\n const [draft, setDraft] = React.useState(\"\");\n const [notice, setNotice] = React.useState(false);\n const skip = React.useRef(false);\n\n React.useEffect(() => {\n if (!notice) return;\n const t = setTimeout(() => setNotice(false), 2000);\n return () => clearTimeout(t);\n }, [notice]);\n\n const commit = () => {\n const text = draft.trim();\n let next: number | null;\n if (text === \"\") next = null;\n else if (/^never$/i.test(text)) next = 0;\n else if (/^\\d+$/.test(text)) next = Number(text);\n else return;\n if (next !== null && next > cap) {\n next = cap;\n setNotice(true);\n }\n if (next !== value) onCommit(next);\n };\n\n const overridden = value !== null;\n\n return (\n <div className={cn(\"flex items-center justify-end\", comfortable ? \"gap-0.5\" : \"gap-1\")}>\n <span\n aria-hidden=\"true\"\n className={cn(\"h-1.5 w-1.5 shrink-0 rounded-full\", overridden ? \"bg-primary\" : \"bg-transparent\")}\n />\n <Tooltip open={notice}>\n <TooltipTrigger asChild>\n <Input\n type=\"text\"\n inputMode=\"numeric\"\n aria-label={`Inline max for ${label}`}\n disabled={disabled}\n value={focused ? draft : overridden ? formatLimit(value) : \"\"}\n placeholder={overridden ? undefined : (placeholder ?? formatLimit(inherited))}\n onFocus={() => {\n setDraft(overridden ? String(value) : \"\");\n setFocused(true);\n }}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n setFocused(false);\n if (skip.current) {\n skip.current = false;\n return;\n }\n commit();\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") e.currentTarget.blur();\n else if (e.key === \"Escape\") {\n e.stopPropagation();\n skip.current = true;\n e.currentTarget.blur();\n }\n }}\n className={cn(\n \"min-w-0 rounded px-1 py-0 text-right tabular-nums shadow-none\",\n comfortable ? \"h-8 w-[6.5ch] text-base\" : \"h-6 w-[6.5ch] text-xs\",\n )}\n />\n </TooltipTrigger>\n <TooltipContent>{`Limit is ${cap}`}</TooltipContent>\n </Tooltip>\n {overridden && !disabled ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={`Reset inline max for ${label}`}\n onClick={() => onCommit(null)}\n className={cn(\n \"inline-flex shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground\",\n comfortable ? \"h-8 w-7\" : \"h-5 w-5\",\n )}\n >\n <RotateCcwIcon className=\"h-3 w-3\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>{`Reset to ${formatLimit(inherited)}`}</TooltipContent>\n </Tooltip>\n ) : (\n <span aria-hidden=\"true\" className={cn(\"shrink-0\", comfortable ? \"w-7\" : \"w-5\")} />\n )}\n </div>\n );\n}\n","import {\n resolveContextRule,\n type ContextDelivery,\n type ContextRowDelivery,\n type ContextLayer,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\n\nexport const LAYER_LABEL: Record<ContextLayer, string> = {\n default: \"Default\",\n page: \"Page\",\n agent: \"Agent\",\n you: \"You\",\n};\n\nexport const DELIVERY_LABEL: Record<ContextRowDelivery, string> = {\n inline: \"Inline\",\n on_request: \"On request\",\n off: \"Off\",\n server: \"Server\",\n};\n\nexport const SERVER_RESOLVED_TOOLTIP = \"Resolved by the server\";\nexport const SELF_CHECK_TOOLTIP = \"Removed by the server's safety check\";\n\n/**\n * The Inline max field's muted text when the person set no number: \"auto\" for\n * a server-resolved value (the server picks its limit), the applied limit\n * once a receipt filled it, else the inherited limit.\n */\nexport function limitPlaceholder(row: ResolvedContextRow, cap: number): string {\n if (row.serverResolved && !row.fromReceipt) return \"auto\";\n if (row.fromReceipt) return formatLimit(row.max_inline_chars);\n return formatLimit(inheritedLimit(row, cap));\n}\n\n/** `0` is \"Never\"; anything else is the number as typed. */\nexport function formatLimit(n: number): string {\n return n === 0 ? \"Never\" : String(n);\n}\n\n/** The limit this row would have without the person's own number. */\nexport function inheritedLimit(row: ResolvedContextRow, cap: number): number {\n return resolveContextRule({ ...(row.layers ?? {}), chars: row.chars, cap, user: null })\n .max_inline_chars;\n}\n\nexport function hasOverride(row: ResolvedContextRow): boolean {\n return row.userRule !== null && Object.keys(row.userRule).length > 0;\n}\n\nexport function withInclude(row: ResolvedContextRow, include: boolean): SavedContextRule {\n return { ...(row.userRule ?? {}), include };\n}\n\nexport function withLimit(row: ResolvedContextRow, limit: number | null): SavedContextRule | null {\n const next: SavedContextRule = { ...(row.userRule ?? {}) };\n if (limit === null) delete next.max_inline_chars;\n else next.max_inline_chars = limit;\n return Object.keys(next).length === 0 ? null : next;\n}\n\nexport function rowId(row: ResolvedContextRow): string {\n return `${row.surfaceKey}::${row.key}`;\n}\n\nfunction show(field: ContextReceiptMismatch[\"field\"], v: unknown): string {\n if (v === null || v === undefined) return \"none\";\n if (typeof v === \"boolean\") return v ? \"On\" : \"Off\";\n if (typeof v === \"number\") return formatLimit(v);\n if (field === \"delivery\" || field === \"missing\") {\n return DELIVERY_LABEL[v as ContextDelivery] ?? String(v);\n }\n if (typeof v === \"object\") {\n const r = v as SavedContextRule;\n const parts: string[] = [];\n if (r.include !== undefined) parts.push(r.include ? \"On\" : \"Off\");\n if (r.max_inline_chars !== undefined) parts.push(formatLimit(r.max_inline_chars));\n return parts.join(\", \") || \"none\";\n }\n return String(v);\n}\n\nconst FIELD_LABEL: Record<ContextReceiptMismatch[\"field\"], string> = {\n include: \"Include\",\n max_inline_chars: \"Inline max\",\n delivery: \"Delivery\",\n user_rule: \"Your rule\",\n missing: \"Not sent\",\n};\n\n/** One line per mismatch — \"Inline max: expected 8000, got 200\". Tooltip-sized. */\nexport function describeMismatches(list: readonly ContextReceiptMismatch[]): string {\n const text = list\n .map((m) =>\n m.reason === \"self_check\"\n ? SELF_CHECK_TOOLTIP\n : m.field === \"missing\"\n ? \"Missing from the server's receipt\"\n : `${FIELD_LABEL[m.field]}: expected ${show(m.field, m.expected)}, got ${show(m.field, m.actual)}`,\n )\n .join(\" · \");\n return text.length > 140 ? `${text.slice(0, 139)}…` : text;\n}\n\n/** Tooltip for the \"on request\" marker, by why the value is not inline. */\nexport function onRequestReason(row: ResolvedContextRow): string {\n if (row.chars === null) return \"Size unknown — the agent reads it on request\";\n if (row.max_inline_chars === 0) return \"Never inline — the agent reads it on request\";\n return \"Over the limit — the agent reads it on request\";\n}\n","import { formatChars, type ResolvedContextRow } from \"../index\";\n\n/**\n * The header's \"N · chars\" total. A row whose size is not known yet (an\n * attachment the server has not measured) never counts as 0: with some sizes\n * unknown the total is a floor (\"1.2k+\"), with none known it is \"—\".\n */\nexport function summarizeContextRows(rows: readonly ResolvedContextRow[]) {\n let count = 0;\n let chars = 0;\n let known = 0;\n for (const r of rows) {\n if (!r.include) continue;\n count += 1;\n if (r.chars === null || r.chars === undefined) continue;\n chars += r.chars;\n known += 1;\n }\n const charsLabel =\n count > 0 && known === 0 ? \"—\" : known < count ? `${formatChars(chars)}+` : formatChars(chars);\n return { count, chars, charsLabel };\n}\n","import * as React from \"react\";\nimport {\n BottomSheet,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Switch,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ContextRulesTable } from \"./ContextRulesTable\";\nimport type { ContextHierarchy, ContextRuleChange } from \"./hierarchy\";\nimport { EyeIcon, EyeOffIcon, PanelRightIcon, RotateCcwIcon, TriangleAlertIcon } from \"./icons\";\nimport { hasOverride } from \"./shared\";\nimport { summarizeContextRows } from \"./summary\";\n\nexport { summarizeContextRows };\n\nexport interface ContextRulesChipProps {\n /**\n * The group's own name — \"Notes\", \"Invoice 1042\". Empty or omitted: the chip\n * shows NO text (icon + count only). Never pass a generic word such as\n * \"Context\" here — when there is no real name, there is no label (Arman,\n * 2026-10-01).\n */\n label?: string | null | undefined;\n rows: readonly ResolvedContextRow[];\n cap: number;\n /**\n * Page context on/off (the face's eye). With no `hierarchy`, also the\n * header's master switch; with one, the page's switch is its level's\n * (`hierarchy.masters`) and the header has none.\n */\n on?: boolean | undefined;\n onToggleAll?: ((next: boolean) => void) | undefined;\n /** Levels and groups with a switch each (see `ContextRulesTable`). */\n hierarchy?: ContextHierarchy | null | undefined;\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /** False: this turn's model cannot read context — muted face, no amber. */\n modelReadsContext?: boolean | undefined;\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n onResetAll: () => void;\n onOpenFullView: () => void;\n mismatchCount?: number;\n mismatches?: readonly ContextReceiptMismatch[];\n onOpenRow?: (key: string) => void;\n /** Bottom sheet instead of a popover. */\n isMobile?: boolean;\n readOnly?: boolean | undefined;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * The chip toggles a view the host shows elsewhere (a canvas tab): `true`\n * while that view is in front. Sets `aria-pressed` and the pressed face.\n * Omitted: the chip is a plain popover trigger, no pressed state.\n */\n pressed?: boolean | undefined;\n className?: string;\n}\n\nconst BLIND_TOOLTIP = \"This model can't read these values\";\nconst BLIND_LABEL = \"Not read\";\n\nfunction IconButton({\n label,\n onClick,\n comfortable,\n children,\n}: {\n label: string;\n onClick: () => void;\n comfortable: boolean;\n children: React.ReactNode;\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={label}\n onClick={onClick}\n className={cn(\n \"inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground\",\n comfortable ? \"h-11 w-11\" : \"h-7 w-7\",\n )}\n >\n {children}\n </button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n );\n}\n\n/**\n * The composer's value-group chip — far right of the composer's one row — and the surface it opens: a header (label,\n * \"N · chars\" summary, page master switch, reset-all, full view) over the\n * compact rules table. Popover on desktop, bottom sheet on mobile.\n */\nexport function ContextRulesChip({\n label,\n rows,\n cap,\n on,\n onToggleAll,\n hierarchy,\n onSetInclude,\n onChange,\n onResetAll,\n onOpenFullView,\n mismatchCount = 0,\n modelReadsContext = true,\n mismatches,\n onOpenRow,\n isMobile,\n readOnly,\n open: openProp,\n onOpenChange,\n pressed,\n className,\n}: ContextRulesChipProps) {\n const [openState, setOpenState] = React.useState(false);\n const open = openProp ?? openState;\n const setOpen = (next: boolean) => {\n if (openProp === undefined) setOpenState(next);\n onOpenChange?.(next);\n };\n const { count, charsLabel } = summarizeContextRows(rows);\n const name = label?.trim() ?? \"\";\n // The face's accessible name and tooltip — the group's name when it has one,\n // otherwise what the number counts.\n const faceName = name ? `${name} · ${count} included` : `${count} included`;\n const anyOverride = rows.some(hasOverride);\n const blind = !modelReadsContext;\n const warn = mismatchCount > 0 && !blind;\n const comfortable = !!isMobile;\n // With a hierarchy the page's name and switch sit on its own level row.\n const hasPage = on !== undefined && !hierarchy;\n const headerName = hierarchy ? \"\" : name;\n // Eye open only when context can reach the model: a page that is on (or no\n // page at all) and a model that reads context.\n const eyeOpen = !blind && on !== false;\n\n // Compact: the same height as the composer's other row pills (h-6). On touch\n // an invisible ring takes the hit area to 44px without growing the row.\n const faceButton = (\n <button\n type=\"button\"\n aria-label={faceName}\n // Full width when the row has room; it truncates only when the row's\n // attachments need the space, and the whole name stays in the title.\n title={name || undefined}\n data-mismatch={warn ? \"true\" : undefined}\n data-blind={blind ? \"true\" : undefined}\n aria-pressed={pressed}\n onClick={isMobile ? () => setOpen(true) : undefined}\n className={cn(\n \"relative inline-flex h-6 min-w-0 shrink items-center gap-1 rounded-md border border-border bg-card px-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent\",\n comfortable && \"after:absolute after:-inset-x-1.5 after:-inset-y-2.5 after:content-['']\",\n !eyeOpen && \"text-muted-foreground\",\n blind && \"border-dashed\",\n warn && \"border-warning/60 ring-1 ring-warning\",\n pressed && \"border-primary bg-primary/15 text-primary ring-1 ring-inset ring-primary/30 hover:bg-primary/20\",\n className,\n )}\n >\n {eyeOpen ? <EyeIcon className=\"h-3 w-3 shrink-0\" /> : <EyeOffIcon className=\"h-3 w-3 shrink-0\" />}\n {name ? <span className=\"min-w-0 truncate\">{name}</span> : null}\n <span className=\"shrink-0 tabular-nums text-muted-foreground\">{count}</span>\n {warn ? (\n <span className=\"inline-flex shrink-0 items-center gap-0.5 tabular-nums text-warning\">\n <TriangleAlertIcon className=\"h-3 w-3\" />\n {mismatchCount}\n </span>\n ) : null}\n </button>\n );\n\n // The blind state says why; a nameless face says what its number counts.\n const faceTip = blind ? BLIND_TOOLTIP : name ? null : faceName;\n const withBlindTip = (trigger: React.ReactElement) =>\n faceTip ? (\n <Tooltip>\n <TooltipTrigger asChild>{trigger}</TooltipTrigger>\n <TooltipContent>{faceTip}</TooltipContent>\n </Tooltip>\n ) : (\n trigger\n );\n\n const body = (\n <div className=\"flex min-h-0 flex-col\">\n <div\n className={cn(\n \"flex shrink-0 items-center gap-2 border-b border-border px-3\",\n comfortable ? \"h-12\" : \"h-10\",\n )}\n >\n {eyeOpen ? (\n <EyeIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n ) : (\n <EyeOffIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n )}\n {headerName ? <span className=\"min-w-0 truncate text-sm font-medium\">{headerName}</span> : null}\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${count} · ${charsLabel} chars`}\n </span>\n <div className=\"ml-auto flex shrink-0 items-center gap-0.5\">\n {blind ? (\n <span className=\"mr-1 text-xs text-muted-foreground\">{BLIND_LABEL}</span>\n ) : null}\n {hasPage ? (\n <Switch\n size=\"sm\"\n aria-label=\"Include this page\"\n checked={on}\n disabled={readOnly || !onToggleAll}\n onCheckedChange={(next) => onToggleAll?.(next)}\n className=\"mr-1\"\n />\n ) : null}\n {anyOverride && !readOnly ? (\n <IconButton label=\"Reset all\" onClick={onResetAll} comfortable={comfortable}>\n <RotateCcwIcon className=\"h-3.5 w-3.5\" />\n </IconButton>\n ) : null}\n <IconButton\n label=\"Open full view\"\n comfortable={comfortable}\n onClick={() => {\n setOpen(false);\n onOpenFullView();\n }}\n >\n <PanelRightIcon className=\"h-3.5 w-3.5\" />\n </IconButton>\n </div>\n </div>\n <div className={cn(\"min-h-0 overflow-y-auto\", comfortable ? \"max-h-[70dvh]\" : \"max-h-[min(24rem,60vh)]\")}>\n <ContextRulesTable\n rows={rows}\n cap={cap}\n readOnly={readOnly}\n density={comfortable ? \"comfortable\" : \"compact\"}\n onChange={onChange}\n hierarchy={hierarchy}\n onSetInclude={onSetInclude}\n {...(mismatches ? { mismatches } : {})}\n {...(onOpenRow ? { onOpenRow } : {})}\n />\n </div>\n </div>\n );\n\n if (isMobile) {\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n {withBlindTip(faceButton)}\n <BottomSheet open={open} onOpenChange={setOpen} title={name || faceName} surface=\"solid\">\n {body}\n </BottomSheet>\n </TooltipProvider>\n );\n }\n\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <Popover open={open} onOpenChange={setOpen}>\n {withBlindTip(<PopoverTrigger asChild>{faceButton}</PopoverTrigger>)}\n <PopoverContent\n align=\"end\"\n className=\"w-[30rem] max-w-[calc(100vw-1rem)] overflow-hidden p-0\"\n >\n {body}\n </PopoverContent>\n </Popover>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport {\n Input,\n Switch,\n TooltipProvider,\n cn,\n} from \"@ai-matrx/design-system\";\n\nimport {\n DEFAULT_INLINE_MAX_CHARS,\n formatChars,\n type ContextLayer,\n type ContextReceiptBlock,\n type ContextViewLoader,\n unclaimedBlocks,\n type ContextReceiptMismatch,\n type ResolvedContextRow,\n type SavedContextRule,\n} from \"../index\";\nimport { ContextRulesTable } from \"./ContextRulesTable\";\nimport type { ContextHierarchy, ContextRuleChange } from \"./hierarchy\";\nimport { ChevronLeftIcon, SearchIcon, TriangleAlertIcon } from \"./icons\";\nimport { ContextDeliveredValue } from \"./ContextDeliveredValue\";\nimport { ContextReceiptBlockDetail, ContextReceiptBlocks } from \"./ContextReceiptBlocks\";\nimport { FrozenInclude } from \"./FrozenInclude\";\nimport { InlineMaxInput } from \"./InlineMaxInput\";\nimport {\n DELIVERY_LABEL,\n LAYER_LABEL,\n describeMismatches,\n formatLimit,\n inheritedLimit,\n limitPlaceholder,\n withInclude,\n withLimit,\n} from \"./shared\";\n\nexport interface ContextRulesPanelBodyProps {\n rows: readonly ResolvedContextRow[];\n cap: number;\n mismatches?: readonly ContextReceiptMismatch[];\n /** The latest receipt's `blocks`: listed read-only under \"Also sent\". */\n blocks?: readonly ContextReceiptBlock[];\n /** The viewer door (RULES.md §5b): fetches a value's or block's exact text when it opens. */\n loadView?: ContextViewLoader;\n readOnly?: boolean | undefined;\n onChange: (key: string, surfaceKey: string, next: SavedContextRule | null) => void;\n /** Levels and groups with a switch each (see `ContextRulesTable`). */\n hierarchy?: ContextHierarchy | null | undefined;\n onSetInclude?: ((changes: ContextRuleChange[]) => void) | undefined;\n /** Host content under the built-in controls (a value preview, source link…). */\n renderDetail?: (row: ResolvedContextRow) => React.ReactNode;\n isMobile?: boolean;\n /** Controlled selection; omit for internal state. */\n selectedKey?: string | null;\n onSelectedKeyChange?: (key: string | null) => void;\n className?: string;\n}\n\ninterface LayerCell {\n include: string;\n limit: string;\n}\n\n/** What each layer says about this row; \"—\" where the layer is silent. */\nfunction layerCells(row: ResolvedContextRow): Record<ContextLayer, LayerCell> {\n const { surface, agent, default_max } = row.layers ?? {};\n const declared = agent?.declared === true;\n const pageOff = surface?.declared === true && surface.auto_context === false;\n const num = (n: number | null | undefined) => (typeof n === \"number\" ? formatLimit(n) : \"—\");\n const rule = row.userRule;\n return {\n default: { include: \"On\", limit: formatLimit(default_max ?? DEFAULT_INLINE_MAX_CHARS) },\n page: { include: pageOff ? \"Off\" : \"—\", limit: num(surface?.max_inline_chars) },\n agent: {\n include: agent?.kill_switch && !declared ? \"Off\" : declared && pageOff ? \"On\" : \"—\",\n limit: declared ? num(agent?.max_inline_chars) : \"—\",\n },\n you: {\n include: rule?.include === undefined ? \"—\" : rule.include ? \"On\" : \"Off\",\n limit: num(rule?.max_inline_chars),\n },\n };\n}\n\nconst LAYERS: ContextLayer[] = [\"default\", \"page\", \"agent\", \"you\"];\n\nfunction LayerTable({ row }: { row: ResolvedContextRow }) {\n const cells = layerCells(row);\n const cell = (text: string, winning: boolean) => (\n <span\n role=\"cell\"\n data-winning={winning ? \"true\" : undefined}\n className={cn(\n \"rounded px-1.5 py-0.5 text-right tabular-nums\",\n winning ? \"bg-primary/10 font-medium text-foreground\" : \"text-muted-foreground\",\n )}\n >\n {text}\n </span>\n );\n return (\n <div role=\"table\" aria-label=\"Layers\" className=\"text-xs\">\n <div\n role=\"row\"\n className=\"grid h-7 grid-cols-[1fr_5rem_5rem] items-center gap-x-2 border-b border-border font-medium text-muted-foreground\"\n >\n <span role=\"columnheader\">Layer</span>\n <span role=\"columnheader\" className=\"text-right\">\n Include\n </span>\n <span role=\"columnheader\" className=\"text-right\">\n Inline max\n </span>\n </div>\n {LAYERS.map((layer) => (\n <div\n role=\"row\"\n key={layer}\n className=\"grid h-7 grid-cols-[1fr_5rem_5rem] items-center gap-x-2 border-b border-border/50\"\n >\n <span role=\"cell\">{LAYER_LABEL[layer]}</span>\n {cell(cells[layer].include, row.decided_by.include === layer)}\n {cell(cells[layer].limit, row.decided_by.max_inline_chars === layer)}\n </div>\n ))}\n </div>\n );\n}\n\nfunction RowDetail({\n row,\n cap,\n readOnly,\n mismatches,\n onChange,\n renderDetail,\n comfortable,\n loadView,\n}: {\n loadView: ContextViewLoader | undefined;\n row: ResolvedContextRow;\n cap: number;\n readOnly: boolean | undefined;\n mismatches: ContextReceiptMismatch[];\n onChange: ContextRulesPanelBodyProps[\"onChange\"];\n renderDetail: ContextRulesPanelBodyProps[\"renderDetail\"];\n comfortable: boolean;\n}) {\n return (\n <div className=\"flex flex-col gap-3 p-3\">\n <div className=\"flex min-w-0 items-baseline gap-2\">\n <h3 className=\"min-w-0 truncate text-sm font-medium\">{row.label}</h3>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${formatChars(row.chars)} chars · ${DELIVERY_LABEL[row.delivery]}`}\n </span>\n </div>\n {mismatches.length > 0 ? (\n <div className=\"flex items-start gap-1.5 rounded-md border border-warning/40 bg-warning/10 px-2 py-1.5 text-xs text-warning\">\n <TriangleAlertIcon className=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\n <span>{describeMismatches(mismatches)}</span>\n </div>\n ) : null}\n <div className=\"grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2 text-xs\">\n <span className=\"text-muted-foreground\">Include</span>\n <div className={cn(\"flex items-center\", comfortable ? \"h-11\" : \"h-7\")}>\n {readOnly ? (\n <FrozenInclude name={row.label} checked={row.include} />\n ) : (\n <Switch\n size=\"sm\"\n aria-label={`Include ${row.label}`}\n checked={row.include}\n onCheckedChange={(next) => onChange(row.key, row.surfaceKey, withInclude(row, next))}\n />\n )}\n </div>\n <span className=\"text-muted-foreground\">Inline max</span>\n <div className=\"flex\">\n <InlineMaxInput\n label={row.label}\n value={row.userRule?.max_inline_chars ?? null}\n inherited={inheritedLimit(row, cap)}\n placeholder={limitPlaceholder(row, cap)}\n cap={cap}\n disabled={readOnly}\n comfortable={comfortable}\n onCommit={(next) => onChange(row.key, row.surfaceKey, withLimit(row, next))}\n />\n </div>\n </div>\n <LayerTable row={row} />\n <ContextDeliveredValue row={row} load={loadView} />\n {renderDetail ? renderDetail(row) : null}\n </div>\n );\n}\n\n/**\n * Master/detail body for a docked context panel: search + compact table, and\n * the open row's controls, layer breakdown and host detail. Nothing open: the\n * list is the whole panel. Open and wide (≥ 40rem): list beside detail. Open\n * and narrow (or `isMobile`): the detail alone, with Back to the list.\n */\nexport function ContextRulesPanelBody({\n rows,\n cap,\n mismatches,\n blocks,\n loadView,\n readOnly,\n onChange,\n hierarchy,\n onSetInclude,\n renderDetail,\n isMobile,\n selectedKey: selectedProp,\n onSelectedKeyChange,\n className,\n}: ContextRulesPanelBodyProps) {\n const [selectedState, setSelectedState] = React.useState<string | null>(null);\n const [query, setQuery] = React.useState(\"\");\n const [openBlockId, setOpenBlockId] = React.useState<string | null>(null);\n const selectedKey = selectedProp !== undefined ? selectedProp : selectedState;\n const select = (key: string | null) => {\n setOpenBlockId(null);\n if (selectedProp === undefined) setSelectedState(key);\n onSelectedKeyChange?.(key);\n };\n const openBlock = (id: string) => {\n select(null);\n setOpenBlockId(id);\n };\n\n const q = query.trim().toLowerCase();\n const visible = q\n ? rows.filter((r) => r.label.toLowerCase().includes(q) || r.key.toLowerCase().includes(q))\n : rows;\n // A block the model read as part of a value (the Organization's catalog) shows in that\n // value's detail and its chars — never listed twice.\n const alsoSent = unclaimedBlocks(\n blocks,\n rows.filter((r) => r.delivered).map((r) => r.key),\n );\n const visibleBlocks = q\n ? alsoSent.filter((b) => b.label.toLowerCase().includes(q) || b.id.toLowerCase().includes(q))\n : alsoSent;\n const openedBlock = openBlockId ? (blocks ?? []).find((b) => b.id === openBlockId) ?? null : null;\n const selected =\n !openedBlock && selectedKey ? rows.find((r) => r.key === selectedKey) ?? null : null;\n const comfortable = !!isMobile;\n\n const search = (\n <div className=\"relative shrink-0 border-b border-border p-2\">\n <SearchIcon className=\"pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground\" />\n <Input\n type=\"search\"\n aria-label=\"Search values\"\n placeholder=\"Search\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n className={cn(\"pl-7 shadow-none\", comfortable ? \"h-11 text-base\" : \"h-8 text-xs\")}\n />\n </div>\n );\n\n const table = (\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n <ContextRulesTable\n rows={visible}\n cap={cap}\n readOnly={readOnly}\n density={comfortable ? \"comfortable\" : \"compact\"}\n selectedKey={selectedKey}\n onChange={onChange}\n hierarchy={hierarchy}\n onSetInclude={onSetInclude}\n onOpenRow={(key) => select(key)}\n {...(mismatches ? { mismatches } : {})}\n />\n <ContextReceiptBlocks\n blocks={visibleBlocks}\n selectedId={openedBlock?.id ?? null}\n onOpenBlock={openBlock}\n density={comfortable ? \"comfortable\" : \"compact\"}\n />\n </div>\n );\n\n const detail = openedBlock ? (\n <ContextReceiptBlockDetail block={openedBlock} load={loadView} />\n ) : selected ? (\n <RowDetail\n row={selected}\n cap={cap}\n readOnly={readOnly}\n mismatches={mismatches?.filter((m) => m.key === selected.key) ?? []}\n onChange={onChange}\n renderDetail={renderDetail}\n comfortable={comfortable}\n loadView={loadView}\n />\n ) : null;\n\n // One layout for every width (CSS container queries, so it is right on the first paint and on\n // the server): nothing open → the list takes the whole width (never an empty half). Something\n // open → side by side when the panel is wide (≥ 40rem), else stacked: the detail with Back.\n // `isMobile` always stacks (and uses comfortable touch sizes).\n const sideBySide = !isMobile;\n return (\n <TooltipProvider delayDuration={300} titleTooltips={false}>\n <div data-slot=\"context-rules-panel\" className={cn(\"@container flex h-full min-h-0 min-w-0\", className)}>\n <aside\n data-slot=\"context-rules-list\"\n className={cn(\n \"flex min-h-0 min-w-0 flex-col\",\n !detail\n ? \"flex-1\"\n : sideBySide\n ? \"hidden border-border @min-[40rem]:flex @min-[40rem]:w-[clamp(18rem,38%,28rem)] @min-[40rem]:shrink-0 @min-[40rem]:border-r\"\n : \"hidden\",\n )}\n >\n {search}\n {table}\n </aside>\n {detail ? (\n <section data-slot=\"context-rules-detail\" className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div\n className={cn(\n \"flex shrink-0 items-center border-b border-border px-1\",\n comfortable ? \"h-12\" : \"h-8\",\n sideBySide && \"@min-[40rem]:hidden\",\n )}\n >\n <button\n type=\"button\"\n onClick={() => select(null)}\n className={cn(\n \"inline-flex items-center gap-1 rounded-md px-2 text-muted-foreground hover:text-foreground\",\n comfortable ? \"h-11 text-sm\" : \"h-7 text-xs\",\n )}\n >\n <ChevronLeftIcon className={comfortable ? \"h-4 w-4\" : \"h-3.5 w-3.5\"} />\n Back\n </button>\n </div>\n <div className=\"min-h-0 flex-1 overflow-y-auto\">{detail}</div>\n </section>\n ) : null}\n </div>\n </TooltipProvider>\n );\n}\n","import * as React from \"react\";\nimport { ErrorBox, Skeleton, cn } from \"@ai-matrx/design-system\";\n\nimport {\n CONTEXT_FETCHABLE_ROWS,\n formatChars,\n isServerAuthoritativeKey,\n type ContextDeliveredRef,\n type ContextReceiptBlock,\n type ContextViewLoader,\n type ContextViewTarget,\n type ResolvedContextRow,\n} from \"../index\";\n\n/**\n * What the model READ for one value — fetched from the viewer when the detail\n * opens, never pushed (RULES.md §5b): its own element (`delivered`), the blocks\n * it rode with (`deliveredBlocks` — the Organization's catalog), and for an\n * on-request value what the `context` tool returns (`onRequest`), and for a\n * value the agent reads through a tool (`CONTEXT_FETCHABLE_ROWS`) what that tool\n * returns now (`fetchable`, sized once loaded). Verbatim;\n * never the client's copy. With no receipt yet: a server-authoritative value\n * says the server fills it; anything else renders nothing (the host may show\n * the value the page will send, labelled so).\n */\nexport function ContextDeliveredValue({\n row,\n load,\n className,\n}: {\n row: Pick<ResolvedContextRow, \"key\" | \"delivered\" | \"onRequest\" | \"deliveredBlocks\"> &\n Partial<Pick<ResolvedContextRow, \"delivery\">>;\n /** The host's viewer door; without one, sizes show and the text reads \"—\". */\n load?: ContextViewLoader | undefined;\n className?: string;\n}) {\n const blocks = row.deliveredBlocks ?? [];\n if (!row.delivered && !row.onRequest && blocks.length === 0) {\n return isServerAuthoritativeKey(row.key) ? (\n <p data-testid=\"context-server-fills\" className={cn(\"text-xs text-muted-foreground\", className)}>\n Filled in by the server\n </p>\n ) : null;\n }\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n {row.delivered ? (\n <DeliveredSection\n title=\"Agent received\"\n target={{ kind: \"delivered\", key: row.key }}\n ref_={row.delivered}\n load={load}\n />\n ) : null}\n {blocks.map((block: ContextReceiptBlock) => (\n <DeliveredSection\n key={block.id}\n title={block.label}\n target={{ kind: \"block\", key: block.id }}\n ref_={block.delivered}\n load={load}\n />\n ))}\n {row.onRequest || (row.delivery === \"on_request\" && row.delivered) ? (\n // A lazy value (a document, a file family …) carries no ref: the turn never reads\n // it. It is fetched — and sized — when opened.\n <DeliveredSection\n title=\"Returned on request\"\n target={{ kind: \"on_request\", key: row.key }}\n ref_={row.onRequest}\n load={load}\n />\n ) : null}\n {row.delivered && CONTEXT_FETCHABLE_ROWS[row.key] ? (\n <DeliveredSection\n title=\"Agent can fetch\"\n target={{ kind: \"fetchable\", key: row.key }}\n load={load}\n />\n ) : null}\n </div>\n );\n}\n\ntype Loaded =\n | { state: \"loading\" }\n | { state: \"error\"; message: string }\n | { state: \"done\"; text: string; chars: number; available: boolean; fetched: boolean | null };\n\n/** One viewed text: its title and size, then the exact text, fetched on mount. */\nexport function DeliveredSection({\n title,\n target,\n ref_,\n load,\n}: {\n title: string;\n target: ContextViewTarget;\n /** The receipt's size; absent for a `fetchable` text, sized once it loads. */\n ref_?: ContextDeliveredRef | undefined;\n load?: ContextViewLoader | undefined;\n}) {\n const [loaded, setLoaded] = React.useState<Loaded>({ state: \"loading\" });\n const [attempt, setAttempt] = React.useState(0);\n const { kind, key } = target;\n React.useEffect(() => {\n if (!load) return;\n let live = true;\n setLoaded({ state: \"loading\" });\n load({ kind, key }).then(\n (viewed) => {\n if (live)\n setLoaded({\n state: \"done\",\n text: viewed.text,\n chars: viewed.chars,\n available: viewed.available !== false,\n fetched: viewed.fetched ?? null,\n });\n },\n (error: unknown) => {\n if (live)\n setLoaded({\n state: \"error\",\n message: error instanceof Error && error.message ? error.message : \"Couldn't load\",\n });\n },\n );\n return () => {\n live = false;\n };\n }, [load, kind, key, attempt]);\n\n const unavailable = loaded.state === \"done\" && !loaded.available;\n return (\n <section className=\"flex flex-col gap-1\" aria-label={title} data-view-kind={kind} data-view-key={key}>\n <div className=\"flex items-baseline gap-2 text-xs\">\n <span className=\"font-medium\">{title}</span>\n {unavailable ? (\n <span\n data-testid=\"context-delivered-unavailable\"\n className=\"rounded border border-border px-1.5 text-[11px] text-muted-foreground\"\n >\n Not available to this agent\n </span>\n ) : ref_ || loaded.state === \"done\" ? (\n <span className=\"tabular-nums text-muted-foreground\">\n {`${formatChars(ref_ ? ref_.chars : loaded.state === \"done\" ? loaded.chars : 0)} chars`}\n </span>\n ) : null}\n {loaded.state === \"done\" && loaded.fetched === false ? (\n <span\n data-testid=\"context-delivered-not-read\"\n className=\"rounded border border-border px-1.5 text-[11px] text-muted-foreground\"\n >\n Not read by the agent\n </span>\n ) : null}\n </div>\n {unavailable ? null : !load ? (\n <span className=\"text-xs text-muted-foreground\">—</span>\n ) : loaded.state === \"loading\" ? (\n <Skeleton data-testid=\"context-delivered-loading\" className=\"h-16 w-full\" />\n ) : loaded.state === \"error\" ? (\n <ErrorBox as=\"div\" message={loaded.message} className=\"flex items-center gap-2 text-xs text-destructive\">\n <span className=\"min-w-0 truncate\" title={loaded.message}>\n {loaded.message}\n </span>\n <button\n type=\"button\"\n onClick={() => setAttempt((n) => n + 1)}\n className=\"shrink-0 rounded px-1.5 py-0.5 text-foreground hover:bg-accent\"\n >\n Retry\n </button>\n </ErrorBox>\n ) : loaded.text === \"\" ? (\n <span data-testid=\"context-delivered-empty\" className=\"text-xs text-muted-foreground\">\n None\n </span>\n ) : (\n <pre\n data-testid=\"context-delivered-text\"\n className={cn(\n \"max-h-[min(50dvh,22rem)] cursor-text select-text overflow-auto\",\n \"whitespace-pre-wrap break-words rounded border border-border\",\n \"bg-muted/40 p-2 font-mono text-[11px] text-foreground\",\n )}\n >\n {loaded.text}\n </pre>\n )}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"@ai-matrx/design-system\";\n\nimport { formatChars, type ContextReceiptBlock, type ContextViewLoader } from \"../index\";\nimport { DeliveredSection } from \"./ContextDeliveredValue\";\nimport { DELIVERY_LABEL } from \"./shared\";\nimport { CONTEXT_RULES_GRID, type ContextRulesDensity } from \"./ContextRulesTable\";\n\nexport interface ContextReceiptBlocksProps {\n blocks: readonly ContextReceiptBlock[];\n /** The open block (master/detail). */\n selectedId?: string | null;\n onOpenBlock?: (id: string) => void;\n density?: ContextRulesDensity;\n className?: string;\n}\n\n/**\n * \"Also sent\" — every block of server text the model received that is not a\n * single value (receipt `blocks`, RULES.md §5): read-only rows, label + chars,\n * aligned to the context table's Chars column. Renders nothing when empty.\n */\nexport function ContextReceiptBlocks({\n blocks,\n selectedId,\n onOpenBlock,\n density = \"compact\",\n className,\n}: ContextReceiptBlocksProps) {\n if (blocks.length === 0) return null;\n const comfortable = density === \"comfortable\";\n return (\n <div role=\"table\" aria-label=\"Also sent\" className={cn(\"text-xs\", className)}>\n <div role=\"rowgroup\">\n <div\n role=\"row\"\n className=\"flex h-6 items-center bg-muted/40 px-2 font-medium text-muted-foreground\"\n >\n <span role=\"cell\">Also sent</span>\n </div>\n {blocks.map((block) => (\n <div\n role=\"row\"\n key={block.id}\n data-block-id={block.id}\n aria-selected={selectedId === block.id || undefined}\n className={cn(\n CONTEXT_RULES_GRID[density],\n \"border-b border-border/50\",\n comfortable ? \"min-h-11\" : \"h-7\",\n selectedId === block.id && \"bg-accent\",\n )}\n >\n <div role=\"cell\" className=\"col-span-2 flex min-w-0 items-center\">\n {onOpenBlock ? (\n <button\n type=\"button\"\n title={block.label}\n onClick={() => onOpenBlock(block.id)}\n className=\"block min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {block.label}\n </button>\n ) : (\n <span title={block.label} className=\"block min-w-0 flex-1 truncate\">\n {block.label}\n </span>\n )}\n </div>\n <div role=\"cell\" className=\"text-right tabular-nums\">\n {formatChars(block.delivered.chars)}\n </div>\n <div role=\"cell\" />\n </div>\n ))}\n </div>\n </div>\n );\n}\n\n/** One block's detail: its name, its size, and exactly what the agent received (on demand). */\nexport function ContextReceiptBlockDetail({\n block,\n load,\n className,\n}: {\n block: ContextReceiptBlock;\n load?: ContextViewLoader | undefined;\n className?: string;\n}) {\n return (\n <div className={cn(\"flex flex-col gap-3 p-3\", className)}>\n <div className=\"flex min-w-0 items-baseline gap-2\">\n <h3 className=\"min-w-0 truncate text-sm font-medium\">{block.label}</h3>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">\n {`${formatChars(block.delivered.chars)} chars · ${DELIVERY_LABEL.inline}`}\n </span>\n </div>\n <DeliveredSection\n title=\"Agent received\"\n target={{ kind: \"block\", key: block.id }}\n ref_={block.delivered}\n load={load}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,SAAuB;AACvB,IAAAC,wBAUO;;;ACUA,IAAM,2BAA2B;AAEjC,IAAM,qBAAqB;AA+L3B,IAAM,qBAAkE;AAAA,EAC7E,cAAc,CAAC,sBAAsB;AACvC;AAQO,IAAM,yBAA2D;AAAA,EACtE,cAAc;AAChB;AAYO,SAAS,gBACd,QACA,SACuB;AACvB,QAAM,UAAU,oBAAI,IAAY;AAChC,aAAW,O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_system","import_jsx_runtime","import_design_system","import_jsx_runtime","import_jsx_runtime","React","import_design_system","import_jsx_runtime","React","import_design_system","React","import_design_system","import_jsx_runtime","import_design_system","import_jsx_runtime","import_jsx_runtime"]}
|