@ai-matrx/alchemy 0.23.42 → 0.23.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/workspace/email-review.tsx","../src/react/workspace/index.tsx","../src/react/workspace/workspace-core.tsx","../src/react/workspace/workspace.tsx","../src/react/workspace/levers.ts","../src/react/workspace/workspace-tree.tsx","../src/react/workspace/extensions.ts","../src/react/workspace/matrx-copy.tsx","../src/react/workspace/table-copy-controls.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { Artifact, TransferOutcome } from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@ai-matrx/design-system\";\nimport type { ContentTransferEmailPort } from \"./extensions\";\n\ntype PendingEmail = {\n artifact: Artifact;\n context: { label: string; signal: AbortSignal };\n resolve(outcome: TransferOutcome): void;\n onAbort(): void;\n};\n\nconst cancelled = (): TransferOutcome => ({ status: \"cancelled\" });\nconst failed = (error: unknown): TransferOutcome => ({\n status: \"error\",\n code: \"email-failed\",\n message: error instanceof Error ? error.message : \"Could not send email.\",\n retryable: true,\n});\n\n/** Adds one explicit review step without changing the sealed artifact handed to the host. */\nexport function useReviewedTransferEmail(email?: ContentTransferEmailPort): {\n email: ContentTransferEmailPort | undefined;\n review: React.ReactNode;\n} {\n const [pending, setPending] = React.useState<PendingEmail | null>(null);\n const [sending, setSending] = React.useState(false);\n const pendingRef = React.useRef<PendingEmail | null>(null);\n const sendingRef = React.useRef(false);\n\n const settle = React.useCallback((request: PendingEmail, outcome: TransferOutcome, render = true) => {\n if (pendingRef.current !== request) return;\n pendingRef.current = null;\n request.context.signal.removeEventListener(\"abort\", request.onAbort);\n request.resolve(outcome);\n sendingRef.current = false;\n if (render) {\n setSending(false);\n setPending(null);\n }\n }, []);\n\n React.useEffect(\n () => () => {\n const request = pendingRef.current;\n if (!request) return;\n pendingRef.current = null;\n request.context.signal.removeEventListener(\"abort\", request.onAbort);\n request.resolve(cancelled());\n sendingRef.current = false;\n },\n [],\n );\n\n const reviewed = React.useMemo<ContentTransferEmailPort | undefined>(() => {\n if (!email) return undefined;\n return {\n send: (artifact, context) => {\n if (context.signal.aborted) return Promise.resolve(cancelled());\n if (pendingRef.current)\n return Promise.resolve({\n status: \"error\",\n code: \"email-review-active\",\n message: \"Finish reviewing the current email before starting another.\",\n retryable: true,\n });\n return new Promise<TransferOutcome>((resolve) => {\n const request: PendingEmail = {\n artifact,\n context,\n resolve,\n onAbort: () => settle(request, cancelled()),\n };\n pendingRef.current = request;\n context.signal.addEventListener(\"abort\", request.onAbort, { once: true });\n setSending(false);\n setPending(request);\n });\n },\n };\n }, [email, settle]);\n\n const cancel = React.useCallback(() => {\n const request = pendingRef.current;\n if (request && !sendingRef.current) settle(request, cancelled());\n }, [settle]);\n const confirm = React.useCallback(() => {\n const request = pendingRef.current;\n if (!request || sendingRef.current || request.context.signal.aborted) return;\n sendingRef.current = true;\n setSending(true);\n void email?.send(request.artifact, request.context).then(\n (outcome) => settle(request, outcome),\n (error) => settle(request, failed(error)),\n );\n }, [email, settle]);\n\n const review = pending ? <Dialog open onOpenChange={(open) => { if (!open) cancel(); }}>\n <DialogContent className=\"matrx-alchemy-workspace matrx-alchemy-email-review\" aria-busy={sending}>\n <DialogHeader>\n <DialogTitle>Review email attachment</DialogTitle>\n <DialogDescription>Email {pending.artifact.file?.filename ?? `${pending.artifact.format} output`} from {pending.context.label}. Review this exact attachment before sending.</DialogDescription>\n </DialogHeader>\n <textarea aria-label=\"Email attachment preview\" readOnly value={pending.artifact.plainText} className=\"matrx-alchemy-preview\" />\n {pending.artifact.omissions.length ? <details className=\"matrx-alchemy-email-adjustments\" open><summary>{pending.artifact.omissions.length} omission{pending.artifact.omissions.length === 1 ? \"\" : \"s\"} or adjustment{pending.artifact.omissions.length === 1 ? \"\" : \"s\"}</summary><ul >{pending.artifact.omissions.map((omission, index) => <li key={`${omission.path}-${omission.reason}-${index}`}>{omission.path || \"/\"}: {omission.reason}{omission.count == null ? \"\" : ` (${omission.count})`}</li>)}</ul></details> : <p className=\"matrx-alchemy-meta\">No omissions or adjustments.</p>}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={sending} onClick={cancel}>Cancel</Button>\n <Button type=\"button\" className=\"matrx-alchemy-workspace-primary\" disabled={sending} onClick={confirm}>{sending ? \"Sending email…\" : \"Send email\"}</Button>\n </DialogFooter>\n </DialogContent>\n </Dialog> : null;\n\n return { email: reviewed, review };\n}\n","\"use client\";\n\nimport { useReviewedTransferEmail } from \"./email-review\";\nimport { useContentTransferSurface } from \"@ai-matrx/alchemy/react/surface\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n applyTransferLimits,\n capture,\n buildAgentPayload,\n collectAllMatching,\n createBrowserTransport,\n createDraft,\n directSource,\n projectSnapshot,\n resolveTransferPreferences,\n resolveTransferRegistry,\n sealTransferArtifact,\n serialize,\n type BoundAllMatching,\n type ExportProjection,\n type FormatAdapter,\n type PageAction,\n type Payload,\n type Section,\n type Source,\n type SurfaceHandle,\n type AiPreparation,\n type TransferOutcome,\n type TransferTarget,\n type TransferPreferenceOverrides,\n type TransferScope,\n type Transport,\n} from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport {\n BUILT_INS,\n COPIES,\n DestinationPresentation,\n DOWNLOADS,\n EMPTY_VARIANTS,\n LABEL,\n MenuPresentation,\n PaletteGlyph,\n ReceiptLink,\n SCOPE_LABEL,\n buildFormat,\n buildWithAdapter,\n errorMessage,\n initialControls,\n isBuiltInFormat,\n materialIdentity,\n offersFormat,\n outcomeMessage,\n rebuild,\n snapshotContent,\n useFence,\n type BuiltInFormat,\n type CaptureResult,\n type SerializableFormat,\n type WorkspaceState,\n} from \"./workspace-core\";\nimport { PreparationWorkspace, WorkspaceWindowSlot, setWorkspaceSessionLive, type WorkspaceWindowHandle, type WorkspaceWindowPort } from \"./workspace\";\nimport { leverSnapshot, type EnvelopeMeta, type WorkspaceLevers } from \"./levers\";\nexport type { SerializableFormat } from \"./workspace-core\";\nexport type { WorkspaceWindowHandle, WorkspaceWindowPort } from \"./workspace\";\nexport type { EnvelopeMeta, WorkspaceLevers } from \"./levers\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@ai-matrx/design-system\";\nimport { TapTargetButton, TapTargetButtonTransparent } from \"@ai-matrx/design-system/tap-target\";\nimport { ALCHEMY_GLYPH_VIEWBOX, ALCHEMY_GLYPH_PATHS, type AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\nexport { ALCHEMY_GLYPH_SVG, ALCHEMY_COPY_TRANSFORM_SVG, type AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\n\nimport { createTransferEmailActions, createTransferHtmlPreviewAction, type ContentTransferReference, type ContentTransferReferencePort, type ContentTransferEmailPort, type ContentTransferHtmlPreviewPort } from \"./extensions\";\nexport { tableSchemaFormat, tableDataFormat, createTransferEmailActions, createTransferHtmlPreviewAction, type ContentTransferReference, type ContentTransferReferencePort, type ContentTransferEmailPort, type ContentTransferHtmlPreviewPort } from \"./extensions\";\nexport type ContentTransferReferenceAction = { id: string; label: string; run(): void | Promise<void> };\n\nexport function AlchemyGlyph({ icon = \"portal\", ...props }: React.SVGAttributes<SVGSVGElement> & { icon?: AlchemyIcon }) {\n return <svg width=\"18\" height=\"18\" viewBox={ALCHEMY_GLYPH_VIEWBOX[icon]} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" {...props}>{ALCHEMY_GLYPH_PATHS[icon].map((d) => <path key={d} d={d}/>)}</svg>;\n}\n\n/** What a host injects into the menu: lazy format adapters (`@ai-matrx/alchemy/operate`) and AI preparation. */\nexport type TransferCapabilities = { formats?: FormatAdapter[]; ai?: AiPreparation };\nexport type ContentTransferCapabilities = TransferCapabilities & {\n /** Opaque host session boundary. It is used only to reset local menu state. */\n identityKey?: string;\n transport?: Transport;\n reference?: ContentTransferReferencePort;\n email?: ContentTransferEmailPort;\n /** The host's HTML preview. Bound: a menu mounted with `htmlPreview` offers the \"HTML preview\" action. */\n htmlPreview?: ContentTransferHtmlPreviewPort;\n actions?: PageAction[];\n preferences?: TransferPreferenceOverrides;\n onOutcome?: (outcome: TransferOutcome) => void;\n /**\n * The host's window system (structurally `@ai-matrx/alchemy/ports` `WindowPort`, PP-01a). Bound:\n * the preparation workspace opens inside a host window (WindowPanel in the web app, an honest\n * full-screen dialog in the dashboard). Unbound: a near-full-screen dialog.\n */\n window?: WorkspaceWindowPort;\n};\nconst CapabilityContext = React.createContext<ContentTransferCapabilities>({});\nexport function ContentTransferCapabilitiesProvider({ value, children }: { value: ContentTransferCapabilities; children: React.ReactNode }) {\n return <CapabilityContext.Provider value={value}>{children}</CapabilityContext.Provider>;\n}\nexport const useContentTransferCapabilities = () => React.useContext(CapabilityContext);\n// ONE surface context, owned by the light `/react/surface` entry (imported by public name so the\n// built entries share it; a relative import would inline a second context into this bundle).\nexport { ContentTransferSurfaceProvider, useContentTransferSurface } from \"@ai-matrx/alchemy/react/surface\";\n\nexport interface TransferMenuPresentation {\n group?: \"save\" | \"chat\" | \"email\";\n prepared?: boolean;\n hint?: string;\n icon?: React.ComponentType<{ className?: string }>;\n ariaLabel?: string;\n /**\n * Download-only actions join the shared format palette instead of a second menu. A \"prepare\"\n * action opens THE preparation workspace (the table's \"Filter & sort before copying…\" door) and\n * sits in \"Edit and prepare\", where people look for it — never under a heading of its own.\n */\n placement?: \"download\" | \"prepare\";\n}\n/**\n * THE PALETTE'S HEADINGS — a closed list. A host never supplies a heading: an action picks one of\n * the named `group`s or its row shows INLINE with no heading (the approved-heading rule of\n * `@ai-matrx/alchemy/menu`; a container word such as \"Actions\" or \"More…\" is never a heading).\n */\nexport const PALETTE_HEADINGS = [\"Copy as\", \"Download as\", \"Quick copy\", \"Copy for AI\", \"Edit and prepare\", \"Other sources\", \"References\", \"Save to Matrx\", \"Continue with AI\", \"Email to me\"] as const;\nexport type PaletteHeading = (typeof PALETTE_HEADINGS)[number];\nconst DESTINATION_HEADING: Record<NonNullable<TransferMenuPresentation[\"group\"]>, PaletteHeading> = { save: \"Save to Matrx\", chat: \"Continue with AI\", email: \"Email to me\" };\nexport interface TransferMenuVariant extends TransferMenuPresentation {\n id: string; label: string; source: Source | Payload;\n copyLabel?: string;\n section?: \"copy\" | \"ai\";\n successMessage?: string;\n}\nfunction PaletteRows({ title, items, onRun, extra, ai = false, glyphKind, fallbackHint }: { title: PaletteHeading; items: readonly TransferMenuVariant[]; onRun?: (item: TransferMenuVariant) => void; extra?: React.ReactNode; ai?: boolean; glyphKind?: \"ai-copy\" | \"sliders\"; fallbackHint?: string }) {\n if (!items.length && !extra) return null;\n return <section className=\"matrx-alchemy-palette-section\"><h3>{title}</h3>{items.map((item) => { const label = item.copyLabel ?? item.label; const hint = item.hint ?? fallbackHint; return <button key={item.id} type=\"button\" className={cn(\"matrx-alchemy-palette-row\", ai && \"matrx-alchemy-palette-row-ai\")} aria-label={item.ariaLabel ?? `${label}${hint ? ` ${hint}` : \"\"}`} onClick={() => onRun?.(item)}>{item.icon ? <item.icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph ai={ai} {...(glyphKind ? { kind: glyphKind } : {})}/>}<span>{label}{hint ? <small className=\"matrx-alchemy-menu-hint\">{hint}</small> : null}</span></button>; })}{extra}</section>;\n}\nexport interface ContentTransferMenuProps {\n source?: Payload | Source;\n projection?: ExportProjection;\n sections?: Section[];\n preferences?: TransferPreferenceOverrides;\n enabled?: boolean;\n surface?: SurfaceHandle;\n label?: string;\n /**\n * Tabular sources. `size` is the live size the host knows (\"1,240 rows · 12 columns\"): the\n * palette's \"Filter & sort before copying…\" door shows it (PP-08).\n */\n table?: { availableScopes: TransferScope[]; initialScope: TransferScope; scopeLabels?: Partial<Record<TransferScope, string>>; size?: string };\n references?: readonly ContentTransferReference[];\n referenceActions?: readonly ContentTransferReferenceAction[];\n /** A quick format may explicitly capture a different representation. */\n formatSources?: Partial<Record<SerializableFormat, Source | Payload>>;\n /** Set false for action-only hosts; source formats and adapters are then omitted. */\n sourceFormats?: boolean;\n /** Named alternate sources open this same preparation workspace. */\n variants?: readonly TransferMenuVariant[];\n actions?: (PageAction & TransferMenuPresentation)[];\n /** Offer \"HTML preview\" (Markdown and text only) when the host bound `capabilities.htmlPreview`. */\n htmlPreview?: boolean;\n capabilities?: ContentTransferCapabilities;\n disabled?: boolean;\n /** Portal is the default Alchemy mark; copy-transform remains opt-in. */\n icon?: AlchemyIcon;\n /** Uses the canonical TapTargetButton presentation. */\n triggerVariant?: \"transparent\" | \"glass\" | \"outline\";\n triggerSize?: \"default\" | \"compact\";\n /** Mount the transfer session without a visible trigger for a host-owned menu command. */\n triggerHidden?: boolean;\n className?: string;\n stopPropagation?: boolean;\n hide?: readonly (\"copy\" | \"prepare\" | \"download\")[];\n controllerRef?: React.Ref<ContentTransferController>;\n /** Who the primary source is, for the AI envelope (PP-10); read when the workspace opens. */\n envelope?: () => EnvelopeMeta | undefined;\n /**\n * Rich-text hosts: one implementation of the three copies. The main Copy click runs \"default\"\n * (text/plain = markdown AND text/html = formatted); the panel leads with \"Copy markdown\" and\n * \"Copy text\". When set, the plain / Markdown tiles give way to those two.\n */\n richCopy?: RichCopyRunner;\n /** The flavors the runner can honestly produce as tiles (default both). A host with no readable-text projection omits \"text\". */\n richCopyFlavors?: readonly Exclude<RichCopyFlavor, \"default\">[];\n /**\n * \"Copy with prompt…\": opens the host's richest composer (its levers) with the instructions box\n * focused. Absent: the primary workspace opens instead.\n */\n copyWithPrompt?: () => Promise<void>;\n}\nexport type RichCopyFlavor = \"default\" | \"markdown\" | \"text\";\nexport type RichCopyRunner = (flavor: RichCopyFlavor) => Promise<TransferOutcome | boolean | void> | TransferOutcome | boolean | void;\nexport interface ContentTransferController {\n focusTrigger(): void;\n /** Mount the one canonical Alchemy palette in a host-owned menu surface. */\n mountPalette(target: HTMLElement | null, onClose?: () => void, restoreFocus?: () => void): void;\n preparePrimary(options?: { restoreFocus?: () => void }): Promise<void>;\n prepare(source: Source | Payload, options?: { id?: string; label?: string; envelope?: EnvelopeMeta }): Promise<void>;\n /** Open the workspace on a host's own levers (aiCustom / groomer): the levers live beside the preview (PP-02). */\n prepareLevers(levers: WorkspaceLevers, options: { id: string; label: string }): Promise<void>;\n}\n\n\nexport function ContentTransferMenu(props: ContentTransferMenuProps) {\n const inherited = React.useContext(CapabilityContext);\n const identityKey = props.capabilities?.identityKey ?? inherited.identityKey;\n return <ContentTransferMenuSession key={identityKey ?? \"anonymous\"} {...props} />;\n}\n\n/**\n * What a source can say about itself without being built: its payload kind (and a text's language),\n * and whether building it is cheap. The menu inspects a source that declares its shape by the shape\n * alone, so opening the menu never builds the content — a person's pick does (sec_8f1a9be1…: a\n * 1,636-organization page capture froze its page for 4.1 s on open). `cheap` sources (a short,\n * already-built string) still take part in the twin check (PP-09); anything else is never built\n * to decide which items to show.\n */\nexport type SourceShape = { kind: \"text\" | \"markdown\" | \"json\"; language?: string; cheap?: boolean };\nexport type ShapedSource = Source & { shape?: SourceShape };\nconst shapeOf = (material: Source | Payload | SurfaceHandle | null | undefined): SourceShape | undefined =>\n material && !(\"kind\" in material) && !(\"instanceId\" in material) ? (material as ShapedSource).shape : undefined;\n/** The empty payload of a declared shape: what the menu's show-or-hide rules read, never content. */\nconst shapePayload = (shape: SourceShape): Payload =>\n shape.kind === \"json\" ? { kind: \"json\", value: {} } : shape.kind === \"markdown\" ? { kind: \"markdown\", text: \"\" } : { kind: \"text\", text: \"\", ...(shape.language ? { language: shape.language } : {}) };\n\n/** How long a non-copy notice stays (download started, action done, degraded copy). */\nexport const NOTICE_MS = 4000;\n/** Failures stay longer — never less than five seconds. */\nexport const NOTICE_ERROR_MS = 8000;\n\nfunction ContentTransferMenuSession({ references = [], referenceActions = [], source, surface, label, projection, sections, preferences, table, formatSources, sourceFormats = true, variants = EMPTY_VARIANTS, actions = [], htmlPreview = false, capabilities: local, disabled, enabled = true, className, stopPropagation = true, hide = [], controllerRef, icon = \"portal\", triggerVariant = \"transparent\", triggerSize = \"default\", triggerHidden = false, envelope: primaryEnvelope, richCopy, richCopyFlavors = [\"markdown\", \"text\"], copyWithPrompt }: ContentTransferMenuProps) {\n const [promptFocus, setPromptFocus] = React.useState(0);\n const triggerRef = React.useRef<HTMLButtonElement>(null);\n const restoreFocusRef = React.useRef<(() => void) | null>(null);\n const inherited = React.useContext(CapabilityContext);\n const nearestSurface = useContentTransferSurface();\n const fence = useFence();\n const inspectionFence = useFence();\n const [copiedFormat, setCopiedFormat] = React.useState<string | null>(null);\n const copiedTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const leaveTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const clipboardQueue = React.useRef<Promise<unknown>>(Promise.resolve());\n React.useEffect(() => () => {\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n }, []);\n const confirmCopy = React.useCallback((format: string) => {\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(format);\n copiedTimer.current = setTimeout(() => setCopiedFormat(null), 3000);\n }, []);\n const [menuCapture, setMenuCapture] = React.useState<CaptureResult | null>(null);\n const [menuStatus, setMenuStatus] = React.useState<\"idle\" | \"loading\" | string>(\"idle\");\n const [workspaces, setWorkspaces] = React.useState<Record<string, WorkspaceState>>({});\n const [workspaceKey, setWorkspaceKey] = React.useState<string | null>(null);\n const [workspaceOpen, setWorkspaceOpen] = React.useState(false);\n const workspaceCaptures = React.useRef(new Map<string, (scope: TransferScope, signal: AbortSignal) => Promise<CaptureResult>>());\n const externalWorkspaceKeys = React.useRef(new Set<string>());\n const [notice, setNotice] = React.useState<string | null>(null);\n const [receiptTarget, setReceiptTarget] = React.useState<TransferTarget | undefined>();\n const [paletteOpen, setPaletteOpen] = React.useState(false);\n const [paletteTarget, setPaletteTarget] = React.useState<HTMLElement | null>(null);\n const externalPaletteClose = React.useRef<(() => void) | null>(null);\n const externalPaletteRestoreFocus = React.useRef<(() => void) | null>(null);\n // A host action closes its submenu before its async outcome arrives. Keep the\n // owner document so feedback and its receipt still have a durable portal.\n const feedbackDocument = React.useRef<Document | null>(null);\n const [mode, setMode] = React.useState<\"copy\" | \"download\">(\"copy\");\n const scopes = React.useMemo(() => table?.availableScopes ?? ([\"target\"] as TransferScope[]), [table]);\n const [requestedScope, setRequestedScope] = React.useState<TransferScope>(table?.initialScope ?? \"target\");\n const initialScope = scopes.includes(requestedScope) ? requestedScope : table?.initialScope ?? \"target\";\n if (!scopes.includes(initialScope)) throw new Error(\"Alchemy initialScope must be included in availableScopes.\");\n const primary = surface ?? source ?? nearestSurface;\n const sourceLabel = label ?? (surface?.surfaceName ?? (source && \"label\" in source ? source.label : nearestSurface?.surfaceName) ?? \"content\");\n const primaryWorkspaceBase = `primary:${materialIdentity(primary)}`;\n const primaryWorkspaceKey = `${primaryWorkspaceBase}:${initialScope}`;\n React.useEffect(() => {\n setCopiedFormat(null);\n setNotice(null);\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n return fence.abortAll;\n }, [primaryWorkspaceBase, initialScope, fence.abortAll]);\n const nearestWorkspaceKey = source && !surface && nearestSurface ? `surface:${materialIdentity(nearestSurface)}` : null;\n const variantWorkspaceKeys = React.useMemo(() => new Map(variants.map((variant) => [variant.id, `variant:${variant.id}:${materialIdentity(variant.source)}`])), [variants]);\n const baseTransport = local?.transport ?? inherited.transport ?? createBrowserTransport();\n const transport: Transport = {\n download: (artifact, signal) => baseTransport.download(artifact, signal),\n copy: (artifact, signal) => {\n const deliver = (): Promise<TransferOutcome> => signal.aborted ? Promise.resolve({status: \"cancelled\"}) : baseTransport.copy(artifact, signal);\n const pending = clipboardQueue.current.then(deliver, deliver);\n clipboardQueue.current = pending;\n return pending;\n },\n };\n const ai = local?.ai ?? inherited.ai;\n const referencePort = local?.reference ?? inherited.reference;\n const { email: emailPort, review: emailReview } = useReviewedTransferEmail(local?.email ?? inherited.email);\n const providerPreferences = React.useMemo(() => resolveTransferPreferences(inherited.preferences, local?.preferences), [inherited.preferences, local?.preferences]);\n // PP-01a/b: with a host window system the workspace is drawn in a host window; its session stays here.\n const windowPort = local?.window ?? inherited.window;\n const sessionId = React.useId();\n const windowHandles = React.useRef(new Map<string, WorkspaceWindowHandle>());\n const sessionKeys = React.useRef(new Set<string>());\n const [windowNodes, setWindowNodes] = React.useState<Record<string, HTMLElement>>({});\n const slotRefs = React.useRef(new Map<string, (node: HTMLDivElement | null) => void>());\n const slotRef = (key: string) => {\n let ref = slotRefs.current.get(key);\n if (!ref) {\n ref = (node) => setWindowNodes((current) => {\n if (node) return current[key] === node ? current : { ...current, [key]: node };\n if (!(key in current)) return current;\n const { [key]: _gone, ...rest } = current;\n return rest;\n });\n slotRefs.current.set(key, ref);\n }\n return ref;\n };\n const [duplicateFormats, setDuplicateFormats] = React.useState<ReadonlySet<string>>(() => new Set());\n const adapters = React.useMemo(() => {\n // A host format under a built-in id supersedes the built-in (hostEngineFor); any other duplicate still refuses.\n const hostIds = new Set([...(inherited.formats ?? []), ...(local?.formats ?? [])].map((format) => format.id));\n return resolveTransferRegistry<{ id: string }>(BUILT_INS.filter((builtIn) => !hostIds.has(builtIn.id)), inherited.formats ?? [], local?.formats ?? []).filter((x): x is FormatAdapter => \"load\" in x);\n }, [inherited.formats, local?.formats]);\n const emailJsonFormat = adapters.find((adapter) => adapter.id === \"table-data\");\n const emailActions = React.useMemo(() => emailPort ? createTransferEmailActions(emailPort, emailJsonFormat ? { jsonFormat: emailJsonFormat } : {}) : [], [emailPort, emailJsonFormat]);\n const htmlPreviewPort = local?.htmlPreview ?? inherited.htmlPreview;\n const htmlPreviewActions = React.useMemo(() => (htmlPreview && htmlPreviewPort ? [createTransferHtmlPreviewAction(htmlPreviewPort)] : []), [htmlPreview, htmlPreviewPort]);\n const registeredActions = React.useMemo(() => resolveTransferRegistry(emailActions, htmlPreviewActions, inherited.actions ?? [], local?.actions ?? [], actions), [actions, emailActions, htmlPreviewActions, inherited.actions, local?.actions]);\n React.useMemo(() => resolveTransferRegistry(variants), [variants]);\n // A landed clipboard copy speaks through the trigger's own check (confirmCopy) — the\n // world-class pattern (macOS, Linear, GitHub): no floating banner for a copy. Every other\n // notice leaves by itself (NOTICE_MS / NOTICE_ERROR_MS) and holds while the pointer is on it.\n const noticeTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const noticeLife = React.useRef(NOTICE_MS);\n const clearNoticeTimer = React.useCallback(() => { if (noticeTimer.current) clearTimeout(noticeTimer.current); noticeTimer.current = null; }, []);\n const startNoticeTimer = React.useCallback(() => { clearNoticeTimer(); noticeTimer.current = setTimeout(() => setNotice(null), noticeLife.current); }, [clearNoticeTimer]);\n React.useEffect(() => clearNoticeTimer, [clearNoticeTimer]);\n const report = React.useCallback((result: TransferOutcome) => {\n inherited.onOutcome?.(result); local?.onOutcome?.(result);\n setReceiptTarget(\"target\" in result ? result.target : undefined);\n const delivered = result.status === \"success\" ? (result as TransferOutcome & { delivered?: string }).delivered : undefined;\n if (result.status === \"success\" && delivered === \"clipboard\" && !(\"target\" in result && result.target)) { clearNoticeTimer(); setNotice(null); return; }\n noticeLife.current = result.status === \"error\" ? NOTICE_ERROR_MS : NOTICE_MS;\n setNotice(outcomeMessage(result));\n startNoticeTimer();\n }, [inherited, local, clearNoticeTimer, startNoticeTimer]);\n React.useEffect(() => {\n const valid = new Set([...scopes.map((scope) => `${primaryWorkspaceBase}:${scope}`), ...(nearestWorkspaceKey ? [nearestWorkspaceKey] : []), ...variantWorkspaceKeys.values(), ...externalWorkspaceKeys.current]);\n setWorkspaces((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key))));\n for (const key of workspaceCaptures.current.keys()) if (!valid.has(key)) workspaceCaptures.current.delete(key);\n if (workspaceKey && !valid.has(workspaceKey)) { setWorkspaceKey(null); setWorkspaceOpen(false); }\n }, [nearestWorkspaceKey, primaryWorkspaceBase, scopes, variantWorkspaceKeys, workspaceKey]);\n\n const captureOne = React.useCallback(async (material: Source | Payload | SurfaceHandle | null, scope: TransferScope, signal: AbortSignal, applyMenuProjection = false, collectPages = true): Promise<CaptureResult> => {\n if (!material) throw new Error(\"Alchemy needs a source or a mounted transfer surface.\");\n let sourceMaterial: Source;\n if (\"instanceId\" in material) {\n if (!material.isMounted()) throw new Error(\"The requested transfer surface is no longer mounted.\");\n const captured = await material.capture(signal);\n sourceMaterial = { id: captured.snapshot.sourceId, label: captured.snapshot.label, capture: async () => captured };\n } else if (\"kind\" in material) {\n sourceMaterial = { id: materialIdentity(material), label: sourceLabel, capture: async () => directSource(material, { sourceId: materialIdentity(material), label: sourceLabel, ...(applyMenuProjection && projection ? { projection } : {}), ...(applyMenuProjection && sections ? { sections } : {}) }) };\n } else if (applyMenuProjection && (projection || sections)) {\n sourceMaterial = {\n id: material.id,\n label: material.label,\n capture: async (request) => {\n const captured = await material.capture(request);\n return {\n ...captured,\n projection: { rules: [...captured.projection.rules, ...(projection?.rules ?? [])] },\n snapshot: { ...captured.snapshot, ...(sections ? { sections } : {}) },\n };\n },\n };\n } else {\n sourceMaterial = material;\n }\n const raw = await sourceMaterial.capture({ scope, signal });\n const constrained = resolveTransferPreferences(providerPreferences, preferences, raw.snapshot.limits);\n const result = await capture({ id: raw.snapshot.sourceId, label: raw.snapshot.label, capture: async () => ({ ...raw, snapshot: { ...raw.snapshot, limits: constrained.limits } }) }, signal, scope);\n if (scope !== \"all-matching\" || !collectPages) return result;\n if (!result.allMatching) throw new Error(\"This source cannot provide a stable all-matching export.\");\n const collected = await collectAllMatching(result.allMatching, signal);\n if (result.snapshot.payload.kind !== \"rows\") throw new Error(\"All-matching export requires tabular content.\");\n return { snapshot: projectSnapshot({ ...result.snapshot, payload: { kind: \"rows\", rows: collected.rows, columns: result.snapshot.payload.columns }, coverage: collected.coverage, omissions: [...collected.omissions] }, { rules: [] }), allMatching: result.allMatching, ...(collected.error ? { collectionError: collected.error.message } : {}) };\n }, [preferences, projection, providerPreferences, sections, sourceLabel]);\n const capturePrimary = React.useCallback((scope: TransferScope, signal: AbortSignal) => captureOne(primary, scope, signal, true), [captureOne, primary]);\n workspaceCaptures.current.set(primaryWorkspaceKey, capturePrimary);\n if (nearestWorkspaceKey && nearestSurface) workspaceCaptures.current.set(nearestWorkspaceKey, (scope, signal) => captureOne(nearestSurface, scope, signal, true));\n for (const variant of variants) {\n const key = variantWorkspaceKeys.get(variant.id)!;\n workspaceCaptures.current.set(key, (scope, signal) => captureOne(variant.source, scope, signal, true));\n }\n\n const runRich = React.useCallback(async (flavor: RichCopyFlavor) => {\n if (!richCopy) return;\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(null);\n setNotice(null);\n try {\n const result = await richCopy(flavor);\n if (result === false) return;\n if (result && typeof result === \"object\") {\n if (result.status === \"success\") confirmCopy(`rich-${flavor}`);\n report(result);\n } else confirmCopy(`rich-${flavor}`);\n } catch (error) { report({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Copy failed\"), retryable: true }); }\n }, [confirmCopy, report, richCopy]);\n\n const preflight = React.useCallback(async (scope = initialScope) => {\n const { controller, id } = inspectionFence.begin(); setMenuCapture(null); setMenuStatus(\"loading\");\n try {\n const probe = primary ?? formatSources?.plain ?? formatSources?.markdown ?? formatSources?.json ?? null;\n const shape = shapeOf(probe);\n // A declared shape is inspected as its empty payload: nothing of the content is built to open the menu.\n const result = await captureOne(shape ? shapePayload(shape) : probe, scope, controller.signal, true, false);\n if (inspectionFence.valid(id, controller)) { setMenuCapture(result); setMenuStatus(\"idle\"); }\n // PP-09: two explicit format sources that produce the same bytes are one choice, not two\n // (\"Text\" and \"Markdown\" of a screen's Markdown-style text). The first in palette order stays.\n // Only sources that are cheap to build are compared; a shaped, costly source is never built to open the menu.\n const explicit = COPIES.filter((format) => formatSources?.[format]);\n const duplicates = new Set<string>();\n const comparable = explicit.every((format) => { const declared = shapeOf(formatSources![format]); return !declared || declared.cheap === true; });\n if (explicit.length > 1 && comparable) {\n const seen = new Set<string>();\n for (const format of explicit) {\n try {\n const captured = await captureOne(formatSources![format]!, scope, controller.signal, true, false);\n const artifact = await buildFormat(createDraft(captured.snapshot), format, captured.snapshot.label, adapters, controller.signal);\n const signature = `${artifact.plainText}\\u0000${artifact.html ?? \"\"}`;\n // Applied as found: a later source's engine may load on first use (print for HTML).\n if (seen.has(signature)) { duplicates.add(format); if (inspectionFence.valid(id, controller)) setDuplicateFormats(new Set(duplicates)); } else seen.add(signature);\n } catch { /* An explicit source that cannot be built stays offered; its own copy reports why. */ }\n }\n }\n if (inspectionFence.valid(id, controller)) setDuplicateFormats(duplicates);\n }\n catch (error) { if (inspectionFence.valid(id, controller)) { setMenuCapture(null); setMenuStatus(errorMessage(error, \"Could not inspect content\")); } }\n finally { inspectionFence.finish(controller); }\n }, [adapters, captureOne, inspectionFence, formatSources, initialScope, primary]);\n\n const closePalette = React.useCallback(() => {\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n leaveTimer.current = null;\n const onClose = externalPaletteClose.current;\n const restoreFocus = externalPaletteRestoreFocus.current;\n externalPaletteClose.current = null;\n externalPaletteRestoreFocus.current = null;\n onClose?.();\n restoreFocus?.();\n setPaletteTarget(null);\n setPaletteOpen(false);\n }, []);\n const mountPalette = React.useCallback((target: HTMLElement | null, onClose?: () => void, restoreFocus?: () => void) => {\n if (!target) {\n // Host cleanup (submenu replacement, mobile drilldown back) must detach\n // without asking that host to close a second time.\n externalPaletteClose.current = null;\n externalPaletteRestoreFocus.current = null;\n setPaletteTarget(null);\n setPaletteOpen(false);\n return;\n }\n if (!enabled) throw new Error(\"Alchemy is not enabled for this record.\");\n if (disabled) throw new Error(\"Alchemy is disabled for this record.\");\n externalPaletteClose.current = onClose ?? null;\n externalPaletteRestoreFocus.current = restoreFocus ?? null;\n feedbackDocument.current = target.ownerDocument;\n restoreFocusRef.current = restoreFocus ?? (() => target.focus());\n setPaletteTarget(target);\n setPaletteOpen(true);\n setMode(\"copy\");\n void preflight();\n }, [closePalette, disabled, enabled, preflight]);\n React.useEffect(() => {\n if (!paletteTarget || !paletteOpen) return;\n const firstControl = paletteTarget.querySelector<HTMLElement>(\"button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [href]\");\n firstControl?.focus();\n }, [paletteOpen, paletteTarget]);\n\n const transfer = React.useCallback(async (format: BuiltInFormat | FormatAdapter | \"default\", download: boolean, alternate?: TransferMenuVariant) => {\n fence.abortAll();\n const { controller, id } = fence.begin();\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(null);\n setNotice(null);\n try {\n const explicit = alternate?.source ?? (format === \"default\" ? formatSources?.plain ?? (!primary ? formatSources?.markdown ?? formatSources?.json : undefined) : typeof format === \"string\" && format !== \"xlsx\" ? formatSources?.[format] : undefined);\n const result = await (explicit ? captureOne(explicit, initialScope, controller.signal, true) : capturePrimary(initialScope, controller.signal));\n if (result.collectionError) throw new Error(`The complete source could not be collected: ${result.collectionError}`);\n if (result.snapshot.coverage.status !== \"complete\" || result.snapshot.omissions.length > 0) {\n const reason = result.snapshot.coverage.reason ?? `${result.snapshot.omissions.length} omission${result.snapshot.omissions.length === 1 ? \"\" : \"s\"}`;\n throw new Error(`Quick transfer is partial (${reason}). Open Prepare for AI to review it before delivery.`);\n }\n const resolved = resolveTransferPreferences(providerPreferences, preferences, result.snapshot.limits);\n const draft = applyTransferLimits(createDraft(result.snapshot), resolved.limits); const revision = draft.revision;\n if (draft.omissions.length > result.snapshot.omissions.length) throw new Error(\"Quick transfer requires content reductions. Open Prepare for AI to review them before delivery.\");\n // Match the core bytes to the palette's canonical tile, including lazy sources.\n const defaultFormat: SerializableFormat = formatSources?.plain ? \"plain\"\n : result.snapshot.payload.kind === \"markdown\" ? \"markdown\"\n : [\"json\", \"registered\", \"rows\"].includes(result.snapshot.payload.kind) ? \"json\" : \"plain\";\n const deliveryFormat = format === \"default\" ? defaultFormat : format;\n if (format === \"default\" && !formatSources?.[defaultFormat] && !offersFormat(defaultFormat, result.snapshot.payload, adapters)) return;\n const artifact = typeof deliveryFormat === \"string\" ? await buildFormat(draft, deliveryFormat, result.snapshot.label, adapters, controller.signal) : await buildWithAdapter(deliveryFormat, draft, controller.signal);\n if (artifact.omissions.length > draft.omissions.length) throw new Error(`Quick format requires ${artifact.omissions.length - draft.omissions.length} adjustment${artifact.omissions.length - draft.omissions.length === 1 ? \"\" : \"s\"}. Open Prepare for AI to review before delivery.`);\n if (!fence.valid(id, controller) || artifact.snapshotId !== result.snapshot.id || artifact.draftRevision !== revision) return;\n // The shared session transport queues writes, including prepared output.\n const outcome = await transport[download ? \"download\" : \"copy\"](artifact, controller.signal);\n if (fence.valid(id, controller)) {\n if (!download && outcome.status === \"success\" && outcome.delivered === \"clipboard\") confirmCopy(alternate?.id ?? (typeof deliveryFormat === \"string\" ? deliveryFormat : deliveryFormat.id));\n else if (!download && outcome.status === \"degraded\" && outcome.delivered === \"plain-text\") confirmCopy(\"plain\");\n report(outcome.status === \"success\" && alternate?.successMessage ? { ...outcome, message: alternate.successMessage } : outcome);\n }\n } catch (error) { if (fence.valid(id, controller)) report({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Preparation failed\"), retryable: true }); }\n finally { fence.finish(controller); }\n }, [adapters, captureOne, capturePrimary, confirmCopy, fence, formatSources, initialScope, preferences, primary, providerPreferences, report, transport]);\n\n const openWorkspace = React.useCallback(\n async (\n key = primaryWorkspaceKey,\n variant?: { source: Source | Payload | SurfaceHandle; label: string; envelope?: EnvelopeMeta | undefined },\n ) => {\n const variantMaterial =\n variant && \"kind\" in variant.source\n ? ({\n id: `variant:${key}`,\n label: variant.label,\n capture: async () =>\n directSource(variant.source as Payload, {\n sourceId: `variant:${key}`,\n label: variant.label,\n }),\n } satisfies Source)\n : variant?.source;\n const captureWorkspace = (\n scope: TransferScope,\n signal: AbortSignal,\n collectPages = true,\n ) =>\n captureOne(variantMaterial ?? primary, scope, signal, true, collectPages);\n workspaceCaptures.current.set(key, captureWorkspace);\n const existing = workspaces[key];\n const { controller, id } = fence.begin();\n if (existing) {\n try {\n const scopeChanged = existing.scope !== initialScope;\n const allMatching = initialScope === \"all-matching\";\n const fresh = await captureWorkspace(\n initialScope,\n controller.signal,\n scopeChanged || !allMatching,\n );\n if (!fence.valid(id, controller) || !workspaceCaptures.current.has(key))\n return;\n if (allMatching && (!fresh.allMatching || (!scopeChanged && !existing.allMatching)))\n throw new Error(\n \"This source can no longer provide an all-matching snapshot.\",\n );\n const collectionIdentity = (value: BoundAllMatching | undefined) =>\n value && {\n query: value.source.query,\n projection: value.projection,\n columns: value.columns,\n limits: value.limits,\n };\n const changed = scopeChanged || (allMatching\n ? JSON.stringify(collectionIdentity(existing.allMatching)) !==\n JSON.stringify(collectionIdentity(fresh.allMatching))\n : snapshotContent(existing.snapshot) !==\n snapshotContent(fresh.snapshot));\n setWorkspaces((current) => {\n const retained = current[key];\n if (!retained) return current;\n return {\n ...current,\n [key]: {\n ...retained,\n error: fresh.collectionError,\n ...(allMatching && !scopeChanged\n ? { sourceStale: changed }\n : changed\n ? { pending: { ...fresh, scope: initialScope } }\n : { pending: undefined }),\n },\n };\n });\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n } catch (error) {\n if (fence.valid(id, controller) && workspaceCaptures.current.has(key)) {\n setWorkspaces((current) =>\n current[key]\n ? {\n ...current,\n [key]: {\n ...current[key]!,\n error: errorMessage(error, \"Could not refresh source\"),\n },\n }\n : current,\n );\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n }\n } finally {\n fence.finish(controller);\n }\n return;\n }\n try {\n const result = await captureWorkspace(initialScope, controller.signal);\n if (!fence.valid(id, controller)) return;\n const resolved = resolveTransferPreferences(\n providerPreferences,\n preferences,\n result.snapshot.limits,\n );\n const original = createDraft(result.snapshot);\n const envelope = variant?.envelope ?? (key === primaryWorkspaceKey ? primaryEnvelope?.() : undefined);\n const base: WorkspaceState = {\n ...result,\n key,\n original,\n draft: original,\n scope: initialScope,\n preferences: resolved,\n ...(result.collectionError ? { error: result.collectionError } : {}),\n ...(envelope ? { envelope } : {}),\n };\n setWorkspaces((current) => ({\n ...current,\n [key]: { ...base, draft: rebuild(base, initialControls(base)) },\n }));\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n } catch (error) {\n if (fence.valid(id, controller)) {\n setReceiptTarget(undefined); noticeLife.current = NOTICE_ERROR_MS; setNotice(errorMessage(error, \"Could not capture content\")); startNoticeTimer();\n }\n } finally {\n fence.finish(controller);\n }\n },\n [\n captureOne,\n capturePrimary,\n fence,\n initialScope,\n preferences,\n primaryWorkspaceKey,\n primary,\n primaryEnvelope,\n providerPreferences,\n startNoticeTimer,\n workspaces,\n ],\n );\n const prepareLevers = React.useCallback(async (levers: WorkspaceLevers, options: { id: string; label: string }) => {\n const key = `levers:${options.id}`;\n externalWorkspaceKeys.current.add(key);\n if (!workspaces[key]) {\n const sourceId = `levers:${sessionId}:${options.id}`;\n let built: ReturnType<WorkspaceLevers[\"build\"]> | null = null;\n let buildError: string | undefined;\n try { built = levers.build(levers.initial); } catch (cause) { buildError = errorMessage(cause, \"This source could not be prepared with these options.\"); }\n const snapshot = leverSnapshot(built?.payload ?? { kind: \"text\", text: \"\" }, sourceId, options.label);\n const original = createDraft(snapshot);\n const base: WorkspaceState = {\n snapshot, key, original, draft: original, scope: initialScope,\n preferences: resolveTransferPreferences(providerPreferences, preferences, snapshot.limits),\n levers, leverValues: levers.initial,\n ...(built?.meta ? { leverMeta: built.meta } : {}),\n ...(built?.sectionSizes ? { leverSizes: built.sectionSizes } : {}),\n ...(built ? { envelope: built.envelope } : {}),\n ...(buildError ? { buildError } : {}),\n };\n setWorkspaces((current) => ({ ...current, [key]: { ...base, draft: rebuild(base, initialControls(base)) } }));\n }\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n }, [initialScope, preferences, providerPreferences, sessionId, workspaces]);\n React.useImperativeHandle(controllerRef, () => ({\n focusTrigger: () => triggerRef.current?.focus(),\n mountPalette,\n preparePrimary: async (options) => {\n if (!enabled) throw new Error(\"Alchemy is not enabled for this record.\");\n if (disabled) throw new Error(\"Alchemy is disabled for this record.\");\n if (hide.includes(\"prepare\")) throw new Error(\"Alchemy preparation is unavailable for this record.\");\n if (!primary) throw new Error(\"Alchemy has no source to prepare.\");\n restoreFocusRef.current = options?.restoreFocus ?? null;\n await openWorkspace(primaryWorkspaceKey, { source: primary, label: sourceLabel });\n },\n prepare: async (requestedSource, options) => {\n const requestedLabel = options?.label ?? (\"label\" in requestedSource ? requestedSource.label : \"content\");\n const requestedKey = `controller:${options?.id ?? \"source\"}:${materialIdentity(requestedSource)}`;\n externalWorkspaceKeys.current.add(requestedKey);\n await openWorkspace(requestedKey, { source: requestedSource, label: requestedLabel, envelope: options?.envelope });\n },\n prepareLevers,\n }), [disabled, enabled, hide, mountPalette, openWorkspace, prepareLevers, primary, primaryWorkspaceKey, sourceLabel]);\n\n React.useEffect(() => {\n if (!windowPort) return;\n const openKey = workspaceOpen ? workspaceKey : null;\n for (const [key, handle] of [...windowHandles.current]) {\n if (key === openKey) continue;\n windowHandles.current.delete(key);\n handle.close();\n }\n if (!openKey || windowHandles.current.has(openKey)) return;\n const label = workspaces[openKey]?.snapshot.label ?? sourceLabel;\n const instanceId = `alchemy-prepare${sessionId}${openKey}`.replace(/[^A-Za-z0-9_-]+/g, \"-\");\n setWorkspaceSessionLive(instanceId, true);\n sessionKeys.current.add(instanceId);\n const handle: WorkspaceWindowHandle = windowPort.open(() => <WorkspaceWindowSlot onNode={slotRef(openKey)} sessionKey={instanceId} onClose={() => handle.close()} />, {\n title: `Prepare ${label}`,\n size: \"full\",\n instanceId,\n onClose: () => {\n if (windowHandles.current.get(openKey) !== handle) return;\n windowHandles.current.delete(openKey);\n setWorkspaceOpen(false);\n },\n });\n windowHandles.current.set(openKey, handle);\n // `workspaces` is read for the title only; opening follows the open key.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [windowPort, workspaceOpen, workspaceKey]);\n React.useEffect(() => () => {\n // The captured content goes with this session: any window a host keeps says so (PP-08).\n for (const key of sessionKeys.current) setWorkspaceSessionLive(key, false);\n sessionKeys.current.clear();\n const handles = [...windowHandles.current.values()];\n windowHandles.current.clear();\n for (const handle of handles) handle.close();\n }, []);\n\n const runAction = React.useCallback(async (action: PageAction) => {\n const { controller, id } = fence.begin();\n try { const actionSource = (action as PageAction & { source?: Source }).source; const { snapshot } = actionSource ? await captureOne(actionSource, initialScope, controller.signal, true) : await capturePrimary(initialScope, controller.signal); const resolved = resolveTransferPreferences(providerPreferences, preferences, snapshot.limits); const draft = applyTransferLimits(createDraft(snapshot), resolved.limits); if (snapshot.coverage.status !== \"complete\" || draft.omissions.length) throw new Error(\"This content is partial or requires reductions. Open Prepare for AI to review it before sending it to a destination.\"); if (!action.supports(snapshot, draft)) throw new Error(`${action.label} is unavailable for this content.`); const result = await action.run({ snapshot, draft, signal: controller.signal }); if (fence.valid(id, controller) && draft.snapshotId === snapshot.id) report(result); }\n catch (error) { if (fence.valid(id, controller)) report({ status: \"error\", code: \"action-failed\", message: errorMessage(error, \"Action failed\"), retryable: true }); }\n finally { fence.finish(controller); }\n }, [captureOne, capturePrimary, fence, initialScope, preferences, providerPreferences, report]);\n\n const copyReference = async (reference: ContentTransferReference) => {\n const { controller, id } = fence.begin();\n closePalette();\n try {\n if (!referencePort?.supports(reference)) throw new Error(\"This reference is not registered or its identity is incomplete.\");\n const text = await referencePort.build(reference);\n if (!text.trim()) throw new Error(\"The reference serializer returned no content.\");\n const artifact = sealTransferArtifact({ snapshotId: `reference:${reference.id}`, draftRevision: 0, format: \"matrx-reference\", plainText: text, omissions: [] });\n if (!fence.valid(id, controller)) return;\n const outcome = await transport.copy(artifact, controller.signal);\n if (fence.valid(id, controller)) {\n if (outcome.status === \"success\" && outcome.delivered === \"clipboard\") confirmCopy(`reference:${reference.id}`);\n report(outcome);\n }\n } catch (error) { if (fence.valid(id, controller)) report({status: \"error\", code: \"reference-failed\", message: errorMessage(error, \"Could not copy reference\"), retryable: true}); }\n finally { fence.finish(controller); }\n };\n const openReference = async (action: ContentTransferReferenceAction) => {\n closePalette();\n try { await action.run(); }\n catch (error) { report({status: \"error\", code: \"reference-failed\", message: errorMessage(error, \"Could not open reference picker\"), retryable: true}); }\n };\n const cancelPointerClose = () => {\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n leaveTimer.current = null;\n };\n const schedulePointerClose = (event: React.PointerEvent) => {\n if (event.pointerType !== \"mouse\" || !paletteOpen) return;\n cancelPointerClose();\n // Allow crossing the gap between the trigger and its portalled palette.\n leaveTimer.current = setTimeout(() => closePalette(), 200);\n };\n // One draft per inspection, never one per action per render.\n const visibleActions = React.useMemo(() => {\n if (!menuCapture) return [];\n const draft = applyTransferLimits(createDraft(menuCapture.snapshot), resolveTransferPreferences(providerPreferences, preferences, menuCapture.snapshot.limits).limits);\n return registeredActions.filter((a) => a.supports(menuCapture.snapshot, draft));\n }, [menuCapture, preferences, providerPreferences, registeredActions]);\n if (!enabled) return null;\n const payload = menuCapture?.snapshot.payload ?? (source && \"kind\" in source ? source : undefined);\n const quickVariants = (section: \"copy\" | \"ai\") => variants.filter((v) => v.copyLabel && (v.section ?? \"ai\") === section);\n const visibleCopies = sourceFormats ? COPIES.filter((f) => !duplicateFormats.has(f) && (Boolean(formatSources?.[f]) || (payload ? offersFormat(f, payload, adapters) : ![\"csv\", \"tsv\"].includes(f)))) : [];\n const visibleDownloads = sourceFormats ? DOWNLOADS.filter((f) => !duplicateFormats.has(f) && ((f !== \"xlsx\" && Boolean(formatSources?.[f])) || (payload ? offersFormat(f, payload, adapters) : ![\"csv\", \"tsv\", \"xlsx\"].includes(f)))) : [];\n const visibleAdapters = sourceFormats && menuCapture ? adapters.filter((a) => !isBuiltInFormat(a.id) && a.supports(menuCapture.snapshot.payload)) : [];\n const downloadActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === \"download\");\n const prepareActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === \"prepare\");\n const ordinaryActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === undefined);\n const preparedActions = registeredActions.filter((action) => (action as TransferMenuPresentation).prepared && !action.source);\n const copyAvailable = !hide.includes(\"copy\") && (Boolean(richCopy) || visibleCopies.length + visibleAdapters.length + quickVariants(\"copy\").length > 0);\n const downloadAvailable = !hide.includes(\"download\") && (visibleDownloads.length + visibleAdapters.length + downloadActions.length > 0);\n const prepareAvailable = !hide.includes(\"prepare\") && (quickVariants(\"ai\").length > 0 || Boolean(primary) || Boolean(nearestWorkspaceKey) || variants.length > 0 || prepareActions.length > 0);\n const resolvedMode = mode === \"copy\" && !copyAvailable ? \"download\" : mode === \"download\" && !downloadAvailable ? \"copy\" : mode;\n const nativeAiFormat: FormatAdapter = {\n id: \"ai-context\", label: \"AI context\", extension: \"txt\", mime: \"text/plain;charset=utf-8\", modes: [\"copy\", \"download\"], runsOn: \"client\", supports: () => true,\n load: async () => ({ build: async (draft) => {\n const envelope = primaryEnvelope?.() ?? { kind: \"matrx_content\", location: sourceLabel, description: \"Captured content for an assistant\", attributes: { source: draft.sourceId } };\n // PP-09: text and Markdown travel as themselves; only structured content is JSON.\n if (draft.payload.kind === \"text\" || draft.payload.kind === \"markdown\") {\n const text = serialize(draft, draft.payload.kind === \"markdown\" ? \"markdown\" : \"plain\");\n return sealTransferArtifact({ snapshotId: draft.snapshotId, draftRevision: draft.revision, format: \"ai-context\", plainText: buildAgentPayload({ ...envelope, data: text.plainText, dataFormat: draft.payload.kind === \"markdown\" ? \"markdown\" : \"text\" }), omissions: [...text.omissions] });\n }\n const json = serialize(draft, \"json\");\n return sealTransferArtifact({ snapshotId: draft.snapshotId, draftRevision: draft.revision, format: \"ai-context\", plainText: buildAgentPayload({ ...envelope, data: JSON.parse(json.plainText) }), omissions: [...json.omissions] });\n } }),\n };\n const copyFirst = sourceFormats && !hide.includes(\"copy\") && Boolean(richCopy || primary || formatSources?.plain || formatSources?.markdown || formatSources?.json);\n const copiedGlyph = <svg className=\"matrx-alchemy-copied-check\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden=\"true\"><path d=\"m5 12 4 4L19 6\"/></svg>;\n const triggerGlyph = copiedFormat ? copiedGlyph : <AlchemyGlyph icon={icon}/>;\n const tile = (id: string, label: string, onClick: () => void, options: { custom?: boolean; action?: PageAction; ai?: boolean; file?: boolean; ariaLabel?: string } = {}) => {\n const presentation = options.action as TransferMenuPresentation | undefined;\n const Icon = presentation?.icon;\n const fallbackLabel = options.file && !/^download\\b/i.test(label) ? `Download ${label}` : label;\n return <button key={id} type=\"button\" className=\"matrx-alchemy-palette-tile\" data-copied={resolvedMode === \"copy\" && copiedFormat === id ? \"true\" : undefined} title={id === \"table-data\" ? \"JSON using column display names\" : id === \"table-schema\" ? \"Table schema and rows\" : label} aria-label={presentation?.ariaLabel ?? (presentation ? fallbackLabel : options.ariaLabel ?? `${resolvedMode === \"copy\" ? \"Copy\" : \"Download\"} ${label}`)} onClick={() => { closePalette(); onClick(); }}>{resolvedMode === \"copy\" && copiedFormat === id ? copiedGlyph : Icon ? <Icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph format={id} ai={Boolean(options.ai)} file={options.file || Boolean(options.custom && id !== \"table-data\" && id !== \"table-schema\")}/>}<span>{label}{resolvedMode === \"copy\" && copiedFormat === id ? <small className=\"matrx-alchemy-copied-label\">Copied to clipboard</small> : null}{presentation?.hint ? <small className=\"matrx-alchemy-menu-hint\">{presentation.hint}</small> : null}</span></button>;\n };\n const palette = <>\n {menuStatus === \"loading\" ? <p className=\"matrx-alchemy-palette-status\">Inspecting content…</p> : menuStatus !== \"idle\" ? <p className=\"matrx-alchemy-error\">{menuStatus}</p> : null}\n {table && scopes.length > 1 ? <label className=\"matrx-alchemy-scope\">Content scope<select aria-label=\"Content scope\" value={initialScope} onChange={(event) => { const next = scopes.find((scope) => scope === event.target.value); if (next) { setRequestedScope(next); void preflight(next); } }}>{scopes.map((scope) => <option key={scope} value={scope}>{table.scopeLabels?.[scope] ?? SCOPE_LABEL[scope]}</option>)}</select></label> : null}\n {copyAvailable || downloadAvailable ? <section className=\"matrx-alchemy-output\"><h3>{resolvedMode === \"copy\" ? \"Copy as\" : \"Download as\"}</h3>{copyAvailable && downloadAvailable ? <div className=\"matrx-alchemy-mode\" aria-label=\"Output action\"><button type=\"button\" aria-label=\"Copy mode\" aria-pressed={resolvedMode === \"copy\"} onClick={() => setMode(\"copy\")}>Copy</button><button type=\"button\" aria-label=\"Download mode\" aria-pressed={resolvedMode === \"download\"} onClick={() => setMode(\"download\")}>Download</button></div> : null}\n {resolvedMode === \"copy\" && copyAvailable ? <><div className=\"matrx-alchemy-palette-grid\">{richCopy ? <>{richCopyFlavors.includes(\"markdown\") ? tile(\"rich-markdown\", \"Copy markdown\", () => void runRich(\"markdown\"), { ariaLabel: \"Copy markdown\" }) : null}{richCopyFlavors.includes(\"text\") ? tile(\"rich-text\", \"Copy text\", () => void runRich(\"text\"), { ariaLabel: \"Copy text\" }) : null}</> : null}{visibleCopies.filter((format) => !richCopy || (format !== \"plain\" && format !== \"markdown\" && (![\"json\", \"compact-json\"].includes(format) || Boolean(formatSources?.[format])))).map((format) => tile(format, ({ plain: \"Text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact\", csv: \"CSV\", tsv: \"Sheets\" } as Record<SerializableFormat, string>)[format]!, () => void transfer(format, false), { ariaLabel: `Copy ${LABEL[format]}` }))}{visibleAdapters.map((adapter) => tile(adapter.id, adapter.label, () => void transfer(adapter, false), { custom: true }))}</div>{quickVariants(\"copy\").length ? <PaletteRows title=\"Quick copy\" items={quickVariants(\"copy\")} onRun={(variant) => { closePalette(); void transfer(\"markdown\", false, variant); }}/>: null}</> : null}\n {resolvedMode === \"download\" && downloadAvailable ? <><div className=\"matrx-alchemy-palette-grid\">{visibleDownloads.map((format) => tile(format, ({ plain: \"Text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact\", csv: \"CSV\", tsv: \"Sheets\", xlsx: \"Excel\" } as Record<BuiltInFormat, string>)[format]!, () => void transfer(format, true), { ariaLabel: `Download ${LABEL[format]}` }))}{visibleAdapters.map((adapter) => tile(adapter.id, adapter.label, () => void transfer(adapter, true), { custom: true }))}{downloadActions.map((action) => tile(action.id, action.label, () => void runAction(action), { custom: true, action, file: true }))}</div></> : null}</section> : null}\n {prepareAvailable ? <><PaletteRows title=\"Copy for AI\" ai glyphKind=\"ai-copy\" fallbackHint=\"Copies immediately\" extra={<>{sourceFormats ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => { closePalette(); void transfer(nativeAiFormat, false); }}><PaletteGlyph kind=\"ai-copy\"/><span>Copy with AI context<small className=\"matrx-alchemy-menu-hint\">Include source context</small></span></button> : null}{copyWithPrompt || primary ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Copy with prompt\" onClick={() => { closePalette(); void (copyWithPrompt ? copyWithPrompt() : openWorkspace()).then(() => setPromptFocus((n) => n + 1)); }}><PaletteGlyph kind=\"ai-copy\"/><span>Copy with prompt…<small className=\"matrx-alchemy-menu-hint\">Add your instructions</small></span></button> : null}</>} items={quickVariants(\"ai\")} onRun={(variant) => { closePalette(); void transfer(\"markdown\", false, variant); }}/><PaletteRows title=\"Edit and prepare\" items={[]} extra={<>{prepareActions.map((action) => { const presentation = action as TransferMenuPresentation; return <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={presentation.ariaLabel ?? `${action.label}${presentation.hint ? ` ${presentation.hint}` : \"\"}`} onClick={() => { closePalette(); void runAction(action); }}><PaletteGlyph kind=\"sliders\"/><span>{action.label}…{presentation.hint ? <small className=\"matrx-alchemy-menu-hint\">{presentation.hint}</small> : null}</span></button>; })}{table ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Filter & sort before copying\" onClick={() => { closePalette(); void openWorkspace(); }}><PaletteGlyph kind=\"sliders\"/><span>Filter & sort before copying…<small className=\"matrx-alchemy-menu-hint\">{table.size ? `${table.size} · search, filter, sort, pick rows` : \"Search, filter, sort, pick rows\"}</small></span></button> : null}<button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Prepare for AI\" onClick={() => { closePalette(); void openWorkspace(); }}><PaletteGlyph kind=\"sliders\"/><span>Prepare for AI<small className=\"matrx-alchemy-menu-hint\">Trim, edit or summarize</small></span></button></>}/></>: null}\n {prepareAvailable && (nearestWorkspaceKey || variants.length) ? <PaletteRows title=\"Other sources\" items={[]} extra={<>{nearestWorkspaceKey && nearestSurface ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => { closePalette(); void openWorkspace(nearestWorkspaceKey, { source: nearestSurface, label: nearestSurface.surfaceName }); }}><PaletteGlyph kind=\"surface\"/><span>Prepare this page</span></button> : null}{variants.map((variant) => <button key={variant.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={variant.ariaLabel} onClick={() => { closePalette(); void openWorkspace(variantWorkspaceKeys.get(variant.id)!, variant); }}><MenuPresentation {...variant} label={`Prepare ${variant.label}`}/></button>)}</>}/>: null}\n {references.length || referenceActions.length ? <section className=\"matrx-alchemy-palette-section\"><h3>References</h3>{referenceActions.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => void openReference(action)}><PaletteGlyph kind=\"link\"/><span>{action.label}</span><svg className=\"matrx-alchemy-disclosure\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" aria-hidden=\"true\"><path d=\"m6 4 4 4-4 4\"/></svg></button>)}{references.map((reference) => <button key={reference.id} type=\"button\" className=\"matrx-alchemy-palette-row\" title=\"Copies a reference to saved data\" onClick={() => void copyReference(reference)}><PaletteGlyph kind=\"link\"/><span>{reference.label}</span></button>)}</section> : null}\n {([\"save\", \"chat\", \"email\"] as const).map((group) => { const entries = ordinaryActions.filter((action) => (action as TransferMenuPresentation).group === group); return entries.length ? <details key={group} className=\"matrx-alchemy-palette-destinations\"><summary>{DESTINATION_HEADING[group]}<span className=\"matrx-alchemy-disclosure-meta\"><span>{entries.length}</span><svg className=\"matrx-alchemy-disclosure\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" aria-hidden=\"true\"><path d=\"m6 4 4 4-4 4\"/></svg></span></summary><div>{entries.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={(action as TransferMenuPresentation).ariaLabel} onClick={() => { closePalette(); void runAction(action); }}><DestinationPresentation action={action}/></button>)}</div></details> : null; })}{ordinaryActions.some((action) => !(action as TransferMenuPresentation).group) ? <section className=\"matrx-alchemy-palette-section\" data-alchemy-inline-actions=\"\">{ordinaryActions.filter((action) => !(action as TransferMenuPresentation).group).map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={(action as TransferMenuPresentation).ariaLabel} onClick={() => { closePalette(); void runAction(action); }}><DestinationPresentation action={action}/></button>)}</section> : null}\n </>;\n const feedbackOwner = paletteTarget ?? triggerRef.current ?? feedbackDocument.current?.body ?? null;\n return <span className={cn(\"matrx-alchemy\", className)} onPointerEnter={cancelPointerClose} onPointerLeave={schedulePointerClose} onClick={stopPropagation ? (event) => event.stopPropagation() : undefined}>\n {!triggerHidden && !paletteTarget ? <Popover open={paletteOpen} onOpenChange={(open) => { if (open) { setPaletteOpen(true); setMode(\"copy\"); void preflight(); if (copyFirst) void (richCopy ? runRich(\"default\") : transfer(\"default\", false)); } else { cancelPointerClose(); closePalette(); } }}><PopoverTrigger asChild>{triggerVariant === \"outline\" ? <Button ref={triggerRef} variant=\"outline\" size=\"icon-sm\" aria-label={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"outline\" data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled}>{triggerGlyph}</Button> : triggerVariant === \"glass\" ? <TapTargetButton ref={triggerRef} icon={triggerGlyph} tooltip={false} ariaLabel={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"glass\" data-alchemy-size={triggerSize} data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled} /> : <TapTargetButtonTransparent ref={triggerRef} icon={triggerGlyph} tooltip={false} ariaLabel={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"transparent\" data-alchemy-size={triggerSize} data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled} />}</PopoverTrigger><PopoverContent align=\"end\" className=\"matrx-alchemy-menu matrx-alchemy-palette\" aria-label=\"Alchemy output options\" onPointerEnter={cancelPointerClose} onPointerLeave={schedulePointerClose} onCloseAutoFocus={() => triggerRef.current?.focus()}>{palette}</PopoverContent></Popover> : null}\n {paletteTarget && paletteOpen ? createPortal(<div className=\"matrx-alchemy-menu matrx-alchemy-palette\" role=\"dialog\" aria-label=\"Alchemy output options\">{palette}</div>, paletteTarget) : null}\n {notice && feedbackOwner ? createPortal(<div className=\"matrx-alchemy-feedback\" onPointerEnter={clearNoticeTimer} onPointerLeave={startNoticeTimer}><span role=\"status\">{notice}</span><ReceiptLink target={receiptTarget}/><button type=\"button\" aria-label=\"Dismiss Alchemy feedback\" onClick={() => setNotice(null)}>×</button></div>, feedbackOwner.ownerDocument.body) : null}\n {Object.values(workspaces).map((saved) => <PreparationWorkspace promptFocus={workspaceKey === saved.key ? promptFocus : 0} restoreFocus={() => restoreFocusRef.current?.() ?? triggerRef.current?.focus()} key={saved.key} frame={windowPort ? \"host\" : \"dialog\"} windowNode={windowNodes[saved.key] ?? null} open={workspaceOpen && workspaceKey === saved.key} state={saved} scopes={scopes} scopeLabels={table?.scopeLabels} onClose={() => setWorkspaceOpen(false)} onChange={(next) => setWorkspaces((current) => ({ ...current, [saved.key]: next }))} transport={transport} adapters={adapters} actions={preparedActions} captureScope={workspaceCaptures.current.get(saved.key) ?? capturePrimary} {...(ai ? { ai } : {})} onOutcome={report}/>)}\n {emailReview}\n </span>;\n}\n\n\nexport * from \"./matrx-copy\";\nexport { AlchemyTableCopyControls } from \"./table-copy-controls\";\n","\"use client\";\n\n/**\n * The preparation workspace's shared core: format ids and labels, the fence, the draft rebuild\n * from workspace controls, the format builders, and the offered-format rule. The menu session\n * (`index.tsx`) and the workspace (`workspace.tsx`) both import it — one copy.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport {\n applyJsonStructure,\n applySectionSelection,\n applySectionStructure,\n assembleAgentPayload,\n applyTransferLimits,\n concretePointers,\n deriveDraft,\n isProseSection,\n jsonTextSpans,\n offsetSpans,\n pointerSegments,\n sectionLayout,\n spanMap,\n stubText,\n readTransferCell,\n reduceJson,\n resetDraft,\n sealTransferArtifact,\n serialize,\n transformRows,\n type Artifact,\n type BoundAllMatching,\n type Column,\n type Json,\n type NodeLimit,\n type OutputSpan,\n type SpanMap,\n type StructureRecipe,\n type Draft,\n type FormatAdapter,\n type FormatOptions,\n type PageAction,\n type Payload,\n type Snapshot,\n type Source,\n type SurfaceHandle,\n type TransferOutcome,\n type TransferPreferences,\n type TransferScope,\n type TransferTarget,\n} from \"@ai-matrx/alchemy/operate\";\nimport type { TransferMenuPresentation } from \"./index\";\nimport { filterAndSortRows } from \"@ai-matrx/design-system/data-table/filter-engine\";\nimport type { LayeredFilterRule } from \"@ai-matrx/design-system/data-table\";\nimport type { ColumnFiltersState, MatrxColumnDef, TableSearchMatchMode } from \"@ai-matrx/design-system/data-table\";\nimport type { EnvelopeMeta, LeverMeta, LeverValues, WorkspaceLevers } from \"./levers\";\n\nexport type SerializableFormat = \"plain\" | \"markdown\" | \"html\" | \"json\" | \"compact-json\" | \"csv\" | \"tsv\";\nexport type BuiltInFormat = SerializableFormat | \"xlsx\";\n\nexport function MenuPresentation({ label, hint, icon: Icon }: TransferMenuPresentation & { label: string }) {\n return <>{Icon ? <Icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph file/>}<span>{label}{hint ? <small className=\"matrx-alchemy-menu-hint\">{hint}</small> : null}</span></>;\n}\nexport function DestinationPresentation({ action }: { action: PageAction & TransferMenuPresentation }) {\n const paths: Record<string, string> = {\n notes: \"M5 3h14v18H5zM8 8h8M8 12h8M8 16h5\",\n scratch: \"M5 3h14v18H5zM9 12h6M12 9v6\",\n document: \"M6 3h8l4 4v14H6zM14 3v5h4M9 12h6M9 16h6\",\n workbook: \"M3 4h18v16H3zM3 9h18M9 4v16M15 9v11M3 15h18\",\n task: \"M9 6h11M9 12h11M9 18h11M3 6l1 1 2-2M3 12l1 1 2-2M3 18l1 1 2-2\",\n attach: \"m9 12 5-5a3 3 0 0 1 4 4l-7 7a5 5 0 0 1-7-7l8-8M7 14l7-7\",\n code: \"m8 6-6 6 6 6m8-12 6 6-6 6m-3-14-2 16\",\n chat: \"M4 4h16v13H9l-5 4zM8 9h8M8 13h5\",\n assistant: \"M3 4h18v16H3zM15 4v16M6 9h6M6 13h4\",\n tools: \"m14 4 3 3 4-1a6 6 0 0 1-8 7l-7 7-3-3 7-7a6 6 0 0 1 4-6z\",\n };\n const path = paths[action.id.replace(/^matrx:/, \"\")];\n return <>{action.icon ? <action.icon className=\"matrx-alchemy-menu-icon\"/> : path ? <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d={path}/></svg> : <PaletteGlyph file/>}<span>{action.label}{action.hint ? <small className=\"matrx-alchemy-menu-hint\">{action.hint}</small> : null}</span></>;\n}\nexport function ReceiptLink({ target }: { target: TransferTarget | undefined }) {\n return target?.href && /^(\\/(?!\\/)|https?:\\/\\/)/.test(target.href) ? <a className=\"matrx-alchemy-receipt-link\" href={target.href}>Open {target.kind}</a> : null;\n}\nexport function PaletteGlyph({ format, ai = false, file = false, kind }: { format?: string; ai?: boolean; file?: boolean; kind?: \"ai-copy\" | \"sliders\" | \"link\" | \"surface\" }) {\n if (kind === \"link\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2\"/></svg>;\n if (kind === \"surface\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"/><path d=\"M3 9h18M9 9v12\"/></svg>;\n if (kind === \"ai-copy\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"5\" y=\"5\" width=\"11\" height=\"14\" rx=\"2\"/><path d=\"M9 3h6a2 2 0 0 1 2 2v10\"/><path d=\"m18.5 3 .55 1.45L20.5 5l-1.45.55L18.5 7l-.55-1.45L16.5 5l1.45-.55z\"/></svg>;\n if (kind === \"sliders\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M4 6h16M4 12h16M4 18h16\"/><path d=\"M8 3v6M16 9v6M10 15v6\"/></svg>;\n if (ai) return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 5a3 3 0 1 0-5.997.125A4 4 0 0 0 3.5 10.9a4 4 0 0 0 .556 6.588A4 4 0 0 0 12 19\"/><path d=\"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.503 5.775 4 4 0 0 1-.556 6.588A4 4 0 0 1 12 19\"/><path d=\"M12 5v14M8 9h1M15 9h1M8 15h1M15 15h1\"/></svg>;\n if (file) return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M6 3h8l4 4v14H6z\"/><path d=\"M14 3v5h5M9 13h6M9 17h6\"/></svg>;\n const path = format === \"json\" || format === \"table-data\" ? <><path d=\"M9 4C7 4 7 7 5 7v3c2 0 2 1 2 2s0 2-2 2v3c2 0 2 3 4 3\"/><path d=\"M15 4c2 0 2 3 4 3v3c-2 0-2 1-2 2s0 2 2 2v3c-2 0-2 3-4 3\"/></>\n : format === \"table-schema\" ? <><rect x=\"8\" y=\"3\" width=\"8\" height=\"5\" rx=\"1\"/><rect x=\"2\" y=\"16\" width=\"8\" height=\"5\" rx=\"1\"/><rect x=\"14\" y=\"16\" width=\"8\" height=\"5\" rx=\"1\"/><path d=\"M12 8v4M6 16v-4h12v4\"/></>\n : format === \"compact-json\" ? <><path d=\"m14 10 7-7\"/><path d=\"M20 10h-6V4\"/><path d=\"m3 21 7-7\"/><path d=\"M4 14h6v6\"/></>\n : format === \"csv\" ? <><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1\"/><path d=\"M4 10h16M10 4v16\"/></>\n : format === \"tsv\" ? <><path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h2M14 13h2M8 17h2M14 17h2\"/></>\n : format === \"xlsx\" ? <><path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h8M8 17h8M12 11v8\"/></>\n : format === \"markdown\" ? <><path d=\"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5z\"/><path d=\"M14 2v6h6M10 13l-2 2 2 2M14 17l2-2-2-2\"/></>\n : format === \"html\" ? <><path d=\"M15 6h6M3 6h7M3 12h18M3 18h12\"/></>\n : <><path d=\"M4 7V4h16v3M9 20h6M12 4v16\"/></>;\n return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">{path}</svg>;\n}\n\nexport const LABEL: Record<BuiltInFormat, string> = { plain: \"Plain text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact JSON\", csv: \"CSV\", tsv: \"Google Sheets\", xlsx: \"Excel workbook\" };\nexport const BUILT_INS = Object.freeze((Object.keys(LABEL) as BuiltInFormat[]).map((id) => ({ id })));\nexport const COPIES: SerializableFormat[] = [\"plain\", \"markdown\", \"html\", \"json\", \"compact-json\", \"csv\", \"tsv\"];\nexport const DOWNLOADS: BuiltInFormat[] = [...COPIES, \"xlsx\"];\nexport const EMPTY_VARIANTS: readonly { id: string; label: string; source: Source | Payload }[] = [];\nexport const SCOPE_LABEL: Record<TransferScope, string> = { target: \"This content\", row: \"This row\", selected: \"Selected rows\", view: \"Current view\", loaded: \"Loaded rows\", \"all-matching\": \"All matching rows\" };\nexport const filenameFor = (label: string) => label.toLocaleLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/(^-|-$)/g, \"\") || \"export\";\nexport const errorMessage = (error: unknown, fallback: string) => error instanceof Error ? error.message : fallback;\nexport const isAbort = (error: unknown) => error instanceof DOMException && error.name === \"AbortError\";\nexport const supportsBuiltIn = (format: BuiltInFormat, payload: Payload) => ![\"csv\", \"tsv\", \"xlsx\"].includes(format) || payload.kind === \"rows\";\nexport const outcomeMessage = (result: TransferOutcome) => {\n if (result.status === \"success\") {\n const success = result as TransferOutcome & { delivered: string; message?: string };\n return success.delivered === \"action\" ? success.message ?? \"Action completed\" : success.delivered === \"download-started\" ? \"Download started\" : success.message ?? \"Copied\";\n }\n // A queued write is NEITHER a delivery nor a failure (kit `TransferOutcome`\n // `queued`): the host's sentence alone reads as \"done\", so the remedy — what\n // has not happened yet and what the person does next — is always spoken with\n // it, and the pending request rides the same receipt door as any target.\n if (result.status === \"queued\") return `${result.message} ${result.remedy}`;\n return result.status === \"degraded\" ? `Copied as plain text: ${result.reason}` : result.status === \"cancelled\" ? \"Cancelled\" : result.message;\n};\nexport const materialIds = new WeakMap<object, number>();\nlet nextMaterialId = 0;\nexport function materialIdentity(material: Source | Payload | SurfaceHandle | null | undefined) {\n if (!material) return \"missing\";\n if (\"instanceId\" in material) return `surface:${material.instanceId}`;\n if (\"id\" in material) return `source:${material.id}`;\n let id = materialIds.get(material);\n if (id === undefined) { id = ++nextMaterialId; materialIds.set(material, id); }\n return `payload:${id}`;\n}\n\nexport type CaptureResult = { snapshot: Snapshot; allMatching?: BoundAllMatching; collectionError?: string };\nexport type WorkspaceState = CaptureResult & {\n sourceStale?: boolean | undefined;\n key: string;\n original: Draft;\n draft: Draft;\n scope: TransferScope;\n preferences: TransferPreferences;\n pending?: (CaptureResult & { scope: TransferScope }) | undefined;\n error?: string | undefined;\n /** The host's own levers for this source (aiCustom options, groomer sections), live beside the preview (PP-02). */\n levers?: WorkspaceLevers | undefined;\n leverValues?: LeverValues | undefined;\n /** The host builder's meta for the current lever values (\"messages 12/40\"), shown in the top bar (PP-03). */\n leverMeta?: LeverMeta | undefined;\n /** A host builder that threw: its sentence is the preview, nothing else breaks (PP-02). */\n buildError?: string | undefined;\n /** Per groomer section, its size in the prepared JSON at its current level (PP-04). */\n leverSizes?: Record<string, number> | undefined;\n /** Who this content is, for the AI envelope (PP-10). Absent = a generic \"matrx_content\" envelope. */\n envelope?: EnvelopeMeta | undefined;\n};\n\n/** Compare captured meaning at the user action boundary, never during render. */\nexport function snapshotContent(snapshot: Snapshot) {\n const { sourceId, label, payload, coverage, unsavedChanges, omissions, sections, limits } = snapshot;\n return JSON.stringify({ sourceId, label, payload, coverage, unsavedChanges, omissions, sections, limits });\n}\n\nexport function useFence() {\n const mounted = React.useRef(true);\n const nextId = React.useRef(0);\n const active = React.useRef(new Set<AbortController>());\n React.useEffect(() => {\n mounted.current = true;\n return () => { mounted.current = false; nextId.current += 1; active.current.forEach((c) => c.abort()); active.current.clear(); };\n }, []);\n const begin = React.useCallback(() => { const controller = new AbortController(); active.current.add(controller); return { controller, id: ++nextId.current }; }, []);\n const finish = React.useCallback((controller: AbortController) => active.current.delete(controller), []);\n const valid = React.useCallback((id: number, controller: AbortController) => mounted.current && !controller.signal.aborted && nextId.current === id, []);\n const abortAll = React.useCallback(() => { nextId.current += 1; active.current.forEach((c) => c.abort()); active.current.clear(); }, []);\n return { begin, finish, valid, abortAll };\n}\n\n/** The one Excel engine (`@ai-matrx/alchemy/operate/formats/xlsx`, SheetJS loads only there). */\nexport async function xlsxArtifact(draft: Draft, label: string): Promise<Artifact> {\n if (draft.payload.kind !== \"rows\") throw new Error(\"Excel workbook export requires tabular content.\");\n const { xlsxEngine } = await import(\"@ai-matrx/alchemy/operate/formats/xlsx\");\n return xlsxEngine.build(draft, { filename: `${filenameFor(label)}.xlsx` }, new AbortController().signal);\n}\n/** A lazy format adapter's bytes (CONTRACT §2.3): its engine loads on first use, then builds. */\nexport async function buildWithAdapter(adapter: FormatAdapter, draft: Draft, signal: AbortSignal, options: FormatOptions = {}): Promise<Artifact> {\n return (await adapter.load()).build(draft, options, signal);\n}\n/**\n * Rich Markdown (the clipboard's text/html beside the Markdown as text/plain): HTML from THE one\n * Markdown→HTML engine (`@ai-matrx/print/markdown-html`, through operate's `rich-html`).\n */\nexport async function markdownRichArtifact(draft: Draft, filename = \"export.html\"): Promise<Artifact> {\n if (draft.payload.kind !== \"markdown\") throw new Error(\"Rich Markdown requires Markdown content.\");\n const { richHtmlEngine } = await import(\"@ai-matrx/alchemy/operate/formats/rich-html\");\n const rich = await richHtmlEngine.build(draft, { filename }, new AbortController().signal);\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"html\",\n plainText: draft.payload.text,\n ...(rich.html === undefined ? {} : { html: rich.html }),\n ...(rich.file === undefined ? {} : { file: rich.file }),\n omissions: [...draft.omissions],\n });\n}\nexport async function buildArtifact(draft: Draft, format: BuiltInFormat, label: string): Promise<Artifact> {\n if (!supportsBuiltIn(format, draft.payload)) throw new Error(`${LABEL[format]} is available for tabular content only.`);\n if (format === \"xlsx\") return xlsxArtifact(draft, label);\n if (format === \"html\" && draft.payload.kind === \"markdown\") return markdownRichArtifact(draft, `${filenameFor(label)}.html`);\n const extension = format === \"plain\" ? \"txt\" : format === \"compact-json\" ? \"json\" : format;\n return serialize(draft, format, { filename: `${filenameFor(label)}.${extension}` });\n}\n/**\n * A host format registered under a built-in id SUPERSEDES that built-in (ALC-15 round 5, A): the\n * host's engine builds it under the built-in's name, never as a second entry. This is how a host\n * gives a Markdown draft real plain text from its one Markdown engine — kit's sync serializer can\n * only echo the Markdown back. The file keeps the source's name.\n */\nexport function hostEngineFor(adapters: readonly FormatAdapter[], format: string): FormatAdapter | undefined {\n return isBuiltInFormat(format) ? adapters.find((adapter) => adapter.id === format) : undefined;\n}\nexport async function buildFormat(draft: Draft, format: BuiltInFormat, label: string, adapters: readonly FormatAdapter[], signal: AbortSignal): Promise<Artifact> {\n const engine = hostEngineFor(adapters, format);\n if (!engine) return buildArtifact(draft, format, label);\n const artifact = await buildWithAdapter(engine, draft, signal);\n if (!artifact.file) return artifact;\n const dot = artifact.file.filename.lastIndexOf(\".\");\n const extension = dot > 0 ? artifact.file.filename.slice(dot) : \"\";\n return sealTransferArtifact({ ...artifact, file: { filename: `${filenameFor(label)}${extension}`, mime: artifact.file.mime, bytes: artifact.file.bytes } });\n}\n/** Offered for this payload: the host engine's own answer when it supersedes the built-in, else the built-in rule. */\nexport function offersFormat(format: BuiltInFormat, payload: Payload, adapters: readonly FormatAdapter[]): boolean {\n // Rows: \"Plain text\" IS the tab-separated table (built-in and the host's one engine alike), so\n // it would be the Google Sheets bytes under a second name — TSV is offered, plain is not.\n if (format === \"plain\" && payload.kind === \"rows\") return false;\n const engine = hostEngineFor(adapters, format);\n return engine ? engine.supports(payload) : supportsBuiltIn(format, payload) && offersDistinctOutput(format, payload);\n}\n\nexport type Preset = \"full\" | \"compact\" | \"brief\" | \"custom\";\nexport type Controls = {\n preset: Preset;\n sections: string[];\n /** Rows: the search that shapes the copy (every shown column), and how it matches (PP-08). */\n search: string;\n searchMode: TableSearchMatchMode;\n filters: Record<string, string>;\n layeredFilters: LayeredFilterRule[];\n sort: string;\n direction: \"asc\" | \"desc\";\n top: number | null;\n visibleColumns: string[];\n /** Rows left out by their include checkbox, as positions in the captured rows (PP-06c). */\n excludedRows: number[];\n /** JSON: excluded patterns and per-node limits (PP-06b, PP-07). */\n structure: StructureRecipe;\n /** Per section id / column id: stub or cap (PP-07). */\n sectionLimits: Record<string, NodeLimit>;\n columnLimits: Record<string, NodeLimit>;\n maxDepth: number | null;\n maxStringChars: number | null;\n maxArrayItems: number | null;\n};\n\nexport const NO_STRUCTURE: StructureRecipe = { exclude: [], limits: {} };\n/** A column a person may export: never one declared non-exportable, secret or a credential. */\nexport const exportableColumn = (column: Column) => column.exportable !== false && column.classification !== \"secret\" && column.classification !== \"credential\";\n\nexport function initialControls(state: WorkspaceState): Controls {\n const rows = state.original.payload.kind === \"rows\" ? state.original.payload : null;\n return {\n preset: state.preferences.initialPreset,\n sections: state.snapshot.sections.filter((s) => s.includedByDefault).map((s) => s.id),\n search: \"\", searchMode: \"contains\", filters: {}, layeredFilters: [], sort: \"\", direction: \"asc\",\n top: state.preferences.limits.maxRows,\n visibleColumns: rows?.columns.filter((c) => c.visible && exportableColumn(c)).map((c) => c.id) ?? [],\n excludedRows: [],\n structure: NO_STRUCTURE, sectionLimits: {}, columnLimits: {},\n maxDepth: state.preferences.limits.maxDepth,\n maxStringChars: state.preferences.limits.maxStringChars,\n maxArrayItems: state.preferences.limits.maxArrayItems ?? null,\n };\n}\nexport function presetLimits(preset: Preset, controls: Controls, preferences: TransferPreferences) {\n const min = (choice: number | null, cap: number | null) => choice == null ? cap : cap == null ? choice : Math.min(choice, cap);\n if (preset === \"full\") return preferences.limits;\n const request = preset === \"brief\" ? { maxDepth: 4, maxStringChars: 800, maxArrayItems: 25 } : preset === \"compact\" ? { maxDepth: 8, maxStringChars: 4000, maxArrayItems: 100 } : { maxDepth: controls.maxDepth, maxStringChars: controls.maxStringChars, maxArrayItems: controls.maxArrayItems };\n return { ...preferences.limits, maxDepth: min(request.maxDepth, preferences.limits.maxDepth), maxStringChars: min(request.maxStringChars, preferences.limits.maxStringChars), maxArrayItems: min(request.maxArrayItems, preferences.limits.maxArrayItems ?? null) };\n}\n\n/** Where the structure choices put things in a rebuilt draft — read by highlighting and the diff. */\nexport interface DraftLayout {\n /** Rows: every captured row position the search and filters match, in output order (included or not). */\n matchedRows?: number[];\n /** Rows: the captured positions that are in the output, in output order. */\n rowOrder?: number[];\n /** Prose sections: where each kept section sits in the draft text. */\n sectionRanges?: Record<string, { start: number; end: number }>;\n sectionText?: string;\n}\nconst layouts = new WeakMap<Draft, DraftLayout>();\nexport const draftLayout = (draft: Draft): DraftLayout => layouts.get(draft) ?? {};\n\n/**\n * Rows the copy-subset way (PP-08): search every shown column (contains or whole words), per-column\n * filters, layered filters and sort through the data table's ONE filter engine — the table and the\n * copy never disagree. Hidden columns neither show nor filter nor sort. The captured rows are only\n * read: the result is new arrays of the same row objects.\n */\nexport function matchRows(payload: Extract<Payload, { kind: \"rows\" }>, controls: Controls): number[] {\n const shown = new Set(controls.visibleColumns);\n const columns = payload.columns.filter((column) => shown.has(column.id) && exportableColumn(column));\n const defs: MatrxColumnDef<number>[] = columns.map((column) => ({ id: column.id, header: column.label, accessorFn: (index: number) => readTransferCell(payload.rows[index]!, column) }));\n const filters: ColumnFiltersState = Object.fromEntries(Object.entries(controls.filters).filter(([id, value]) => value && shown.has(id)).map(([id, value]) => [id, { kind: \"text\" as const, value }]));\n const sort = controls.sort && shown.has(controls.sort) ? { id: controls.sort, direction: controls.direction } : null;\n return filterAndSortRows(payload.rows.map((_, index) => index), defs, filters, sort, controls.search, undefined, controls.layeredFilters.filter((rule) => shown.has(rule.field)), controls.searchMode);\n}\n\nfunction applyColumnLimits(draft: Draft, limits: Record<string, NodeLimit>): Draft {\n const payload = draft.payload;\n const entries = Object.entries(limits);\n if (payload.kind !== \"rows\" || !entries.length) return draft;\n const omissions: Draft[\"omissions\"] = [];\n let rows = payload.rows;\n for (const [id, limit] of entries) {\n const column = payload.columns.find((candidate) => candidate.id === id);\n if (!column || limit.kind === \"maxItems\") continue;\n let count = 0;\n rows = rows.map((row) => {\n const value = row[id];\n if (value === undefined || value === null) return row;\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n if (limit.kind === \"stub\") { count++; return { ...row, [id]: stubText(value) }; }\n if (text.length <= limit.value) return row;\n count++;\n return { ...row, [id]: `${text.slice(0, limit.value)} … [truncated — ${formatCount(text.length, { locale: \"en-US\" })} chars]` };\n });\n if (count) omissions.push({ path: `/columns/${id}`, reason: \"truncated\", count, label: `${column.label} — ${limit.kind === \"stub\" ? \"stubbed\" : `cut to ${formatCount(limit.value)} chars per cell`}` });\n }\n return omissions.length ? deriveDraft(draft, { ...payload, rows }, omissions, \"Column limits\") : draft;\n}\n\nexport function rebuild(state: WorkspaceState, controls: Controls): Draft {\n let draft = resetDraft(state.snapshot);\n const layout: DraftLayout = {};\n const sections = state.snapshot.sections;\n if (sections.length) {\n const payload = draft.payload;\n if ((payload.kind === \"text\" || payload.kind === \"markdown\") && sections.every(isProseSection)) {\n const laid = sectionLayout(payload.text, sections, controls.sections, controls.sectionLimits);\n draft = deriveDraft(draft, { ...payload, text: laid.text }, laid.omissions, \"Selected sections\");\n layout.sectionRanges = laid.ranges;\n layout.sectionText = laid.text;\n } else if (payload.kind === \"json\" || payload.kind === \"registered\") {\n draft = applySectionStructure(draft, sections, controls.sections, controls.sectionLimits);\n } else draft = applySectionSelection(draft, state.snapshot, controls.sections);\n }\n if (draft.payload.kind === \"rows\") {\n const payload = draft.payload;\n const matched = matchRows(payload, controls);\n const left = new Set(controls.excludedRows);\n const order = matched.filter((index) => !left.has(index));\n layout.matchedRows = matched;\n layout.rowOrder = order;\n const omissions: Draft[\"omissions\"] = [];\n if (matched.length < payload.rows.length) omissions.push({ path: \"/rows\", reason: \"filtered\", count: payload.rows.length - matched.length, label: \"rows the search and filters leave out\" });\n if (order.length < matched.length) omissions.push({ path: \"/rows\", reason: \"excluded\", count: matched.length - order.length, label: \"rows you left out\" });\n const identity = order.length === payload.rows.length && order.every((index, position) => index === position);\n if (!identity) draft = deriveDraft(draft, { ...payload, rows: order.map((index) => payload.rows[index]!) }, omissions, \"Rows you chose\");\n const visible = controls.visibleColumns.filter((id) => payload.columns.some((column) => column.id === id && exportableColumn(column)));\n draft = transformRows(draft, { visibleColumns: visible, structuredProjection: \"visible\", top: controls.top });\n if (controls.top != null && order.length > controls.top) layout.rowOrder = order.slice(0, controls.top);\n draft = applyColumnLimits(draft, controls.columnLimits);\n }\n if (draft.payload.kind === \"json\" || draft.payload.kind === \"registered\") draft = applyJsonStructure(draft, controls.structure);\n const limits = presetLimits(controls.preset, controls, state.preferences);\n if (draft.payload.kind === \"json\" || draft.payload.kind === \"registered\") {\n draft = reduceJson(draft, { maxDepth: limits.maxDepth, maxStringChars: limits.maxStringChars, maxArrayItems: limits.maxArrayItems ?? null });\n }\n const final = applyTransferLimits(draft, limits);\n layouts.set(final, layout);\n return final;\n}\n/**\n * A format is offered only when it produces its OWN bytes for this payload (ALC-15 round 4, A):\n * the workspace's sync serializer writes a Markdown draft's \"plain text\" as the same Markdown, and a\n * prose draft's compact JSON as the same JSON string, and a JSON draft's plain text and Markdown as the\n * JSON — two labels, one output. A host that registers its own engine under the built-in id (the app's\n * one Markdown engine for plain text) brings the format back with real output (hostEngineFor).\n */\nexport function offersDistinctOutput(format: BuiltInFormat, payload: Payload): boolean {\n if (payload.kind === \"markdown\") return format !== \"plain\" && format !== \"compact-json\";\n // Structured content: kit writes its \"plain text\" and \"Markdown\" as the same pretty JSON — JSON is offered as JSON.\n if (payload.kind === \"json\" || payload.kind === \"registered\") return format !== \"plain\" && format !== \"markdown\";\n if (payload.kind === \"text\") return format !== \"compact-json\" && (format !== \"markdown\" || Boolean(payload.language));\n return true;\n}\n/** \"message\" → \"messages\"; the count unit a source declared, else \"section\". */\nexport function countNoun(unit: string, n: number): string { return n === 1 ? unit : `${unit}s`; }\nexport function isBuiltInFormat(format: string): format is BuiltInFormat { return format in LABEL; }\nexport function preview(draft: Draft, format: string) {\n const resolved = isBuiltInFormat(format) ? format : \"plain\";\n return serialize(draft, resolved === \"xlsx\" ? \"tsv\" : resolved).plainText;\n}\n\n// ── PP-10: the AI envelope around the chosen format, sealed ───────────────────────────────────\n\n/** The envelope's `<data format>` for an output format, or null when the format is not text for a model. */\nexport function envelopeDataFormat(format: string, artifact: Artifact): string | null {\n if (format === \"html\" || format === \"xlsx\" || artifact.html !== undefined) return null;\n if (format === \"plain\") return \"text\";\n return /^[a-z][a-z0-9-]*$/.test(format) ? format : \"text\";\n}\nexport function defaultEnvelope(snapshot: Snapshot): EnvelopeMeta {\n return { kind: \"matrx_content\", location: snapshot.label, description: \"Captured content for an assistant\", attributes: { source: snapshot.sourceId } };\n}\n/** Where the envelope wrote its body in a sealed For-AI artifact (for the span map, PP-06a). */\nconst envelopeBodies = new WeakMap<Artifact, { body: string; bodyOffset: number; dataFormat: string }>();\n/**\n * The one artifact the preview shows and Copy writes when \"For AI\" is on: the chosen format's\n * bytes inside the AI envelope, the person's instructions first — all inside the seal.\n */\nexport function sealForAi(formatArtifact: Artifact, dataFormat: string, envelope: EnvelopeMeta, instructions: string, label: string): Artifact {\n const data = dataFormat === \"json\" ? (JSON.parse(formatArtifact.plainText) as unknown) : formatArtifact.plainText;\n const { text, body, bodyOffset } = assembleAgentPayload({ ...envelope, data, dataFormat, ...(instructions.trim() ? { instructions } : {}) });\n const artifact = sealTransferArtifact({\n snapshotId: formatArtifact.snapshotId,\n draftRevision: formatArtifact.draftRevision,\n format: `ai-context:${formatArtifact.format}`,\n plainText: text,\n file: { filename: `${filenameFor(label)}-for-ai.md`, mime: \"text/markdown;charset=utf-8\", bytes: new TextEncoder().encode(text) },\n omissions: [...formatArtifact.omissions],\n });\n envelopeBodies.set(artifact, { body, bodyOffset, dataFormat });\n return artifact;\n}\n\n/**\n * Every node → its span in the text the preview SHOWS (the bare format, or the For-AI envelope\n * around it). Null when this format has no span map (a host engine's own format) — the caller says\n * so instead of guessing.\n */\nexport function shownSpans(draft: Draft, formatArtifact: Artifact, shown: Artifact): SpanMap | null {\n let base: SpanMap;\n try { base = spanMap(draft, formatArtifact); } catch { return null; }\n if (shown === formatArtifact) return base;\n const envelope = envelopeBodies.get(shown);\n if (!envelope) return null;\n try {\n if (envelope.dataFormat !== \"json\") return envelope.body === formatArtifact.plainText ? offsetSpans(base, envelope.bodyOffset) : null;\n const spans = jsonTextSpans(envelope.body, \"\", envelope.bodyOffset);\n return draft.payload.kind === \"rows\" ? spans.map((span) => ({ ...span, path: `/rows${span.path}` })) : spans;\n } catch { return null; }\n}\n/** A prose section's span: the draft text's own span plus where the section landed in it. */\nexport function sectionSpan(draft: Draft, spans: SpanMap, text: string, sectionId: string): OutputSpan | null {\n const layout = draftLayout(draft);\n const range = layout.sectionRanges?.[sectionId];\n const whole = spans.find((span) => span.path === \"\");\n const payload = draft.payload;\n if (!range || !whole || (payload.kind !== \"text\" && payload.kind !== \"markdown\") || layout.sectionText !== payload.text) return null;\n if (text.slice(whole.start, whole.end) !== payload.text) return null;\n return { path: `/sections/${sectionId}`, start: whole.start + range.start, end: whole.start + range.end };\n}\n\nexport const encodePointer = (segment: string) => segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\nexport type Mark = { start: number; end: number; kind: \"focus\" | \"match\" | \"removed\" | \"changed\" };\nconst sortMarks = (marks: Mark[]) => marks.sort((a, b) => a.start - b.start || b.end - a.end);\n/** Drop marks nested inside an earlier mark of the same kind (a removed row holds its cells). */\nfunction outermost(marks: Mark[]): Mark[] {\n const out: Mark[] = [];\n for (const mark of sortMarks(marks)) {\n const last = out[out.length - 1];\n if (last && mark.start >= last.start && mark.end <= last.end) continue;\n out.push(mark);\n }\n return out;\n}\n\n/**\n * \"Show what was removed\" (PP-07): the Full text (this format, before the structure choices) with\n * every removed node and every stubbed or capped node marked, read through the span map — exact,\n * never a guess by text similarity.\n */\n/**\n * Where each prose section landed in an output a host engine REWROTE (Markdown → plain text): each\n * section's own text projected alone through the same engine and found, in order, in the output.\n * Exact when the engine projects block by block (it does: sections start at line starts); a\n * section it cannot find is simply absent — the caller says so, it never guesses a range.\n */\nexport async function locateProjectedSections(output: string, pieces: readonly { id: string; text: string }[], engine: FormatAdapter, signal: AbortSignal): Promise<Record<string, { start: number; end: number }>> {\n const found: Record<string, { start: number; end: number }> = {};\n let cursor = 0;\n for (const piece of pieces) {\n const draft = { snapshotId: \"section\", sourceId: \"section\", sourceRevision: \"section\", revision: 0, payload: { kind: \"markdown\", text: piece.text }, omissions: [], manuallyEdited: false, provenance: [] } as unknown as Draft;\n const projected = (await buildWithAdapter(engine, draft, signal)).plainText.trim();\n if (!projected) continue;\n const at = output.indexOf(projected, cursor);\n if (at < 0) continue;\n found[piece.id] = { start: at, end: at + projected.length };\n cursor = at + projected.length;\n }\n return found;\n}\n\nexport function removedMarks(state: WorkspaceState, controls: Controls, full: Draft, fullArtifact: Artifact, projected?: Record<string, { start: number; end: number }>): { marks: Mark[]; removed: number; changed: number; chars: number } | null {\n let spans: SpanMap;\n try { spans = spanMap(full, fullArtifact); } catch { return null; }\n const byPath = new Map(spans.map((span) => [span.path, span]));\n const marks: Mark[] = [];\n const mark = (path: string, kind: Mark[\"kind\"]) => { const span = byPath.get(path); if (span && span.end > span.start) marks.push({ start: span.start, end: span.end, kind }); };\n const payload = full.payload;\n if (payload.kind === \"json\" || payload.kind === \"registered\") {\n for (const pattern of controls.structure.exclude) concretePointers(payload.value, pattern).forEach((pointer) => mark(pointer, \"removed\"));\n for (const pattern of Object.keys(controls.structure.limits)) concretePointers(payload.value, pattern).forEach((pointer) => mark(pointer, \"changed\"));\n }\n const sections = state.snapshot.sections;\n if (sections.length) {\n const keep = new Set(controls.sections);\n if ((payload.kind === \"text\" || payload.kind === \"markdown\") && sections.every(isProseSection)) {\n const whole = byPath.get(\"\");\n const exact = whole && fullArtifact.plainText.slice(whole.start, whole.end) === payload.text;\n for (const section of sections) {\n const [, a, b] = /^\\/text\\/(\\d+)-(\\d+)$/.exec(section.path)!;\n const kind: Mark[\"kind\"] | null = !keep.has(section.id) ? \"removed\" : controls.sectionLimits[section.id] ? \"changed\" : null;\n if (!kind) continue;\n if (exact) marks.push({ start: whole.start + Number(a), end: whole.start + Number(b), kind });\n else if (projected?.[section.id]) marks.push({ ...projected[section.id]!, kind });\n }\n } else for (const section of sections) {\n if (!keep.has(section.id)) mark(section.path, \"removed\");\n else if (controls.sectionLimits[section.id]) mark(section.path, \"changed\");\n }\n }\n if (payload.kind === \"rows\") {\n const kept = new Set(draftLayout(state.draft).rowOrder ?? payload.rows.map((_, index) => index));\n const shown = new Set(controls.visibleColumns);\n const hidden = payload.columns.filter((column) => column.visible && exportableColumn(column) && !shown.has(column.id));\n payload.rows.forEach((_, index) => {\n if (!kept.has(index)) { mark(`/rows/${index}`, \"removed\"); return; }\n // A cell sits at its column path (CSV, TSV, Markdown, plain) or under its id (JSON records).\n const cell = (column: Column, kind: Mark[\"kind\"]) => { mark(`/rows/${index}${column.path}`, kind); mark(`/rows/${index}/${encodePointer(column.id)}`, kind); };\n for (const column of hidden) cell(column, \"removed\");\n for (const id of Object.keys(controls.columnLimits)) {\n const column = payload.columns.find((candidate) => candidate.id === id);\n if (column && shown.has(id)) cell(column, \"changed\");\n }\n });\n for (const column of hidden) mark(`/columns/${encodePointer(column.id)}`, \"removed\");\n }\n const merged = [...outermost(marks.filter((m) => m.kind === \"removed\")), ...outermost(marks.filter((m) => m.kind === \"changed\"))];\n return {\n marks: sortMarks(merged),\n removed: merged.filter((m) => m.kind === \"removed\").length,\n changed: merged.filter((m) => m.kind === \"changed\").length,\n chars: merged.filter((m) => m.kind === \"removed\").reduce((sum, m) => sum + m.end - m.start, 0),\n };\n}\n\n/** Matches of a search in the shown text (contains, or whole words), capped for drawing. */\nexport function findMatches(text: string, query: string, mode: TableSearchMatchMode, cap = 1000): { marks: Mark[]; total: number } {\n const trimmed = query.trim();\n if (!trimmed) return { marks: [], total: 0 };\n const escape = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = mode === \"whole_words\"\n ? new RegExp(trimmed.split(/[^\\p{L}\\p{N}]+/u).filter(Boolean).map((word) => `(?<![\\\\p{L}\\\\p{N}])${escape(word)}(?![\\\\p{L}\\\\p{N}])`).join(\"|\") || \"(?!)\", \"giu\")\n : new RegExp(escape(trimmed), \"gi\");\n const marks: Mark[] = [];\n let total = 0;\n for (const match of text.matchAll(pattern)) {\n if (!match[0]) continue;\n total++;\n if (marks.length < cap) marks.push({ start: match.index ?? 0, end: (match.index ?? 0) + match[0].length, kind: \"match\" });\n }\n return { marks, total };\n}\n/** Re-export for the trees (one import site). */\nexport { pointerSegments };\nexport type { Json };\n\n// ── PP-04: sizes ───────────────────────────────────────────────────────────────────────────────\n\nconst decodePointer = (segment: string) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n/** A section's own size in the prepared text: a prose range's length, or its JSON as it sits nested. */\nexport function sectionSize(payload: Payload, path: string): number | null {\n const range = /^\\/text\\/(\\d+)-(\\d+)$/.exec(path);\n if (range && (payload.kind === \"text\" || payload.kind === \"markdown\")) return Math.max(0, Number(range[2]) - Number(range[1]));\n if (payload.kind !== \"json\" && payload.kind !== \"registered\") return null;\n const segments = path.split(\"/\").slice(1).map(decodePointer);\n let value: unknown = payload.value;\n for (const segment of segments) {\n if (value === null || typeof value !== \"object\") return null;\n value = (value as Record<string, unknown>)[segment];\n }\n const text = JSON.stringify(value, null, 2);\n return text === undefined ? null : text.replace(/\\n/g, `\\n${\" \".repeat(segments.length)}`).length;\n}\nexport function columnSize(rows: Extract<Payload, { kind: \"rows\" }>, columnId: string): number {\n const column = rows.columns.find((c) => c.id === columnId);\n if (!column) return 0;\n let total = 0;\n for (const row of rows.rows) {\n const value = readTransferCell(row, column);\n total += value === null || value === undefined ? 0 : typeof value === \"string\" ? value.length : JSON.stringify(value).length;\n }\n return total;\n}\n/** \"12,345 chars · ≈3,087 tokens\" — the token figure always says it is an estimate. */\nexport function sizeLabel(chars: number): string {\n return `${formatCount(chars)} chars · ≈${formatCount(Math.ceil(chars / 4))} tokens`;\n}\n","\"use client\";\n\n/**\n * THE preparation workspace (Preparation parity PP-01b, PP-01c, PP-02, PP-03, PP-04, PP-09, PP-10).\n *\n * One surface: the source's structure (sections, groomer sections, columns and rows) on the left,\n * ONE read-only preview of the exact sealed bytes in the middle, and the host's own levers,\n * instructions, AI preparation and destinations on the right. The envelope toggle (Text / For AI)\n * chooses the one artifact the preview shows and the one Copy writes — preview = copy = download.\n *\n * Frames: inside a host window (`ContentTransferCapabilities.window`, the host's `WindowPort`) the\n * host draws the title bar and the close control; without one it is a near-full-screen dialog.\n * Below 768px of its own width it is three tabs (Structure / Preview / Settings) with Copy in a\n * footer every tab shares.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport { createPortal, flushSync } from \"react-dom\";\nimport {\n concretePointers,\n createDraft,\n editDraft,\n outputPointer,\n patternCovers,\n readTransferCell,\n resetDraft,\n resolveTransferPreferences,\n sealTransferArtifact,\n serialize,\n undoDraft,\n type Column,\n type Draft,\n type NodeLimit,\n type AiPreparation,\n type Artifact,\n type FormatAdapter,\n type Json,\n type PageAction,\n type Payload,\n type TransferOutcome,\n type TransferScope,\n type Transport,\n} from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from \"@ai-matrx/design-system\";\nimport { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuLabel, ContextMenuTrigger } from \"@ai-matrx/design-system\";\nimport { LayeredFilterBuilder } from \"@ai-matrx/design-system/data-table\";\nimport type { LayeredFilterField } from \"@ai-matrx/design-system/data-table\";\nimport {\n COPIES,\n DestinationPresentation,\n LABEL,\n SCOPE_LABEL,\n buildArtifact,\n buildFormat,\n columnSize,\n countNoun,\n defaultEnvelope,\n draftLayout,\n encodePointer,\n exportableColumn,\n findMatches,\n locateProjectedSections,\n removedMarks,\n sectionSpan,\n shownSpans,\n envelopeDataFormat,\n errorMessage,\n buildWithAdapter,\n hostEngineFor,\n initialControls,\n isAbort,\n isBuiltInFormat,\n offersFormat,\n outcomeMessage,\n rebuild,\n sealForAi,\n sectionSize,\n sizeLabel,\n useFence,\n type CaptureResult,\n type Controls,\n type Mark,\n type Preset,\n type WorkspaceState,\n} from \"./workspace-core\";\nimport {\n activeGroomerPreset,\n applyGroomerPreset,\n leverSnapshot,\n sectionLeverKey,\n type AlchemyGroomerSection,\n type AlchemySourceOption,\n type LeverValues,\n type SectionLevel,\n} from \"./levers\";\nimport {\n CELL_LIMITS,\n KEEP,\n LockGlyph,\n StructureTreeList,\n TEXT_LIMITS,\n decodeLimit,\n encodeLimit,\n itemPattern,\n jsonSearchItems,\n jsonTreeItems,\n toggleNode,\n type TreeHandlers,\n type TreeItem,\n} from \"./workspace-tree\";\n\n/** Structural twin of `@ai-matrx/alchemy/ports` `WindowPort` (design-system sits below alchemy). */\nexport interface WorkspaceWindowHandle {\n readonly instanceId: string;\n close(): void;\n focus(): void;\n isOpen(): boolean;\n}\nexport interface WorkspaceWindowPort {\n readonly presentation: \"window\" | \"dialog\";\n readonly multiInstance: boolean;\n open(\n render: (window: WorkspaceWindowHandle) => unknown,\n options: { title: string; size?: { width: number; height: number } | \"full\"; instanceId?: string; onClose?: () => void },\n ): WorkspaceWindowHandle;\n}\n\ntype Frame = \"dialog\" | \"host\";\ntype Tab = \"structure\" | \"preview\" | \"settings\";\ntype Pending = { kind: \"controls\"; controls: Controls } | { kind: \"levers\"; values: LeverValues };\n\nconst PANE_KEY = \"matrx-alchemy:prepare-panes\";\nconst TAB_KEY = \"matrx-alchemy:prepare-tab\";\nconst DEFAULT_PANES = { left: 320, right: 340 };\nconst MIN_PANE = 220;\nconst MOBILE_WIDTH = 768;\nconst PREVIEW_CHUNK_LINES = 200;\n\nfunction readStored<T>(key: string, fallback: T, valid: (value: unknown) => value is T): T {\n try {\n const raw = globalThis.localStorage?.getItem(key);\n if (!raw) return fallback;\n const value: unknown = JSON.parse(raw);\n return valid(value) ? value : fallback;\n } catch {\n return fallback;\n }\n}\nfunction writeStored(key: string, value: unknown) {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(value));\n } catch {\n // Storage blocked (private window, policy): the layout still works at its defaults.\n }\n}\nconst isPanes = (value: unknown): value is { left: number; right: number } =>\n Boolean(value) && typeof value === \"object\" && Number.isFinite((value as { left: unknown }).left) && Number.isFinite((value as { right: unknown }).right);\nconst isTab = (value: unknown): value is Tab => value === \"structure\" || value === \"preview\" || value === \"settings\";\n\n/** The root's own width (a window can be narrow on a wide screen). */\nfunction useNarrow(ref: React.RefObject<HTMLElement | null>): boolean {\n const [narrow, setNarrow] = React.useState(() => typeof window !== \"undefined\" && window.innerWidth < MOBILE_WIDTH);\n React.useLayoutEffect(() => {\n const node = ref.current;\n if (!node) return;\n const measure = () => {\n const width = node.getBoundingClientRect().width || window.innerWidth;\n setNarrow(width < MOBILE_WIDTH);\n };\n measure();\n if (typeof ResizeObserver === \"undefined\") {\n window.addEventListener(\"resize\", measure);\n return () => window.removeEventListener(\"resize\", measure);\n }\n const observer = new ResizeObserver(measure);\n observer.observe(node);\n return () => observer.disconnect();\n });\n return narrow;\n}\n\n/**\n * The read-only preview: the sealed text in line-aligned chunks the browser skips laying out when\n * off screen (`content-visibility: auto`), so a megabyte of transcript scrolls without a long\n * main-thread task. Concatenated, the chunks are exactly the sealed text — marks (a selected node's\n * span, search matches, removed text) wrap ranges of it and never add a character.\n */\nfunction PreviewText({ text, id, marks = EMPTY_MARKS, label = \"Prepared output\" }: { text: string; id?: string; marks?: readonly Mark[]; label?: string }) {\n const chunks = React.useMemo(() => {\n const out: { start: number; text: string }[] = [];\n let start = 0;\n let lines = 0;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) === 10 && ++lines === PREVIEW_CHUNK_LINES) {\n out.push({ start, text: text.slice(start, i + 1) });\n start = i + 1;\n lines = 0;\n }\n }\n if (start < text.length || out.length === 0) out.push({ start, text: text.slice(start) });\n return out;\n }, [text]);\n const ref = React.useRef<HTMLDivElement>(null);\n const focusStart = marks.find((mark) => mark.kind === \"focus\")?.start ?? -1;\n React.useEffect(() => {\n if (focusStart < 0) return;\n ref.current?.querySelector<HTMLElement>(\"[data-mark~='focus']\")?.scrollIntoView?.({ block: \"center\" });\n }, [focusStart]);\n return (\n <div ref={ref} id={id} className=\"matrx-alchemy-preview matrx-alchemy-prep-preview\" role=\"region\" aria-label={label} tabIndex={0} data-chars={text.length}>\n {chunks.map((chunk, index) => <pre key={index} className=\"matrx-alchemy-prep-chunk\">{marked(chunk.text, chunk.start, marks)}</pre>)}\n </div>\n );\n}\nconst EMPTY_MARKS: readonly Mark[] = [];\n/** One chunk's text with every overlapping mark as a `<mark>` (overlaps carry every kind). */\nfunction marked(text: string, offset: number, marks: readonly Mark[]): React.ReactNode {\n const end = offset + text.length;\n const inside = marks.filter((mark) => mark.end > offset && mark.start < end && mark.end > mark.start);\n if (!inside.length) return text;\n const cuts = new Set<number>([offset, end]);\n for (const mark of inside) { cuts.add(Math.max(offset, mark.start)); cuts.add(Math.min(end, mark.end)); }\n const points = [...cuts].sort((a, b) => a - b);\n const out: React.ReactNode[] = [];\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]!;\n const b = points[i + 1]!;\n const piece = text.slice(a - offset, b - offset);\n const kinds = [...new Set(inside.filter((mark) => mark.start <= a && mark.end >= b).map((mark) => mark.kind))];\n out.push(kinds.length ? <mark key={a} className=\"matrx-alchemy-mark\" data-mark={kinds.join(\" \")}>{piece}</mark> : piece);\n }\n return out;\n}\n\n/** \"Formatted\" is rich HTML on the clipboard: the preview shows that HTML rendered, sandboxed (no scripts). */\nfunction PreviewHtml({ html }: { html: string }) {\n return <iframe className=\"matrx-alchemy-preview matrx-alchemy-prep-html\" title=\"Prepared output (formatted)\" sandbox=\"\" srcDoc={html} />;\n}\n\nfunction ShareBar({ part, whole }: { part: number; whole: number }) {\n const share = whole > 0 ? Math.min(1, part / whole) : 0;\n return <span className=\"matrx-alchemy-prep-share\" aria-hidden=\"true\"><span style={{ width: `${(share * 100).toFixed(1)}%` }} /></span>;\n}\nfunction SizeNote({ chars, whole }: { chars: number | null; whole: number }) {\n if (chars === null) return null;\n return <span className=\"matrx-alchemy-prep-size\"><ShareBar part={chars} whole={whole} /><span>{sizeLabel(chars)}</span></span>;\n}\n\n/** Plain-text labels from the host's one plain-text projection (\"plain\" engine); raw text until it answers. */\nfunction useProjectedLabels(labels: readonly string[], adapters: readonly FormatAdapter[]): readonly string[] {\n const engine = hostEngineFor(adapters, \"plain\");\n const key = labels.join(\"\\u0000\");\n const [projected, setProjected] = React.useState<{ key: string; labels: readonly string[] } | null>(null);\n React.useEffect(() => {\n if (!engine || !labels.some((label) => /[#*_`[\\]>~|]/.test(label))) return;\n const controller = new AbortController();\n void Promise.all(\n labels.map(async (label) => {\n const artifact = await buildWithAdapter(\n engine,\n // A label is Markdown flattened onto one line (\"2. Assistant: ### Claim …\"): a heading\n // marker mid-line is only a heading again at a line start, so give it one first.\n { snapshotId: \"label\", sourceId: \"label\", sourceRevision: \"label\", revision: 0, payload: { kind: \"markdown\", text: label.replace(/\\s+(#{1,6}\\s)/g, \"\\n$1\") }, omissions: [], manuallyEdited: false, provenance: [] },\n controller.signal,\n );\n return artifact.plainText.replace(/\\s+/g, \" \").trim() || label;\n }),\n ).then((result) => { if (!controller.signal.aborted) setProjected({ key, labels: result }); }).catch(() => undefined);\n return () => controller.abort();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [engine, key]);\n return projected?.key === key ? projected.labels : labels;\n}\n\n/** A segmented control: one pressed button per choice (PP-03 preset buttons, PP-05 levels). */\nfunction Segmented<T extends string | number>({ label, value, choices, onChange }: { label: string; value: T; choices: readonly { value: T; label: string; title?: string }[]; onChange: (value: T) => void }) {\n return (\n <div className=\"matrx-alchemy-prep-segmented\" role=\"group\" aria-label={label}>\n {choices.map((choice) => (\n <button key={String(choice.value)} type=\"button\" aria-pressed={choice.value === value} title={choice.title} onClick={() => onChange(choice.value)}>{choice.label}</button>\n ))}\n </div>\n );\n}\n\n/** One host lever, drawn as the rich control its kind deserves (PP-03). */\nfunction LeverControl({ option, value, onChange }: { option: AlchemySourceOption; value: boolean | number; onChange: (value: boolean | number) => void }) {\n const hint = \"hint\" in option && option.hint ? <small className=\"matrx-alchemy-prep-hint\">{option.hint}</small> : null;\n if (option.kind === \"toggle\") {\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <button type=\"button\" role=\"switch\" aria-checked={Boolean(value)} className=\"matrx-alchemy-prep-switch\" onClick={() => onChange(!value)}>\n <span className=\"matrx-alchemy-prep-switch-track\" aria-hidden=\"true\"><span /></span>\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n </button>\n {hint}\n </div>\n );\n }\n if (option.kind === \"preset\") {\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n <Segmented label={option.label} value={Number(value)} choices={option.options.map((choice) => ({ value: choice.value, label: choice.label }))} onChange={onChange} />\n </div>\n );\n }\n if (option.kind === \"slider\") {\n const index = Math.max(0, option.stops.indexOf(Number(value)));\n return (\n <label className=\"matrx-alchemy-prep-lever\">\n <span className=\"matrx-alchemy-prep-lever-row\"><span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span><output className=\"matrx-alchemy-prep-value\">{option.formatValue(Number(value))}</output></span>\n <input type=\"range\" aria-label={option.label} min={0} max={Math.max(0, option.stops.length - 1)} step={1} value={index} aria-valuetext={option.formatValue(Number(value))} onChange={(event) => onChange(option.stops[Number(event.target.value)]!)} />\n {hint}\n </label>\n );\n }\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <label className=\"matrx-alchemy-prep-lever-row\">\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n <input type=\"number\" aria-label={option.label} min={option.min} step={option.step} value={Number(value)} onChange={(event) => { if (!Number.isNaN(event.target.valueAsNumber)) onChange(event.target.valueAsNumber); }} />\n </label>\n {option.presets?.length ? <Segmented label={`${option.label} presets`} value={Number(value)} choices={option.presets.map((preset) => ({ value: preset.value, label: preset.label }))} onChange={onChange} /> : null}\n {hint}\n </div>\n );\n}\n\nconst LEVEL_NAMES: Record<SectionLevel, string> = { full: \"Full\", compact: \"Compact\", brief: \"Brief\", off: \"Off\" };\n\nfunction GroomerSection({ section, level, size, whole, onChange }: { section: AlchemyGroomerSection; level: SectionLevel; size: number; whole: number; onChange: (level: SectionLevel) => void }) {\n const levels: SectionLevel[] = section.cuttable ? [\"full\", \"compact\", \"brief\", \"off\"] : [\"full\", \"compact\", \"brief\"];\n return (\n <div className=\"matrx-alchemy-prep-node\" data-level={level}>\n <div className=\"matrx-alchemy-prep-node-head\">\n <span className=\"matrx-alchemy-prep-node-title\">{section.title}{section.cuttable ? <span className=\"matrx-alchemy-prep-cut\" title=\"Safe to cut\">✂</span> : null}</span>\n <SizeNote chars={size} whole={whole} />\n </div>\n {section.description ? <small className=\"matrx-alchemy-prep-hint\">{section.description}</small> : null}\n <Segmented label={`${section.title} detail`} value={level} choices={levels.map((value) => ({ value, label: LEVEL_NAMES[value], ...(value !== \"off\" && section.levelLabels?.[value] ? { title: section.levelLabels[value] } : {}) }))} onChange={onChange} />\n {level !== \"off\" && section.levelLabels?.[level] ? <small className=\"matrx-alchemy-prep-hint\">{section.levelLabels[level]}</small> : null}\n </div>\n );\n}\n\nexport interface PreparationWorkspaceProps {\n restoreFocus: () => void;\n open: boolean;\n frame: Frame;\n /** Host frame only: the node the host's window gave this session. */\n windowNode?: HTMLElement | null;\n state: WorkspaceState;\n scopes: TransferScope[];\n scopeLabels?: Partial<Record<TransferScope, string>> | undefined;\n onClose: () => void;\n onChange: (next: WorkspaceState) => void;\n transport: Transport;\n ai?: AiPreparation;\n adapters: FormatAdapter[];\n actions: PageAction[];\n onOutcome: (outcome: TransferOutcome) => void;\n captureScope: (scope: TransferScope, signal: AbortSignal) => Promise<CaptureResult>;\n /** Bumped by \"Copy with prompt…\": the AI envelope turns on and the instructions box takes focus. */\n promptFocus?: number;\n}\n\nexport function PreparationWorkspace({ restoreFocus, open, frame, windowNode, state, scopes, scopeLabels, onClose, onChange, transport, ai, adapters, actions, onOutcome, captureScope, promptFocus = 0 }: PreparationWorkspaceProps) {\n const fence = useFence();\n const latest = React.useRef(state); latest.current = state;\n const aiSession = React.useRef<AiPreparation | undefined>(undefined);\n if (!aiSession.current && ai) aiSession.current = ai.fork?.() ?? ai;\n const [controls, setControls] = React.useState(() => initialControls(state));\n const [controlsHistory, setControlsHistory] = React.useState<Controls[]>([]);\n const [pending, setPending] = React.useState<Pending | null>(null);\n const requestedFormat = state.preferences.initialFormat;\n // The payload's own format first (JSON for JSON, the sheet for rows, Markdown for Markdown), then palette order.\n const firstOffered = () => {\n const kind = state.draft.payload.kind;\n const natural: (typeof COPIES)[number] = kind === \"json\" || kind === \"registered\" ? \"json\" : kind === \"rows\" ? \"tsv\" : kind === \"markdown\" ? \"markdown\" : \"plain\";\n return [natural, ...COPIES].find((f) => offersFormat(f, state.draft.payload, adapters)) ?? \"plain\";\n };\n const [format, setFormat] = React.useState<string>(() => isBuiltInFormat(requestedFormat) ? (offersFormat(requestedFormat, state.draft.payload, adapters) ? requestedFormat : firstOffered()) : adapters.some((adapter) => adapter.id === requestedFormat && adapter.supports(state.draft.payload)) ? requestedFormat : firstOffered());\n const [envelopeOn, setEnvelopeOn] = React.useState(state.preferences.initialEnvelope !== \"text\");\n const [instructions, setInstructions] = React.useState(\"\");\n const instructionsRef = React.useRef<HTMLTextAreaElement>(null);\n const [sealedInstructions, setSealedInstructions] = React.useState(\"\");\n const [formatArtifact, setFormatArtifact] = React.useState<Artifact | null>(null);\n const [formatError, setFormatError] = React.useState<string | null>(null);\n const [editing, setEditing] = React.useState(false);\n const [buffer, setBuffer] = React.useState(\"\");\n const [bufferError, setBufferError] = React.useState<string | null>(null);\n const [aiInstruction, setAiInstruction] = React.useState(\"\");\n const [busy, setBusy] = React.useState<\"ai\" | \"capture\" | \"copy\" | \"download\" | \"action\" | null>(null);\n const [aiFailed, setAiFailed] = React.useState(false);\n const [biggestFirst, setBiggestFirst] = React.useState(false);\n // The node whose span the preview highlights (PP-06b–d), the data search (PP-08), the JSON\n // tree's open nodes, and \"Show what was removed\" (PP-07).\n const [focus, setFocus] = React.useState<{ kind: \"json\" | \"section\" | \"row\" | \"column\"; id: string; key: string } | null>(null);\n const [treeQuery, setTreeQuery] = React.useState(\"\");\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set([\"\"]));\n const [showRemoved, setShowRemoved] = React.useState(false);\n const [removedView, setRemovedView] = React.useState<{ text: string; marks: Mark[]; summary: string } | { error: string } | null>(null);\n const [panes, setPanes] = React.useState(() => readStored(PANE_KEY, DEFAULT_PANES, isPanes));\n const [tab, setTab] = React.useState<Tab>(() => readStored(TAB_KEY, \"preview\" as Tab, isTab));\n React.useEffect(() => {\n if (!promptFocus || !open) return;\n setEnvelopeOn(true);\n setTab(\"settings\");\n const timer = setTimeout(() => instructionsRef.current?.focus(), 50);\n return () => clearTimeout(timer);\n }, [promptFocus, open]);\n const root = React.useRef<HTMLDivElement>(null);\n const narrow = useNarrow(root);\n React.useEffect(() => { setAiFailed(false); }, [state.snapshot.id, state.draft.revision]);\n const handingOff = React.useRef(false);\n React.useEffect(() => { if (open) handingOff.current = false; }, [open]);\n const activeAi = React.useRef<AbortController | null>(null);\n const activeCapture = React.useRef<AbortController | null>(null);\n\n // Instructions are sealed a beat after typing stops, so each keystroke never reseals a megabyte.\n React.useEffect(() => {\n const timer = setTimeout(() => setSealedInstructions(instructions), 200);\n return () => clearTimeout(timer);\n }, [instructions]);\n\n // Build the chosen format's bytes. Toggling the envelope or typing instructions never rebuilds them.\n React.useEffect(() => {\n if (state.buildError) { setFormatArtifact(null); setFormatError(null); return; }\n if (bufferError) return;\n const adapter = adapters.find((candidate) => candidate.id === format);\n const controller = new AbortController();\n const snapshotId = state.snapshot.id; const revision = state.draft.revision;\n setFormatError(null);\n const artifactPromise = isBuiltInFormat(format) ? buildFormat(state.draft, format, state.snapshot.label, adapters, controller.signal) : adapter ? buildWithAdapter(adapter, state.draft, controller.signal) : buildArtifact(state.draft, \"plain\", state.snapshot.label);\n void artifactPromise.then((artifact) => {\n if (!controller.signal.aborted && artifact.snapshotId === snapshotId && artifact.draftRevision === revision) setFormatArtifact(artifact);\n }).catch((error) => { if (!controller.signal.aborted) setFormatError(errorMessage(error, \"Format preview failed\")); });\n return () => controller.abort();\n }, [adapters, bufferError, format, state.buildError, state.draft, state.snapshot.id, state.snapshot.label]);\n // The ONE artifact: the format's bytes, or (For AI) those bytes sealed in the envelope with the\n // instructions first. The preview shows exactly `shown`; Copy and Download deliver exactly `shown`.\n const sealed = React.useMemo((): { artifact: Artifact | null; error: string | null } => {\n if (state.buildError || !formatArtifact || formatArtifact.snapshotId !== state.snapshot.id || formatArtifact.draftRevision !== state.draft.revision) return { artifact: null, error: null };\n const dataFormat = envelopeDataFormat(format, formatArtifact);\n if (!envelopeOn || !dataFormat) return { artifact: formatArtifact, error: null };\n try {\n return { artifact: sealForAi(formatArtifact, dataFormat, state.envelope ?? defaultEnvelope(state.snapshot), sealedInstructions, state.snapshot.label), error: null };\n } catch (cause) {\n return { artifact: null, error: errorMessage(cause, \"The AI envelope could not be sealed.\") };\n }\n }, [envelopeOn, format, formatArtifact, sealedInstructions, state.buildError, state.draft.revision, state.envelope, state.snapshot]);\n const shown = sealed.artifact;\n\n const close = React.useCallback(() => { activeAi.current?.abort(); activeCapture.current?.abort(); activeAi.current = null; activeCapture.current = null; fence.abortAll(); setBusy(null); onClose(); }, [fence, onClose]);\n\n // ── Levers (PP-02): the host builder is the capture; a lever change rebuilds from it. ──\n const applyLevers = (values: LeverValues, base: WorkspaceState = latest.current, withControls: Controls = controls) => {\n const levers = base.levers;\n if (!levers) return;\n try {\n const built = levers.build(values);\n const snapshot = leverSnapshot(built.payload, base.snapshot.sourceId, base.snapshot.label);\n const original = createDraft(snapshot);\n const next: WorkspaceState = { ...base, snapshot, original, draft: original, leverValues: values, leverMeta: built.meta, leverSizes: built.sectionSizes, envelope: built.envelope, buildError: undefined, error: undefined };\n onChange({ ...next, draft: rebuild(next, withControls) });\n } catch (cause) {\n onChange({ ...base, leverValues: values, buildError: errorMessage(cause, \"This source could not be prepared with these options.\") });\n }\n };\n const changeLevers = (values: LeverValues) => {\n if (state.draft.manuallyEdited) { setPending({ kind: \"levers\", values }); return; }\n React.startTransition(() => applyLevers(values));\n };\n const leverTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n React.useEffect(() => () => { if (leverTimer.current) clearTimeout(leverTimer.current); }, []);\n const [typedLevers, setTypedLevers] = React.useState<LeverValues | null>(null);\n const leverValues = typedLevers ?? state.leverValues ?? state.levers?.initial ?? {};\n const setLever = (key: string, value: boolean | number | string, debounce = false) => {\n const next = { ...leverValues, [key]: value };\n if (!debounce) { setTypedLevers(null); changeLevers(next); return; }\n setTypedLevers(next);\n if (leverTimer.current) clearTimeout(leverTimer.current);\n leverTimer.current = setTimeout(() => { setTypedLevers(null); changeLevers(next); }, 150);\n };\n\n const changeControls = (next: Controls) => {\n if (state.draft.manuallyEdited) { setPending({ kind: \"controls\", controls: next }); return; }\n setControlsHistory((history) => [...history, controls]); setControls(next);\n React.startTransition(() => onChange({ ...latest.current, draft: rebuild(latest.current, next), error: undefined }));\n };\n const applyPending = () => {\n if (!pending) return;\n setBufferError(null); setEditing(false);\n if (pending.kind === \"controls\") {\n setControlsHistory((history) => [...history, controls]); setControls(pending.controls);\n onChange({ ...state, draft: rebuild(state, pending.controls), error: undefined });\n } else applyLevers(pending.values, state);\n setPending(null);\n };\n const rebuildFromSource = () => {\n setBufferError(null); setEditing(false); setPending(null);\n if (state.levers) applyLevers(state.leverValues ?? state.levers.initial, state);\n else onChange({ ...state, draft: rebuild(state, controls), error: undefined });\n };\n\n const startEditing = () => { setBuffer(formatArtifact?.plainText ?? \"\"); setEditing(true); };\n const editBuffer = (text: string) => {\n setBuffer(text);\n setFormatError(null);\n const payload = state.draft.payload;\n if (payload.kind === \"json\" || payload.kind === \"registered\") {\n try {\n const value = JSON.parse(text) as Json;\n const next: Payload = payload.kind === \"json\" ? { kind: \"json\", value } : { kind: \"registered\", format: payload.format, value };\n setBufferError(null); onChange({ ...state, draft: editDraft(state.draft, next), error: undefined });\n } catch { setBufferError(\"JSON is incomplete or invalid. Fix it before copying or downloading.\"); }\n return;\n }\n setBufferError(null);\n const kind = payload.kind === \"markdown\" || format === \"markdown\" ? \"markdown\" : \"text\";\n if (payload.kind === \"rows\" || !isBuiltInFormat(format)) setFormat(\"plain\");\n onChange({ ...state, draft: editDraft(state.draft, { kind, text }), error: undefined });\n };\n\n const requestCapture = async (scope: TransferScope) => {\n activeCapture.current?.abort();\n const { controller, id } = fence.begin(); activeCapture.current = controller; const revision = state.draft.revision; setBusy(\"capture\");\n try {\n const result = await captureScope(scope, controller.signal);\n if (fence.valid(id, controller) && latest.current.draft.revision === revision) onChange({ ...latest.current, pending: { ...result, scope }, sourceStale: false, error: result.collectionError });\n } catch (error) { if (fence.valid(id, controller)) onChange({ ...latest.current, error: errorMessage(error, \"Refresh failed\") }); }\n finally { fence.finish(controller); if (activeCapture.current === controller) activeCapture.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const resolveCapture = (choice: \"keep\" | \"regenerate\") => {\n if (!state.pending) return;\n if (choice === \"keep\") { const { pending: _pending, ...kept } = state; onChange({ ...kept, error: undefined }); return; }\n const fresh = state.pending;\n const preferences = resolveTransferPreferences({}, state.preferences, fresh.snapshot.limits);\n const base: WorkspaceState = { ...fresh, key: state.key, original: createDraft(fresh.snapshot), draft: createDraft(fresh.snapshot), scope: fresh.scope, preferences, ...(fresh.collectionError ? { error: fresh.collectionError } : {}), ...(state.envelope ? { envelope: state.envelope } : {}) };\n const nextControls = initialControls(base); setControls(nextControls); setControlsHistory([]); setPending(null); setBufferError(null); setEditing(false);\n onChange({ ...base, draft: rebuild(base, nextControls) });\n };\n\n const runAi = async (recover = false) => {\n const adapter = aiSession.current;\n if (!adapter || !adapter.supports(state.snapshot) || (!recover && !aiInstruction.trim()) || (recover && !adapter.recover)) return;\n activeAi.current?.abort();\n const { controller, id } = fence.begin(); activeAi.current = controller;\n const snapshotId = state.snapshot.id; const revision = state.draft.revision; setBusy(\"ai\"); setAiFailed(false);\n try {\n const next = recover ? await adapter.recover!({ snapshot: state.snapshot, draft: state.draft, signal: controller.signal }) : await adapter.run({ snapshot: state.snapshot, draft: state.draft, instruction: aiInstruction, signal: controller.signal });\n const current = latest.current;\n if (!fence.valid(id, controller) || current.snapshot.id !== snapshotId || current.draft.revision !== revision || next.snapshotId !== snapshotId || next.sourceId !== state.draft.sourceId || next.sourceRevision !== state.draft.sourceRevision || next.revision <= revision) return;\n try { serialize(next, \"plain\"); } catch { onChange({ ...current, error: \"AI returned an invalid transfer draft.\" }); setAiFailed(true); return; }\n onChange({ ...current, draft: next, error: undefined }); setBufferError(null);\n } catch (error) {\n if (!isAbort(error) && fence.valid(id, controller)) { setAiFailed(true); onChange({ ...latest.current, error: errorMessage(error, \"AI preparation failed\") }); }\n } finally { fence.finish(controller); if (activeAi.current === controller) activeAi.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const cancelAi = async () => {\n const aiController = activeAi.current;\n const { controller, id } = fence.begin();\n try { await aiSession.current?.cancel?.(); }\n catch (error) { if (fence.valid(id, controller)) onChange({ ...latest.current, error: errorMessage(error, \"AI cancellation failed\") }); }\n finally { aiController?.abort(); fence.finish(controller); if (activeAi.current === aiController) activeAi.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const [deliveryNotice, setDeliveryNotice] = React.useState<string | null>(null);\n React.useEffect(() => { setDeliveryNotice(null); }, [state.draft.revision]);\n const reportDelivery = (outcome: TransferOutcome) => { setDeliveryNotice(outcomeMessage(outcome)); onOutcome(outcome); };\n const deliver = async (download: boolean) => {\n if (bufferError) return;\n const { controller, id } = fence.begin(); const snapshotId = state.snapshot.id; const revision = state.draft.revision; setBusy(download ? \"download\" : \"copy\");\n try {\n if (!shown) throw new Error(\"Wait for the preview before delivery.\");\n const artifact = shown;\n const current = latest.current;\n if (!fence.valid(id, controller) || current.snapshot.id !== snapshotId || current.draft.revision !== revision || artifact.snapshotId !== snapshotId || artifact.draftRevision !== revision) return;\n const result = await transport[download ? \"download\" : \"copy\"](artifact, controller.signal);\n if (fence.valid(id, controller)) reportDelivery(result);\n } catch (error) { if (fence.valid(id, controller)) reportDelivery({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Preparation failed\"), retryable: true }); }\n finally { fence.finish(controller); if (fence.valid(id, controller)) setBusy(null); }\n };\n const deliverAction = async (action: PageAction) => {\n if (busy || bufferError || formatError || !shown) return;\n const { controller, id } = fence.begin();\n const current = latest.current;\n setBusy(\"action\");\n try {\n if (!action.supports(current.snapshot, current.draft)) throw new Error(`${action.label} is unavailable for this prepared content.`);\n // Release the preparation focus trap before a host opens its destination.\n handingOff.current = true;\n flushSync(() => onClose());\n const result = await action.run({ snapshot: current.snapshot, draft: current.draft, signal: controller.signal });\n if (fence.valid(id, controller)) reportDelivery(result);\n } catch (error) {\n if (fence.valid(id, controller)) reportDelivery({ status: \"error\", code: \"destination-failed\", message: errorMessage(error, \"Could not deliver prepared content\"), retryable: false });\n } finally { fence.finish(controller); if (fence.valid(id, controller)) setBusy(null); }\n };\n const eligibleActions = state.buildError ? [] : actions.filter((action) => action.supports(state.snapshot, state.draft));\n\n // ── Derived view ──\n const rows = state.original.payload.kind === \"rows\" ? state.original.payload : null;\n const formats = COPIES.filter((f) => offersFormat(f, state.draft.payload, adapters));\n const workspaceAdapters = adapters.filter((adapter) => !isBuiltInFormat(adapter.id) && adapter.supports(state.draft.payload));\n const displayedOmissions = shown?.omissions ?? state.draft.omissions;\n const shownText = shown?.plainText ?? \"\";\n const chars = shownText.length;\n const bytes = React.useMemo(() => new TextEncoder().encode(shownText).length, [shownText]);\n const envelopeOffered = formatArtifact ? envelopeDataFormat(format, formatArtifact) !== null : format !== \"html\" && format !== \"xlsx\";\n const snapshotSections = state.snapshot.sections;\n const sectionLabels = useProjectedLabels(snapshotSections.map((section) => section.label), adapters);\n const sectionRows = snapshotSections.map((section, index) => ({ section, label: sectionLabels[index] ?? section.label, size: sectionSize(state.original.payload, section.path) }));\n const sectionWhole = sectionRows.reduce((sum, row) => sum + (row.size ?? 0), 0);\n const orderedSections = biggestFirst ? [...sectionRows].sort((a, b) => (b.size ?? 0) - (a.size ?? 0)) : sectionRows;\n const groomer = state.levers?.sections ?? null;\n const groomerWhole = Object.values(state.leverSizes ?? {}).reduce((sum, size) => sum + size, 0);\n const orderedGroomer = groomer ? (biggestFirst ? [...groomer].sort((a, b) => (state.leverSizes?.[b.id] ?? 0) - (state.leverSizes?.[a.id] ?? 0)) : groomer) : null;\n const activePreset = groomer ? activeGroomerPreset(leverValues, groomer) : null;\n const options = state.levers?.options ?? null;\n const jsonRoot = !groomer && (state.original.payload.kind === \"json\" || state.original.payload.kind === \"registered\") ? state.original.payload.value : undefined;\n const hasStructure = Boolean(rows || snapshotSections.length || groomer || jsonRoot !== undefined);\n const editHeld = state.draft.manuallyEdited;\n const meta = Object.entries(state.leverMeta ?? {}).filter(([, value]) => value !== undefined && value !== \"\");\n const title = `Prepare ${state.snapshot.label}`;\n const copyVisible = !state.buildError && !formatError && !bufferError && !sealed.error && !showRemoved;\n\n // ── Spans, highlight and search (PP-06a–d, PP-08) ──\n const spans = React.useMemo(() => (shown && formatArtifact && formatArtifact.snapshotId === state.snapshot.id && formatArtifact.draftRevision === state.draft.revision ? shownSpans(state.draft, formatArtifact, shown) : null), [formatArtifact, shown, state.draft, state.snapshot.id]);\n // A host engine that rewrites the text (Markdown → plain) moves every section: find each one by\n // projecting it alone through the same engine (PP-06d), for this draft and this format.\n const [projectedSections, setProjectedSections] = React.useState<{ artifact: Artifact; ranges: Record<string, { start: number; end: number }> } | null>(null);\n React.useEffect(() => {\n const engine = hostEngineFor(adapters, format);\n const layout = draftLayout(state.draft);\n const payload = state.draft.payload;\n if (!engine || !formatArtifact || !layout.sectionRanges || (payload.kind !== \"text\" && payload.kind !== \"markdown\") || formatArtifact.draftRevision !== state.draft.revision) { setProjectedSections(null); return; }\n const controller = new AbortController();\n const pieces = Object.entries(layout.sectionRanges).sort((a, b) => a[1].start - b[1].start).map(([id, range]) => ({ id, text: payload.text.slice(range.start, range.end) }));\n void locateProjectedSections(formatArtifact.plainText, pieces, engine, controller.signal)\n .then((ranges) => { if (!controller.signal.aborted) setProjectedSections({ artifact: formatArtifact, ranges }); })\n .catch(() => { if (!controller.signal.aborted) setProjectedSections(null); });\n return () => controller.abort();\n }, [adapters, format, formatArtifact, state.draft]);\n const focusResult = React.useMemo((): { marks: Mark[]; note: string | null } => {\n if (!focus || !shown) return { marks: [], note: null };\n if (!spans) return { marks: [], note: \"This format has no highlight map. Choose JSON, Markdown, CSV, Google Sheets or plain text to see where it lands.\" };\n const byPath = new Map(spans.map((span) => [span.path, span]));\n let found: { start: number; end: number }[] = [];\n if (focus.kind === \"json\" && jsonRoot !== undefined) {\n const pointers = focus.id.includes(\"*\") ? concretePointers(jsonRoot, focus.id).slice(0, 500) : [focus.id];\n found = pointers.map((pointer) => outputPointer(jsonRoot, controls.structure, pointer)).flatMap((pointer) => (pointer === null ? [] : [byPath.get(pointer)].filter((span): span is NonNullable<typeof span> => Boolean(span))));\n } else if (focus.kind === \"section\") {\n const section = snapshotSections.find((candidate) => candidate.id === focus.id);\n let span = section ? sectionSpan(state.draft, spans, shownText, section.id) ?? byPath.get(section.path) : undefined;\n const projected = section && projectedSections?.artifact === formatArtifact ? projectedSections.ranges[section.id] : undefined;\n const whole = byPath.get(\"\");\n if (!span && projected && whole) span = { path: `/sections/${section!.id}`, start: whole.start + projected.start, end: whole.start + projected.end };\n if (span) found = [span];\n } else if (focus.kind === \"row\") {\n const position = draftLayout(state.draft).rowOrder?.indexOf(Number(focus.id)) ?? -1;\n const span = position >= 0 ? byPath.get(`/rows/${position}`) : undefined;\n if (span) found = [span];\n } else {\n const span = byPath.get(`/columns/${encodePointer(focus.id)}`);\n if (span) found = [span];\n }\n if (!found.length) {\n const included = focus.kind === \"section\" ? controls.sections.includes(focus.id) : focus.kind === \"row\" ? !controls.excludedRows.includes(Number(focus.id)) : true;\n return { marks: [], note: included && focus.kind === \"section\" ? \"This format rewrites the text, so this section's place cannot be pointed at yet. Choose Markdown to see exactly where it lands.\" : \"Not in the output: it is left out, or a limit trimmed it.\" };\n }\n return { marks: found.map((span) => ({ start: span.start, end: span.end, kind: \"focus\" as const })), note: null };\n }, [controls.excludedRows, controls.sections, controls.structure, focus, formatArtifact, jsonRoot, projectedSections, shown, shownText, snapshotSections, spans, state.draft]);\n const searchQuery = rows ? controls.search : treeQuery;\n const matches = React.useMemo(() => findMatches(shownText, searchQuery, rows ? controls.searchMode : \"contains\"), [controls.searchMode, rows, searchQuery, shownText]);\n const previewMarks = React.useMemo(() => [...focusResult.marks, ...matches.marks], [focusResult.marks, matches.marks]);\n\n const copyText = (text: string, what: string) => {\n const artifact = sealTransferArtifact({ snapshotId: state.draft.snapshotId, draftRevision: state.draft.revision, format: \"plain\", plainText: text, omissions: [] });\n void transport.copy(artifact, new AbortController().signal)\n .then((outcome) => { setDeliveryNotice(outcome.status === \"success\" ? `${what} copied` : outcomeMessage(outcome)); onOutcome(outcome); })\n .catch((error: unknown) => setDeliveryNotice(errorMessage(error, `${what} could not be copied`)));\n };\n\n // ── \"Show what was removed\" (PP-07): Full in this format, removals marked through its span map ──\n React.useEffect(() => {\n if (!showRemoved) { setRemovedView(null); return; }\n if (!isBuiltInFormat(format) || format === \"xlsx\" || format === \"html\") { setRemovedView({ error: \"Choose JSON, Markdown, CSV, Google Sheets or plain text to see what was removed.\" }); return; }\n const controller = new AbortController();\n const full = resetDraft(state.snapshot);\n void buildFormat(full, format, state.snapshot.label, adapters, controller.signal).then(async (artifact) => {\n if (controller.signal.aborted) return;\n const engine = hostEngineFor(adapters, format);\n const payload = full.payload;\n const prose = (payload.kind === \"text\" || payload.kind === \"markdown\") && snapshotSections.length > 0 && snapshotSections.every((section) => /^\\/text\\/\\d+-\\d+$/.test(section.path));\n const projected = engine && prose\n ? await locateProjectedSections(artifact.plainText, snapshotSections.map((section) => { const [, a, b] = /^\\/text\\/(\\d+)-(\\d+)$/.exec(section.path)!; return { id: section.id, text: payload.text.slice(Number(a), Number(b)) }; }), engine, controller.signal)\n : undefined;\n if (controller.signal.aborted) return;\n const result = removedMarks(state, controls, full, artifact, projected);\n setRemovedView(result\n ? { text: artifact.plainText, marks: result.marks, summary: `${formatCount(result.removed)} removed · ${formatCount(result.changed)} shortened · ${formatCount(result.chars)} chars left out` }\n : { error: \"This format has no span map, so its removals cannot be pointed at.\" });\n }).catch((error: unknown) => { if (!controller.signal.aborted) setRemovedView({ error: errorMessage(error, \"Full could not be built in this format.\") }); });\n return () => controller.abort();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [adapters, controls, format, showRemoved, state.draft, state.snapshot]);\n\n // ── The JSON tree (PP-06b) ──\n const jsonItems = React.useMemo(() => (jsonRoot === undefined ? [] : treeQuery.trim() ? jsonSearchItems(jsonRoot, controls.structure, treeQuery) : jsonTreeItems(jsonRoot, controls.structure, expanded)), [controls.structure, expanded, jsonRoot, treeQuery]);\n const jsonWhole = jsonItems.find((item) => item.key === \"#root\")?.chars ?? jsonItems.reduce((max, item) => Math.max(max, item.chars ?? 0), 0);\n const setStructure = (structure: Controls[\"structure\"]) => changeControls({ ...controls, structure });\n const jsonHandlers: TreeHandlers = {\n toggle: (item) => setStructure(toggleNode(controls.structure, itemPattern(item))),\n includeAgain: (item) => {\n const pattern = itemPattern(item);\n const cover = controls.structure.exclude.find((candidate) => candidate !== pattern && patternCovers(candidate, pattern));\n if (cover !== undefined) setStructure({ ...controls.structure, exclude: controls.structure.exclude.filter((candidate) => candidate !== cover) });\n },\n expand: (item) => setExpanded((current) => { const next = new Set(current); const pattern = itemPattern(item); if (next.has(pattern)) next.delete(pattern); else next.add(pattern); return next; }),\n focus: (item) => setFocus({ kind: \"json\", id: itemPattern(item), key: item.key }),\n limit: (item, value) => {\n const pattern = itemPattern(item);\n const limits: Record<string, NodeLimit> = { ...controls.structure.limits };\n const limit = decodeLimit(value);\n if (limit) limits[pattern] = limit; else delete limits[pattern];\n setStructure({ ...controls.structure, limits });\n },\n copyPath: (path) => copyText(path, \"Path\"),\n };\n\n // ── The sections tree (PP-06d) ──\n const sectionText = (path: string) => { const m = /^\\/text\\/(\\d+)-(\\d+)$/.exec(path); const payload = state.original.payload; return m && (payload.kind === \"text\" || payload.kind === \"markdown\") ? payload.text.slice(Number(m[1]), Number(m[2])) : \"\"; };\n const sectionQuery = treeQuery.trim().toLocaleLowerCase();\n const sectionItems: TreeItem[] = orderedSections\n .filter(({ section, label }) => !sectionQuery || label.toLocaleLowerCase().includes(sectionQuery) || sectionText(section.path).toLocaleLowerCase().includes(sectionQuery))\n .map(({ section, label, size }) => ({ key: `section:${section.id}`, depth: 0, label, chars: size, state: controls.sections.includes(section.id) ? \"on\" : \"off\", limitChoices: TEXT_LIMITS, limit: encodeLimit(controls.sectionLimits[section.id]) }));\n const sectionId = (item: TreeItem) => item.key.slice(\"section:\".length);\n const sectionHandlers: TreeHandlers = {\n toggle: (item) => { const id = sectionId(item); changeControls({ ...controls, sections: controls.sections.includes(id) ? controls.sections.filter((value) => value !== id) : [...controls.sections, id] }); },\n focus: (item) => setFocus({ kind: \"section\", id: sectionId(item), key: item.key }),\n limit: (item, value) => { const id = sectionId(item); const limits = { ...controls.sectionLimits }; const limit = decodeLimit(value); if (limit) limits[id] = limit; else delete limits[id]; changeControls({ ...controls, sectionLimits: limits }); },\n };\n\n // ── Panes (PP-01b): draggable dividers, widths remembered per viewer (storage may be blocked). ──\n const drag = React.useRef<{ side: \"left\" | \"right\"; startX: number; start: number } | null>(null);\n const clampPane = (width: number) => {\n const total = root.current?.getBoundingClientRect().width || 1600;\n return Math.round(Math.min(Math.max(width, MIN_PANE), Math.max(MIN_PANE, total * 0.45)));\n };\n const setPane = (side: \"left\" | \"right\", width: number, persist: boolean) => {\n setPanes((current) => {\n const next = { ...current, [side]: clampPane(width) };\n if (persist) writeStored(PANE_KEY, next);\n return next;\n });\n };\n const divider = (side: \"left\" | \"right\") => (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label={side === \"left\" ? \"Resize structure pane\" : \"Resize settings pane\"}\n aria-valuenow={panes[side]}\n aria-valuemin={MIN_PANE}\n tabIndex={0}\n className=\"matrx-alchemy-prep-divider\"\n onPointerDown={(event) => { drag.current = { side, startX: event.clientX, start: panes[side] }; event.currentTarget.setPointerCapture?.(event.pointerId); }}\n onPointerMove={(event) => { const d = drag.current; if (!d || d.side !== side) return; const delta = event.clientX - d.startX; setPane(side, side === \"left\" ? d.start + delta : d.start - delta, false); }}\n onPointerUp={(event) => { if (!drag.current) return; drag.current = null; event.currentTarget.releasePointerCapture?.(event.pointerId); setPanes((current) => { writeStored(PANE_KEY, current); return current; }); }}\n onKeyDown={(event) => {\n const step = event.shiftKey ? 64 : 16;\n if (event.key === \"ArrowLeft\") { event.preventDefault(); setPane(side, panes[side] + (side === \"left\" ? -step : step), true); }\n if (event.key === \"ArrowRight\") { event.preventDefault(); setPane(side, panes[side] + (side === \"left\" ? step : -step), true); }\n }}\n />\n );\n const chooseTab = (next: Tab) => { setTab(next); writeStored(TAB_KEY, next); };\n\n // ── Regions ──\n const topBar = (\n <div className=\"matrx-alchemy-prep-top\">\n {scopes.length > 1 ? <label className=\"matrx-alchemy-prep-field\">Scope<select aria-label=\"Transfer scope\" value={state.scope} disabled={busy !== null} onChange={(e) => void requestCapture(e.target.value as TransferScope)}>{scopes.map((scope) => <option key={scope} value={scope}>{scopeLabels?.[scope] ?? SCOPE_LABEL[scope]}</option>)}</select></label> : null}\n <label className=\"matrx-alchemy-prep-field\">Detail<select aria-label=\"Detail preset\" value={controls.preset} onChange={(e) => changeControls({ ...controls, preset: e.target.value as Preset })}><option value=\"full\">Full</option><option value=\"compact\">Compact</option><option value=\"brief\">Brief</option><option value=\"custom\">Custom</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">Format<select aria-label=\"Output format\" value={format} onChange={(e) => { setFormat(e.target.value); setEditing(false); }}>{formats.map((f) => <option key={f} value={f}>{LABEL[f]}</option>)}{state.draft.payload.kind === \"rows\" ? <option value=\"xlsx\">Excel workbook</option> : null}{workspaceAdapters.map((adapter) => <option key={adapter.id} value={adapter.id}>{adapter.label}</option>)}</select></label>\n {envelopeOffered ? <Segmented label=\"Copy as\" value={envelopeOn ? \"ai\" : \"text\"} choices={[{ value: \"text\", label: \"Text\", title: \"The format's bytes alone\" }, { value: \"ai\", label: \"For AI\", title: \"Inside the AI envelope, with your instructions first\" }]} onChange={(value) => setEnvelopeOn(value === \"ai\")} /> : null}\n <span className=\"matrx-alchemy-prep-totals\" aria-live=\"polite\">{shown ? <>{formatCount(chars)} chars · {formatCount(bytes)} bytes · ≈{formatCount(Math.ceil(chars / 4))} tokens <small>(estimate)</small></> : state.buildError ? \"Nothing to copy\" : \"Preparing…\"}</span>\n {meta.length ? <span className=\"matrx-alchemy-prep-meta\">{meta.map(([key, value]) => `${key.replace(/_/g, \" \")} ${String(value)}`).join(\" · \")}</span> : null}\n </div>\n );\n\n const structure = hasStructure ? (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-structure\" aria-label=\"Structure\">\n <div className=\"matrx-alchemy-prep-pane-head\"><h3>Structure</h3>{(snapshotSections.length > 1 || (groomer?.length ?? 0) > 1) ? <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={biggestFirst} onClick={() => setBiggestFirst(!biggestFirst)}>Biggest first</button> : null}</div>\n {editHeld ? <p className=\"matrx-alchemy-prep-held\">Editing — rebuild from source to change the structure.</p> : null}\n {focusResult.note ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{focusResult.note}</p> : null}\n {groomer && orderedGroomer ? (\n <div className=\"matrx-alchemy-prep-group\">\n <div className=\"matrx-alchemy-prep-lever-row\"><span className=\"matrx-alchemy-prep-lever-label\">Sections</span><span className=\"matrx-alchemy-prep-hint\">{activePreset ? `${activePreset[0]!.toUpperCase()}${activePreset.slice(1)}` : \"Custom\"}</span></div>\n <Segmented label=\"Section preset\" value={activePreset ?? \"custom\"} choices={[{ value: \"everything\", label: \"Everything\" }, { value: \"balanced\", label: \"Balanced\" }, { value: \"minimal\", label: \"Minimal\" }, ...(activePreset ? [] : [{ value: \"custom\" as const, label: \"Custom\" }])]} onChange={(value) => { if (value === \"custom\") return; const levels = applyGroomerPreset(value, groomer); changeLevers({ ...leverValues, ...Object.fromEntries(Object.entries(levels).map(([id, level]) => [sectionLeverKey(id), level])) }); }} />\n {orderedGroomer.map((section) => <GroomerSection key={section.id} section={section} level={(leverValues[sectionLeverKey(section.id)] ?? \"full\") as SectionLevel} size={state.leverSizes?.[section.id] ?? 0} whole={groomerWhole} onChange={(level) => setLever(sectionLeverKey(section.id), level)} />)}\n </div>\n ) : null}\n {jsonRoot !== undefined ? (\n <div className=\"matrx-alchemy-prep-group\">\n <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label=\"Find in data\" placeholder=\"Find a key or value\" value={treeQuery} onChange={(e) => setTreeQuery(e.target.value)} />\n {treeQuery.trim() ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{jsonItems.length >= 500 ? \"500+\" : formatCount(jsonItems.length)} {jsonItems.length === 1 ? \"node matches\" : \"nodes match\"} · {formatCount(matches.total)} in the preview</small> : null}\n <StructureTreeList label=\"Data\" items={jsonItems} whole={jsonWhole} focusKey={focus?.key ?? null} handlers={jsonHandlers} maxHeight=\"calc(92dvh - 16rem)\" />\n </div>\n ) : null}\n {snapshotSections.length ? (\n <fieldset className=\"matrx-alchemy-prep-group\" aria-label=\"Included sections\">\n <legend className=\"matrx-alchemy-prep-legend\">{controls.sections.length.toLocaleString()} of {snapshotSections.length.toLocaleString()} {countNoun(state.snapshot.coverage.unit ?? \"section\", snapshotSections.length)} included</legend>\n {snapshotSections.length > 6 ? <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label={`Find a ${state.snapshot.coverage.unit ?? \"section\"}`} placeholder=\"Find by name or text\" value={treeQuery} onChange={(e) => setTreeQuery(e.target.value)} /> : null}\n {sectionQuery ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{formatCount(sectionItems.length)} {sectionItems.length === 1 ? \"matches\" : \"match\"} · {formatCount(matches.total)} in the preview</small> : null}\n <StructureTreeList label=\"Sections\" items={sectionItems} whole={sectionWhole} focusKey={focus?.key ?? null} handlers={sectionHandlers} maxHeight=\"calc(92dvh - 16rem)\" />\n </fieldset>\n ) : null}\n {rows ? <RowsStructure rows={rows} controls={controls} change={changeControls} draft={state.draft} focusKey={focus?.key ?? null} matchesInPreview={matches.total} onFocus={(kind, id) => setFocus({ kind, id, key: `${kind}:${id}` })} onCopyRow={(text) => copyText(text, \"Row\")} /> : null}\n </section>\n ) : null;\n\n const previewPane = (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-center\" aria-label=\"Preview\">\n <div className=\"matrx-alchemy-prep-pane-head\">\n <h3>{editing ? \"Editing\" : showRemoved ? \"Removed compared with Full\" : envelopeOn && envelopeOffered ? \"Preview — for AI\" : \"Preview\"}</h3>\n {searchQuery.trim() && shown && !showRemoved ? <span className=\"matrx-alchemy-prep-hint\" role=\"status\" aria-label=\"Matches in the preview\">{matches.total.toLocaleString()} {matches.total === 1 ? \"match\" : \"matches\"}</span> : null}\n {hasStructure && !editing && !state.buildError ? <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>{showRemoved ? \"Back to preview\" : \"Show what was removed\"}</button> : null}\n {!state.buildError && !showRemoved && (formatArtifact || editing) ? (editing\n ? <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={() => setEditing(false)}>Done</Button>\n : <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={startEditing}>Edit</Button>) : null}\n </div>\n {editHeld && !editing && !pending ? <div className=\"matrx-alchemy-prep-held\" role=\"status\"><span>Editing — rebuild from source to change the structure.</span><Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={rebuildFromSource}>Rebuild from source</Button></div> : null}\n {pending ? <div className=\"matrx-alchemy-decision\" role=\"alert\"><p>This control would replace your manual edit.</p><Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => setPending(null)}>Keep edited draft</Button><Button className=\"matrx-alchemy-workspace-primary\" type=\"button\" onClick={applyPending}>Rebuild from source</Button></div> : null}\n {state.buildError ? (\n <div className=\"matrx-alchemy-preview matrx-alchemy-prep-preview matrx-alchemy-prep-failed\" role=\"alert\" aria-label=\"Prepared output\">\n <p><strong>This source could not be prepared.</strong></p>\n <p>{state.buildError}</p>\n <p className=\"matrx-alchemy-prep-hint\">Change an option to try again; nothing was copied.</p>\n </div>\n ) : editing ? (\n <>\n {envelopeOn && envelopeOffered ? <p className=\"matrx-alchemy-prep-hint\">Copy wraps this text in the AI envelope{sealedInstructions.trim() ? \" with your instructions first\" : \"\"}.</p> : null}\n <textarea className=\"matrx-alchemy-preview matrx-alchemy-prep-editor\" aria-label=\"Edit prepared output\" aria-invalid={bufferError ? true : undefined} aria-describedby={bufferError ? \"alchemy-buffer-error\" : undefined} value={buffer} onChange={(e) => editBuffer(e.target.value)} autoFocus />\n </>\n ) : showRemoved ? (\n removedView === null ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">Building Full to compare…</p>\n : \"error\" in removedView ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{removedView.error}</p>\n : <>\n <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{removedView.summary}. Full, before your structure choices — this is not what you copy.</p>\n <PreviewText text={removedView.text} marks={removedView.marks} label=\"Removed compared with Full\" />\n </>\n ) : shown ? (\n shown.html !== undefined && !(envelopeOn && envelopeOffered) ? <PreviewHtml html={shown.html} /> : <PreviewText text={shownText} marks={previewMarks} />\n ) : formatError ? null : <p className=\"matrx-alchemy-prep-hint\" role=\"status\">Preparing preview…</p>}\n {bufferError ? <p id=\"alchemy-buffer-error\" role=\"alert\" className=\"matrx-alchemy-error\">{bufferError}</p> : null}\n {formatError ? <p role=\"alert\" className=\"matrx-alchemy-error\">{formatError}</p> : null}\n {sealed.error ? <p role=\"alert\" className=\"matrx-alchemy-error\">{sealed.error}</p> : null}\n {bufferError ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" disabled={busy !== null} onClick={() => { const fallback = editDraft(state.draft, { kind: \"text\", text: buffer }); setBufferError(null); onChange({ ...state, draft: fallback, error: undefined }); setFormat(\"plain\"); }}>Use invalid JSON as plain text</Button> : null}\n <div className=\"matrx-alchemy-coverage\">\n <span>{snapshotSections.length ? `${formatCount(controls.sections.length)} of ${formatCount(snapshotSections.length)} ${countNoun(state.snapshot.coverage.unit ?? \"section\", snapshotSections.length)} included` : `${formatCount(state.snapshot.coverage.included)} included${state.snapshot.coverage.total == null ? \"\" : ` of ${formatCount(state.snapshot.coverage.total)}`}`} · {state.snapshot.coverage.status}</span>\n {state.snapshot.coverage.reason ? <span>{state.snapshot.coverage.reason}</span> : null}\n {displayedOmissions.length ? <details><summary>{displayedOmissions.length} omissions or adjustments</summary><ul>{displayedOmissions.map((o, i) => <li key={`${o.path}-${o.reason}-${i}`}>{o.label ? `${o.label}: ${o.reason}` : `${o.path || \"/\"}: ${o.reason}`}{o.count == null ? \"\" : ` (${o.count})`}</li>)}</ul></details> : null}\n </div>\n </section>\n );\n\n const settings = (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-settings\" aria-label=\"Settings\">\n <div className=\"matrx-alchemy-prep-pane-head\"><h3>Settings</h3></div>\n {options?.length ? (\n <div className=\"matrx-alchemy-prep-group\" role=\"group\" aria-label=\"Source options\">\n <h4>Source options</h4>\n {options.map((option) => <LeverControl key={option.key} option={option} value={(leverValues[option.key] ?? option.default) as boolean | number} onChange={(value) => setLever(option.key, value, option.kind === \"number\")} />)}\n </div>\n ) : null}\n {controls.preset === \"custom\" ? <fieldset className=\"matrx-alchemy-prep-group\"><legend className=\"matrx-alchemy-prep-legend\">{state.draft.payload.kind === \"json\" || state.draft.payload.kind === \"registered\" ? \"JSON limits\" : \"Content limits\"}</legend>{([[\"maxDepth\", \"Maximum depth\"], [\"maxStringChars\", state.draft.payload.kind === \"rows\" ? \"Maximum characters per cell\" : \"Maximum string characters\"], [\"maxArrayItems\", \"Maximum array items\"]] as const).filter(([key]) => key === \"maxStringChars\" || state.draft.payload.kind === \"json\" || state.draft.payload.kind === \"registered\").map(([key, text]) => <label key={key} className=\"matrx-alchemy-prep-lever-row\"><span>{text}</span><input type=\"number\" min=\"0\" value={controls[key] ?? \"\"} onChange={(e) => changeControls({ ...controls, [key]: Number.isNaN(e.target.valueAsNumber) ? null : e.target.valueAsNumber })} /></label>)}</fieldset> : null}\n {envelopeOn && envelopeOffered ? (\n <label className=\"matrx-alchemy-prep-group\">\n <h4>Instructions for the model</h4>\n <textarea ref={instructionsRef} aria-label=\"Instructions for the model\" value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder=\"e.g. Review this conversation for tool errors\" />\n <small className=\"matrx-alchemy-prep-hint\">Sealed first in what you copy, and counted in the total.</small>\n </label>\n ) : null}\n {ai ? (\n <div className=\"matrx-alchemy-prep-group\">\n <h4>Prepare with AI</h4>\n <label className=\"matrx-alchemy-prep-field\">Start with<select aria-label=\"AI preparation recipe\" defaultValue=\"\" onChange={(event) => { if (event.target.value) setAiInstruction(event.target.value); }}><option value=\"\">Choose an instruction</option><option value=\"Summarize this content concisely. Preserve important facts, names, decisions, and source references.\">Summarize</option><option value=\"Extract decisions, action items, owners, and due dates. Mark missing details as unspecified.\">Extract action items</option><option value=\"Prepare a complete handoff for another assistant. Include the objective, relevant facts, constraints, decisions, and unresolved questions.\">Assistant handoff</option><option value=\"Condense this content by removing repetition and formatting noise. Preserve every unique fact and all identifiers.\">Condense without losing facts</option><option value=\"Turn this content into a clear structured outline. Keep the original meaning and explicitly flag uncertainty.\">Create an outline</option><option value=\"Analyze this data. Identify patterns, anomalies, and useful comparisons. Distinguish observations from inferences.\">Analyze the data</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">AI instruction<textarea value={aiInstruction} onChange={(e) => setAiInstruction(e.target.value)} placeholder=\"Tell AI how to prepare this content\" /></label>\n <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" disabled={!aiSession.current || !aiInstruction.trim() || busy !== null || !aiSession.current.supports(state.snapshot)} onClick={() => void runAi(false)}>Generate preview</Button>\n {busy === \"ai\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => void cancelAi()}>{aiSession.current?.cancel ? \"Cancel AI\" : \"Stop waiting\"}</Button> : null}\n {aiFailed && aiSession.current?.recover && busy !== \"ai\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => void runAi(true)}>Retry or rejoin AI run</Button> : null}\n <p className=\"matrx-alchemy-meta\">AI updates the preview; copy it when you are ready. Closing this window lets the AI run continue.</p>\n </div>\n ) : null}\n {!options?.length && controls.preset !== \"custom\" && !(envelopeOn && envelopeOffered) && !ai && !eligibleActions.length ? <p className=\"matrx-alchemy-prep-hint\">{envelopeOffered ? \"Choose For AI to seal instructions for the model with what you copy.\" : \"This format has no further settings.\"}</p> : null}\n {busy === \"capture\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => { activeCapture.current?.abort(); activeCapture.current = null; setBusy(null); }}>Stop loading rows</Button> : null}\n {state.error ? <p role=\"alert\" className=\"matrx-alchemy-error\">{state.error}</p> : null}\n {eligibleActions.length ? <details className=\"matrx-alchemy-prep-group matrx-alchemy-destinations\"><summary>Use prepared content · {eligibleActions.length} {eligibleActions.length === 1 ? \"destination\" : \"destinations\"}</summary><div className=\"matrx-alchemy-destination-grid\">{eligibleActions.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" disabled={busy !== null || Boolean(bufferError || formatError) || !shown} onClick={() => void deliverAction(action)}><DestinationPresentation action={action} /></button>)}</div></details> : null}\n </section>\n );\n\n const footer = (\n <div className=\"matrx-alchemy-prep-footer\">\n {state.sourceStale ? <p role=\"alert\" className=\"matrx-alchemy-decision\">The source changed since this draft. Use Refresh source to review the latest data.</p> : null}\n {state.pending ? <div className=\"matrx-alchemy-decision\" role=\"alert\"><p>A fresh source snapshot is ready.</p>{state.pending.scope !== state.scope ? <p>Switch from {scopeLabels?.[state.scope] ?? SCOPE_LABEL[state.scope]} to {scopeLabels?.[state.pending.scope] ?? SCOPE_LABEL[state.pending.scope]} by regenerating. Your current draft is retained until you choose.</p> : null}<Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => resolveCapture(\"keep\")}>Keep current snapshot and draft</Button><Button className=\"matrx-alchemy-workspace-primary\" type=\"button\" onClick={() => resolveCapture(\"regenerate\")}>Regenerate from fresh source</Button></div> : null}\n <div className=\"matrx-alchemy-prep-actions\">\n {deliveryNotice ? <p role=\"status\" className=\"matrx-alchemy-meta\">{deliveryNotice}</p> : null}\n {showRemoved ? <Button type=\"button\" size=\"sm\" className=\"matrx-alchemy-workspace-primary\" onClick={() => setShowRemoved(false)}>Back to preview to copy</Button> : null}\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={(!state.draft.history?.length && !controlsHistory.length) || busy !== null} onClick={() => { setBufferError(null); if (controlsHistory.length) { const next = controlsHistory[controlsHistory.length - 1]!; setControls(next); setControlsHistory((history) => history.slice(0, -1)); onChange({ ...state, draft: rebuild(state, next), error: undefined }); } else onChange({ ...state, draft: undoDraft(state.draft), error: undefined }); }}>Undo</Button>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={busy !== null} onClick={() => { const next = initialControls(state); setControls(next); setControlsHistory([]); setPending(null); setBufferError(null); setEditing(false); if (state.levers) applyLevers(state.levers.initial, state, next); else onChange({ ...state, draft: rebuild(state, next), error: undefined }); }}>Reset</Button>\n {state.levers ? null : <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={busy !== null} onClick={() => void requestCapture(state.scope)}>Refresh source</Button>}\n {frame === \"dialog\" ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={close}>Close</Button> : null}\n {copyVisible ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" aria-label=\"Download prepared output\" disabled={busy !== null || !shown} onClick={() => void deliver(true)}>Download</Button> : null}\n {copyVisible ? <Button type=\"button\" className=\"matrx-alchemy-workspace-primary\" aria-label=\"Copy prepared output\" disabled={busy !== null || !shown} onClick={() => void deliver(false)}>{shown ? (envelopeOn && envelopeOffered ? \"Copy for AI\" : \"Copy\") : \"Preparing…\"}</Button> : null}\n </div>\n </div>\n );\n\n const layout = narrow ? (\n <>\n <div className=\"matrx-alchemy-prep-tabs\" role=\"tablist\" aria-label=\"Workspace sections\">\n {([...(hasStructure ? [[\"structure\", \"Structure\"]] : []), [\"preview\", \"Preview\"], [\"settings\", \"Settings\"]] as [Tab, string][]).map(([id, label]) => (\n <button key={id} type=\"button\" role=\"tab\" aria-selected={(hasStructure || tab !== \"structure\" ? tab : \"preview\") === id} onClick={() => chooseTab(id)}>{label}</button>\n ))}\n </div>\n <div className=\"matrx-alchemy-prep-tabpanel\" role=\"tabpanel\">\n {(hasStructure || tab !== \"structure\" ? tab : \"preview\") === \"structure\" ? structure : tab === \"settings\" ? settings : previewPane}\n </div>\n </>\n ) : (\n <div className=\"matrx-alchemy-prep-panes\" style={{ gridTemplateColumns: hasStructure ? `${panes.left}px 8px minmax(0, 1fr) 8px ${panes.right}px` : `minmax(0, 1fr) 8px ${panes.right}px` }}>\n {structure}\n {hasStructure ? divider(\"left\") : null}\n {previewPane}\n {divider(\"right\")}\n {settings}\n </div>\n );\n\n const body = (\n <div ref={root} className={cn(\"matrx-alchemy-prep\", narrow && \"matrx-alchemy-prep-narrow\")} data-frame={frame} aria-busy={busy !== null}>\n {frame === \"host\" && state.snapshot.unsavedChanges ? <p className=\"matrx-alchemy-prep-hint\">Includes your unsaved changes.</p> : null}\n {topBar}\n {layout}\n {footer}\n </div>\n );\n\n if (frame === \"host\") return open && windowNode ? createPortal(body, windowNode) : null;\n return <Dialog open={open} onOpenChange={(next) => { if (!next) close(); }}><DialogContent onCloseAutoFocus={(event) => { event.preventDefault(); if (!handingOff.current) restoreFocus(); }} className=\"matrx-alchemy-workspace matrx-alchemy-prep-dialog\" aria-busy={busy !== null}>\n <DialogHeader><DialogTitle>{title}</DialogTitle><DialogDescription>{state.snapshot.unsavedChanges ? \"Includes your unsaved changes. \" : \"\"}Review and edit this copy. Your original stays unchanged.</DialogDescription></DialogHeader>\n {body}\n </DialogContent></Dialog>;\n}\n\n\n/**\n * The rows tree (PP-06c) with copy-subset parity (PP-08): search every shown column (contains or\n * whole words), per-column and layered filters, sort, top N; every column with its own include\n * box, size, filter and per-cell limit; every matching row with its include box, size and span\n * highlight; right-click a row to copy just that row's shown columns. Hiding a column drops its\n * filter, its layered rules, its sort and its limit — the table cannot show a filter on a column\n * it does not show. The captured rows are only ever read.\n */\nfunction RowsStructure({ rows, controls, change, draft, focusKey, matchesInPreview, onFocus, onCopyRow }: {\n rows: Extract<Payload, { kind: \"rows\" }>;\n controls: Controls;\n change: (next: Controls) => void;\n draft: Draft;\n focusKey: string | null;\n matchesInPreview: number;\n onFocus: (kind: \"row\" | \"column\", id: string) => void;\n onCopyRow: (text: string) => void;\n}) {\n const [columnSearch, setColumnSearch] = React.useState(\"\");\n const [menuRow, setMenuRow] = React.useState<number | null>(null);\n const shown = React.useMemo(() => new Set(controls.visibleColumns), [controls.visibleColumns]);\n const filterCount = Object.values(controls.filters).filter(Boolean).length + controls.layeredFilters.length;\n const sizes = React.useMemo(() => Object.fromEntries(rows.columns.map((column) => [column.id, columnSize(rows, column.id)])), [rows]);\n const whole = Object.values(sizes).reduce((sum, size) => sum + size, 0);\n const shownColumns = rows.columns.filter((column) => !columnSearch.trim() || column.label.toLowerCase().includes(columnSearch.trim().toLowerCase()));\n const visibleDefs = rows.columns.filter((column) => shown.has(column.id) && exportableColumn(column));\n const matched = draftLayout(draft).matchedRows ?? rows.rows.map((_, index) => index);\n const left = React.useMemo(() => new Set(controls.excludedRows), [controls.excludedRows]);\n const included = matched.filter((index) => !left.has(index)).length;\n const rowText = React.useCallback((index: number) => visibleDefs.map((column) => cellText(readTransferCell(rows.rows[index]!, column))), [rows, visibleDefs]);\n const rowItems = React.useMemo((): TreeItem[] => matched.map((index) => {\n const cells = rowText(index);\n const summary = cells.slice(0, 2).filter(Boolean).join(\" · \");\n return { key: `row:${index}`, depth: 0, label: `Row ${index + 1}${summary ? ` — ${summary}` : \"\"}`, chars: cells.reduce((sum, cell) => sum + cell.length, 0), state: left.has(index) ? \"off\" : \"on\", rowIndex: index };\n }), [left, matched, rowText]);\n const rowWhole = rowItems.reduce((sum, item) => sum + (item.chars ?? 0), 0);\n const setRowIncluded = (index: number, include: boolean) => change({ ...controls, excludedRows: include ? controls.excludedRows.filter((value) => value !== index) : [...controls.excludedRows, index] });\n const rowHandlers: TreeHandlers = {\n toggle: (item) => setRowIncluded(item.rowIndex!, left.has(item.rowIndex!)),\n focus: (item) => onFocus(\"row\", String(item.rowIndex)),\n };\n const everyRow: \"on\" | \"off\" | \"mixed\" = included === matched.length ? \"on\" : included === 0 ? \"off\" : \"mixed\";\n const toggleEveryRow = () => {\n const inView = new Set(matched);\n change({ ...controls, excludedRows: everyRow === \"off\" ? controls.excludedRows.filter((index) => !inView.has(index)) : [...new Set([...controls.excludedRows, ...matched])] });\n };\n /** Hiding a column drops its filter, layered rules, sort and limit with it. */\n const setColumnShown = (column: Column, visible: boolean) => {\n if (visible) { change({ ...controls, visibleColumns: [...controls.visibleColumns, column.id] }); return; }\n const { [column.id]: _filter, ...filters } = controls.filters;\n const { [column.id]: _limit, ...columnLimits } = controls.columnLimits;\n change({\n ...controls,\n visibleColumns: controls.visibleColumns.filter((id) => id !== column.id),\n filters,\n columnLimits,\n layeredFilters: controls.layeredFilters.filter((rule) => rule.field !== column.id),\n ...(controls.sort === column.id ? { sort: \"\", direction: \"asc\" as const } : {}),\n });\n };\n const layeredFields: LayeredFilterField[] = visibleDefs.map((column) => column.schema?.dataType === \"number\" || column.schema?.dataType === \"integer\" ? { id: column.id, label: column.label, kind: \"number\" } : { id: column.id, label: column.label, kind: \"text\" });\n const rowCopy = (index: number) => visibleDefs.map((column) => `${column.label}: ${cellText(readTransferCell(rows.rows[index]!, column))}`).join(\"\\n\");\n return <div className=\"matrx-alchemy-prep-group\">\n <div className=\"matrx-alchemy-prep-rowbar\">\n <label className=\"matrx-alchemy-prep-field\">Search<input type=\"search\" aria-label=\"Search\" value={controls.search} placeholder=\"Every shown column\" onChange={(e) => change({ ...controls, search: e.target.value })} /></label>\n <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={controls.searchMode === \"whole_words\"} title=\"Match whole words only: “are” finds “we are ready”, never “hardware”\" onClick={() => change({ ...controls, searchMode: controls.searchMode === \"whole_words\" ? \"contains\" : \"whole_words\" })}>Whole words</button>\n <label className=\"matrx-alchemy-prep-field\">Sort<select aria-label=\"Sort\" value={controls.sort} onChange={(e) => change({ ...controls, sort: e.target.value })}><option value=\"\">None</option>{visibleDefs.map((column) => <option key={column.id} value={column.id}>{column.label}</option>)}</select></label>\n <label className=\"matrx-alchemy-prep-field\">Direction<select aria-label=\"Direction\" value={controls.direction} disabled={!controls.sort} onChange={(e) => change({ ...controls, direction: e.target.value as \"asc\" | \"desc\" })}><option value=\"asc\">Ascending</option><option value=\"desc\">Descending</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">Top rows<input type=\"number\" aria-label=\"Top rows\" min=\"0\" value={controls.top ?? \"\"} onChange={(e) => change({ ...controls, top: Number.isNaN(e.target.valueAsNumber) ? null : e.target.valueAsNumber })} /></label>\n <LayeredFilterBuilder fields={layeredFields} rules={controls.layeredFilters} onChange={(layeredFilters) => change({ ...controls, layeredFilters })} label=\"Advanced row filters\" />\n </div>\n {controls.search.trim() ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{formatCount(matched.length)} of {formatCount(rows.rows.length)} rows match · {formatCount(matchesInPreview)} in the preview</small> : null}\n <fieldset className=\"matrx-alchemy-prep-group\" aria-label=\"Columns and filters\">\n <legend className=\"matrx-alchemy-prep-legend\">{visibleDefs.length} of {rows.columns.length} columns{filterCount ? ` · ${filterCount} filter${filterCount === 1 ? \"\" : \"s\"}` : \"\"}</legend>\n {rows.columns.length > 6 ? <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label=\"Find a column\" placeholder=\"Find a column\" value={columnSearch} onChange={(e) => setColumnSearch(e.target.value)} /> : null}\n {shownColumns.map((column) => {\n const exportable = exportableColumn(column);\n const on = exportable && shown.has(column.id);\n return <div className=\"matrx-alchemy-prep-node matrx-alchemy-column\" key={column.id} data-focused={focusKey === `column:${column.id}` || undefined}>\n <div className=\"matrx-alchemy-tree-row matrx-alchemy-column-head\">\n {exportable\n ? <input type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label={column.label} checked={on} onChange={(e) => setColumnShown(column, e.target.checked)} />\n : <span className=\"matrx-alchemy-tree-lock\" role=\"img\" aria-label={`${column.label} is declared ${column.classification === \"secret\" || column.classification === \"credential\" ? column.classification : \"not exportable\"} and never leaves this page`} title=\"Declared not exportable — it never leaves this page\"><LockGlyph /></span>}\n <button type=\"button\" className=\"matrx-alchemy-tree-label\" aria-label={`Highlight ${column.label}`} aria-pressed={focusKey === `column:${column.id}`} onClick={() => onFocus(\"column\", column.id)}><span className=\"matrx-alchemy-tree-name\">{column.label}</span></button>\n {on ? <select className=\"matrx-alchemy-tree-limit\" aria-label={`Limit ${column.label}`} value={encodeLimit(controls.columnLimits[column.id])} onChange={(e) => { const limit = decodeLimit(e.target.value); const { [column.id]: _old, ...rest } = controls.columnLimits; change({ ...controls, columnLimits: limit && e.target.value !== KEEP ? { ...rest, [column.id]: limit } : rest }); }}>{CELL_LIMITS.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select> : null}\n </div>\n <div className=\"matrx-alchemy-column-meta\">\n <SizeNote chars={sizes[column.id] ?? 0} whole={whole} />\n {on ? <input aria-label={`Filter ${column.label}`} placeholder=\"Filter\" value={controls.filters[column.id] ?? \"\"} onChange={(e) => change({ ...controls, filters: { ...controls.filters, [column.id]: e.target.value } })} /> : null}\n </div>\n </div>;\n })}\n </fieldset>\n <div className=\"matrx-alchemy-prep-group\" role=\"group\" aria-label=\"Rows\">\n <div className=\"matrx-alchemy-tree-row matrx-alchemy-rows-head\">\n <RowsCheckbox state={everyRow} onChange={toggleEveryRow} />\n <span className=\"matrx-alchemy-prep-legend\">Rows — {formatCount(included)} of {formatCount(matched.length)} included{matched.length < rows.rows.length ? ` (${formatCount(rows.rows.length)} captured)` : \"\"}</span>\n </div>\n <ContextMenu>\n <ContextMenuTrigger asChild>\n <div onContextMenu={(event) => { const index = (event.target as HTMLElement).closest(\"[data-row-index]\")?.getAttribute(\"data-row-index\"); setMenuRow(index == null ? null : Number(index)); }}>\n <StructureTreeList label=\"Rows\" items={rowItems} whole={rowWhole} focusKey={focusKey} handlers={rowHandlers} maxHeight=\"min(24rem, 50dvh)\" />\n </div>\n </ContextMenuTrigger>\n <ContextMenuContent>\n {menuRow === null ? <ContextMenuLabel>Right-click a row to copy it</ContextMenuLabel> : <>\n <ContextMenuLabel>Row {menuRow + 1}</ContextMenuLabel>\n <ContextMenuItem onSelect={() => onCopyRow(rowCopy(menuRow))}>Copy this row’s shown columns</ContextMenuItem>\n <ContextMenuItem onSelect={() => setRowIncluded(menuRow, left.has(menuRow))}>{left.has(menuRow) ? \"Include this row\" : \"Leave this row out\"}</ContextMenuItem>\n </>}\n </ContextMenuContent>\n </ContextMenu>\n </div>\n </div>;\n}\nfunction RowsCheckbox({ state, onChange }: { state: \"on\" | \"off\" | \"mixed\"; onChange: () => void }) {\n const ref = React.useRef<HTMLInputElement>(null);\n React.useEffect(() => { if (ref.current) ref.current.indeterminate = state === \"mixed\"; }, [state]);\n return <input ref={ref} type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label=\"Include every matching row\" checked={state === \"on\"} aria-checked={state === \"mixed\" ? \"mixed\" : state === \"on\"} onChange={onChange} />;\n}\n\n/** A cell as one line of text: objects (including prototype-less JSON) as JSON, never `String(object)`. */\nfunction cellText(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value) ?? \"\";\n}\n\n/**\n * Which workspace sessions still hold their content. A host window can outlive the page that\n * opened it (a restored or kept window); its slot then says so, with the remedy, instead of\n * standing empty (PP-08, the copy-subset \"rows were released\" message).\n */\nconst liveSessions = new Set<string>();\nconst sessionListeners = new Set<() => void>();\nexport function setWorkspaceSessionLive(key: string, live: boolean) {\n if (live) liveSessions.add(key); else liveSessions.delete(key);\n sessionListeners.forEach((listener) => listener());\n}\nconst subscribeSessions = (listener: () => void) => { sessionListeners.add(listener); return () => { sessionListeners.delete(listener); }; };\n\n/** The node a host window gives a session (its content is portalled in by the session). */\nexport function WorkspaceWindowSlot({ onNode, sessionKey, onClose }: { onNode: (node: HTMLDivElement | null) => void; sessionKey?: string; onClose?: () => void }) {\n const live = React.useSyncExternalStore(subscribeSessions, () => sessionKey === undefined || liveSessions.has(sessionKey), () => true);\n if (!live) {\n return (\n <div className=\"matrx-alchemy-prep-released\" role=\"status\">\n <p><strong>The rows this held were released.</strong></p>\n <p>The page that opened this preparation closed or reloaded, so what it captured is gone. Reopen Prepare from the table or page to start again.</p>\n {onClose ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={onClose}>Close</Button> : null}\n </div>\n );\n }\n return <div className=\"matrx-alchemy-prep-slot\" ref={onNode} />;\n}\n","/**\n * Host levers (Preparation parity PP-02, PP-03, PP-05): the controls a screen declares for its own\n * data — \"tool results\", \"last N messages\", \"per-message cap\", a groomer section's Full / Compact /\n * Brief / Off — and how a lever value becomes the payload the workspace prepares.\n *\n * The levers live INSIDE the one preparation workspace, beside the preview: changing one rebuilds\n * the payload from the host builder and the preview follows. There is no second dialog and no\n * \"Prepare in Alchemy\" handoff that loses them.\n *\n * Text stays text (PP-09): a builder that returns text becomes a text payload whose AI envelope\n * carries it as `<data format=\"text\">`, never one escaped JSON string.\n */\nimport {\n directSource,\n normalizeTransferJson,\n projectSnapshot,\n type AgentPayloadInput,\n type Payload,\n type Snapshot,\n} from \"@ai-matrx/alchemy/operate\";\n\nexport type AlchemyOptionValues = Record<string, boolean | number>;\nexport type AlchemySourceOption =\n | {\n kind: \"toggle\";\n key: string;\n label: string;\n hint?: string;\n default: boolean;\n }\n | {\n kind: \"preset\";\n key: string;\n label: string;\n options: { label: string; value: number }[];\n default: number;\n }\n | {\n kind: \"slider\";\n key: string;\n label: string;\n hint?: string;\n stops: number[];\n default: number;\n formatValue: (value: number) => string;\n }\n | {\n kind: \"number\";\n key: string;\n label: string;\n hint?: string;\n min?: number;\n step?: number;\n presets?: { label: string; value: number }[];\n default: number;\n };\nexport type LeverMeta = Record<string, string | number | boolean | undefined>;\nexport interface AlchemyCustomSource {\n label?: string;\n hint?: string;\n options: AlchemySourceOption[];\n build(values: AlchemyOptionValues): {\n text: string;\n meta?: LeverMeta;\n };\n wrap(\n text: string,\n values: AlchemyOptionValues,\n meta?: LeverMeta,\n ): AgentPayloadInput;\n dialogTitle?: string;\n dialogDescription?: string;\n}\nexport type AlchemyDetail = \"full\" | \"compact\" | \"brief\";\nexport interface AlchemyGroomerSection {\n id: string;\n title: string;\n description?: string;\n cuttable?: boolean;\n levelLabels?: Partial<Record<AlchemyDetail, string>>;\n build(level: AlchemyDetail): unknown;\n defaultSelection?: AlchemyDetail | \"off\";\n}\nexport interface AlchemyGroomerConfig {\n label: string;\n kind: string;\n location: string;\n description: string;\n attributes?: AgentPayloadInput[\"attributes\"];\n context?: AgentPayloadInput[\"context\"];\n summary?: string;\n sections: AlchemyGroomerSection[];\n}\n\n/** Who a piece of content is, for the AI envelope — everything but the body. */\nexport type EnvelopeMeta = Omit<AgentPayloadInput, \"data\" | \"dataFormat\" | \"instructions\">;\nexport type LeverValue = boolean | number | string;\nexport type LeverValues = Record<string, LeverValue>;\nexport type SectionLevel = AlchemyDetail | \"off\";\n\nexport interface LeverBuild {\n payload: Payload;\n envelope: EnvelopeMeta;\n meta?: LeverMeta;\n /** Per groomer section: its size in the prepared JSON at its current level (PP-04). */\n sectionSizes?: Record<string, number>;\n}\n/** The levers one workspace session carries: the host's controls and the one builder they feed. */\nexport interface WorkspaceLevers {\n /** Source options (custom levers), shown in Settings. */\n options?: readonly AlchemySourceOption[];\n /** Groomer sections, shown in Structure with their level control. */\n sections?: readonly AlchemyGroomerSection[];\n initial: LeverValues;\n build(values: LeverValues): LeverBuild;\n}\n\nexport const sectionLeverKey = (id: string) => `section:${id}`;\n\n/**\n * A payload for text the host built: Markdown when the host said so (`dataFormat: \"markdown\"`),\n * else plain text. A JSON body stays JSON. Never a text body wrapped as a JSON string (PP-09).\n */\nexport function payloadForEnvelope(value: AgentPayloadInput | string): { payload: Payload; envelope?: EnvelopeMeta } {\n if (typeof value === \"string\") return { payload: { kind: \"markdown\", text: value } };\n const { data, dataFormat, instructions: _instructions, ...envelope } = value;\n const clean = (record?: AgentPayloadInput[\"context\"]) =>\n Object.fromEntries(Object.entries(record ?? {}).filter(([, entry]) => entry !== undefined));\n const meta: EnvelopeMeta = {\n ...envelope,\n attributes: clean(envelope.attributes),\n context: clean(envelope.context),\n };\n if (typeof data === \"string\") {\n return { payload: dataFormat === \"markdown\" ? { kind: \"markdown\", text: data } : { kind: \"text\", text: data }, envelope: meta };\n }\n return {\n payload: { kind: \"json\", value: normalizeTransferJson(data, { omitUndefinedObjectProperties: true }) },\n envelope: meta,\n };\n}\n\n/** The custom levers of `aiCustom`: option values → the host's text → a TEXT payload. */\nexport function customLevers(custom: AlchemyCustomSource): WorkspaceLevers {\n return {\n options: custom.options,\n initial: Object.fromEntries(custom.options.map((option) => [option.key, option.default])),\n build(values) {\n const optionValues = values as AlchemyOptionValues;\n const result = custom.build(optionValues);\n // The wrap decides what travels: text data stays text (PP-09), structured data stays JSON.\n const { payload, envelope } = payloadForEnvelope(custom.wrap(result.text, optionValues, result.meta));\n return { payload, envelope: envelope!, ...(result.meta ? { meta: result.meta } : {}) };\n },\n };\n}\n\n/** Pretty JSON of `value` exactly as it sits one level inside the prepared object. */\nfunction nestedJsonLength(key: string, value: unknown): number {\n const text = JSON.stringify(value, null, 2);\n if (text === undefined) return 0;\n // ` \"key\": <value with every line indented two more>,\\n`\n return 2 + JSON.stringify(key).length + 2 + text.replace(/\\n/g, \"\\n \").length + 2;\n}\n\n/** The groomer levers: a level per section → the JSON object of the included sections. */\nexport function groomerLevers(config: AlchemyGroomerConfig): WorkspaceLevers {\n return {\n sections: config.sections,\n initial: Object.fromEntries(config.sections.map((section) => [sectionLeverKey(section.id), section.defaultSelection ?? \"full\"])),\n build(values) {\n const data: Record<string, unknown> = {};\n const dropped: string[] = [];\n const sectionSizes: Record<string, number> = {};\n for (const section of config.sections) {\n const level = (values[sectionLeverKey(section.id)] ?? \"full\") as SectionLevel;\n if (level === \"off\") {\n dropped.push(section.id);\n sectionSizes[section.id] = 0;\n continue;\n }\n const value = section.build(level);\n if (value !== undefined && value !== null) {\n data[section.id] = value;\n sectionSizes[section.id] = nestedJsonLength(section.id, normalizeTransferJson(value, { omitUndefinedObjectProperties: true }));\n } else sectionSizes[section.id] = 0;\n }\n return {\n payload: { kind: \"json\", value: normalizeTransferJson(data, { omitUndefinedObjectProperties: true }) },\n envelope: {\n kind: config.kind,\n location: config.location,\n description: config.description,\n ...(config.summary !== undefined ? { summary: config.summary } : {}),\n attributes: { ...config.attributes, ...(dropped.length ? { dropped_sections: dropped.join(\",\") } : {}) },\n ...(config.context ? { context: config.context } : {}),\n },\n sectionSizes,\n };\n },\n };\n}\n\n/** Presets over groomer sections (O4's Everything / Balanced / Minimal). */\nexport type AlchemyGroomerPreset = \"everything\" | \"balanced\" | \"minimal\";\nexport function applyGroomerPreset(\n preset: AlchemyGroomerPreset,\n sections: readonly AlchemyGroomerSection[],\n): Record<string, SectionLevel> {\n return Object.fromEntries(\n sections.map((section) => [\n section.id,\n preset === \"everything\" ? \"full\" : preset === \"balanced\" ? \"compact\" : section.cuttable ? \"off\" : \"brief\",\n ]),\n );\n}\n/** The preset these levels are, or null when hand-tuned (\"Custom\") — PP-05 active-preset detection. */\nexport function activeGroomerPreset(\n values: LeverValues,\n sections: readonly AlchemyGroomerSection[],\n): AlchemyGroomerPreset | null {\n for (const preset of [\"everything\", \"balanced\", \"minimal\"] as const) {\n const levels = applyGroomerPreset(preset, sections);\n if (sections.every((section) => (values[sectionLeverKey(section.id)] ?? \"full\") === levels[section.id])) return preset;\n }\n return null;\n}\n\n/** A snapshot of a lever build, synchronously (the builder is the capture). */\nexport function leverSnapshot(payload: Payload, sourceId: string, label: string): Snapshot {\n const raw = directSource(payload, { sourceId, label });\n return projectSnapshot(raw.snapshot, raw.projection);\n}\n","\"use client\";\n\n/**\n * The preparation workspace's Structure trees (Preparation parity PP-06b JSON, PP-06c rows,\n * PP-06d sections, PP-07 per-node limits, PP-08 search).\n *\n * One row shape for every tree: an include checkbox (tri-state for parents), the node's name,\n * its size (chars · ≈tokens) with a share bar, a per-node limit (Keep / Stub / Max …), and — for a\n * JSON node — copy-path. Selecting a node's name highlights its span in the preview through the\n * serializer span map. Lists are windowed (only the rows on screen are drawn), so a 5,000-row\n * table or a thousand-message conversation stays responsive.\n *\n * A node the person cannot include is honest about it: a declared non-exportable column shows a\n * lock and its sentence (no checkbox at all), and a node excluded by a broader pattern offers\n * \"Include … again\" by name rather than a dead checkbox.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport { computeWindow } from \"@ai-matrx/design-system/data-table\";\nimport { displayPath, jsonSize, nodeChars, patternBelow, patternCovers, pointerSegments, type Json, type NodeLimit, type StructureRecipe } from \"@ai-matrx/alchemy/operate\";\nimport { sizeLabel } from \"./workspace-core\";\n\nexport type NodeState = \"on\" | \"off\" | \"mixed\";\nexport interface LimitChoice { value: string; label: string }\nexport interface TreeItem {\n key: string;\n depth: number;\n label: string;\n detail?: string | undefined;\n chars: number | null;\n /** Absent: the node has no include choice of its own (the root). */\n state?: NodeState | undefined;\n /** Why this node cannot be included (declared non-exportable / secret). Shown instead of a checkbox. */\n locked?: string | undefined;\n /** The broader pattern that excludes this node; its control includes that pattern again. */\n coveredBy?: string | undefined;\n expandable?: boolean | undefined;\n expanded?: boolean | undefined;\n limitChoices?: readonly LimitChoice[] | undefined;\n limit?: string | undefined;\n copyPath?: string | undefined;\n /** Rows tree: the captured row position, for the row menu. */\n rowIndex?: number | undefined;\n}\nexport interface TreeHandlers {\n toggle(item: TreeItem): void;\n focus(item: TreeItem): void;\n expand?(item: TreeItem): void;\n limit?(item: TreeItem, value: string): void;\n includeAgain?(item: TreeItem): void;\n copyPath?(path: string): void;\n}\n\nexport const KEEP = \"keep\";\nexport const TEXT_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" },\n { value: \"chars:200\", label: \"Max 200 chars\" }, { value: \"chars:1000\", label: \"Max 1,000 chars\" }, { value: \"chars:4000\", label: \"Max 4,000 chars\" },\n];\nexport const LIST_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" },\n { value: \"items:5\", label: \"First 5 items\" }, { value: \"items:25\", label: \"First 25 items\" }, { value: \"items:100\", label: \"First 100 items\" },\n];\nexport const OBJECT_LIMITS: readonly LimitChoice[] = [{ value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" }, { value: \"chars:1000\", label: \"Max 1,000 chars per text\" }];\nexport const CELL_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub cells\" },\n { value: \"chars:100\", label: \"Max 100 chars\" }, { value: \"chars:500\", label: \"Max 500 chars\" }, { value: \"chars:2000\", label: \"Max 2,000 chars\" },\n];\nexport function encodeLimit(limit: NodeLimit | undefined): string {\n if (!limit) return KEEP;\n return limit.kind === \"stub\" ? \"stub\" : limit.kind === \"maxChars\" ? `chars:${limit.value}` : `items:${limit.value}`;\n}\nexport function decodeLimit(value: string): NodeLimit | null {\n if (value === \"stub\") return { kind: \"stub\" };\n const m = /^(chars|items):(\\d+)$/.exec(value);\n if (!m) return null;\n return m[1] === \"chars\" ? { kind: \"maxChars\", value: Number(m[2]) } : { kind: \"maxItems\", value: Number(m[2]) };\n}\n\n// ── The windowed list ────────────────────────────────────────────────────────────────────────\n\nfunction useRowHeight(): number {\n const [coarse, setCoarse] = React.useState(() => typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" && window.matchMedia(\"(pointer: coarse)\").matches);\n React.useEffect(() => {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n const query = window.matchMedia(\"(pointer: coarse)\");\n const update = () => setCoarse(query.matches);\n query.addEventListener?.(\"change\", update);\n return () => query.removeEventListener?.(\"change\", update);\n }, []);\n // 44px targets on a coarse pointer (touch), a compact row with a mouse.\n // Two lines (name, then size and value) — 44px targets on a coarse pointer (touch).\n return coarse ? 48 : 40;\n}\n\nfunction Checkbox({ state, label, onChange }: { state: NodeState; label: string; onChange: () => void }) {\n const ref = React.useRef<HTMLInputElement>(null);\n React.useEffect(() => { if (ref.current) ref.current.indeterminate = state === \"mixed\"; }, [state]);\n return <input ref={ref} type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label={label} checked={state === \"on\"} aria-checked={state === \"mixed\" ? \"mixed\" : state === \"on\"} onChange={onChange} />;\n}\n\nexport const LockGlyph = () => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"5\" y=\"11\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 11V7a4 4 0 0 1 8 0v4\"/></svg>;\nconst CopyGlyph = () => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"9\" y=\"9\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1\"/></svg>;\nconst Chevron = ({ open }: { open: boolean }) => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" style={{ transform: open ? \"rotate(90deg)\" : undefined, transition: \"transform 120ms\" }}><path d=\"m9 6 6 6-6 6\"/></svg>;\n\nfunction TreeRow({ item, whole, focused, height, handlers }: { item: TreeItem; whole: number; focused: boolean; height: number; handlers: TreeHandlers }) {\n const share = whole > 0 && item.chars !== null ? Math.min(1, item.chars / whole) : 0;\n return (\n <div\n role=\"treeitem\"\n aria-level={item.depth + 1}\n aria-expanded={item.expandable ? Boolean(item.expanded) : undefined}\n aria-selected={focused}\n data-row-index={item.rowIndex}\n className=\"matrx-alchemy-tree-row\"\n data-state={item.state ?? \"root\"}\n style={{ height, paddingLeft: `${0.25 + item.depth * 0.875}rem` }}\n >\n {item.expandable ? (\n <button type=\"button\" className=\"matrx-alchemy-tree-twisty\" aria-label={`${item.expanded ? \"Collapse\" : \"Expand\"} ${item.label}`} onClick={() => handlers.expand?.(item)}><Chevron open={Boolean(item.expanded)} /></button>\n ) : <span className=\"matrx-alchemy-tree-twisty\" aria-hidden=\"true\" />}\n {item.locked ? (\n <span className=\"matrx-alchemy-tree-lock\" role=\"img\" aria-label={item.locked} title={item.locked}><LockGlyph /></span>\n ) : item.coveredBy ? (\n <button type=\"button\" className=\"matrx-alchemy-tree-covered\" aria-label={`Left out by ${item.coveredBy} — include it again`} title={`Left out by ${item.coveredBy}. Include it again.`} onClick={() => handlers.includeAgain?.(item)}>\n <input type=\"checkbox\" tabIndex={-1} aria-hidden=\"true\" checked={false} readOnly />\n </button>\n ) : item.state ? <Checkbox state={item.state} label={item.label} onChange={() => handlers.toggle(item)} /> : <span className=\"matrx-alchemy-tree-twisty\" aria-hidden=\"true\" />}\n <button type=\"button\" className=\"matrx-alchemy-tree-label\" aria-label={`Highlight ${item.label}`} aria-pressed={focused} onClick={() => handlers.focus(item)} title={item.detail ? `${item.label} — ${item.detail}` : item.label}>\n <span className=\"matrx-alchemy-tree-name\">{item.label}</span>\n <span className=\"matrx-alchemy-tree-meta\">\n {item.chars !== null ? <span className=\"matrx-alchemy-prep-size matrx-alchemy-tree-size\" title={sizeLabel(item.chars)}><span className=\"matrx-alchemy-prep-share\" aria-hidden=\"true\"><span style={{ width: `${(share * 100).toFixed(1)}%` }} /></span><span>{compactSize(item.chars)}</span></span> : null}\n {item.detail ? <small className=\"matrx-alchemy-tree-detail\">{item.detail}</small> : null}\n </span>\n </button>\n {item.limitChoices && handlers.limit && item.state !== \"off\" && !item.locked && !item.coveredBy ? (\n <select className=\"matrx-alchemy-tree-limit\" aria-label={`Limit ${item.label}`} value={item.limit ?? KEEP} onChange={(event) => handlers.limit!(item, event.target.value)}>\n {item.limitChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}\n </select>\n ) : null}\n {item.copyPath && handlers.copyPath ? <button type=\"button\" className=\"matrx-alchemy-tree-icon\" aria-label={`Copy path ${item.copyPath}`} title={`Copy ${item.copyPath}`} onClick={() => handlers.copyPath!(item.copyPath!)}><CopyGlyph /></button> : null}\n </div>\n );\n}\n\n/** \"1.2k chars · ≈300 tok\" — compact enough for a tree row; the full figure is the title. */\nfunction compactSize(chars: number): string {\n const short = (value: number) => formatCount(value, { style: \"compact\" });\n return `${short(chars)} · ≈${short(Math.ceil(chars / 4))} tok`;\n}\n\n/** A windowed tree: only the rows in view (plus a few) are in the DOM. */\nexport function StructureTreeList({ label, items, whole, focusKey, handlers, maxHeight = \"24rem\", onContextMenu }: {\n label: string;\n items: readonly TreeItem[];\n whole: number;\n focusKey: string | null;\n handlers: TreeHandlers;\n maxHeight?: string;\n onContextMenu?: (event: React.MouseEvent<HTMLDivElement>) => void;\n}) {\n const height = useRowHeight();\n const ref = React.useRef<HTMLDivElement>(null);\n const [offset, setOffset] = React.useState(0);\n const [viewport, setViewport] = React.useState(0);\n React.useLayoutEffect(() => {\n const node = ref.current;\n if (!node) return;\n const measure = () => setViewport(node.clientHeight);\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(node);\n return () => observer.disconnect();\n }, []);\n // An unmeasured list (first paint, a test DOM) draws a screenful rather than nothing.\n const view = computeWindow({ count: items.length, itemSize: height, viewport: viewport || 640, offset });\n const rows: React.ReactNode[] = [];\n for (let index = view.start; index < view.end; index++) {\n const item = items[index]!;\n rows.push(<TreeRow key={item.key} item={item} whole={whole} focused={item.key === focusKey} height={height} handlers={handlers} />);\n }\n return (\n <div ref={ref} role=\"tree\" aria-label={label} className=\"matrx-alchemy-tree\" style={{ maxHeight }} onScroll={(event) => setOffset(event.currentTarget.scrollTop)} onContextMenu={onContextMenu}>\n <div style={{ height: view.padStart }} aria-hidden=\"true\" />\n {rows}\n <div style={{ height: view.padEnd }} aria-hidden=\"true\" />\n </div>\n );\n}\n\n// ── JSON tree (PP-06b) ───────────────────────────────────────────────────────────────────────\n\ninterface JsonNode { pattern: string; label: string; values: Json[]; concrete: boolean }\nconst isRecord = (value: Json): value is { [key: string]: Json } => value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst enc = (segment: string) => segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nfunction jsonChildren(node: JsonNode): JsonNode[] {\n const values = node.values;\n if (values.length && values.every(Array.isArray)) {\n const items = (values as Json[][]).flat();\n const out: JsonNode[] = [];\n // `[*]` — every item at once: unticking `messages[*].metadata` reaches all messages.\n if (items.length > 1) out.push({ pattern: `${node.pattern}/*`, label: \"[*] every item\", values: items, concrete: false });\n if (node.concrete) (values[0] as Json[]).forEach((item, index) => out.push({ pattern: `${node.pattern}/${index}`, label: `[${index}]`, values: [item], concrete: true }));\n return out;\n }\n const objects = values.filter(isRecord);\n if (!objects.length) return [];\n const keys: string[] = [];\n const seen = new Set<string>();\n for (const object of objects) for (const key of Object.keys(object)) if (!seen.has(key)) { seen.add(key); keys.push(key); }\n return keys.map((key) => ({ pattern: `${node.pattern}/${enc(key)}`, label: key, values: objects.filter((object) => Object.prototype.hasOwnProperty.call(object, key)).map((object) => object[key]!), concrete: node.concrete }));\n}\nconst hasChildren = (node: JsonNode) => node.values.some((value) => (Array.isArray(value) && value.length > 0) || (isRecord(value) && Object.keys(value).length > 0));\nfunction preview(value: Json): string {\n if (typeof value === \"string\") return value.length > 60 ? `\"${value.slice(0, 60).replace(/\\s+/g, \" \")}…\"` : JSON.stringify(value);\n if (Array.isArray(value)) return `[${formatCount(value.length)} items]`;\n if (isRecord(value)) return `{${formatCount(Object.keys(value).length)} keys}`;\n return String(value);\n}\nfunction limitChoicesFor(node: JsonNode): readonly LimitChoice[] {\n if (node.values.every(Array.isArray)) return LIST_LIMITS;\n if (node.values.every((value) => typeof value === \"string\")) return TEXT_LIMITS;\n if (node.values.every(isRecord)) return OBJECT_LIMITS;\n return [{ value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" }];\n}\n\n/** Two patterns name overlapping nodes at the same depth (`/a/*\\/m` and `/a/2/m`). */\nfunction overlaps(a: string, b: string): boolean {\n const x = pointerSegments(a);\n const y = pointerSegments(b);\n return x.length === y.length && x.every((segment, index) => segment === y[index] || segment === \"*\" || y[index] === \"*\");\n}\nexport function nodeState(pattern: string, exclude: readonly string[]): { state: NodeState; coveredBy?: string } {\n if (exclude.includes(pattern)) return { state: \"off\" };\n const cover = exclude.find((candidate) => patternCovers(candidate, pattern));\n if (cover !== undefined) return { state: \"off\", coveredBy: cover };\n return exclude.some((candidate) => patternBelow(candidate, pattern) || overlaps(candidate, pattern)) ? { state: \"mixed\" } : { state: \"on\" };\n}\n/** The recipe after ticking or unticking one node (a parent's choice replaces its descendants'). */\nexport function toggleNode(recipe: StructureRecipe, pattern: string): StructureRecipe {\n const { state } = nodeState(pattern, recipe.exclude);\n if (state === \"off\") return { ...recipe, exclude: recipe.exclude.filter((candidate) => candidate !== pattern) };\n const limits = Object.fromEntries(Object.entries(recipe.limits).filter(([candidate]) => !patternCovers(pattern, candidate)));\n return { exclude: [...recipe.exclude.filter((candidate) => !patternCovers(pattern, candidate)), pattern], limits };\n}\n\nexport function jsonTreeItems(root: Json, recipe: StructureRecipe, expanded: ReadonlySet<string>): TreeItem[] {\n const items: TreeItem[] = [];\n const visit = (node: JsonNode, depth: number) => {\n const expandable = hasChildren(node);\n const isOpen = expandable && expanded.has(node.pattern);\n const chars = node.values.reduce<number>((sum, value) => sum + (node.pattern === \"\" ? jsonSize(value) : nodeChars(value)), 0);\n const { state, coveredBy } = node.pattern === \"\" ? { state: undefined, coveredBy: undefined } : nodeState(node.pattern, recipe.exclude);\n items.push({\n key: node.pattern || \"#root\",\n depth,\n label: node.label,\n detail: node.concrete ? preview(node.values[0] ?? null) : `in ${formatCount(node.values.length)} items`,\n chars,\n state,\n coveredBy: coveredBy === undefined ? undefined : displayPath(coveredBy),\n expandable,\n expanded: isOpen,\n ...(node.pattern ? { limitChoices: limitChoicesFor(node), limit: encodeLimit(recipe.limits[node.pattern]), copyPath: displayPath(node.pattern) } : { copyPath: \"data\" }),\n });\n if (isOpen && state !== \"off\") for (const child of jsonChildren(node)) visit(child, depth + 1);\n };\n visit({ pattern: \"\", label: \"data\", values: [root], concrete: true }, 0);\n return items;\n}\n\n/** Search the data by key and value (PP-08): every concrete node whose key or text holds the query. */\nexport function jsonSearchItems(root: Json, recipe: StructureRecipe, query: string, cap = 500): TreeItem[] {\n const q = query.trim().toLocaleLowerCase();\n if (!q) return [];\n const items: TreeItem[] = [];\n const walk = (value: Json, segments: string[]) => {\n if (items.length >= cap) return;\n const key = segments[segments.length - 1] ?? \"\";\n const scalar = value === null || typeof value !== \"object\";\n const hit = key.toLocaleLowerCase().includes(q) || (scalar && String(value).toLocaleLowerCase().includes(q));\n if (hit && segments.length) {\n const pattern = segments.map((segment) => `/${enc(segment)}`).join(\"\");\n const { state, coveredBy } = nodeState(pattern, recipe.exclude);\n const node: JsonNode = { pattern, label: key, values: [value], concrete: true };\n items.push({ key: `search:${pattern}`, depth: 0, label: displayPath(pattern), detail: preview(value), chars: nodeChars(value), state, coveredBy: coveredBy === undefined ? undefined : displayPath(coveredBy), limitChoices: limitChoicesFor(node), limit: encodeLimit(recipe.limits[pattern]), copyPath: displayPath(pattern) });\n }\n if (Array.isArray(value)) value.forEach((item, index) => walk(item, [...segments, String(index)]));\n else if (isRecord(value)) for (const [child, item] of Object.entries(value)) walk(item, [...segments, child]);\n };\n walk(root, []);\n return items;\n}\n/** The pointer a tree item stands for (search results carry a prefix). */\nexport const itemPattern = (item: TreeItem) => (item.key.startsWith(\"search:\") ? item.key.slice(7) : item.key === \"#root\" ? \"\" : item.key);\n","import {\n ContentTransferError,\n readTransferCell,\n sealTransferArtifact,\n serialize,\n type Artifact,\n type Draft,\n type FormatAdapter,\n type FormatOptions,\n type Json,\n type PageAction,\n type Payload,\n type TransferOutcome,\n} from \"@ai-matrx/alchemy/operate\";\n\n/** The table copy contract declares it (design-system sits below alchemy); one definition. */\nexport type { ContentTransferReference } from \"@ai-matrx/design-system/data-table/host\";\nimport type { ContentTransferReference } from \"@ai-matrx/design-system/data-table/host\";\n\nexport type ContentTransferReferencePort = {\n supports(reference: ContentTransferReference): boolean;\n build(reference: ContentTransferReference): string | Promise<string>;\n};\n\nexport type ContentTransferEmailPort = {\n send(\n artifact: Artifact,\n context: { label: string; signal: AbortSignal },\n ): Promise<TransferOutcome>;\n};\n\n/** The host's HTML preview (a window or overlay that renders the document); Alchemy only decides when to offer it. */\nexport type ContentTransferHtmlPreviewPort = {\n open(request: { content: string; title: string }): void | Promise<void>;\n};\n\nconst exportableColumns = (payload: Extract<Payload, { kind: \"rows\" }>) =>\n payload.columns.filter(\n (column) =>\n column.visible &&\n column.exportable !== false &&\n column.classification !== \"secret\" &&\n column.classification !== \"credential\",\n );\n\n/** A sealed, projection-safe representation of a tabular draft's declared schema and values. */\nexport const tableSchemaFormat: FormatAdapter = {\n id: \"table-schema\",\n label: \"Schema\",\n supports: (payload) => payload.kind === \"rows\",\n extension: \"json\",\n mime: \"application/json\",\n modes: [\"copy\", \"download\"],\n runsOn: \"client\",\n load: async () => ({ async build(draft: Draft, _options: FormatOptions, signal: AbortSignal): Promise<Artifact> {\n if (signal.aborted) throw new DOMException(\"Cancelled\", \"AbortError\");\n if (draft.payload.kind !== \"rows\")\n throw new ContentTransferError(\n \"unsupported-format\",\n \"Schema + rows requires tabular content; manually edited text cannot carry a table schema.\",\n );\n const rowColumns = exportableColumns(draft.payload);\n const columns = rowColumns.map((column) => ({\n id: column.id,\n label: column.label,\n path: column.path,\n ...(column.schema === undefined ? {} : { schema: column.schema }),\n }));\n const body = {\n sourceId: draft.sourceId,\n columns,\n rows: draft.payload.rows.map((row) =>\n Object.fromEntries(rowColumns.map((column) => [column.id, readTransferCell(row, column) ?? null])),\n ),\n } satisfies Json;\n const plainText = JSON.stringify(body, null, 2);\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"table-schema\",\n plainText,\n file: {\n filename: \"table-schema.json\",\n mime: \"application/json\",\n bytes: new TextEncoder().encode(plainText),\n },\n omissions: [...draft.omissions],\n });\n } }),\n};\n\nfunction displayLabels(payload: Extract<Payload, { kind: \"rows\" }>): [string, typeof payload.columns[number]][] {\n const columns = exportableColumns(payload);\n const counts = new Map<string, number>();\n for (const column of columns) counts.set(column.label, (counts.get(column.label) ?? 0) + 1);\n const used = new Set<string>();\n return columns.map((column) => {\n const base = counts.get(column.label) === 1 ? column.label : `${column.label} [${column.id}]`;\n let label = base;\n for (let suffix = 2; used.has(label); suffix += 1) label = `${base} (${suffix})`;\n used.add(label);\n return [label, column];\n });\n}\n\n/** Flat row JSON keyed by user-facing display labels, never raw table records. */\nexport const tableDataFormat: FormatAdapter = {\n id: \"table-data\",\n label: \"Table JSON\",\n supports: (payload) => payload.kind === \"rows\",\n extension: \"json\",\n mime: \"application/json;charset=utf-8\",\n modes: [\"copy\", \"download\"],\n runsOn: \"client\",\n load: async () => ({ async build(draft: Draft, _options: FormatOptions, signal: AbortSignal): Promise<Artifact> {\n if (signal.aborted) throw new DOMException(\"Cancelled\", \"AbortError\");\n if (draft.payload.kind !== \"rows\")\n throw new ContentTransferError(\"unsupported-format\", \"Display-label JSON requires tabular content.\");\n const columns = displayLabels(draft.payload);\n const plainText = JSON.stringify(\n draft.payload.rows.map((row) =>\n Object.fromEntries(columns.map(([label, column]) => [label, readTransferCell(row, column) ?? null])),\n ),\n null,\n 2,\n );\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"json\",\n plainText,\n file: {\n filename: \"data.json\",\n mime: \"application/json;charset=utf-8\",\n bytes: new TextEncoder().encode(plainText),\n },\n omissions: [...draft.omissions],\n });\n } }),\n};\n\ntype EmailFormat = \"csv\" | \"json\" | \"markdown\";\nexport type TransferHtmlPreviewAction = PageAction;\nexport type TransferEmailAction = PageAction & { prepared: true; group: \"email\" };\n\nconst emailArtifact = (draft: Draft, format: EmailFormat, signal: AbortSignal, jsonFormat?: FormatAdapter): Promise<Artifact> =>\n format === \"json\" && jsonFormat?.supports(draft.payload)\n ? jsonFormat.load().then((engine) => engine.build(draft, {}, signal))\n : Promise.resolve(serialize(draft, format));\n\n/** Prepared-only delivery actions always serialize the current draft, never a host source. */\nexport function createTransferEmailActions(\n email: ContentTransferEmailPort,\n options: { jsonFormat?: FormatAdapter } = {},\n): TransferEmailAction[] {\n return ([\"csv\", \"json\", \"markdown\"] as const).map((format) => ({\n id: `email-${format}`,\n label: `Email ${format === \"csv\" ? \"CSV\" : format === \"json\" ? \"JSON\" : \"Markdown\"}`,\n prepared: true,\n group: \"email\",\n supports: (_snapshot, draft) => Boolean(draft) && (format !== \"csv\" || draft?.payload.kind === \"rows\"),\n async run({ draft, signal, snapshot }) {\n if (signal.aborted) return { status: \"cancelled\" };\n const artifact = await emailArtifact(draft, format, signal, options.jsonFormat);\n return email.send(artifact, { label: snapshot.label, signal });\n },\n }));\n}\n\n/**\n * \"HTML preview\": opens the host's preview on the PREPARED text (what the person would copy, edits\n * and thinking-strip included). Offered for Markdown and text drafts only — a table has no document.\n */\nexport function createTransferHtmlPreviewAction(port: ContentTransferHtmlPreviewPort): TransferHtmlPreviewAction {\n return {\n id: \"html-preview\",\n label: \"HTML preview\",\n supports: (snapshot, draft) => {\n const kind = (draft?.payload ?? snapshot.payload).kind;\n return kind === \"markdown\" || kind === \"text\";\n },\n async run({ draft, snapshot, signal }) {\n if (signal.aborted) return { status: \"cancelled\" };\n if (draft.payload.kind !== \"markdown\" && draft.payload.kind !== \"text\")\n throw new ContentTransferError(\"unsupported-format\", \"HTML preview requires text.\");\n await port.open({ content: draft.payload.text, title: snapshot.label });\n return { status: \"success\", delivered: \"action\", mimeTypes: [], message: \"HTML preview opened\" };\n },\n };\n}\n","\"use client\";\n\nimport * as React from \"react\";\nimport {\n buildAgentPayload,\n capture,\n createBrowserTransport,\n createDraft,\n serialize,\n directSource,\n hasThinking,\n stripThinking,\n normalizeTransferJson,\n sealTransferArtifact,\n type AgentPayloadInput,\n type PageAction,\n type Payload,\n type TransferOutcome,\n} from \"@ai-matrx/alchemy/operate\";\nimport {\n ContentTransferMenu,\n useContentTransferCapabilities,\n type RichCopyFlavor,\n type ContentTransferController,\n type ContentTransferReference,\n type ContentTransferReferenceAction,\n type ShapedSource,\n type SourceShape,\n type TransferMenuPresentation,\n} from \"./index\";\nimport { markdownRichArtifact } from \"./workspace-core\";\nimport type { TableCopyController } from \"@ai-matrx/design-system/data-table/host\";\nimport type { AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport {\n applyGroomerPreset,\n customLevers,\n groomerLevers,\n payloadForEnvelope,\n type AlchemyCustomSource,\n type AlchemyDetail,\n type AlchemyGroomerConfig,\n type AlchemyGroomerPreset,\n type AlchemyGroomerSection,\n type EnvelopeMeta,\n} from \"./levers\";\n\nexport type {\n AlchemyCustomSource,\n AlchemyDetail,\n AlchemyGroomerConfig,\n AlchemyGroomerPreset,\n AlchemyGroomerSection,\n AlchemyOptionValues,\n AlchemySourceOption,\n} from \"./levers\";\nexport { applyGroomerPreset } from \"./levers\";\nexport interface AlchemyCopyVariant {\n id: string;\n label: string;\n hint?: string;\n icon?: React.ComponentType<{ className?: string }>;\n section?: \"copy\" | \"ai\";\n ariaLabel?: string;\n successMessage?: string;\n build?: () =>\n AgentPayloadInput | string | Promise<AgentPayloadInput | string>;\n onSelect?: () => void | Promise<void>;\n modal?: (props: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n }) => React.ReactNode;\n /** Opens THE preparation workspace on this content (the rows tree for rows, PP-08). */\n prepare?: () => { payload: Payload; label: string; envelope?: EnvelopeMeta };\n}\nexport interface AlchemyExportItem {\n id: string;\n label: string;\n build?: () => {\n content: BlobPart;\n extension: string;\n mime: string;\n /** Optional exact safe basename captured with bytes; omission derives a default, invalid values error. */\n filename?: string;\n };\n onSelect?: () => void | Promise<void>;\n}\ntype Resolvable<T> = T | (() => T);\nexport interface MatrxCopyMenuProps {\n label: string;\n /** Stable record identity when this mounted control can switch between records. */\n sourceId?: string;\n references?: readonly ContentTransferReference[];\n referenceActions?: readonly ContentTransferReferenceAction[];\n /** Prepare the tabular view while keeping raw JSON and human copy formats. */\n primarySource?: \"table\";\n human?: Resolvable<string>;\n /**\n * What `human` is. \"markdown\" makes it rich text: the main Copy click writes text/plain = the\n * markdown plus text/html = formatted, and the panel leads with \"Copy markdown\" and \"Copy text\".\n * Default \"plain\": a plain string, the existing Text / Markdown tiles.\n */\n contentFlavor?: \"plain\" | \"markdown\";\n /**\n * The host's own rich copy, so one implementation serves every surface (matrx-frontend injects\n * `copyRichContent`). Absent: the package writes the main click and Copy markdown through the session\n * transport and offers no Copy text tile (readable text is the host's one projection).\n */\n richCopy?: (markdown: string, flavor: RichCopyFlavor) => Promise<TransferOutcome | boolean | void> | TransferOutcome | boolean | void;\n /**\n * Which \"Copy markdown\" / \"Copy text\" tiles the panel leads with when `richCopy` is on. A host that\n * already shows those two choices itself (the split Copy's own menu rows) passes `[]` so the panel\n * carries only what is unique to it (Formatted, download, AI). Default: every flavor the host has.\n */\n richCopyFlavors?: readonly (\"markdown\" | \"text\")[];\n /**\n * Model output: every copy of `human` leaves out its reasoning blocks (`<thinking>`, `<think>`,\n * `<reasoning>`), and when it held any the panel offers \"Copy including thinking\" with the full text.\n * A function `human` is never read to decide this (opening the menu prepares nothing), so the\n * variant is offered for a string `human` only.\n */\n stripThinking?: boolean;\n /**\n * Offer \"HTML preview\" for `human` (markdown) when the host bound `capabilities.htmlPreview`.\n * Default true for `contentFlavor=\"markdown\"`; pass false where the host's editable preview is the one action.\n */\n htmlPreview?: boolean;\n json?: Resolvable<unknown>;\n agent?: Resolvable<AgentPayloadInput | string>;\n aiVariants?: AlchemyCopyVariant[];\n aiCustom?: AlchemyCustomSource;\n groomer?: () => AlchemyGroomerConfig;\n agentVariant?: {\n id?: string;\n label?: string;\n hint?: string;\n position?: \"first\" | \"last\";\n };\n export?: {\n items: AlchemyExportItem[];\n /** May be async: a server-paged host hands its whole selected result, read when a format is picked. */\n sheetRows?: () => Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>;\n sheetColumns?: () => Array<{ id: string; label: string }>;\n };\n /** Host-owned authenticated destination, not a second export serializer. */\n sendToSheet?: (\n rows: Array<Record<string, unknown>>,\n label: string,\n ) => Promise<TransferOutcome>;\n hide?: Array<\"copy\" | \"ai\" | \"export\">;\n disabled?: boolean;\n className?: string;\n stopPropagation?: boolean;\n size?: \"xs\" | \"icon\" | \"sm\" | \"toolbar\";\n appearance?: \"bare\" | \"segmented\";\n unified?: boolean;\n grouped?: boolean;\n icon?: AlchemyIcon;\n triggerVariant?: \"transparent\" | \"glass\" | \"outline\";\n /** The full controller, or the table's subset (`TableCopyController`, design-system's copy contract). */\n controllerRef?: React.Ref<ContentTransferController> | React.Ref<TableCopyController>;\n triggerHidden?: boolean;\n}\n/** The longest already-built text the twin check (PP-09) builds when the menu opens. */\nconst TWIN_CHECK_MAX_CHARS = 20_000;\nconst resolve = <T,>(value: Resolvable<T>): T =>\n typeof value === \"function\" ? (value as () => T)() : value;\nconst asPayload = (value: AgentPayloadInput | string): Payload => ({\n kind: \"markdown\",\n text: typeof value === \"string\" ? value : buildAgentPayload(value),\n});\n/** PP-09: a text body stays text (its envelope says so); structured data stays JSON. */\nconst structuredPayload = (value: AgentPayloadInput | string) => payloadForEnvelope(value);\nconst actionDone = (message: string): TransferOutcome => ({\n status: \"success\",\n delivered: \"action\",\n mimeTypes: [],\n message,\n});\nconst isSafeFilename = (filename: string) =>\n filename === filename.trim() &&\n filename.length > 0 &&\n !/^\\.+$/.test(filename) &&\n !/[\\\\/\\x00-\\x1F\\x7F]/.test(filename);\nconst sourceFor = (\n id: string,\n label: string,\n build: () => Payload | Promise<Payload>,\n shape?: SourceShape,\n): ShapedSource => ({\n id,\n label,\n ...(shape ? { shape } : {}),\n capture: async ({ signal }) => {\n signal.throwIfAborted();\n const payload = await build();\n signal.throwIfAborted();\n return directSource(payload, { sourceId: id, label });\n },\n});\n\n/** Opinionated bridge for Matrx's existing content builders, with one transfer UI. */\nexport function MatrxCopyMenu(props: MatrxCopyMenuProps) {\n const inherited = useContentTransferCapabilities();\n return (\n <MatrxCopyMenuSession\n key={JSON.stringify([\n inherited.identityKey ?? null,\n props.sourceId ?? props.label,\n ])}\n {...props}\n />\n );\n}\n\nfunction MatrxCopyMenuSession(props: MatrxCopyMenuProps) {\n const instance = React.useId();\n const controller = React.useRef<ContentTransferController>(null);\n const capabilities = useContentTransferCapabilities();\n const transport = capabilities.transport ?? createBrowserTransport();\n const [modal, setModal] = React.useState<AlchemyCopyVariant | null>(null);\n const copyVisible = !props.hide?.includes(\"copy\");\n const humanSource = (): string => {\n const text = resolve(props.human!);\n return props.stripThinking ? stripThinking(text) : text;\n };\n const richText = props.contentFlavor === \"markdown\" && props.human !== undefined && copyVisible;\n const richCopy = richText\n ? async (flavor: RichCopyFlavor) => {\n const markdown = humanSource();\n if (props.richCopy) return props.richCopy(markdown, flavor);\n const signal = new AbortController().signal;\n const { snapshot } = await capture({ kind: \"markdown\", text: markdown }, signal);\n const draft = createDraft(snapshot);\n // No host projection for \"text\": the package does not invent a second readable-text implementation.\n const artifact = flavor === \"default\" ? await markdownRichArtifact(draft) : serialize(draft, \"markdown\");\n return transport.copy(artifact, signal);\n }\n : undefined;\n const aiVisible = !props.hide?.includes(\"ai\");\n const exportVisible = !props.hide?.includes(\"export\");\n const make = (\n suffix: string,\n build: () => Payload | Promise<Payload>,\n label = props.label,\n shape?: SourceShape,\n ) =>\n sourceFor(\n `${props.sourceId ?? `${instance}:${props.label}`}:${suffix}`,\n label,\n build,\n shape,\n );\n // The menu inspects these by their kind alone, so opening it builds nothing (sec_8f1a9be1…). Only a\n // short, already-built string is cheap enough for the twin check (PP-09) to build it on open.\n const humanCheap =\n typeof props.human === \"string\" && props.human.length <= TWIN_CHECK_MAX_CHARS;\n const human =\n copyVisible && props.human !== undefined\n ? make(\"human\", () => ({ kind: \"text\", text: humanSource() }), props.label, { kind: \"text\", cheap: humanCheap })\n : undefined;\n const humanMarkdown =\n copyVisible && props.human !== undefined\n ? make(\"human-markdown\", () => ({\n kind: \"markdown\",\n text: humanSource(),\n }), props.label, { kind: \"markdown\", cheap: humanCheap })\n : undefined;\n // \"Text\" of Markdown-style text is the host's one plain-text projection of that Markdown (no \"##\",\n // no \"**\"); where that projection is only an echo, the menu offers one of the twins, never both.\n const humanText =\n copyVisible && props.human !== undefined\n ? make(\"human-text\", () => ({\n kind: \"markdown\",\n text: humanSource(),\n }), props.label, { kind: \"markdown\", cheap: humanCheap })\n : undefined;\n const json =\n aiVisible && props.json !== undefined\n ? make(\"json\", () => ({\n kind: \"json\",\n value: normalizeTransferJson(resolve(props.json!), {\n omitUndefinedObjectProperties: true,\n }),\n }), props.label, { kind: \"json\" })\n : undefined;\n const agent =\n aiVisible && props.agent !== undefined\n ? make(\"agent\", () => asPayload(resolve(props.agent!)))\n : undefined;\n const structuredAgent =\n aiVisible && props.agent !== undefined\n ? make(\"structured-agent\", () => structuredPayload(resolve(props.agent!)).payload)\n : undefined;\n const table =\n (exportVisible || props.primarySource === \"table\") &&\n props.export?.sheetRows\n ? make(\"rows\", async () => {\n const value = normalizeTransferJson(await props.export!.sheetRows!(), {\n omitUndefinedObjectProperties: true,\n });\n if (\n !Array.isArray(value) ||\n value.some(\n (row) =>\n row === null || typeof row !== \"object\" || Array.isArray(row),\n )\n )\n throw new Error(\"Sheet rows must be JSON objects.\");\n const rows = value as Array<\n Record<string, import(\"@ai-matrx/alchemy/operate\").Json>\n >;\n const suppliedColumns = props.export!.sheetColumns?.();\n const columns = suppliedColumns ?? [...new Set(rows.flatMap((row) => Object.keys(row)))].map((id) => ({ id, label: id }));\n const ids = new Set<string>();\n for (const column of columns) {\n if (!column.id || !column.label || ids.has(column.id)) throw new Error(\"Sheet columns require unique nonempty ids and labels.\");\n ids.add(column.id);\n }\n for (const row of rows) for (const key of Object.keys(row)) if (!ids.has(key)) throw new Error(\"Table data contains a field outside its declared columns.\");\n return {\n kind: \"rows\",\n rows,\n columns: columns.map((column) => ({\n id: column.id,\n label: column.label,\n path: `/${column.id.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`,\n visible: true,\n })),\n };\n })\n : undefined;\n const builderVariants = aiVisible\n ? (props.aiVariants ?? [])\n .filter(\n (variant) => variant.build && !variant.onSelect && !variant.modal && !variant.prepare,\n )\n .map((variant) => ({\n ...variant,\n copyLabel: variant.label,\n source: make(\n `variant:${variant.id}`,\n async () => asPayload(await variant.build!()),\n variant.label,\n ),\n }))\n : [];\n const faithful = agent\n ? [\n {\n id: props.agentVariant?.id ?? \"faithful\",\n label: props.agentVariant?.label ?? \"Full AI context\",\n source: agent,\n copyLabel: props.agentVariant?.label ?? \"Copy for AI\",\n ...(props.agentVariant?.hint\n ? { hint: props.agentVariant.hint }\n : {}),\n },\n ]\n : [];\n // The full text is its own source: it never passes through the strip.\n const thinkingVariants =\n copyVisible && props.stripThinking && typeof props.human === \"string\" && hasThinking(props.human)\n ? [\n {\n id: \"include-thinking\",\n label: \"Including thinking\",\n copyLabel: \"Copy including thinking\",\n hint: \"Includes the original reasoning content\",\n section: \"copy\" as const,\n source: make(\"include-thinking\", () => ({ kind: \"markdown\", text: props.human as string }), props.label, { kind: \"markdown\", cheap: false }),\n },\n ]\n : [];\n const variants =\n props.agentVariant?.position === \"last\"\n ? [...thinkingVariants, ...builderVariants, ...faithful]\n : [...thinkingVariants, ...faithful, ...builderVariants];\n const actions: (PageAction & TransferMenuPresentation)[] = [];\n if (aiVisible)\n for (const variant of props.aiVariants ?? []) {\n if (!variant.onSelect && !variant.modal && !variant.prepare) continue;\n actions.push({\n ...variant,\n id: `variant-action:${variant.id}`,\n label: variant.label,\n // A door into THE preparation workspace sits in \"Edit and prepare\" (never a heading of its own).\n ...(variant.prepare ? { placement: \"prepare\" as const } : {}),\n supports: () => true,\n run: async () => {\n if (variant.prepare) {\n // PP-08: the door opens THE preparation workspace (the rows tree), not a second dialog.\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n const prepared = variant.prepare();\n await controller.current.prepare(prepared.payload, { id: `${instance}:${variant.id}`, label: prepared.label, ...(prepared.envelope ? { envelope: prepared.envelope } : {}) });\n } else if (variant.onSelect) await variant.onSelect();\n else setModal(variant);\n return actionDone(`Opened ${variant.label}`);\n },\n });\n }\n if (aiVisible && props.aiCustom)\n actions.push({\n id: \"configure-source\",\n label: props.aiCustom.label ?? \"Customize source\",\n ...(props.aiCustom.hint ? { hint: props.aiCustom.hint } : {}),\n supports: () => true,\n run: async () => {\n // PP-02: the levers open INSIDE the one workspace, beside the preview.\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n await controller.current.prepareLevers(customLevers(props.aiCustom!), {\n id: `${instance}:custom`,\n label: props.aiCustom!.dialogTitle ?? props.label,\n });\n return actionDone(\"Source options opened\");\n },\n });\n if (aiVisible && props.groomer)\n actions.push({\n id: \"groom-source\",\n label: \"Customize sections\",\n supports: () => true,\n run: async () => {\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n const config = props.groomer!();\n await controller.current.prepareLevers(groomerLevers(config), {\n id: `${instance}:groomer`,\n label: config.label,\n });\n return actionDone(\"Section options opened\");\n },\n });\n if (exportVisible)\n for (const item of props.export?.items ?? [])\n actions.push({\n id: `export:${item.id}`,\n label: item.label,\n supports: () => true,\n ...(item.build && !item.onSelect\n ? {\n placement: \"download\" as const,\n source: make(\n `export:${item.id}`,\n async () => {\n const file = item.build!();\n const bytes = new Uint8Array(\n await new Blob([file.content], {\n type: file.mime,\n }).arrayBuffer(),\n );\n return {\n kind: \"registered\",\n format: \"matrx-file\",\n value: {\n bytes: Array.from(bytes),\n mime: file.mime,\n extension: file.extension,\n ...(file.filename !== undefined\n ? { filename: file.filename }\n : {}),\n },\n };\n },\n item.label,\n ),\n }\n : {}),\n run: async ({ snapshot, draft, signal }) => {\n if (item.onSelect) {\n await item.onSelect();\n return actionDone(`Opened ${item.label}`);\n }\n const value =\n draft.payload.kind === \"registered\" ? draft.payload.value : null;\n if (\n !value ||\n Array.isArray(value) ||\n typeof value !== \"object\" ||\n !Array.isArray(value.bytes) ||\n typeof value.mime !== \"string\" ||\n typeof value.extension !== \"string\" ||\n value.bytes.some(\n (byte) =>\n typeof byte !== \"number\" ||\n !Number.isInteger(byte) ||\n byte < 0 ||\n byte > 255,\n )\n )\n throw new Error(`${item.label} did not capture a valid file.`);\n if (\n value.filename !== undefined &&\n (typeof value.filename !== \"string\" ||\n !isSafeFilename(value.filename))\n )\n throw new Error(\n `${item.label} has an unsafe filename. Use a nonempty basename without leading or trailing whitespace, dots only, path separators, or control characters.`,\n );\n if (\n draft.omissions.some((omission) => omission.reason !== \"duplicate\")\n )\n throw new Error(\n \"This custom file exceeds the configured export limits or contains excluded content. Use a standard format or revise the source options.\",\n );\n const bytes = new Uint8Array(value.bytes as number[]);\n const filename =\n typeof value.filename === \"string\"\n ? value.filename\n : `${\n props.label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\") || \"export\"\n }.${value.extension.replace(/[^a-zA-Z0-9.-]/g, \"\") || \"bin\"}`;\n return transport.download(\n sealTransferArtifact({\n snapshotId: snapshot.id,\n draftRevision: draft.revision,\n format: `export:${item.id}`,\n plainText: \"\",\n file: { filename, mime: value.mime, bytes },\n omissions: [...draft.omissions],\n }),\n signal,\n );\n },\n });\n if (exportVisible && table && props.sendToSheet)\n actions.push({\n id: \"send-google-sheet\",\n label: \"Send to Google Sheet\",\n source: table,\n supports: () => true,\n run: async ({ draft }) => {\n if (draft.payload.kind !== \"rows\")\n throw new Error(\"Google Sheets requires captured rows.\");\n return props.sendToSheet!(draft.payload.rows, props.label);\n },\n });\n const source =\n (props.primarySource === \"table\" ? table : undefined) ??\n json ??\n table ??\n structuredAgent ??\n human ??\n builderVariants[0]?.source;\n if (!source && !actions.length) return null;\n // Action-only targets carry an explicit description, never invented record data.\n const target =\n source ?? make(\"actions\", () => ({ kind: \"text\", text: props.label }));\n return (\n <>\n <ContentTransferMenu\n triggerSize={props.size === \"xs\" || props.size === \"toolbar\" ? \"compact\" : \"default\"}\n source={target}\n {...(source && source === structuredAgent\n ? { envelope: () => structuredPayload(resolve(props.agent!)).envelope }\n : {})}\n {...(props.references ? { references: props.references } : {})}\n {...(props.referenceActions ? { referenceActions: props.referenceActions } : {})}\n {...(props.icon !== undefined ? { icon: props.icon } : {})}\n {...(props.triggerVariant !== undefined\n ? { triggerVariant: props.triggerVariant }\n : {})}\n controllerRef={(value) => {\n controller.current = value;\n if (typeof props.controllerRef === \"function\") props.controllerRef(value);\n else if (props.controllerRef) (props.controllerRef as React.MutableRefObject<ContentTransferController | null>).current = value;\n }}\n {...(props.triggerHidden ? { triggerHidden: true } : {})}\n {...(richCopy ? { richCopy, ...(props.richCopyFlavors ? { richCopyFlavors: props.richCopyFlavors } : props.richCopy ? {} : { richCopyFlavors: [\"markdown\" as const] }) } : {})}\n label={props.label}\n {...(aiVisible && props.aiCustom\n ? {\n copyWithPrompt: async () => {\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n await controller.current.prepareLevers(customLevers(props.aiCustom!), {\n id: `${instance}:custom`,\n label: props.aiCustom!.dialogTitle ?? props.label,\n });\n },\n }\n : {})}\n variants={variants}\n actions={actions}\n {...(richText && props.htmlPreview !== false ? { htmlPreview: true } : {})}\n sourceFormats={Boolean(source)}\n hide={[\n ...(!copyVisible || !source ? [\"copy\" as const] : []),\n ...(!aiVisible || !source ? [\"prepare\" as const] : []),\n ...(!exportVisible ? [\"download\" as const] : []),\n ]}\n formatSources={{\n ...(human\n ? { plain: humanText!, markdown: humanMarkdown!, html: humanMarkdown! }\n : {}),\n ...(json ? { json, \"compact-json\": json } : {}),\n ...(table && exportVisible ? { csv: table, tsv: table } : {}),\n }}\n {...(props.disabled !== undefined ? { disabled: props.disabled } : {})}\n className={cn(\n props.className,\n props.size === \"xs\" && \"matrx-alchemy-xs\",\n props.size === \"sm\" && \"matrx-alchemy-sm\",\n props.size === \"toolbar\" && \"matrx-alchemy-toolbar-target\",\n )}\n {...(props.stopPropagation !== undefined\n ? { stopPropagation: props.stopPropagation }\n : {})}\n />\n {modal?.modal?.({\n open: true,\n onOpenChange: (open) => {\n if (!open) setModal(null);\n },\n })}\n </>\n );\n}\n\nexport const GROOMER_LEVELS: AlchemyDetail[] = [\"full\", \"compact\", \"brief\"];\nexport function defaultGroomerSelections(\n sections: AlchemyGroomerSection[],\n): Record<string, AlchemyDetail | \"off\"> {\n return Object.fromEntries(\n sections.map((section) => [section.id, section.defaultSelection ?? \"full\"]),\n );\n}\nexport function buildGroomerPresetPayload(\n config: AlchemyGroomerConfig,\n preset: AlchemyGroomerPreset,\n): AgentPayloadInput {\n const selections = applyGroomerPreset(preset, config.sections);\n const data: Record<string, unknown> = {};\n const dropped: string[] = [];\n for (const section of config.sections) {\n const selection = selections[section.id] ?? \"full\";\n if (selection === \"off\") {\n dropped.push(section.id);\n continue;\n }\n const value = section.build(selection);\n if (value !== undefined && value !== null) data[section.id] = value;\n }\n return {\n kind: config.kind,\n location: config.location,\n description:\n preset === \"everything\"\n ? config.description\n : `${config.description} (${preset} detail)`,\n data,\n ...(config.summary !== undefined ? { summary: config.summary } : {}),\n attributes: {\n ...config.attributes,\n detail: preset,\n ...(dropped.length ? { dropped_sections: dropped.join(\",\") } : {}),\n },\n ...(config.context ? { context: config.context } : {}),\n };\n}\nexport function groomerPresetVariants(\n getConfig: () => AlchemyGroomerConfig,\n): AlchemyCopyVariant[] {\n return [\n {\n id: \"balanced\",\n label: \"Balanced\",\n hint: \"Compact sections\",\n build: () => buildGroomerPresetPayload(getConfig(), \"balanced\"),\n },\n {\n id: \"minimal\",\n label: \"Minimal\",\n hint: \"Brief sections with optional detail excluded\",\n build: () => buildGroomerPresetPayload(getConfig(), \"minimal\"),\n },\n ];\n}\n","\"use client\";\n\nimport type { CopyControlProps } from \"@ai-matrx/design-system/data-table/host\";\nimport { MatrxCopyMenu } from \"./matrx-copy\";\n\n/**\n * THE table copy control (ALC-16): what a host binds as `MatrxDataTableHost.CopyControls`.\n * design-system's table sits below alchemy, so it speaks only the copy contract\n * (`CopyControlProps`); this answers it with the one Alchemy menu.\n */\nexport function AlchemyTableCopyControls(props: CopyControlProps) {\n return <MatrxCopyMenu {...props} />;\n}\n"],"mappings":";aAEA,UAAY,UAAW,QAEvB,OAAS,WAAc,0BACvB,OAAS,OAAQ,cAAe,kBAAmB,aAAc,aAAc,gBAAmB,0BAkG1F,WACA,SADA,oBAxFR,IAAM,UAAY,KAAwB,CAAE,OAAQ,WAAY,GAC1D,OAAU,QAAqC,CACnD,OAAQ,QACR,KAAM,eACN,QAAS,iBAAiB,MAAQ,MA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AU,2CAA2C,aAAW,yBAAyB,eAAgB,mBAAoB,eAAgB,qBAAsB,iBAAkB,IAAM,WAAW,SAAS,MAAM,EAAI,iBAAQ,GAAiB,EAAa,KACrnD,eAAiB,YAAcgB,cAAahB,KAAC,OAAI,UAAU,2CAA2C,KAAK,SAAS,aAAW,yBAA0B,iBAAQ,EAAQ,aAAa,EAAI,KAC1L,QAAU,cAAgBgB,cAAaf,MAAC,OAAI,UAAU,yBAAyB,eAAgB,iBAAkB,eAAgB,iBAAkB,UAAAD,KAAC,QAAK,KAAK,SAAU,gBAAO,EAAOA,KAAC,aAAY,OAAQ,cAAc,EAAEA,KAAC,UAAO,KAAK,SAAS,aAAW,2BAA2B,QAAS,IAAM,UAAU,IAAI,EAAG,gBAAC,GAAS,EAAQ,cAAc,cAAc,IAAI,EAAI,KAC7W,OAAO,OAAO,UAAU,EAAE,IAAK,OAAUA,KAAC,sBAAqB,YAAa,eAAiB,MAAM,IAAM,YAAc,EAAG,aAAc,IAAM,gBAAgB,UAAU,GAAK,WAAW,SAAS,MAAM,EAAmB,MAAO,WAAa,OAAS,SAAU,WAAY,YAAY,MAAM,GAAG,GAAK,KAAM,KAAM,eAAiB,eAAiB,MAAM,IAAK,MAAO,MAAO,OAAgB,YAAa,OAAO,YAAa,QAAS,IAAM,iBAAiB,EAAK,EAAG,SAAW,MAAS,cAAe,UAAa,CAAE,GAAG,QAAS,CAAC,MAAM,GAAG,EAAG,IAAK,EAAE,EAAG,UAAsB,SAAoB,QAAS,gBAAiB,aAAc,kBAAkB,QAAQ,IAAI,MAAM,GAAG,GAAK,eAAiB,GAAI,GAAK,CAAE,EAAG,EAAI,CAAC,EAAI,UAAW,QAA9f,MAAM,GAA+f,CAAE,EACttB,aACH,CACF","names":["resolve","React","createPortal","applyTransferLimits","capture","buildAgentPayload","createBrowserTransport","createDraft","directSource","projectSnapshot","resolveTransferPreferences","sealTransferArtifact","serialize","Button","cn","React","jsx","jsxs","React","formatCount","concretePointers","patternCovers","readTransferCell","resetDraft","sealTransferArtifact","serialize","Button","Dialog","DialogContent","DialogDescription","DialogHeader","DialogTitle","React","formatCount","pointerSegments","jsx","jsxs","formatCount","pointerSegments","Fragment","jsx","jsxs","serialize","layout","concretePointers","sealTransferArtifact","resetDraft","formatCount","structure","patternCovers","Button","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","readTransferCell","readTransferCell","sealTransferArtifact","serialize","useContentTransferSurface","React","createDraft","serialize","directSource","normalizeTransferJson","sealTransferArtifact","cn","Fragment","jsx","jsxs","directSource","createDraft","serialize","normalizeTransferJson","sealTransferArtifact","cn","jsx","Fragment","jsx","jsxs","cn","createBrowserTransport","resolveTransferPreferences","directSource","capture","projectSnapshot","createDraft","applyTransferLimits","handle","label","sealTransferArtifact","serialize","buildAgentPayload","Button","createPortal"]}
|
|
1
|
+
{"version":3,"sources":["../src/react/workspace/email-review.tsx","../src/react/workspace/index.tsx","../src/react/workspace/workspace-core.tsx","../src/react/workspace/workspace.tsx","../src/react/workspace/levers.ts","../src/react/workspace/workspace-tree.tsx","../src/react/workspace/extensions.ts","../src/react/workspace/matrx-copy.tsx","../src/react/workspace/table-copy-controls.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { Artifact, TransferOutcome } from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@ai-matrx/design-system\";\nimport type { ContentTransferEmailPort } from \"./extensions\";\n\ntype PendingEmail = {\n artifact: Artifact;\n context: { label: string; signal: AbortSignal };\n resolve(outcome: TransferOutcome): void;\n onAbort(): void;\n};\n\nconst cancelled = (): TransferOutcome => ({ status: \"cancelled\" });\nconst failed = (error: unknown): TransferOutcome => ({\n status: \"error\",\n code: \"email-failed\",\n message: error instanceof Error ? error.message : \"Could not send email.\",\n retryable: true,\n});\n\n/** Adds one explicit review step without changing the sealed artifact handed to the host. */\nexport function useReviewedTransferEmail(email?: ContentTransferEmailPort): {\n email: ContentTransferEmailPort | undefined;\n review: React.ReactNode;\n} {\n const [pending, setPending] = React.useState<PendingEmail | null>(null);\n const [sending, setSending] = React.useState(false);\n const pendingRef = React.useRef<PendingEmail | null>(null);\n const sendingRef = React.useRef(false);\n\n const settle = React.useCallback((request: PendingEmail, outcome: TransferOutcome, render = true) => {\n if (pendingRef.current !== request) return;\n pendingRef.current = null;\n request.context.signal.removeEventListener(\"abort\", request.onAbort);\n request.resolve(outcome);\n sendingRef.current = false;\n if (render) {\n setSending(false);\n setPending(null);\n }\n }, []);\n\n React.useEffect(\n () => () => {\n const request = pendingRef.current;\n if (!request) return;\n pendingRef.current = null;\n request.context.signal.removeEventListener(\"abort\", request.onAbort);\n request.resolve(cancelled());\n sendingRef.current = false;\n },\n [],\n );\n\n const reviewed = React.useMemo<ContentTransferEmailPort | undefined>(() => {\n if (!email) return undefined;\n return {\n send: (artifact, context) => {\n if (context.signal.aborted) return Promise.resolve(cancelled());\n if (pendingRef.current)\n return Promise.resolve({\n status: \"error\",\n code: \"email-review-active\",\n message: \"Finish reviewing the current email before starting another.\",\n retryable: true,\n });\n return new Promise<TransferOutcome>((resolve) => {\n const request: PendingEmail = {\n artifact,\n context,\n resolve,\n onAbort: () => settle(request, cancelled()),\n };\n pendingRef.current = request;\n context.signal.addEventListener(\"abort\", request.onAbort, { once: true });\n setSending(false);\n setPending(request);\n });\n },\n };\n }, [email, settle]);\n\n const cancel = React.useCallback(() => {\n const request = pendingRef.current;\n if (request && !sendingRef.current) settle(request, cancelled());\n }, [settle]);\n const confirm = React.useCallback(() => {\n const request = pendingRef.current;\n if (!request || sendingRef.current || request.context.signal.aborted) return;\n sendingRef.current = true;\n setSending(true);\n void email?.send(request.artifact, request.context).then(\n (outcome) => settle(request, outcome),\n (error) => settle(request, failed(error)),\n );\n }, [email, settle]);\n\n const review = pending ? <Dialog open onOpenChange={(open) => { if (!open) cancel(); }}>\n <DialogContent className=\"matrx-alchemy-workspace matrx-alchemy-email-review\" aria-busy={sending}>\n <DialogHeader>\n <DialogTitle>Review email attachment</DialogTitle>\n <DialogDescription>Email {pending.artifact.file?.filename ?? `${pending.artifact.format} output`} from {pending.context.label}. Review this exact attachment before sending.</DialogDescription>\n </DialogHeader>\n <textarea aria-label=\"Email attachment preview\" readOnly value={pending.artifact.plainText} className=\"matrx-alchemy-preview\" />\n {pending.artifact.omissions.length ? <details className=\"matrx-alchemy-email-adjustments\" open><summary>{pending.artifact.omissions.length} omission{pending.artifact.omissions.length === 1 ? \"\" : \"s\"} or adjustment{pending.artifact.omissions.length === 1 ? \"\" : \"s\"}</summary><ul >{pending.artifact.omissions.map((omission, index) => <li key={`${omission.path}-${omission.reason}-${index}`}>{omission.path || \"/\"}: {omission.reason}{omission.count == null ? \"\" : ` (${omission.count})`}</li>)}</ul></details> : <p className=\"matrx-alchemy-meta\">No omissions or adjustments.</p>}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={sending} onClick={cancel}>Cancel</Button>\n <Button type=\"button\" className=\"matrx-alchemy-workspace-primary\" disabled={sending} onClick={confirm}>{sending ? \"Sending email…\" : \"Send email\"}</Button>\n </DialogFooter>\n </DialogContent>\n </Dialog> : null;\n\n return { email: reviewed, review };\n}\n","\"use client\";\n\nimport { useReviewedTransferEmail } from \"./email-review\";\nimport { useContentTransferSurface } from \"@ai-matrx/alchemy/react/surface\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n applyTransferLimits,\n capture,\n buildAgentPayload,\n collectAllMatching,\n createBrowserTransport,\n createDraft,\n directSource,\n projectSnapshot,\n resolveTransferPreferences,\n resolveTransferRegistry,\n sealTransferArtifact,\n serialize,\n type BoundAllMatching,\n type ExportProjection,\n type FormatAdapter,\n type PageAction,\n type Payload,\n type Section,\n type Source,\n type SurfaceHandle,\n type AiPreparation,\n type TransferOutcome,\n type TransferTarget,\n type TransferPreferenceOverrides,\n type TransferScope,\n type Transport,\n} from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport {\n BUILT_INS,\n COPIES,\n DestinationPresentation,\n DOWNLOADS,\n EMPTY_VARIANTS,\n LABEL,\n MenuPresentation,\n PaletteGlyph,\n ReceiptLink,\n SCOPE_LABEL,\n buildFormat,\n buildWithAdapter,\n errorMessage,\n initialControls,\n isBuiltInFormat,\n materialIdentity,\n offersFormat,\n outcomeMessage,\n rebuild,\n snapshotContent,\n useFence,\n type BuiltInFormat,\n type CaptureResult,\n type SerializableFormat,\n type WorkspaceState,\n} from \"./workspace-core\";\nimport { PreparationWorkspace, WorkspaceWindowSlot, setWorkspaceSessionLive, type WorkspaceWindowHandle, type WorkspaceWindowPort } from \"./workspace\";\nimport { leverSnapshot, type EnvelopeMeta, type WorkspaceLevers } from \"./levers\";\nexport type { SerializableFormat } from \"./workspace-core\";\nexport type { WorkspaceWindowHandle, WorkspaceWindowPort } from \"./workspace\";\nexport type { EnvelopeMeta, WorkspaceLevers } from \"./levers\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@ai-matrx/design-system\";\nimport { TapTargetButton, TapTargetButtonTransparent } from \"@ai-matrx/design-system/tap-target\";\nimport { ALCHEMY_GLYPH_VIEWBOX, ALCHEMY_GLYPH_PATHS, type AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\nexport { ALCHEMY_GLYPH_SVG, ALCHEMY_COPY_TRANSFORM_SVG, type AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\n\nimport { createTransferEmailActions, createTransferHtmlPreviewAction, type ContentTransferReference, type ContentTransferReferencePort, type ContentTransferEmailPort, type ContentTransferHtmlPreviewPort } from \"./extensions\";\nexport { tableSchemaFormat, tableDataFormat, createTransferEmailActions, createTransferHtmlPreviewAction, type ContentTransferReference, type ContentTransferReferencePort, type ContentTransferEmailPort, type ContentTransferHtmlPreviewPort } from \"./extensions\";\nexport type ContentTransferReferenceAction = { id: string; label: string; run(): void | Promise<void> };\n\nexport function AlchemyGlyph({ icon = \"portal\", ...props }: React.SVGAttributes<SVGSVGElement> & { icon?: AlchemyIcon }) {\n return <svg width=\"18\" height=\"18\" viewBox={ALCHEMY_GLYPH_VIEWBOX[icon]} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" {...props}>{ALCHEMY_GLYPH_PATHS[icon].map((d) => <path key={d} d={d}/>)}</svg>;\n}\n\n/** What a host injects into the menu: lazy format adapters (`@ai-matrx/alchemy/operate`) and AI preparation. */\nexport type TransferCapabilities = { formats?: FormatAdapter[]; ai?: AiPreparation };\nexport type ContentTransferCapabilities = TransferCapabilities & {\n /** Opaque host session boundary. It is used only to reset local menu state. */\n identityKey?: string;\n transport?: Transport;\n reference?: ContentTransferReferencePort;\n email?: ContentTransferEmailPort;\n /** The host's HTML preview. Bound: a menu mounted with `htmlPreview` offers the \"HTML preview\" action. */\n htmlPreview?: ContentTransferHtmlPreviewPort;\n actions?: PageAction[];\n preferences?: TransferPreferenceOverrides;\n onOutcome?: (outcome: TransferOutcome) => void;\n /**\n * The host's window system (structurally `@ai-matrx/alchemy/ports` `WindowPort`, PP-01a). Bound:\n * the preparation workspace opens inside a host window (WindowPanel in the web app, an honest\n * full-screen dialog in the dashboard). Unbound: a near-full-screen dialog.\n */\n window?: WorkspaceWindowPort;\n};\nconst CapabilityContext = React.createContext<ContentTransferCapabilities>({});\nexport function ContentTransferCapabilitiesProvider({ value, children }: { value: ContentTransferCapabilities; children: React.ReactNode }) {\n return <CapabilityContext.Provider value={value}>{children}</CapabilityContext.Provider>;\n}\nexport const useContentTransferCapabilities = () => React.useContext(CapabilityContext);\n// ONE surface context, owned by the light `/react/surface` entry (imported by public name so the\n// built entries share it; a relative import would inline a second context into this bundle).\nexport { ContentTransferSurfaceProvider, useContentTransferSurface } from \"@ai-matrx/alchemy/react/surface\";\n\nexport interface TransferMenuPresentation {\n group?: \"save\" | \"chat\" | \"email\";\n prepared?: boolean;\n hint?: string;\n icon?: React.ComponentType<{ className?: string }>;\n ariaLabel?: string;\n /**\n * Download-only actions join the shared format palette instead of a second menu. A \"prepare\"\n * action opens THE preparation workspace (the table's \"Filter & sort before copying…\" door) and\n * sits in \"Edit and prepare\", where people look for it — never under a heading of its own.\n */\n placement?: \"download\" | \"prepare\";\n}\n/**\n * THE PALETTE'S HEADINGS — a closed list. A host never supplies a heading: an action picks one of\n * the named `group`s or its row shows INLINE with no heading (the approved-heading rule of\n * `@ai-matrx/alchemy/menu`; a container word such as \"Actions\" or \"More…\" is never a heading).\n */\nexport const PALETTE_HEADINGS = [\"Copy as\", \"Download as\", \"Quick copy\", \"Copy for AI\", \"Edit and prepare\", \"Other sources\", \"References\", \"Save to Matrx\", \"Continue with AI\", \"Email to me\"] as const;\nexport type PaletteHeading = (typeof PALETTE_HEADINGS)[number];\nconst DESTINATION_HEADING: Record<NonNullable<TransferMenuPresentation[\"group\"]>, PaletteHeading> = { save: \"Save to Matrx\", chat: \"Continue with AI\", email: \"Email to me\" };\nexport interface TransferMenuVariant extends TransferMenuPresentation {\n id: string; label: string; source: Source | Payload;\n copyLabel?: string;\n section?: \"copy\" | \"ai\";\n successMessage?: string;\n}\nfunction PaletteRows({ title, items, onRun, extra, ai = false, glyphKind, fallbackHint }: { title: PaletteHeading; items: readonly TransferMenuVariant[]; onRun?: (item: TransferMenuVariant) => void; extra?: React.ReactNode; ai?: boolean; glyphKind?: \"ai-copy\" | \"sliders\"; fallbackHint?: string }) {\n if (!items.length && !extra) return null;\n return <section className=\"matrx-alchemy-palette-section\"><h3>{title}</h3>{items.map((item) => { const label = item.copyLabel ?? item.label; const hint = item.hint ?? fallbackHint; return <button key={item.id} type=\"button\" className={cn(\"matrx-alchemy-palette-row\", ai && \"matrx-alchemy-palette-row-ai\")} aria-label={item.ariaLabel ?? `${label}${hint ? ` ${hint}` : \"\"}`} onClick={() => onRun?.(item)}>{item.icon ? <item.icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph ai={ai} {...(glyphKind ? { kind: glyphKind } : {})}/>}<span>{label}{hint ? <small className=\"matrx-alchemy-menu-hint\">{hint}</small> : null}</span></button>; })}{extra}</section>;\n}\nexport interface ContentTransferMenuProps {\n source?: Payload | Source;\n projection?: ExportProjection;\n sections?: Section[];\n preferences?: TransferPreferenceOverrides;\n enabled?: boolean;\n surface?: SurfaceHandle;\n label?: string;\n /**\n * Tabular sources. `size` is the live size the host knows (\"1,240 rows · 12 columns\"): the\n * palette's \"Filter & sort before copying…\" door shows it (PP-08).\n */\n table?: { availableScopes: TransferScope[]; initialScope: TransferScope; scopeLabels?: Partial<Record<TransferScope, string>>; size?: string };\n references?: readonly ContentTransferReference[];\n referenceActions?: readonly ContentTransferReferenceAction[];\n /** A quick format may explicitly capture a different representation. */\n formatSources?: Partial<Record<SerializableFormat, Source | Payload>>;\n /** Set false for action-only hosts; source formats and adapters are then omitted. */\n sourceFormats?: boolean;\n /** Named alternate sources open this same preparation workspace. */\n variants?: readonly TransferMenuVariant[];\n actions?: (PageAction & TransferMenuPresentation)[];\n /** Offer \"HTML preview\" (Markdown and text only) when the host bound `capabilities.htmlPreview`. */\n htmlPreview?: boolean;\n capabilities?: ContentTransferCapabilities;\n disabled?: boolean;\n /** Portal is the default Alchemy mark; copy-transform remains opt-in. */\n icon?: AlchemyIcon;\n /** Uses the canonical TapTargetButton presentation. */\n triggerVariant?: \"transparent\" | \"glass\" | \"outline\";\n triggerSize?: \"default\" | \"compact\";\n /** Mount the transfer session without a visible trigger for a host-owned menu command. */\n triggerHidden?: boolean;\n className?: string;\n stopPropagation?: boolean;\n hide?: readonly (\"copy\" | \"prepare\" | \"download\")[];\n controllerRef?: React.Ref<ContentTransferController>;\n /** Who the primary source is, for the AI envelope (PP-10); read when the workspace opens. */\n envelope?: () => EnvelopeMeta | undefined;\n /**\n * Rich-text hosts: one implementation of the three copies. The main Copy click runs \"default\"\n * (text/plain = markdown AND text/html = formatted); the panel leads with \"Copy as Markdown\",\n * \"Copy content\" and \"Copy formatted\". When set, the plain / Markdown / Formatted tiles give way.\n */\n richCopy?: RichCopyRunner;\n /** The flavors the runner can honestly produce as tiles (default both). A host with no readable-text projection omits \"text\". */\n richCopyFlavors?: readonly Exclude<RichCopyFlavor, \"default\">[];\n /**\n * \"Copy with prompt…\": opens the host's richest composer (its levers) with the instructions box\n * focused. Absent: the primary workspace opens instead.\n */\n copyWithPrompt?: () => Promise<void>;\n}\nexport type RichCopyFlavor = \"default\" | \"markdown\" | \"text\" | \"formatted\";\n/** THE three names of a rich copy (Arman, 2026-10-11) — the host's rows carry the same words. */\nexport const RICH_COPY_LABELS = { markdown: \"Copy as Markdown\", text: \"Copy content\", formatted: \"Copy formatted\" } as const;\nexport type RichCopyRunner = (flavor: RichCopyFlavor) => Promise<TransferOutcome | boolean | void> | TransferOutcome | boolean | void;\nexport interface ContentTransferController {\n focusTrigger(): void;\n /** Mount the one canonical Alchemy palette in a host-owned menu surface. */\n mountPalette(target: HTMLElement | null, onClose?: () => void, restoreFocus?: () => void): void;\n preparePrimary(options?: { restoreFocus?: () => void }): Promise<void>;\n prepare(source: Source | Payload, options?: { id?: string; label?: string; envelope?: EnvelopeMeta }): Promise<void>;\n /** Open the workspace on a host's own levers (aiCustom / groomer): the levers live beside the preview (PP-02). */\n prepareLevers(levers: WorkspaceLevers, options: { id: string; label: string }): Promise<void>;\n}\n\n\nexport function ContentTransferMenu(props: ContentTransferMenuProps) {\n const inherited = React.useContext(CapabilityContext);\n const identityKey = props.capabilities?.identityKey ?? inherited.identityKey;\n return <ContentTransferMenuSession key={identityKey ?? \"anonymous\"} {...props} />;\n}\n\n/**\n * What a source can say about itself without being built: its payload kind (and a text's language),\n * and whether building it is cheap. The menu inspects a source that declares its shape by the shape\n * alone, so opening the menu never builds the content — a person's pick does (sec_8f1a9be1…: a\n * 1,636-organization page capture froze its page for 4.1 s on open). `cheap` sources (a short,\n * already-built string) still take part in the twin check (PP-09); anything else is never built\n * to decide which items to show.\n */\nexport type SourceShape = { kind: \"text\" | \"markdown\" | \"json\"; language?: string; cheap?: boolean };\nexport type ShapedSource = Source & { shape?: SourceShape };\nconst shapeOf = (material: Source | Payload | SurfaceHandle | null | undefined): SourceShape | undefined =>\n material && !(\"kind\" in material) && !(\"instanceId\" in material) ? (material as ShapedSource).shape : undefined;\n/** The empty payload of a declared shape: what the menu's show-or-hide rules read, never content. */\nconst shapePayload = (shape: SourceShape): Payload =>\n shape.kind === \"json\" ? { kind: \"json\", value: {} } : shape.kind === \"markdown\" ? { kind: \"markdown\", text: \"\" } : { kind: \"text\", text: \"\", ...(shape.language ? { language: shape.language } : {}) };\n\n/** How long a non-copy notice stays (download started, action done, degraded copy). */\nexport const NOTICE_MS = 4000;\n/** Failures stay longer — never less than five seconds. */\nexport const NOTICE_ERROR_MS = 8000;\n\nfunction ContentTransferMenuSession({ references = [], referenceActions = [], source, surface, label, projection, sections, preferences, table, formatSources, sourceFormats = true, variants = EMPTY_VARIANTS, actions = [], htmlPreview = false, capabilities: local, disabled, enabled = true, className, stopPropagation = true, hide = [], controllerRef, icon = \"portal\", triggerVariant = \"transparent\", triggerSize = \"default\", triggerHidden = false, envelope: primaryEnvelope, richCopy, richCopyFlavors = [\"markdown\", \"text\", \"formatted\"], copyWithPrompt }: ContentTransferMenuProps) {\n const [promptFocus, setPromptFocus] = React.useState(0);\n const triggerRef = React.useRef<HTMLButtonElement>(null);\n const restoreFocusRef = React.useRef<(() => void) | null>(null);\n const inherited = React.useContext(CapabilityContext);\n const nearestSurface = useContentTransferSurface();\n const fence = useFence();\n const inspectionFence = useFence();\n const [copiedFormat, setCopiedFormat] = React.useState<string | null>(null);\n const copiedTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const leaveTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const clipboardQueue = React.useRef<Promise<unknown>>(Promise.resolve());\n React.useEffect(() => () => {\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n }, []);\n const confirmCopy = React.useCallback((format: string) => {\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(format);\n copiedTimer.current = setTimeout(() => setCopiedFormat(null), 3000);\n }, []);\n const [menuCapture, setMenuCapture] = React.useState<CaptureResult | null>(null);\n const [menuStatus, setMenuStatus] = React.useState<\"idle\" | \"loading\" | string>(\"idle\");\n const [workspaces, setWorkspaces] = React.useState<Record<string, WorkspaceState>>({});\n const [workspaceKey, setWorkspaceKey] = React.useState<string | null>(null);\n const [workspaceOpen, setWorkspaceOpen] = React.useState(false);\n const workspaceCaptures = React.useRef(new Map<string, (scope: TransferScope, signal: AbortSignal) => Promise<CaptureResult>>());\n const externalWorkspaceKeys = React.useRef(new Set<string>());\n const [notice, setNotice] = React.useState<string | null>(null);\n const [receiptTarget, setReceiptTarget] = React.useState<TransferTarget | undefined>();\n const [paletteOpen, setPaletteOpen] = React.useState(false);\n const [paletteTarget, setPaletteTarget] = React.useState<HTMLElement | null>(null);\n const externalPaletteClose = React.useRef<(() => void) | null>(null);\n const externalPaletteRestoreFocus = React.useRef<(() => void) | null>(null);\n // A host action closes its submenu before its async outcome arrives. Keep the\n // owner document so feedback and its receipt still have a durable portal.\n const feedbackDocument = React.useRef<Document | null>(null);\n const [mode, setMode] = React.useState<\"copy\" | \"download\">(\"copy\");\n const scopes = React.useMemo(() => table?.availableScopes ?? ([\"target\"] as TransferScope[]), [table]);\n const [requestedScope, setRequestedScope] = React.useState<TransferScope>(table?.initialScope ?? \"target\");\n const initialScope = scopes.includes(requestedScope) ? requestedScope : table?.initialScope ?? \"target\";\n if (!scopes.includes(initialScope)) throw new Error(\"Alchemy initialScope must be included in availableScopes.\");\n const primary = surface ?? source ?? nearestSurface;\n const sourceLabel = label ?? (surface?.surfaceName ?? (source && \"label\" in source ? source.label : nearestSurface?.surfaceName) ?? \"content\");\n const primaryWorkspaceBase = `primary:${materialIdentity(primary)}`;\n const primaryWorkspaceKey = `${primaryWorkspaceBase}:${initialScope}`;\n React.useEffect(() => {\n setCopiedFormat(null);\n setNotice(null);\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n return fence.abortAll;\n }, [primaryWorkspaceBase, initialScope, fence.abortAll]);\n const nearestWorkspaceKey = source && !surface && nearestSurface ? `surface:${materialIdentity(nearestSurface)}` : null;\n const variantWorkspaceKeys = React.useMemo(() => new Map(variants.map((variant) => [variant.id, `variant:${variant.id}:${materialIdentity(variant.source)}`])), [variants]);\n const baseTransport = local?.transport ?? inherited.transport ?? createBrowserTransport();\n const transport: Transport = {\n download: (artifact, signal) => baseTransport.download(artifact, signal),\n copy: (artifact, signal) => {\n const deliver = (): Promise<TransferOutcome> => signal.aborted ? Promise.resolve({status: \"cancelled\"}) : baseTransport.copy(artifact, signal);\n const pending = clipboardQueue.current.then(deliver, deliver);\n clipboardQueue.current = pending;\n return pending;\n },\n };\n const ai = local?.ai ?? inherited.ai;\n const referencePort = local?.reference ?? inherited.reference;\n const { email: emailPort, review: emailReview } = useReviewedTransferEmail(local?.email ?? inherited.email);\n const providerPreferences = React.useMemo(() => resolveTransferPreferences(inherited.preferences, local?.preferences), [inherited.preferences, local?.preferences]);\n // PP-01a/b: with a host window system the workspace is drawn in a host window; its session stays here.\n const windowPort = local?.window ?? inherited.window;\n const sessionId = React.useId();\n const windowHandles = React.useRef(new Map<string, WorkspaceWindowHandle>());\n const sessionKeys = React.useRef(new Set<string>());\n const [windowNodes, setWindowNodes] = React.useState<Record<string, HTMLElement>>({});\n const slotRefs = React.useRef(new Map<string, (node: HTMLDivElement | null) => void>());\n const slotRef = (key: string) => {\n let ref = slotRefs.current.get(key);\n if (!ref) {\n ref = (node) => setWindowNodes((current) => {\n if (node) return current[key] === node ? current : { ...current, [key]: node };\n if (!(key in current)) return current;\n const { [key]: _gone, ...rest } = current;\n return rest;\n });\n slotRefs.current.set(key, ref);\n }\n return ref;\n };\n const [duplicateFormats, setDuplicateFormats] = React.useState<ReadonlySet<string>>(() => new Set());\n const adapters = React.useMemo(() => {\n // A host format under a built-in id supersedes the built-in (hostEngineFor); any other duplicate still refuses.\n const hostIds = new Set([...(inherited.formats ?? []), ...(local?.formats ?? [])].map((format) => format.id));\n return resolveTransferRegistry<{ id: string }>(BUILT_INS.filter((builtIn) => !hostIds.has(builtIn.id)), inherited.formats ?? [], local?.formats ?? []).filter((x): x is FormatAdapter => \"load\" in x);\n }, [inherited.formats, local?.formats]);\n const emailJsonFormat = adapters.find((adapter) => adapter.id === \"table-data\");\n const emailActions = React.useMemo(() => emailPort ? createTransferEmailActions(emailPort, emailJsonFormat ? { jsonFormat: emailJsonFormat } : {}) : [], [emailPort, emailJsonFormat]);\n const htmlPreviewPort = local?.htmlPreview ?? inherited.htmlPreview;\n const htmlPreviewActions = React.useMemo(() => (htmlPreview && htmlPreviewPort ? [createTransferHtmlPreviewAction(htmlPreviewPort)] : []), [htmlPreview, htmlPreviewPort]);\n const registeredActions = React.useMemo(() => resolveTransferRegistry(emailActions, htmlPreviewActions, inherited.actions ?? [], local?.actions ?? [], actions), [actions, emailActions, htmlPreviewActions, inherited.actions, local?.actions]);\n React.useMemo(() => resolveTransferRegistry(variants), [variants]);\n // A landed clipboard copy speaks through the trigger's own check (confirmCopy) — the\n // world-class pattern (macOS, Linear, GitHub): no floating banner for a copy. Every other\n // notice leaves by itself (NOTICE_MS / NOTICE_ERROR_MS) and holds while the pointer is on it.\n const noticeTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const noticeLife = React.useRef(NOTICE_MS);\n const clearNoticeTimer = React.useCallback(() => { if (noticeTimer.current) clearTimeout(noticeTimer.current); noticeTimer.current = null; }, []);\n const startNoticeTimer = React.useCallback(() => { clearNoticeTimer(); noticeTimer.current = setTimeout(() => setNotice(null), noticeLife.current); }, [clearNoticeTimer]);\n React.useEffect(() => clearNoticeTimer, [clearNoticeTimer]);\n const report = React.useCallback((result: TransferOutcome) => {\n inherited.onOutcome?.(result); local?.onOutcome?.(result);\n setReceiptTarget(\"target\" in result ? result.target : undefined);\n const delivered = result.status === \"success\" ? (result as TransferOutcome & { delivered?: string }).delivered : undefined;\n if (result.status === \"success\" && delivered === \"clipboard\" && !(\"target\" in result && result.target)) { clearNoticeTimer(); setNotice(null); return; }\n noticeLife.current = result.status === \"error\" ? NOTICE_ERROR_MS : NOTICE_MS;\n setNotice(outcomeMessage(result));\n startNoticeTimer();\n }, [inherited, local, clearNoticeTimer, startNoticeTimer]);\n React.useEffect(() => {\n const valid = new Set([...scopes.map((scope) => `${primaryWorkspaceBase}:${scope}`), ...(nearestWorkspaceKey ? [nearestWorkspaceKey] : []), ...variantWorkspaceKeys.values(), ...externalWorkspaceKeys.current]);\n setWorkspaces((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key))));\n for (const key of workspaceCaptures.current.keys()) if (!valid.has(key)) workspaceCaptures.current.delete(key);\n if (workspaceKey && !valid.has(workspaceKey)) { setWorkspaceKey(null); setWorkspaceOpen(false); }\n }, [nearestWorkspaceKey, primaryWorkspaceBase, scopes, variantWorkspaceKeys, workspaceKey]);\n\n const captureOne = React.useCallback(async (material: Source | Payload | SurfaceHandle | null, scope: TransferScope, signal: AbortSignal, applyMenuProjection = false, collectPages = true): Promise<CaptureResult> => {\n if (!material) throw new Error(\"Alchemy needs a source or a mounted transfer surface.\");\n let sourceMaterial: Source;\n if (\"instanceId\" in material) {\n if (!material.isMounted()) throw new Error(\"The requested transfer surface is no longer mounted.\");\n const captured = await material.capture(signal);\n sourceMaterial = { id: captured.snapshot.sourceId, label: captured.snapshot.label, capture: async () => captured };\n } else if (\"kind\" in material) {\n sourceMaterial = { id: materialIdentity(material), label: sourceLabel, capture: async () => directSource(material, { sourceId: materialIdentity(material), label: sourceLabel, ...(applyMenuProjection && projection ? { projection } : {}), ...(applyMenuProjection && sections ? { sections } : {}) }) };\n } else if (applyMenuProjection && (projection || sections)) {\n sourceMaterial = {\n id: material.id,\n label: material.label,\n capture: async (request) => {\n const captured = await material.capture(request);\n return {\n ...captured,\n projection: { rules: [...captured.projection.rules, ...(projection?.rules ?? [])] },\n snapshot: { ...captured.snapshot, ...(sections ? { sections } : {}) },\n };\n },\n };\n } else {\n sourceMaterial = material;\n }\n const raw = await sourceMaterial.capture({ scope, signal });\n const constrained = resolveTransferPreferences(providerPreferences, preferences, raw.snapshot.limits);\n const result = await capture({ id: raw.snapshot.sourceId, label: raw.snapshot.label, capture: async () => ({ ...raw, snapshot: { ...raw.snapshot, limits: constrained.limits } }) }, signal, scope);\n if (scope !== \"all-matching\" || !collectPages) return result;\n if (!result.allMatching) throw new Error(\"This source cannot provide a stable all-matching export.\");\n const collected = await collectAllMatching(result.allMatching, signal);\n if (result.snapshot.payload.kind !== \"rows\") throw new Error(\"All-matching export requires tabular content.\");\n return { snapshot: projectSnapshot({ ...result.snapshot, payload: { kind: \"rows\", rows: collected.rows, columns: result.snapshot.payload.columns }, coverage: collected.coverage, omissions: [...collected.omissions] }, { rules: [] }), allMatching: result.allMatching, ...(collected.error ? { collectionError: collected.error.message } : {}) };\n }, [preferences, projection, providerPreferences, sections, sourceLabel]);\n const capturePrimary = React.useCallback((scope: TransferScope, signal: AbortSignal) => captureOne(primary, scope, signal, true), [captureOne, primary]);\n workspaceCaptures.current.set(primaryWorkspaceKey, capturePrimary);\n if (nearestWorkspaceKey && nearestSurface) workspaceCaptures.current.set(nearestWorkspaceKey, (scope, signal) => captureOne(nearestSurface, scope, signal, true));\n for (const variant of variants) {\n const key = variantWorkspaceKeys.get(variant.id)!;\n workspaceCaptures.current.set(key, (scope, signal) => captureOne(variant.source, scope, signal, true));\n }\n\n const runRich = React.useCallback(async (flavor: RichCopyFlavor) => {\n if (!richCopy) return;\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(null);\n setNotice(null);\n try {\n const result = await richCopy(flavor);\n if (result === false) return;\n if (result && typeof result === \"object\") {\n if (result.status === \"success\") confirmCopy(`rich-${flavor}`);\n report(result);\n } else confirmCopy(`rich-${flavor}`);\n } catch (error) { report({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Copy failed\"), retryable: true }); }\n }, [confirmCopy, report, richCopy]);\n\n const preflight = React.useCallback(async (scope = initialScope) => {\n const { controller, id } = inspectionFence.begin(); setMenuCapture(null); setMenuStatus(\"loading\");\n try {\n const probe = primary ?? formatSources?.plain ?? formatSources?.markdown ?? formatSources?.json ?? null;\n const shape = shapeOf(probe);\n // A declared shape is inspected as its empty payload: nothing of the content is built to open the menu.\n const result = await captureOne(shape ? shapePayload(shape) : probe, scope, controller.signal, true, false);\n if (inspectionFence.valid(id, controller)) { setMenuCapture(result); setMenuStatus(\"idle\"); }\n // PP-09: two explicit format sources that produce the same bytes are one choice, not two\n // (\"Text\" and \"Markdown\" of a screen's Markdown-style text). The first in palette order stays.\n // Only sources that are cheap to build are compared; a shaped, costly source is never built to open the menu.\n const explicit = COPIES.filter((format) => formatSources?.[format]);\n const duplicates = new Set<string>();\n const comparable = explicit.every((format) => { const declared = shapeOf(formatSources![format]); return !declared || declared.cheap === true; });\n if (explicit.length > 1 && comparable) {\n const seen = new Set<string>();\n for (const format of explicit) {\n try {\n const captured = await captureOne(formatSources![format]!, scope, controller.signal, true, false);\n const artifact = await buildFormat(createDraft(captured.snapshot), format, captured.snapshot.label, adapters, controller.signal);\n const signature = `${artifact.plainText}\\u0000${artifact.html ?? \"\"}`;\n // Applied as found: a later source's engine may load on first use (print for HTML).\n if (seen.has(signature)) { duplicates.add(format); if (inspectionFence.valid(id, controller)) setDuplicateFormats(new Set(duplicates)); } else seen.add(signature);\n } catch { /* An explicit source that cannot be built stays offered; its own copy reports why. */ }\n }\n }\n if (inspectionFence.valid(id, controller)) setDuplicateFormats(duplicates);\n }\n catch (error) { if (inspectionFence.valid(id, controller)) { setMenuCapture(null); setMenuStatus(errorMessage(error, \"Could not inspect content\")); } }\n finally { inspectionFence.finish(controller); }\n }, [adapters, captureOne, inspectionFence, formatSources, initialScope, primary]);\n\n const closePalette = React.useCallback(() => {\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n leaveTimer.current = null;\n const onClose = externalPaletteClose.current;\n const restoreFocus = externalPaletteRestoreFocus.current;\n externalPaletteClose.current = null;\n externalPaletteRestoreFocus.current = null;\n onClose?.();\n restoreFocus?.();\n setPaletteTarget(null);\n setPaletteOpen(false);\n }, []);\n const mountPalette = React.useCallback((target: HTMLElement | null, onClose?: () => void, restoreFocus?: () => void) => {\n if (!target) {\n // Host cleanup (submenu replacement, mobile drilldown back) must detach\n // without asking that host to close a second time.\n externalPaletteClose.current = null;\n externalPaletteRestoreFocus.current = null;\n setPaletteTarget(null);\n setPaletteOpen(false);\n return;\n }\n if (!enabled) throw new Error(\"Alchemy is not enabled for this record.\");\n if (disabled) throw new Error(\"Alchemy is disabled for this record.\");\n externalPaletteClose.current = onClose ?? null;\n externalPaletteRestoreFocus.current = restoreFocus ?? null;\n feedbackDocument.current = target.ownerDocument;\n restoreFocusRef.current = restoreFocus ?? (() => target.focus());\n setPaletteTarget(target);\n setPaletteOpen(true);\n setMode(\"copy\");\n void preflight();\n }, [closePalette, disabled, enabled, preflight]);\n React.useEffect(() => {\n if (!paletteTarget || !paletteOpen) return;\n const firstControl = paletteTarget.querySelector<HTMLElement>(\"button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [href]\");\n firstControl?.focus();\n }, [paletteOpen, paletteTarget]);\n\n const transfer = React.useCallback(async (format: BuiltInFormat | FormatAdapter | \"default\", download: boolean, alternate?: TransferMenuVariant) => {\n fence.abortAll();\n const { controller, id } = fence.begin();\n if (copiedTimer.current) clearTimeout(copiedTimer.current);\n setCopiedFormat(null);\n setNotice(null);\n try {\n const explicit = alternate?.source ?? (format === \"default\" ? formatSources?.plain ?? (!primary ? formatSources?.markdown ?? formatSources?.json : undefined) : typeof format === \"string\" && format !== \"xlsx\" ? formatSources?.[format] : undefined);\n const result = await (explicit ? captureOne(explicit, initialScope, controller.signal, true) : capturePrimary(initialScope, controller.signal));\n if (result.collectionError) throw new Error(`The complete source could not be collected: ${result.collectionError}`);\n if (result.snapshot.coverage.status !== \"complete\" || result.snapshot.omissions.length > 0) {\n const reason = result.snapshot.coverage.reason ?? `${result.snapshot.omissions.length} omission${result.snapshot.omissions.length === 1 ? \"\" : \"s\"}`;\n throw new Error(`Quick transfer is partial (${reason}). Open Prepare for AI to review it before delivery.`);\n }\n const resolved = resolveTransferPreferences(providerPreferences, preferences, result.snapshot.limits);\n const draft = applyTransferLimits(createDraft(result.snapshot), resolved.limits); const revision = draft.revision;\n if (draft.omissions.length > result.snapshot.omissions.length) throw new Error(\"Quick transfer requires content reductions. Open Prepare for AI to review them before delivery.\");\n // Match the core bytes to the palette's canonical tile, including lazy sources.\n const defaultFormat: SerializableFormat = formatSources?.plain ? \"plain\"\n : result.snapshot.payload.kind === \"markdown\" ? \"markdown\"\n : [\"json\", \"registered\", \"rows\"].includes(result.snapshot.payload.kind) ? \"json\" : \"plain\";\n const deliveryFormat = format === \"default\" ? defaultFormat : format;\n if (format === \"default\" && !formatSources?.[defaultFormat] && !offersFormat(defaultFormat, result.snapshot.payload, adapters)) return;\n const artifact = typeof deliveryFormat === \"string\" ? await buildFormat(draft, deliveryFormat, result.snapshot.label, adapters, controller.signal) : await buildWithAdapter(deliveryFormat, draft, controller.signal);\n if (artifact.omissions.length > draft.omissions.length) throw new Error(`Quick format requires ${artifact.omissions.length - draft.omissions.length} adjustment${artifact.omissions.length - draft.omissions.length === 1 ? \"\" : \"s\"}. Open Prepare for AI to review before delivery.`);\n if (!fence.valid(id, controller) || artifact.snapshotId !== result.snapshot.id || artifact.draftRevision !== revision) return;\n // The shared session transport queues writes, including prepared output.\n const outcome = await transport[download ? \"download\" : \"copy\"](artifact, controller.signal);\n if (fence.valid(id, controller)) {\n if (!download && outcome.status === \"success\" && outcome.delivered === \"clipboard\") confirmCopy(alternate?.id ?? (typeof deliveryFormat === \"string\" ? deliveryFormat : deliveryFormat.id));\n else if (!download && outcome.status === \"degraded\" && outcome.delivered === \"plain-text\") confirmCopy(\"plain\");\n report(outcome.status === \"success\" && alternate?.successMessage ? { ...outcome, message: alternate.successMessage } : outcome);\n }\n } catch (error) { if (fence.valid(id, controller)) report({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Preparation failed\"), retryable: true }); }\n finally { fence.finish(controller); }\n }, [adapters, captureOne, capturePrimary, confirmCopy, fence, formatSources, initialScope, preferences, primary, providerPreferences, report, transport]);\n\n const openWorkspace = React.useCallback(\n async (\n key = primaryWorkspaceKey,\n variant?: { source: Source | Payload | SurfaceHandle; label: string; envelope?: EnvelopeMeta | undefined },\n ) => {\n const variantMaterial =\n variant && \"kind\" in variant.source\n ? ({\n id: `variant:${key}`,\n label: variant.label,\n capture: async () =>\n directSource(variant.source as Payload, {\n sourceId: `variant:${key}`,\n label: variant.label,\n }),\n } satisfies Source)\n : variant?.source;\n const captureWorkspace = (\n scope: TransferScope,\n signal: AbortSignal,\n collectPages = true,\n ) =>\n captureOne(variantMaterial ?? primary, scope, signal, true, collectPages);\n workspaceCaptures.current.set(key, captureWorkspace);\n const existing = workspaces[key];\n const { controller, id } = fence.begin();\n if (existing) {\n try {\n const scopeChanged = existing.scope !== initialScope;\n const allMatching = initialScope === \"all-matching\";\n const fresh = await captureWorkspace(\n initialScope,\n controller.signal,\n scopeChanged || !allMatching,\n );\n if (!fence.valid(id, controller) || !workspaceCaptures.current.has(key))\n return;\n if (allMatching && (!fresh.allMatching || (!scopeChanged && !existing.allMatching)))\n throw new Error(\n \"This source can no longer provide an all-matching snapshot.\",\n );\n const collectionIdentity = (value: BoundAllMatching | undefined) =>\n value && {\n query: value.source.query,\n projection: value.projection,\n columns: value.columns,\n limits: value.limits,\n };\n const changed = scopeChanged || (allMatching\n ? JSON.stringify(collectionIdentity(existing.allMatching)) !==\n JSON.stringify(collectionIdentity(fresh.allMatching))\n : snapshotContent(existing.snapshot) !==\n snapshotContent(fresh.snapshot));\n setWorkspaces((current) => {\n const retained = current[key];\n if (!retained) return current;\n return {\n ...current,\n [key]: {\n ...retained,\n error: fresh.collectionError,\n ...(allMatching && !scopeChanged\n ? { sourceStale: changed }\n : changed\n ? { pending: { ...fresh, scope: initialScope } }\n : { pending: undefined }),\n },\n };\n });\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n } catch (error) {\n if (fence.valid(id, controller) && workspaceCaptures.current.has(key)) {\n setWorkspaces((current) =>\n current[key]\n ? {\n ...current,\n [key]: {\n ...current[key]!,\n error: errorMessage(error, \"Could not refresh source\"),\n },\n }\n : current,\n );\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n }\n } finally {\n fence.finish(controller);\n }\n return;\n }\n try {\n const result = await captureWorkspace(initialScope, controller.signal);\n if (!fence.valid(id, controller)) return;\n const resolved = resolveTransferPreferences(\n providerPreferences,\n preferences,\n result.snapshot.limits,\n );\n const original = createDraft(result.snapshot);\n const envelope = variant?.envelope ?? (key === primaryWorkspaceKey ? primaryEnvelope?.() : undefined);\n const base: WorkspaceState = {\n ...result,\n key,\n original,\n draft: original,\n scope: initialScope,\n preferences: resolved,\n ...(result.collectionError ? { error: result.collectionError } : {}),\n ...(envelope ? { envelope } : {}),\n };\n setWorkspaces((current) => ({\n ...current,\n [key]: { ...base, draft: rebuild(base, initialControls(base)) },\n }));\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n } catch (error) {\n if (fence.valid(id, controller)) {\n setReceiptTarget(undefined); noticeLife.current = NOTICE_ERROR_MS; setNotice(errorMessage(error, \"Could not capture content\")); startNoticeTimer();\n }\n } finally {\n fence.finish(controller);\n }\n },\n [\n captureOne,\n capturePrimary,\n fence,\n initialScope,\n preferences,\n primaryWorkspaceKey,\n primary,\n primaryEnvelope,\n providerPreferences,\n startNoticeTimer,\n workspaces,\n ],\n );\n const prepareLevers = React.useCallback(async (levers: WorkspaceLevers, options: { id: string; label: string }) => {\n const key = `levers:${options.id}`;\n externalWorkspaceKeys.current.add(key);\n if (!workspaces[key]) {\n const sourceId = `levers:${sessionId}:${options.id}`;\n let built: ReturnType<WorkspaceLevers[\"build\"]> | null = null;\n let buildError: string | undefined;\n try { built = levers.build(levers.initial); } catch (cause) { buildError = errorMessage(cause, \"This source could not be prepared with these options.\"); }\n const snapshot = leverSnapshot(built?.payload ?? { kind: \"text\", text: \"\" }, sourceId, options.label);\n const original = createDraft(snapshot);\n const base: WorkspaceState = {\n snapshot, key, original, draft: original, scope: initialScope,\n preferences: resolveTransferPreferences(providerPreferences, preferences, snapshot.limits),\n levers, leverValues: levers.initial,\n ...(built?.meta ? { leverMeta: built.meta } : {}),\n ...(built?.sectionSizes ? { leverSizes: built.sectionSizes } : {}),\n ...(built ? { envelope: built.envelope } : {}),\n ...(buildError ? { buildError } : {}),\n };\n setWorkspaces((current) => ({ ...current, [key]: { ...base, draft: rebuild(base, initialControls(base)) } }));\n }\n setWorkspaceKey(key);\n setWorkspaceOpen(true);\n }, [initialScope, preferences, providerPreferences, sessionId, workspaces]);\n React.useImperativeHandle(controllerRef, () => ({\n focusTrigger: () => triggerRef.current?.focus(),\n mountPalette,\n preparePrimary: async (options) => {\n if (!enabled) throw new Error(\"Alchemy is not enabled for this record.\");\n if (disabled) throw new Error(\"Alchemy is disabled for this record.\");\n if (hide.includes(\"prepare\")) throw new Error(\"Alchemy preparation is unavailable for this record.\");\n if (!primary) throw new Error(\"Alchemy has no source to prepare.\");\n restoreFocusRef.current = options?.restoreFocus ?? null;\n await openWorkspace(primaryWorkspaceKey, { source: primary, label: sourceLabel });\n },\n prepare: async (requestedSource, options) => {\n const requestedLabel = options?.label ?? (\"label\" in requestedSource ? requestedSource.label : \"content\");\n const requestedKey = `controller:${options?.id ?? \"source\"}:${materialIdentity(requestedSource)}`;\n externalWorkspaceKeys.current.add(requestedKey);\n await openWorkspace(requestedKey, { source: requestedSource, label: requestedLabel, envelope: options?.envelope });\n },\n prepareLevers,\n }), [disabled, enabled, hide, mountPalette, openWorkspace, prepareLevers, primary, primaryWorkspaceKey, sourceLabel]);\n\n React.useEffect(() => {\n if (!windowPort) return;\n const openKey = workspaceOpen ? workspaceKey : null;\n for (const [key, handle] of [...windowHandles.current]) {\n if (key === openKey) continue;\n windowHandles.current.delete(key);\n handle.close();\n }\n if (!openKey || windowHandles.current.has(openKey)) return;\n const label = workspaces[openKey]?.snapshot.label ?? sourceLabel;\n const instanceId = `alchemy-prepare${sessionId}${openKey}`.replace(/[^A-Za-z0-9_-]+/g, \"-\");\n setWorkspaceSessionLive(instanceId, true);\n sessionKeys.current.add(instanceId);\n const handle: WorkspaceWindowHandle = windowPort.open(() => <WorkspaceWindowSlot onNode={slotRef(openKey)} sessionKey={instanceId} onClose={() => handle.close()} />, {\n title: `Prepare ${label}`,\n size: \"full\",\n instanceId,\n onClose: () => {\n if (windowHandles.current.get(openKey) !== handle) return;\n windowHandles.current.delete(openKey);\n setWorkspaceOpen(false);\n },\n });\n windowHandles.current.set(openKey, handle);\n // `workspaces` is read for the title only; opening follows the open key.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [windowPort, workspaceOpen, workspaceKey]);\n React.useEffect(() => () => {\n // The captured content goes with this session: any window a host keeps says so (PP-08).\n for (const key of sessionKeys.current) setWorkspaceSessionLive(key, false);\n sessionKeys.current.clear();\n const handles = [...windowHandles.current.values()];\n windowHandles.current.clear();\n for (const handle of handles) handle.close();\n }, []);\n\n const runAction = React.useCallback(async (action: PageAction) => {\n const { controller, id } = fence.begin();\n try { const actionSource = (action as PageAction & { source?: Source }).source; const { snapshot } = actionSource ? await captureOne(actionSource, initialScope, controller.signal, true) : await capturePrimary(initialScope, controller.signal); const resolved = resolveTransferPreferences(providerPreferences, preferences, snapshot.limits); const draft = applyTransferLimits(createDraft(snapshot), resolved.limits); if (snapshot.coverage.status !== \"complete\" || draft.omissions.length) throw new Error(\"This content is partial or requires reductions. Open Prepare for AI to review it before sending it to a destination.\"); if (!action.supports(snapshot, draft)) throw new Error(`${action.label} is unavailable for this content.`); const result = await action.run({ snapshot, draft, signal: controller.signal }); if (fence.valid(id, controller) && draft.snapshotId === snapshot.id) report(result); }\n catch (error) { if (fence.valid(id, controller)) report({ status: \"error\", code: \"action-failed\", message: errorMessage(error, \"Action failed\"), retryable: true }); }\n finally { fence.finish(controller); }\n }, [captureOne, capturePrimary, fence, initialScope, preferences, providerPreferences, report]);\n\n const copyReference = async (reference: ContentTransferReference) => {\n const { controller, id } = fence.begin();\n closePalette();\n try {\n if (!referencePort?.supports(reference)) throw new Error(\"This reference is not registered or its identity is incomplete.\");\n const text = await referencePort.build(reference);\n if (!text.trim()) throw new Error(\"The reference serializer returned no content.\");\n const artifact = sealTransferArtifact({ snapshotId: `reference:${reference.id}`, draftRevision: 0, format: \"matrx-reference\", plainText: text, omissions: [] });\n if (!fence.valid(id, controller)) return;\n const outcome = await transport.copy(artifact, controller.signal);\n if (fence.valid(id, controller)) {\n if (outcome.status === \"success\" && outcome.delivered === \"clipboard\") confirmCopy(`reference:${reference.id}`);\n report(outcome);\n }\n } catch (error) { if (fence.valid(id, controller)) report({status: \"error\", code: \"reference-failed\", message: errorMessage(error, \"Could not copy reference\"), retryable: true}); }\n finally { fence.finish(controller); }\n };\n const openReference = async (action: ContentTransferReferenceAction) => {\n closePalette();\n try { await action.run(); }\n catch (error) { report({status: \"error\", code: \"reference-failed\", message: errorMessage(error, \"Could not open reference picker\"), retryable: true}); }\n };\n const cancelPointerClose = () => {\n if (leaveTimer.current) clearTimeout(leaveTimer.current);\n leaveTimer.current = null;\n };\n const schedulePointerClose = (event: React.PointerEvent) => {\n if (event.pointerType !== \"mouse\" || !paletteOpen) return;\n cancelPointerClose();\n // Allow crossing the gap between the trigger and its portalled palette.\n leaveTimer.current = setTimeout(() => closePalette(), 200);\n };\n // One draft per inspection, never one per action per render.\n const visibleActions = React.useMemo(() => {\n if (!menuCapture) return [];\n const draft = applyTransferLimits(createDraft(menuCapture.snapshot), resolveTransferPreferences(providerPreferences, preferences, menuCapture.snapshot.limits).limits);\n return registeredActions.filter((a) => a.supports(menuCapture.snapshot, draft));\n }, [menuCapture, preferences, providerPreferences, registeredActions]);\n if (!enabled) return null;\n const payload = menuCapture?.snapshot.payload ?? (source && \"kind\" in source ? source : undefined);\n const quickVariants = (section: \"copy\" | \"ai\") => variants.filter((v) => v.copyLabel && (v.section ?? \"ai\") === section);\n const visibleCopies = sourceFormats ? COPIES.filter((f) => !duplicateFormats.has(f) && (Boolean(formatSources?.[f]) || (payload ? offersFormat(f, payload, adapters) : ![\"csv\", \"tsv\"].includes(f)))) : [];\n const visibleDownloads = sourceFormats ? DOWNLOADS.filter((f) => !duplicateFormats.has(f) && ((f !== \"xlsx\" && Boolean(formatSources?.[f])) || (payload ? offersFormat(f, payload, adapters) : ![\"csv\", \"tsv\", \"xlsx\"].includes(f)))) : [];\n const visibleAdapters = sourceFormats && menuCapture ? adapters.filter((a) => !isBuiltInFormat(a.id) && a.supports(menuCapture.snapshot.payload)) : [];\n const downloadActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === \"download\");\n const prepareActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === \"prepare\");\n const ordinaryActions = visibleActions.filter((action) => (action as TransferMenuPresentation).placement === undefined);\n const preparedActions = registeredActions.filter((action) => (action as TransferMenuPresentation).prepared && !action.source);\n const copyAvailable = !hide.includes(\"copy\") && (Boolean(richCopy) || visibleCopies.length + visibleAdapters.length + quickVariants(\"copy\").length > 0);\n const downloadAvailable = !hide.includes(\"download\") && (visibleDownloads.length + visibleAdapters.length + downloadActions.length > 0);\n const prepareAvailable = !hide.includes(\"prepare\") && (quickVariants(\"ai\").length > 0 || Boolean(primary) || Boolean(nearestWorkspaceKey) || variants.length > 0 || prepareActions.length > 0);\n const resolvedMode = mode === \"copy\" && !copyAvailable ? \"download\" : mode === \"download\" && !downloadAvailable ? \"copy\" : mode;\n const nativeAiFormat: FormatAdapter = {\n id: \"ai-context\", label: \"AI context\", extension: \"txt\", mime: \"text/plain;charset=utf-8\", modes: [\"copy\", \"download\"], runsOn: \"client\", supports: () => true,\n load: async () => ({ build: async (draft) => {\n const envelope = primaryEnvelope?.() ?? { kind: \"matrx_content\", location: sourceLabel, description: \"Captured content for an assistant\", attributes: { source: draft.sourceId } };\n // PP-09: text and Markdown travel as themselves; only structured content is JSON.\n if (draft.payload.kind === \"text\" || draft.payload.kind === \"markdown\") {\n const text = serialize(draft, draft.payload.kind === \"markdown\" ? \"markdown\" : \"plain\");\n return sealTransferArtifact({ snapshotId: draft.snapshotId, draftRevision: draft.revision, format: \"ai-context\", plainText: buildAgentPayload({ ...envelope, data: text.plainText, dataFormat: draft.payload.kind === \"markdown\" ? \"markdown\" : \"text\" }), omissions: [...text.omissions] });\n }\n const json = serialize(draft, \"json\");\n return sealTransferArtifact({ snapshotId: draft.snapshotId, draftRevision: draft.revision, format: \"ai-context\", plainText: buildAgentPayload({ ...envelope, data: JSON.parse(json.plainText) }), omissions: [...json.omissions] });\n } }),\n };\n const copyFirst = sourceFormats && !hide.includes(\"copy\") && Boolean(richCopy || primary || formatSources?.plain || formatSources?.markdown || formatSources?.json);\n const copiedGlyph = <svg className=\"matrx-alchemy-copied-check\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden=\"true\"><path d=\"m5 12 4 4L19 6\"/></svg>;\n const triggerGlyph = copiedFormat ? copiedGlyph : <AlchemyGlyph icon={icon}/>;\n const tile = (id: string, label: string, onClick: () => void, options: { custom?: boolean; action?: PageAction; ai?: boolean; file?: boolean; ariaLabel?: string } = {}) => {\n const presentation = options.action as TransferMenuPresentation | undefined;\n const Icon = presentation?.icon;\n const fallbackLabel = options.file && !/^download\\b/i.test(label) ? `Download ${label}` : label;\n return <button key={id} type=\"button\" className=\"matrx-alchemy-palette-tile\" data-copied={resolvedMode === \"copy\" && copiedFormat === id ? \"true\" : undefined} title={id === \"table-data\" ? \"JSON using column display names\" : id === \"table-schema\" ? \"Table schema and rows\" : label} aria-label={presentation?.ariaLabel ?? (presentation ? fallbackLabel : options.ariaLabel ?? `${resolvedMode === \"copy\" ? \"Copy\" : \"Download\"} ${label}`)} onClick={() => { closePalette(); onClick(); }}>{resolvedMode === \"copy\" && copiedFormat === id ? copiedGlyph : Icon ? <Icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph format={id} ai={Boolean(options.ai)} file={options.file || Boolean(options.custom && id !== \"table-data\" && id !== \"table-schema\")}/>}<span>{label}{resolvedMode === \"copy\" && copiedFormat === id ? <small className=\"matrx-alchemy-copied-label\">Copied to clipboard</small> : null}{presentation?.hint ? <small className=\"matrx-alchemy-menu-hint\">{presentation.hint}</small> : null}</span></button>;\n };\n const palette = <>\n {menuStatus === \"loading\" ? <p className=\"matrx-alchemy-palette-status\">Inspecting content…</p> : menuStatus !== \"idle\" ? <p className=\"matrx-alchemy-error\">{menuStatus}</p> : null}\n {table && scopes.length > 1 ? <label className=\"matrx-alchemy-scope\">Content scope<select aria-label=\"Content scope\" value={initialScope} onChange={(event) => { const next = scopes.find((scope) => scope === event.target.value); if (next) { setRequestedScope(next); void preflight(next); } }}>{scopes.map((scope) => <option key={scope} value={scope}>{table.scopeLabels?.[scope] ?? SCOPE_LABEL[scope]}</option>)}</select></label> : null}\n {copyAvailable || downloadAvailable ? <section className=\"matrx-alchemy-output\"><h3>{resolvedMode === \"copy\" ? \"Copy as\" : \"Download as\"}</h3>{copyAvailable && downloadAvailable ? <div className=\"matrx-alchemy-mode\" aria-label=\"Output action\"><button type=\"button\" aria-label=\"Copy mode\" aria-pressed={resolvedMode === \"copy\"} onClick={() => setMode(\"copy\")}>Copy</button><button type=\"button\" aria-label=\"Download mode\" aria-pressed={resolvedMode === \"download\"} onClick={() => setMode(\"download\")}>Download</button></div> : null}\n {resolvedMode === \"copy\" && copyAvailable ? <><div className=\"matrx-alchemy-palette-grid\">{richCopy ? <>{([\"markdown\", \"text\", \"formatted\"] as const).filter((flavor) => richCopyFlavors.includes(flavor)).map((flavor) => tile(`rich-${flavor}`, RICH_COPY_LABELS[flavor], () => void runRich(flavor), { ariaLabel: RICH_COPY_LABELS[flavor] }))}</> : null}{visibleCopies.filter((format) => !richCopy || (format !== \"plain\" && format !== \"markdown\" && !(format === \"html\" && richCopyFlavors.includes(\"formatted\")) && (![\"json\", \"compact-json\"].includes(format) || Boolean(formatSources?.[format])))).map((format) => tile(format, ({ plain: \"Text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact\", csv: \"CSV\", tsv: \"Sheets\" } as Record<SerializableFormat, string>)[format]!, () => void transfer(format, false), { ariaLabel: `Copy ${LABEL[format]}` }))}{visibleAdapters.map((adapter) => tile(adapter.id, adapter.label, () => void transfer(adapter, false), { custom: true }))}</div>{quickVariants(\"copy\").length ? <PaletteRows title=\"Quick copy\" items={quickVariants(\"copy\")} onRun={(variant) => { closePalette(); void transfer(\"markdown\", false, variant); }}/>: null}</> : null}\n {resolvedMode === \"download\" && downloadAvailable ? <><div className=\"matrx-alchemy-palette-grid\">{visibleDownloads.map((format) => tile(format, ({ plain: \"Text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact\", csv: \"CSV\", tsv: \"Sheets\", xlsx: \"Excel\" } as Record<BuiltInFormat, string>)[format]!, () => void transfer(format, true), { ariaLabel: `Download ${LABEL[format]}` }))}{visibleAdapters.map((adapter) => tile(adapter.id, adapter.label, () => void transfer(adapter, true), { custom: true }))}{downloadActions.map((action) => tile(action.id, action.label, () => void runAction(action), { custom: true, action, file: true }))}</div></> : null}</section> : null}\n {prepareAvailable ? <><PaletteRows title=\"Copy for AI\" ai glyphKind=\"ai-copy\" fallbackHint=\"Copies immediately\" extra={<>{sourceFormats ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => { closePalette(); void transfer(nativeAiFormat, false); }}><PaletteGlyph kind=\"ai-copy\"/><span>Copy with AI context<small className=\"matrx-alchemy-menu-hint\">Include source context</small></span></button> : null}{copyWithPrompt || primary ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Copy with prompt\" onClick={() => { closePalette(); void (copyWithPrompt ? copyWithPrompt() : openWorkspace()).then(() => setPromptFocus((n) => n + 1)); }}><PaletteGlyph kind=\"ai-copy\"/><span>Copy with prompt…<small className=\"matrx-alchemy-menu-hint\">Add your instructions</small></span></button> : null}</>} items={quickVariants(\"ai\")} onRun={(variant) => { closePalette(); void transfer(\"markdown\", false, variant); }}/><PaletteRows title=\"Edit and prepare\" items={[]} extra={<>{prepareActions.map((action) => { const presentation = action as TransferMenuPresentation; return <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={presentation.ariaLabel ?? `${action.label}${presentation.hint ? ` ${presentation.hint}` : \"\"}`} onClick={() => { closePalette(); void runAction(action); }}><PaletteGlyph kind=\"sliders\"/><span>{action.label}…{presentation.hint ? <small className=\"matrx-alchemy-menu-hint\">{presentation.hint}</small> : null}</span></button>; })}{table ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Filter & sort before copying\" onClick={() => { closePalette(); void openWorkspace(); }}><PaletteGlyph kind=\"sliders\"/><span>Filter & sort before copying…<small className=\"matrx-alchemy-menu-hint\">{table.size ? `${table.size} · search, filter, sort, pick rows` : \"Search, filter, sort, pick rows\"}</small></span></button> : null}<button type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label=\"Prepare for AI\" onClick={() => { closePalette(); void openWorkspace(); }}><PaletteGlyph kind=\"sliders\"/><span>Prepare for AI<small className=\"matrx-alchemy-menu-hint\">Trim, edit or summarize</small></span></button></>}/></>: null}\n {prepareAvailable && (nearestWorkspaceKey || variants.length) ? <PaletteRows title=\"Other sources\" items={[]} extra={<>{nearestWorkspaceKey && nearestSurface ? <button type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => { closePalette(); void openWorkspace(nearestWorkspaceKey, { source: nearestSurface, label: nearestSurface.surfaceName }); }}><PaletteGlyph kind=\"surface\"/><span>Prepare this page</span></button> : null}{variants.map((variant) => <button key={variant.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={variant.ariaLabel} onClick={() => { closePalette(); void openWorkspace(variantWorkspaceKeys.get(variant.id)!, variant); }}><MenuPresentation {...variant} label={`Prepare ${variant.label}`}/></button>)}</>}/>: null}\n {references.length || referenceActions.length ? <section className=\"matrx-alchemy-palette-section\"><h3>References</h3>{referenceActions.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" onClick={() => void openReference(action)}><PaletteGlyph kind=\"link\"/><span>{action.label}</span><svg className=\"matrx-alchemy-disclosure\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" aria-hidden=\"true\"><path d=\"m6 4 4 4-4 4\"/></svg></button>)}{references.map((reference) => <button key={reference.id} type=\"button\" className=\"matrx-alchemy-palette-row\" title=\"Copies a reference to saved data\" onClick={() => void copyReference(reference)}><PaletteGlyph kind=\"link\"/><span>{reference.label}</span></button>)}</section> : null}\n {([\"save\", \"chat\", \"email\"] as const).map((group) => { const entries = ordinaryActions.filter((action) => (action as TransferMenuPresentation).group === group); return entries.length ? <details key={group} className=\"matrx-alchemy-palette-destinations\"><summary>{DESTINATION_HEADING[group]}<span className=\"matrx-alchemy-disclosure-meta\"><span>{entries.length}</span><svg className=\"matrx-alchemy-disclosure\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" aria-hidden=\"true\"><path d=\"m6 4 4 4-4 4\"/></svg></span></summary><div>{entries.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={(action as TransferMenuPresentation).ariaLabel} onClick={() => { closePalette(); void runAction(action); }}><DestinationPresentation action={action}/></button>)}</div></details> : null; })}{ordinaryActions.some((action) => !(action as TransferMenuPresentation).group) ? <section className=\"matrx-alchemy-palette-section\" data-alchemy-inline-actions=\"\">{ordinaryActions.filter((action) => !(action as TransferMenuPresentation).group).map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" aria-label={(action as TransferMenuPresentation).ariaLabel} onClick={() => { closePalette(); void runAction(action); }}><DestinationPresentation action={action}/></button>)}</section> : null}\n </>;\n const feedbackOwner = paletteTarget ?? triggerRef.current ?? feedbackDocument.current?.body ?? null;\n return <span className={cn(\"matrx-alchemy\", className)} onPointerEnter={cancelPointerClose} onPointerLeave={schedulePointerClose} onClick={stopPropagation ? (event) => event.stopPropagation() : undefined}>\n {!triggerHidden && !paletteTarget ? <Popover open={paletteOpen} onOpenChange={(open) => { if (open) { setPaletteOpen(true); setMode(\"copy\"); void preflight(); if (copyFirst) void (richCopy ? runRich(\"default\") : transfer(\"default\", false)); } else { cancelPointerClose(); closePalette(); } }}><PopoverTrigger asChild>{triggerVariant === \"outline\" ? <Button ref={triggerRef} variant=\"outline\" size=\"icon-sm\" aria-label={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"outline\" data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled}>{triggerGlyph}</Button> : triggerVariant === \"glass\" ? <TapTargetButton ref={triggerRef} icon={triggerGlyph} tooltip={false} ariaLabel={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"glass\" data-alchemy-size={triggerSize} data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled} /> : <TapTargetButtonTransparent ref={triggerRef} icon={triggerGlyph} tooltip={false} ariaLabel={`Copy, transform or export ${sourceLabel}`} data-alchemy-trigger=\"transparent\" data-alchemy-size={triggerSize} data-copied={copiedFormat ? \"true\" : undefined} aria-description={copiedFormat ? \"Copied to clipboard\" : undefined} disabled={disabled} />}</PopoverTrigger><PopoverContent align=\"end\" className=\"matrx-alchemy-menu matrx-alchemy-palette\" aria-label=\"Alchemy output options\" onPointerEnter={cancelPointerClose} onPointerLeave={schedulePointerClose} onCloseAutoFocus={() => triggerRef.current?.focus()}>{palette}</PopoverContent></Popover> : null}\n {paletteTarget && paletteOpen ? createPortal(<div className=\"matrx-alchemy-menu matrx-alchemy-palette\" role=\"dialog\" aria-label=\"Alchemy output options\">{palette}</div>, paletteTarget) : null}\n {notice && feedbackOwner ? createPortal(<div className=\"matrx-alchemy-feedback\" onPointerEnter={clearNoticeTimer} onPointerLeave={startNoticeTimer}><span role=\"status\">{notice}</span><ReceiptLink target={receiptTarget}/><button type=\"button\" aria-label=\"Dismiss Alchemy feedback\" onClick={() => setNotice(null)}>×</button></div>, feedbackOwner.ownerDocument.body) : null}\n {Object.values(workspaces).map((saved) => <PreparationWorkspace promptFocus={workspaceKey === saved.key ? promptFocus : 0} restoreFocus={() => restoreFocusRef.current?.() ?? triggerRef.current?.focus()} key={saved.key} frame={windowPort ? \"host\" : \"dialog\"} windowNode={windowNodes[saved.key] ?? null} open={workspaceOpen && workspaceKey === saved.key} state={saved} scopes={scopes} scopeLabels={table?.scopeLabels} onClose={() => setWorkspaceOpen(false)} onChange={(next) => setWorkspaces((current) => ({ ...current, [saved.key]: next }))} transport={transport} adapters={adapters} actions={preparedActions} captureScope={workspaceCaptures.current.get(saved.key) ?? capturePrimary} {...(ai ? { ai } : {})} onOutcome={report}/>)}\n {emailReview}\n </span>;\n}\n\n\nexport * from \"./matrx-copy\";\nexport { AlchemyTableCopyControls } from \"./table-copy-controls\";\n","\"use client\";\n\n/**\n * The preparation workspace's shared core: format ids and labels, the fence, the draft rebuild\n * from workspace controls, the format builders, and the offered-format rule. The menu session\n * (`index.tsx`) and the workspace (`workspace.tsx`) both import it — one copy.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport {\n applyJsonStructure,\n applySectionSelection,\n applySectionStructure,\n assembleAgentPayload,\n applyTransferLimits,\n concretePointers,\n deriveDraft,\n isProseSection,\n jsonTextSpans,\n offsetSpans,\n pointerSegments,\n sectionLayout,\n spanMap,\n stubText,\n readTransferCell,\n reduceJson,\n resetDraft,\n sealTransferArtifact,\n serialize,\n transformRows,\n type Artifact,\n type BoundAllMatching,\n type Column,\n type Json,\n type NodeLimit,\n type OutputSpan,\n type SpanMap,\n type StructureRecipe,\n type Draft,\n type FormatAdapter,\n type FormatOptions,\n type PageAction,\n type Payload,\n type Snapshot,\n type Source,\n type SurfaceHandle,\n type TransferOutcome,\n type TransferPreferences,\n type TransferScope,\n type TransferTarget,\n} from \"@ai-matrx/alchemy/operate\";\nimport type { TransferMenuPresentation } from \"./index\";\nimport { filterAndSortRows } from \"@ai-matrx/design-system/data-table/filter-engine\";\nimport type { LayeredFilterRule } from \"@ai-matrx/design-system/data-table\";\nimport type { ColumnFiltersState, MatrxColumnDef, TableSearchMatchMode } from \"@ai-matrx/design-system/data-table\";\nimport type { EnvelopeMeta, LeverMeta, LeverValues, WorkspaceLevers } from \"./levers\";\n\nexport type SerializableFormat = \"plain\" | \"markdown\" | \"html\" | \"json\" | \"compact-json\" | \"csv\" | \"tsv\";\nexport type BuiltInFormat = SerializableFormat | \"xlsx\";\n\nexport function MenuPresentation({ label, hint, icon: Icon }: TransferMenuPresentation & { label: string }) {\n return <>{Icon ? <Icon className=\"matrx-alchemy-menu-icon\"/> : <PaletteGlyph file/>}<span>{label}{hint ? <small className=\"matrx-alchemy-menu-hint\">{hint}</small> : null}</span></>;\n}\nexport function DestinationPresentation({ action }: { action: PageAction & TransferMenuPresentation }) {\n const paths: Record<string, string> = {\n notes: \"M5 3h14v18H5zM8 8h8M8 12h8M8 16h5\",\n scratch: \"M5 3h14v18H5zM9 12h6M12 9v6\",\n document: \"M6 3h8l4 4v14H6zM14 3v5h4M9 12h6M9 16h6\",\n workbook: \"M3 4h18v16H3zM3 9h18M9 4v16M15 9v11M3 15h18\",\n task: \"M9 6h11M9 12h11M9 18h11M3 6l1 1 2-2M3 12l1 1 2-2M3 18l1 1 2-2\",\n attach: \"m9 12 5-5a3 3 0 0 1 4 4l-7 7a5 5 0 0 1-7-7l8-8M7 14l7-7\",\n code: \"m8 6-6 6 6 6m8-12 6 6-6 6m-3-14-2 16\",\n chat: \"M4 4h16v13H9l-5 4zM8 9h8M8 13h5\",\n assistant: \"M3 4h18v16H3zM15 4v16M6 9h6M6 13h4\",\n tools: \"m14 4 3 3 4-1a6 6 0 0 1-8 7l-7 7-3-3 7-7a6 6 0 0 1 4-6z\",\n };\n const path = paths[action.id.replace(/^matrx:/, \"\")];\n return <>{action.icon ? <action.icon className=\"matrx-alchemy-menu-icon\"/> : path ? <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d={path}/></svg> : <PaletteGlyph file/>}<span>{action.label}{action.hint ? <small className=\"matrx-alchemy-menu-hint\">{action.hint}</small> : null}</span></>;\n}\nexport function ReceiptLink({ target }: { target: TransferTarget | undefined }) {\n return target?.href && /^(\\/(?!\\/)|https?:\\/\\/)/.test(target.href) ? <a className=\"matrx-alchemy-receipt-link\" href={target.href}>Open {target.kind}</a> : null;\n}\nexport function PaletteGlyph({ format, ai = false, file = false, kind }: { format?: string; ai?: boolean; file?: boolean; kind?: \"ai-copy\" | \"sliders\" | \"link\" | \"surface\" }) {\n if (kind === \"link\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2\"/></svg>;\n if (kind === \"surface\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"/><path d=\"M3 9h18M9 9v12\"/></svg>;\n if (kind === \"ai-copy\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"5\" y=\"5\" width=\"11\" height=\"14\" rx=\"2\"/><path d=\"M9 3h6a2 2 0 0 1 2 2v10\"/><path d=\"m18.5 3 .55 1.45L20.5 5l-1.45.55L18.5 7l-.55-1.45L16.5 5l1.45-.55z\"/></svg>;\n if (kind === \"sliders\") return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M4 6h16M4 12h16M4 18h16\"/><path d=\"M8 3v6M16 9v6M10 15v6\"/></svg>;\n if (ai) return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 5a3 3 0 1 0-5.997.125A4 4 0 0 0 3.5 10.9a4 4 0 0 0 .556 6.588A4 4 0 0 0 12 19\"/><path d=\"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.503 5.775 4 4 0 0 1-.556 6.588A4 4 0 0 1 12 19\"/><path d=\"M12 5v14M8 9h1M15 9h1M8 15h1M15 15h1\"/></svg>;\n if (file) return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M6 3h8l4 4v14H6z\"/><path d=\"M14 3v5h5M9 13h6M9 17h6\"/></svg>;\n const path = format === \"json\" || format === \"table-data\" ? <><path d=\"M9 4C7 4 7 7 5 7v3c2 0 2 1 2 2s0 2-2 2v3c2 0 2 3 4 3\"/><path d=\"M15 4c2 0 2 3 4 3v3c-2 0-2 1-2 2s0 2 2 2v3c-2 0-2 3-4 3\"/></>\n : format === \"table-schema\" ? <><rect x=\"8\" y=\"3\" width=\"8\" height=\"5\" rx=\"1\"/><rect x=\"2\" y=\"16\" width=\"8\" height=\"5\" rx=\"1\"/><rect x=\"14\" y=\"16\" width=\"8\" height=\"5\" rx=\"1\"/><path d=\"M12 8v4M6 16v-4h12v4\"/></>\n : format === \"compact-json\" ? <><path d=\"m14 10 7-7\"/><path d=\"M20 10h-6V4\"/><path d=\"m3 21 7-7\"/><path d=\"M4 14h6v6\"/></>\n : format === \"csv\" ? <><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1\"/><path d=\"M4 10h16M10 4v16\"/></>\n : format === \"tsv\" ? <><path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h2M14 13h2M8 17h2M14 17h2\"/></>\n : format === \"xlsx\" ? <><path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h8M8 17h8M12 11v8\"/></>\n : format === \"markdown\" ? <><path d=\"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5z\"/><path d=\"M14 2v6h6M10 13l-2 2 2 2M14 17l2-2-2-2\"/></>\n : format === \"html\" ? <><path d=\"M15 6h6M3 6h7M3 12h18M3 18h12\"/></>\n : <><path d=\"M4 7V4h16v3M9 20h6M12 4v16\"/></>;\n return <svg className=\"matrx-alchemy-palette-glyph\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">{path}</svg>;\n}\n\nexport const LABEL: Record<BuiltInFormat, string> = { plain: \"Plain text\", markdown: \"Markdown\", html: \"Formatted\", json: \"JSON\", \"compact-json\": \"Compact JSON\", csv: \"CSV\", tsv: \"Google Sheets\", xlsx: \"Excel workbook\" };\nexport const BUILT_INS = Object.freeze((Object.keys(LABEL) as BuiltInFormat[]).map((id) => ({ id })));\nexport const COPIES: SerializableFormat[] = [\"plain\", \"markdown\", \"html\", \"json\", \"compact-json\", \"csv\", \"tsv\"];\nexport const DOWNLOADS: BuiltInFormat[] = [...COPIES, \"xlsx\"];\nexport const EMPTY_VARIANTS: readonly { id: string; label: string; source: Source | Payload }[] = [];\nexport const SCOPE_LABEL: Record<TransferScope, string> = { target: \"This content\", row: \"This row\", selected: \"Selected rows\", view: \"Current view\", loaded: \"Loaded rows\", \"all-matching\": \"All matching rows\" };\nexport const filenameFor = (label: string) => label.toLocaleLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/(^-|-$)/g, \"\") || \"export\";\nexport const errorMessage = (error: unknown, fallback: string) => error instanceof Error ? error.message : fallback;\nexport const isAbort = (error: unknown) => error instanceof DOMException && error.name === \"AbortError\";\nexport const supportsBuiltIn = (format: BuiltInFormat, payload: Payload) => ![\"csv\", \"tsv\", \"xlsx\"].includes(format) || payload.kind === \"rows\";\nexport const outcomeMessage = (result: TransferOutcome) => {\n if (result.status === \"success\") {\n const success = result as TransferOutcome & { delivered: string; message?: string };\n return success.delivered === \"action\" ? success.message ?? \"Action completed\" : success.delivered === \"download-started\" ? \"Download started\" : success.message ?? \"Copied\";\n }\n // A queued write is NEITHER a delivery nor a failure (kit `TransferOutcome`\n // `queued`): the host's sentence alone reads as \"done\", so the remedy — what\n // has not happened yet and what the person does next — is always spoken with\n // it, and the pending request rides the same receipt door as any target.\n if (result.status === \"queued\") return `${result.message} ${result.remedy}`;\n return result.status === \"degraded\" ? `Copied as plain text: ${result.reason}` : result.status === \"cancelled\" ? \"Cancelled\" : result.message;\n};\nexport const materialIds = new WeakMap<object, number>();\nlet nextMaterialId = 0;\nexport function materialIdentity(material: Source | Payload | SurfaceHandle | null | undefined) {\n if (!material) return \"missing\";\n if (\"instanceId\" in material) return `surface:${material.instanceId}`;\n if (\"id\" in material) return `source:${material.id}`;\n let id = materialIds.get(material);\n if (id === undefined) { id = ++nextMaterialId; materialIds.set(material, id); }\n return `payload:${id}`;\n}\n\nexport type CaptureResult = { snapshot: Snapshot; allMatching?: BoundAllMatching; collectionError?: string };\nexport type WorkspaceState = CaptureResult & {\n sourceStale?: boolean | undefined;\n key: string;\n original: Draft;\n draft: Draft;\n scope: TransferScope;\n preferences: TransferPreferences;\n pending?: (CaptureResult & { scope: TransferScope }) | undefined;\n error?: string | undefined;\n /** The host's own levers for this source (aiCustom options, groomer sections), live beside the preview (PP-02). */\n levers?: WorkspaceLevers | undefined;\n leverValues?: LeverValues | undefined;\n /** The host builder's meta for the current lever values (\"messages 12/40\"), shown in the top bar (PP-03). */\n leverMeta?: LeverMeta | undefined;\n /** A host builder that threw: its sentence is the preview, nothing else breaks (PP-02). */\n buildError?: string | undefined;\n /** Per groomer section, its size in the prepared JSON at its current level (PP-04). */\n leverSizes?: Record<string, number> | undefined;\n /** Who this content is, for the AI envelope (PP-10). Absent = a generic \"matrx_content\" envelope. */\n envelope?: EnvelopeMeta | undefined;\n};\n\n/** Compare captured meaning at the user action boundary, never during render. */\nexport function snapshotContent(snapshot: Snapshot) {\n const { sourceId, label, payload, coverage, unsavedChanges, omissions, sections, limits } = snapshot;\n return JSON.stringify({ sourceId, label, payload, coverage, unsavedChanges, omissions, sections, limits });\n}\n\nexport function useFence() {\n const mounted = React.useRef(true);\n const nextId = React.useRef(0);\n const active = React.useRef(new Set<AbortController>());\n React.useEffect(() => {\n mounted.current = true;\n return () => { mounted.current = false; nextId.current += 1; active.current.forEach((c) => c.abort()); active.current.clear(); };\n }, []);\n const begin = React.useCallback(() => { const controller = new AbortController(); active.current.add(controller); return { controller, id: ++nextId.current }; }, []);\n const finish = React.useCallback((controller: AbortController) => active.current.delete(controller), []);\n const valid = React.useCallback((id: number, controller: AbortController) => mounted.current && !controller.signal.aborted && nextId.current === id, []);\n const abortAll = React.useCallback(() => { nextId.current += 1; active.current.forEach((c) => c.abort()); active.current.clear(); }, []);\n return { begin, finish, valid, abortAll };\n}\n\n/** The one Excel engine (`@ai-matrx/alchemy/operate/formats/xlsx`, SheetJS loads only there). */\nexport async function xlsxArtifact(draft: Draft, label: string): Promise<Artifact> {\n if (draft.payload.kind !== \"rows\") throw new Error(\"Excel workbook export requires tabular content.\");\n const { xlsxEngine } = await import(\"@ai-matrx/alchemy/operate/formats/xlsx\");\n return xlsxEngine.build(draft, { filename: `${filenameFor(label)}.xlsx` }, new AbortController().signal);\n}\n/** A lazy format adapter's bytes (CONTRACT §2.3): its engine loads on first use, then builds. */\nexport async function buildWithAdapter(adapter: FormatAdapter, draft: Draft, signal: AbortSignal, options: FormatOptions = {}): Promise<Artifact> {\n return (await adapter.load()).build(draft, options, signal);\n}\n/**\n * Rich Markdown (the clipboard's text/html beside the Markdown as text/plain): HTML from THE one\n * Markdown→HTML engine (`@ai-matrx/print/markdown-html`, through operate's `rich-html`).\n */\nexport async function markdownRichArtifact(draft: Draft, filename = \"export.html\"): Promise<Artifact> {\n if (draft.payload.kind !== \"markdown\") throw new Error(\"Rich Markdown requires Markdown content.\");\n const { richHtmlEngine } = await import(\"@ai-matrx/alchemy/operate/formats/rich-html\");\n const rich = await richHtmlEngine.build(draft, { filename }, new AbortController().signal);\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"html\",\n plainText: draft.payload.text,\n ...(rich.html === undefined ? {} : { html: rich.html }),\n ...(rich.file === undefined ? {} : { file: rich.file }),\n omissions: [...draft.omissions],\n });\n}\nexport async function buildArtifact(draft: Draft, format: BuiltInFormat, label: string): Promise<Artifact> {\n if (!supportsBuiltIn(format, draft.payload)) throw new Error(`${LABEL[format]} is available for tabular content only.`);\n if (format === \"xlsx\") return xlsxArtifact(draft, label);\n if (format === \"html\" && draft.payload.kind === \"markdown\") return markdownRichArtifact(draft, `${filenameFor(label)}.html`);\n const extension = format === \"plain\" ? \"txt\" : format === \"compact-json\" ? \"json\" : format;\n return serialize(draft, format, { filename: `${filenameFor(label)}.${extension}` });\n}\n/**\n * A host format registered under a built-in id SUPERSEDES that built-in (ALC-15 round 5, A): the\n * host's engine builds it under the built-in's name, never as a second entry. This is how a host\n * gives a Markdown draft real plain text from its one Markdown engine — kit's sync serializer can\n * only echo the Markdown back. The file keeps the source's name.\n */\nexport function hostEngineFor(adapters: readonly FormatAdapter[], format: string): FormatAdapter | undefined {\n return isBuiltInFormat(format) ? adapters.find((adapter) => adapter.id === format) : undefined;\n}\nexport async function buildFormat(draft: Draft, format: BuiltInFormat, label: string, adapters: readonly FormatAdapter[], signal: AbortSignal): Promise<Artifact> {\n const engine = hostEngineFor(adapters, format);\n if (!engine) return buildArtifact(draft, format, label);\n const artifact = await buildWithAdapter(engine, draft, signal);\n if (!artifact.file) return artifact;\n const dot = artifact.file.filename.lastIndexOf(\".\");\n const extension = dot > 0 ? artifact.file.filename.slice(dot) : \"\";\n return sealTransferArtifact({ ...artifact, file: { filename: `${filenameFor(label)}${extension}`, mime: artifact.file.mime, bytes: artifact.file.bytes } });\n}\n/** Offered for this payload: the host engine's own answer when it supersedes the built-in, else the built-in rule. */\nexport function offersFormat(format: BuiltInFormat, payload: Payload, adapters: readonly FormatAdapter[]): boolean {\n // Rows: \"Plain text\" IS the tab-separated table (built-in and the host's one engine alike), so\n // it would be the Google Sheets bytes under a second name — TSV is offered, plain is not.\n if (format === \"plain\" && payload.kind === \"rows\") return false;\n const engine = hostEngineFor(adapters, format);\n return engine ? engine.supports(payload) : supportsBuiltIn(format, payload) && offersDistinctOutput(format, payload);\n}\n\nexport type Preset = \"full\" | \"compact\" | \"brief\" | \"custom\";\nexport type Controls = {\n preset: Preset;\n sections: string[];\n /** Rows: the search that shapes the copy (every shown column), and how it matches (PP-08). */\n search: string;\n searchMode: TableSearchMatchMode;\n filters: Record<string, string>;\n layeredFilters: LayeredFilterRule[];\n sort: string;\n direction: \"asc\" | \"desc\";\n top: number | null;\n visibleColumns: string[];\n /** Rows left out by their include checkbox, as positions in the captured rows (PP-06c). */\n excludedRows: number[];\n /** JSON: excluded patterns and per-node limits (PP-06b, PP-07). */\n structure: StructureRecipe;\n /** Per section id / column id: stub or cap (PP-07). */\n sectionLimits: Record<string, NodeLimit>;\n columnLimits: Record<string, NodeLimit>;\n maxDepth: number | null;\n maxStringChars: number | null;\n maxArrayItems: number | null;\n};\n\nexport const NO_STRUCTURE: StructureRecipe = { exclude: [], limits: {} };\n/** A column a person may export: never one declared non-exportable, secret or a credential. */\nexport const exportableColumn = (column: Column) => column.exportable !== false && column.classification !== \"secret\" && column.classification !== \"credential\";\n\nexport function initialControls(state: WorkspaceState): Controls {\n const rows = state.original.payload.kind === \"rows\" ? state.original.payload : null;\n return {\n preset: state.preferences.initialPreset,\n sections: state.snapshot.sections.filter((s) => s.includedByDefault).map((s) => s.id),\n search: \"\", searchMode: \"contains\", filters: {}, layeredFilters: [], sort: \"\", direction: \"asc\",\n top: state.preferences.limits.maxRows,\n visibleColumns: rows?.columns.filter((c) => c.visible && exportableColumn(c)).map((c) => c.id) ?? [],\n excludedRows: [],\n structure: NO_STRUCTURE, sectionLimits: {}, columnLimits: {},\n maxDepth: state.preferences.limits.maxDepth,\n maxStringChars: state.preferences.limits.maxStringChars,\n maxArrayItems: state.preferences.limits.maxArrayItems ?? null,\n };\n}\nexport function presetLimits(preset: Preset, controls: Controls, preferences: TransferPreferences) {\n const min = (choice: number | null, cap: number | null) => choice == null ? cap : cap == null ? choice : Math.min(choice, cap);\n if (preset === \"full\") return preferences.limits;\n const request = preset === \"brief\" ? { maxDepth: 4, maxStringChars: 800, maxArrayItems: 25 } : preset === \"compact\" ? { maxDepth: 8, maxStringChars: 4000, maxArrayItems: 100 } : { maxDepth: controls.maxDepth, maxStringChars: controls.maxStringChars, maxArrayItems: controls.maxArrayItems };\n return { ...preferences.limits, maxDepth: min(request.maxDepth, preferences.limits.maxDepth), maxStringChars: min(request.maxStringChars, preferences.limits.maxStringChars), maxArrayItems: min(request.maxArrayItems, preferences.limits.maxArrayItems ?? null) };\n}\n\n/** Where the structure choices put things in a rebuilt draft — read by highlighting and the diff. */\nexport interface DraftLayout {\n /** Rows: every captured row position the search and filters match, in output order (included or not). */\n matchedRows?: number[];\n /** Rows: the captured positions that are in the output, in output order. */\n rowOrder?: number[];\n /** Prose sections: where each kept section sits in the draft text. */\n sectionRanges?: Record<string, { start: number; end: number }>;\n sectionText?: string;\n}\nconst layouts = new WeakMap<Draft, DraftLayout>();\nexport const draftLayout = (draft: Draft): DraftLayout => layouts.get(draft) ?? {};\n\n/**\n * Rows the copy-subset way (PP-08): search every shown column (contains or whole words), per-column\n * filters, layered filters and sort through the data table's ONE filter engine — the table and the\n * copy never disagree. Hidden columns neither show nor filter nor sort. The captured rows are only\n * read: the result is new arrays of the same row objects.\n */\nexport function matchRows(payload: Extract<Payload, { kind: \"rows\" }>, controls: Controls): number[] {\n const shown = new Set(controls.visibleColumns);\n const columns = payload.columns.filter((column) => shown.has(column.id) && exportableColumn(column));\n const defs: MatrxColumnDef<number>[] = columns.map((column) => ({ id: column.id, header: column.label, accessorFn: (index: number) => readTransferCell(payload.rows[index]!, column) }));\n const filters: ColumnFiltersState = Object.fromEntries(Object.entries(controls.filters).filter(([id, value]) => value && shown.has(id)).map(([id, value]) => [id, { kind: \"text\" as const, value }]));\n const sort = controls.sort && shown.has(controls.sort) ? { id: controls.sort, direction: controls.direction } : null;\n return filterAndSortRows(payload.rows.map((_, index) => index), defs, filters, sort, controls.search, undefined, controls.layeredFilters.filter((rule) => shown.has(rule.field)), controls.searchMode);\n}\n\nfunction applyColumnLimits(draft: Draft, limits: Record<string, NodeLimit>): Draft {\n const payload = draft.payload;\n const entries = Object.entries(limits);\n if (payload.kind !== \"rows\" || !entries.length) return draft;\n const omissions: Draft[\"omissions\"] = [];\n let rows = payload.rows;\n for (const [id, limit] of entries) {\n const column = payload.columns.find((candidate) => candidate.id === id);\n if (!column || limit.kind === \"maxItems\") continue;\n let count = 0;\n rows = rows.map((row) => {\n const value = row[id];\n if (value === undefined || value === null) return row;\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n if (limit.kind === \"stub\") { count++; return { ...row, [id]: stubText(value) }; }\n if (text.length <= limit.value) return row;\n count++;\n return { ...row, [id]: `${text.slice(0, limit.value)} … [truncated — ${formatCount(text.length, { locale: \"en-US\" })} chars]` };\n });\n if (count) omissions.push({ path: `/columns/${id}`, reason: \"truncated\", count, label: `${column.label} — ${limit.kind === \"stub\" ? \"stubbed\" : `cut to ${formatCount(limit.value)} chars per cell`}` });\n }\n return omissions.length ? deriveDraft(draft, { ...payload, rows }, omissions, \"Column limits\") : draft;\n}\n\nexport function rebuild(state: WorkspaceState, controls: Controls): Draft {\n let draft = resetDraft(state.snapshot);\n const layout: DraftLayout = {};\n const sections = state.snapshot.sections;\n if (sections.length) {\n const payload = draft.payload;\n if ((payload.kind === \"text\" || payload.kind === \"markdown\") && sections.every(isProseSection)) {\n const laid = sectionLayout(payload.text, sections, controls.sections, controls.sectionLimits);\n draft = deriveDraft(draft, { ...payload, text: laid.text }, laid.omissions, \"Selected sections\");\n layout.sectionRanges = laid.ranges;\n layout.sectionText = laid.text;\n } else if (payload.kind === \"json\" || payload.kind === \"registered\") {\n draft = applySectionStructure(draft, sections, controls.sections, controls.sectionLimits);\n } else draft = applySectionSelection(draft, state.snapshot, controls.sections);\n }\n if (draft.payload.kind === \"rows\") {\n const payload = draft.payload;\n const matched = matchRows(payload, controls);\n const left = new Set(controls.excludedRows);\n const order = matched.filter((index) => !left.has(index));\n layout.matchedRows = matched;\n layout.rowOrder = order;\n const omissions: Draft[\"omissions\"] = [];\n if (matched.length < payload.rows.length) omissions.push({ path: \"/rows\", reason: \"filtered\", count: payload.rows.length - matched.length, label: \"rows the search and filters leave out\" });\n if (order.length < matched.length) omissions.push({ path: \"/rows\", reason: \"excluded\", count: matched.length - order.length, label: \"rows you left out\" });\n const identity = order.length === payload.rows.length && order.every((index, position) => index === position);\n if (!identity) draft = deriveDraft(draft, { ...payload, rows: order.map((index) => payload.rows[index]!) }, omissions, \"Rows you chose\");\n const visible = controls.visibleColumns.filter((id) => payload.columns.some((column) => column.id === id && exportableColumn(column)));\n draft = transformRows(draft, { visibleColumns: visible, structuredProjection: \"visible\", top: controls.top });\n if (controls.top != null && order.length > controls.top) layout.rowOrder = order.slice(0, controls.top);\n draft = applyColumnLimits(draft, controls.columnLimits);\n }\n if (draft.payload.kind === \"json\" || draft.payload.kind === \"registered\") draft = applyJsonStructure(draft, controls.structure);\n const limits = presetLimits(controls.preset, controls, state.preferences);\n if (draft.payload.kind === \"json\" || draft.payload.kind === \"registered\") {\n draft = reduceJson(draft, { maxDepth: limits.maxDepth, maxStringChars: limits.maxStringChars, maxArrayItems: limits.maxArrayItems ?? null });\n }\n const final = applyTransferLimits(draft, limits);\n layouts.set(final, layout);\n return final;\n}\n/**\n * A format is offered only when it produces its OWN bytes for this payload (ALC-15 round 4, A):\n * the workspace's sync serializer writes a Markdown draft's \"plain text\" as the same Markdown, and a\n * prose draft's compact JSON as the same JSON string, and a JSON draft's plain text and Markdown as the\n * JSON — two labels, one output. A host that registers its own engine under the built-in id (the app's\n * one Markdown engine for plain text) brings the format back with real output (hostEngineFor).\n */\nexport function offersDistinctOutput(format: BuiltInFormat, payload: Payload): boolean {\n if (payload.kind === \"markdown\") return format !== \"plain\" && format !== \"compact-json\";\n // Structured content: kit writes its \"plain text\" and \"Markdown\" as the same pretty JSON — JSON is offered as JSON.\n if (payload.kind === \"json\" || payload.kind === \"registered\") return format !== \"plain\" && format !== \"markdown\";\n if (payload.kind === \"text\") return format !== \"compact-json\" && (format !== \"markdown\" || Boolean(payload.language));\n return true;\n}\n/** \"message\" → \"messages\"; the count unit a source declared, else \"section\". */\nexport function countNoun(unit: string, n: number): string { return n === 1 ? unit : `${unit}s`; }\nexport function isBuiltInFormat(format: string): format is BuiltInFormat { return format in LABEL; }\nexport function preview(draft: Draft, format: string) {\n const resolved = isBuiltInFormat(format) ? format : \"plain\";\n return serialize(draft, resolved === \"xlsx\" ? \"tsv\" : resolved).plainText;\n}\n\n// ── PP-10: the AI envelope around the chosen format, sealed ───────────────────────────────────\n\n/** The envelope's `<data format>` for an output format, or null when the format is not text for a model. */\nexport function envelopeDataFormat(format: string, artifact: Artifact): string | null {\n if (format === \"html\" || format === \"xlsx\" || artifact.html !== undefined) return null;\n if (format === \"plain\") return \"text\";\n return /^[a-z][a-z0-9-]*$/.test(format) ? format : \"text\";\n}\nexport function defaultEnvelope(snapshot: Snapshot): EnvelopeMeta {\n return { kind: \"matrx_content\", location: snapshot.label, description: \"Captured content for an assistant\", attributes: { source: snapshot.sourceId } };\n}\n/** Where the envelope wrote its body in a sealed For-AI artifact (for the span map, PP-06a). */\nconst envelopeBodies = new WeakMap<Artifact, { body: string; bodyOffset: number; dataFormat: string }>();\n/**\n * The one artifact the preview shows and Copy writes when \"For AI\" is on: the chosen format's\n * bytes inside the AI envelope, the person's instructions first — all inside the seal.\n */\nexport function sealForAi(formatArtifact: Artifact, dataFormat: string, envelope: EnvelopeMeta, instructions: string, label: string): Artifact {\n const data = dataFormat === \"json\" ? (JSON.parse(formatArtifact.plainText) as unknown) : formatArtifact.plainText;\n const { text, body, bodyOffset } = assembleAgentPayload({ ...envelope, data, dataFormat, ...(instructions.trim() ? { instructions } : {}) });\n const artifact = sealTransferArtifact({\n snapshotId: formatArtifact.snapshotId,\n draftRevision: formatArtifact.draftRevision,\n format: `ai-context:${formatArtifact.format}`,\n plainText: text,\n file: { filename: `${filenameFor(label)}-for-ai.md`, mime: \"text/markdown;charset=utf-8\", bytes: new TextEncoder().encode(text) },\n omissions: [...formatArtifact.omissions],\n });\n envelopeBodies.set(artifact, { body, bodyOffset, dataFormat });\n return artifact;\n}\n\n/**\n * Every node → its span in the text the preview SHOWS (the bare format, or the For-AI envelope\n * around it). Null when this format has no span map (a host engine's own format) — the caller says\n * so instead of guessing.\n */\nexport function shownSpans(draft: Draft, formatArtifact: Artifact, shown: Artifact): SpanMap | null {\n let base: SpanMap;\n try { base = spanMap(draft, formatArtifact); } catch { return null; }\n if (shown === formatArtifact) return base;\n const envelope = envelopeBodies.get(shown);\n if (!envelope) return null;\n try {\n if (envelope.dataFormat !== \"json\") return envelope.body === formatArtifact.plainText ? offsetSpans(base, envelope.bodyOffset) : null;\n const spans = jsonTextSpans(envelope.body, \"\", envelope.bodyOffset);\n return draft.payload.kind === \"rows\" ? spans.map((span) => ({ ...span, path: `/rows${span.path}` })) : spans;\n } catch { return null; }\n}\n/** A prose section's span: the draft text's own span plus where the section landed in it. */\nexport function sectionSpan(draft: Draft, spans: SpanMap, text: string, sectionId: string): OutputSpan | null {\n const layout = draftLayout(draft);\n const range = layout.sectionRanges?.[sectionId];\n const whole = spans.find((span) => span.path === \"\");\n const payload = draft.payload;\n if (!range || !whole || (payload.kind !== \"text\" && payload.kind !== \"markdown\") || layout.sectionText !== payload.text) return null;\n if (text.slice(whole.start, whole.end) !== payload.text) return null;\n return { path: `/sections/${sectionId}`, start: whole.start + range.start, end: whole.start + range.end };\n}\n\nexport const encodePointer = (segment: string) => segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\nexport type Mark = { start: number; end: number; kind: \"focus\" | \"match\" | \"removed\" | \"changed\" };\nconst sortMarks = (marks: Mark[]) => marks.sort((a, b) => a.start - b.start || b.end - a.end);\n/** Drop marks nested inside an earlier mark of the same kind (a removed row holds its cells). */\nfunction outermost(marks: Mark[]): Mark[] {\n const out: Mark[] = [];\n for (const mark of sortMarks(marks)) {\n const last = out[out.length - 1];\n if (last && mark.start >= last.start && mark.end <= last.end) continue;\n out.push(mark);\n }\n return out;\n}\n\n/**\n * \"Show what was removed\" (PP-07): the Full text (this format, before the structure choices) with\n * every removed node and every stubbed or capped node marked, read through the span map — exact,\n * never a guess by text similarity.\n */\n/**\n * Where each prose section landed in an output a host engine REWROTE (Markdown → plain text): each\n * section's own text projected alone through the same engine and found, in order, in the output.\n * Exact when the engine projects block by block (it does: sections start at line starts); a\n * section it cannot find is simply absent — the caller says so, it never guesses a range.\n */\nexport async function locateProjectedSections(output: string, pieces: readonly { id: string; text: string }[], engine: FormatAdapter, signal: AbortSignal): Promise<Record<string, { start: number; end: number }>> {\n const found: Record<string, { start: number; end: number }> = {};\n let cursor = 0;\n for (const piece of pieces) {\n const draft = { snapshotId: \"section\", sourceId: \"section\", sourceRevision: \"section\", revision: 0, payload: { kind: \"markdown\", text: piece.text }, omissions: [], manuallyEdited: false, provenance: [] } as unknown as Draft;\n const projected = (await buildWithAdapter(engine, draft, signal)).plainText.trim();\n if (!projected) continue;\n const at = output.indexOf(projected, cursor);\n if (at < 0) continue;\n found[piece.id] = { start: at, end: at + projected.length };\n cursor = at + projected.length;\n }\n return found;\n}\n\nexport function removedMarks(state: WorkspaceState, controls: Controls, full: Draft, fullArtifact: Artifact, projected?: Record<string, { start: number; end: number }>): { marks: Mark[]; removed: number; changed: number; chars: number } | null {\n let spans: SpanMap;\n try { spans = spanMap(full, fullArtifact); } catch { return null; }\n const byPath = new Map(spans.map((span) => [span.path, span]));\n const marks: Mark[] = [];\n const mark = (path: string, kind: Mark[\"kind\"]) => { const span = byPath.get(path); if (span && span.end > span.start) marks.push({ start: span.start, end: span.end, kind }); };\n const payload = full.payload;\n if (payload.kind === \"json\" || payload.kind === \"registered\") {\n for (const pattern of controls.structure.exclude) concretePointers(payload.value, pattern).forEach((pointer) => mark(pointer, \"removed\"));\n for (const pattern of Object.keys(controls.structure.limits)) concretePointers(payload.value, pattern).forEach((pointer) => mark(pointer, \"changed\"));\n }\n const sections = state.snapshot.sections;\n if (sections.length) {\n const keep = new Set(controls.sections);\n if ((payload.kind === \"text\" || payload.kind === \"markdown\") && sections.every(isProseSection)) {\n const whole = byPath.get(\"\");\n const exact = whole && fullArtifact.plainText.slice(whole.start, whole.end) === payload.text;\n for (const section of sections) {\n const [, a, b] = /^\\/text\\/(\\d+)-(\\d+)$/.exec(section.path)!;\n const kind: Mark[\"kind\"] | null = !keep.has(section.id) ? \"removed\" : controls.sectionLimits[section.id] ? \"changed\" : null;\n if (!kind) continue;\n if (exact) marks.push({ start: whole.start + Number(a), end: whole.start + Number(b), kind });\n else if (projected?.[section.id]) marks.push({ ...projected[section.id]!, kind });\n }\n } else for (const section of sections) {\n if (!keep.has(section.id)) mark(section.path, \"removed\");\n else if (controls.sectionLimits[section.id]) mark(section.path, \"changed\");\n }\n }\n if (payload.kind === \"rows\") {\n const kept = new Set(draftLayout(state.draft).rowOrder ?? payload.rows.map((_, index) => index));\n const shown = new Set(controls.visibleColumns);\n const hidden = payload.columns.filter((column) => column.visible && exportableColumn(column) && !shown.has(column.id));\n payload.rows.forEach((_, index) => {\n if (!kept.has(index)) { mark(`/rows/${index}`, \"removed\"); return; }\n // A cell sits at its column path (CSV, TSV, Markdown, plain) or under its id (JSON records).\n const cell = (column: Column, kind: Mark[\"kind\"]) => { mark(`/rows/${index}${column.path}`, kind); mark(`/rows/${index}/${encodePointer(column.id)}`, kind); };\n for (const column of hidden) cell(column, \"removed\");\n for (const id of Object.keys(controls.columnLimits)) {\n const column = payload.columns.find((candidate) => candidate.id === id);\n if (column && shown.has(id)) cell(column, \"changed\");\n }\n });\n for (const column of hidden) mark(`/columns/${encodePointer(column.id)}`, \"removed\");\n }\n const merged = [...outermost(marks.filter((m) => m.kind === \"removed\")), ...outermost(marks.filter((m) => m.kind === \"changed\"))];\n return {\n marks: sortMarks(merged),\n removed: merged.filter((m) => m.kind === \"removed\").length,\n changed: merged.filter((m) => m.kind === \"changed\").length,\n chars: merged.filter((m) => m.kind === \"removed\").reduce((sum, m) => sum + m.end - m.start, 0),\n };\n}\n\n/** Matches of a search in the shown text (contains, or whole words), capped for drawing. */\nexport function findMatches(text: string, query: string, mode: TableSearchMatchMode, cap = 1000): { marks: Mark[]; total: number } {\n const trimmed = query.trim();\n if (!trimmed) return { marks: [], total: 0 };\n const escape = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = mode === \"whole_words\"\n ? new RegExp(trimmed.split(/[^\\p{L}\\p{N}]+/u).filter(Boolean).map((word) => `(?<![\\\\p{L}\\\\p{N}])${escape(word)}(?![\\\\p{L}\\\\p{N}])`).join(\"|\") || \"(?!)\", \"giu\")\n : new RegExp(escape(trimmed), \"gi\");\n const marks: Mark[] = [];\n let total = 0;\n for (const match of text.matchAll(pattern)) {\n if (!match[0]) continue;\n total++;\n if (marks.length < cap) marks.push({ start: match.index ?? 0, end: (match.index ?? 0) + match[0].length, kind: \"match\" });\n }\n return { marks, total };\n}\n/** Re-export for the trees (one import site). */\nexport { pointerSegments };\nexport type { Json };\n\n// ── PP-04: sizes ───────────────────────────────────────────────────────────────────────────────\n\nconst decodePointer = (segment: string) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n/** A section's own size in the prepared text: a prose range's length, or its JSON as it sits nested. */\nexport function sectionSize(payload: Payload, path: string): number | null {\n const range = /^\\/text\\/(\\d+)-(\\d+)$/.exec(path);\n if (range && (payload.kind === \"text\" || payload.kind === \"markdown\")) return Math.max(0, Number(range[2]) - Number(range[1]));\n if (payload.kind !== \"json\" && payload.kind !== \"registered\") return null;\n const segments = path.split(\"/\").slice(1).map(decodePointer);\n let value: unknown = payload.value;\n for (const segment of segments) {\n if (value === null || typeof value !== \"object\") return null;\n value = (value as Record<string, unknown>)[segment];\n }\n const text = JSON.stringify(value, null, 2);\n return text === undefined ? null : text.replace(/\\n/g, `\\n${\" \".repeat(segments.length)}`).length;\n}\nexport function columnSize(rows: Extract<Payload, { kind: \"rows\" }>, columnId: string): number {\n const column = rows.columns.find((c) => c.id === columnId);\n if (!column) return 0;\n let total = 0;\n for (const row of rows.rows) {\n const value = readTransferCell(row, column);\n total += value === null || value === undefined ? 0 : typeof value === \"string\" ? value.length : JSON.stringify(value).length;\n }\n return total;\n}\n/** \"12,345 chars · ≈3,087 tokens\" — the token figure always says it is an estimate. */\nexport function sizeLabel(chars: number): string {\n return `${formatCount(chars)} chars · ≈${formatCount(Math.ceil(chars / 4))} tokens`;\n}\n","\"use client\";\n\n/**\n * THE preparation workspace (Preparation parity PP-01b, PP-01c, PP-02, PP-03, PP-04, PP-09, PP-10).\n *\n * One surface: the source's structure (sections, groomer sections, columns and rows) on the left,\n * ONE read-only preview of the exact sealed bytes in the middle, and the host's own levers,\n * instructions, AI preparation and destinations on the right. The envelope toggle (Text / For AI)\n * chooses the one artifact the preview shows and the one Copy writes — preview = copy = download.\n *\n * Frames: inside a host window (`ContentTransferCapabilities.window`, the host's `WindowPort`) the\n * host draws the title bar and the close control; without one it is a near-full-screen dialog.\n * Below 768px of its own width it is three tabs (Structure / Preview / Settings) with Copy in a\n * footer every tab shares.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport { createPortal, flushSync } from \"react-dom\";\nimport {\n concretePointers,\n createDraft,\n editDraft,\n outputPointer,\n patternCovers,\n readTransferCell,\n resetDraft,\n resolveTransferPreferences,\n sealTransferArtifact,\n serialize,\n undoDraft,\n type Column,\n type Draft,\n type NodeLimit,\n type AiPreparation,\n type Artifact,\n type FormatAdapter,\n type Json,\n type PageAction,\n type Payload,\n type TransferOutcome,\n type TransferScope,\n type Transport,\n} from \"@ai-matrx/alchemy/operate\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from \"@ai-matrx/design-system\";\nimport { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuLabel, ContextMenuTrigger } from \"@ai-matrx/design-system\";\nimport { LayeredFilterBuilder } from \"@ai-matrx/design-system/data-table\";\nimport type { LayeredFilterField } from \"@ai-matrx/design-system/data-table\";\nimport {\n COPIES,\n DestinationPresentation,\n LABEL,\n SCOPE_LABEL,\n buildArtifact,\n buildFormat,\n columnSize,\n countNoun,\n defaultEnvelope,\n draftLayout,\n encodePointer,\n exportableColumn,\n findMatches,\n locateProjectedSections,\n removedMarks,\n sectionSpan,\n shownSpans,\n envelopeDataFormat,\n errorMessage,\n buildWithAdapter,\n hostEngineFor,\n initialControls,\n isAbort,\n isBuiltInFormat,\n offersFormat,\n outcomeMessage,\n rebuild,\n sealForAi,\n sectionSize,\n sizeLabel,\n useFence,\n type CaptureResult,\n type Controls,\n type Mark,\n type Preset,\n type WorkspaceState,\n} from \"./workspace-core\";\nimport {\n activeGroomerPreset,\n applyGroomerPreset,\n leverSnapshot,\n sectionLeverKey,\n type AlchemyGroomerSection,\n type AlchemySourceOption,\n type LeverValues,\n type SectionLevel,\n} from \"./levers\";\nimport {\n CELL_LIMITS,\n KEEP,\n LockGlyph,\n StructureTreeList,\n TEXT_LIMITS,\n decodeLimit,\n encodeLimit,\n itemPattern,\n jsonSearchItems,\n jsonTreeItems,\n toggleNode,\n type TreeHandlers,\n type TreeItem,\n} from \"./workspace-tree\";\n\n/** Structural twin of `@ai-matrx/alchemy/ports` `WindowPort` (design-system sits below alchemy). */\nexport interface WorkspaceWindowHandle {\n readonly instanceId: string;\n close(): void;\n focus(): void;\n isOpen(): boolean;\n}\nexport interface WorkspaceWindowPort {\n readonly presentation: \"window\" | \"dialog\";\n readonly multiInstance: boolean;\n open(\n render: (window: WorkspaceWindowHandle) => unknown,\n options: { title: string; size?: { width: number; height: number } | \"full\"; instanceId?: string; onClose?: () => void },\n ): WorkspaceWindowHandle;\n}\n\ntype Frame = \"dialog\" | \"host\";\ntype Tab = \"structure\" | \"preview\" | \"settings\";\ntype Pending = { kind: \"controls\"; controls: Controls } | { kind: \"levers\"; values: LeverValues };\n\nconst PANE_KEY = \"matrx-alchemy:prepare-panes\";\nconst TAB_KEY = \"matrx-alchemy:prepare-tab\";\nconst DEFAULT_PANES = { left: 320, right: 340 };\nconst MIN_PANE = 220;\nconst MOBILE_WIDTH = 768;\nconst PREVIEW_CHUNK_LINES = 200;\n\nfunction readStored<T>(key: string, fallback: T, valid: (value: unknown) => value is T): T {\n try {\n const raw = globalThis.localStorage?.getItem(key);\n if (!raw) return fallback;\n const value: unknown = JSON.parse(raw);\n return valid(value) ? value : fallback;\n } catch {\n return fallback;\n }\n}\nfunction writeStored(key: string, value: unknown) {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(value));\n } catch {\n // Storage blocked (private window, policy): the layout still works at its defaults.\n }\n}\nconst isPanes = (value: unknown): value is { left: number; right: number } =>\n Boolean(value) && typeof value === \"object\" && Number.isFinite((value as { left: unknown }).left) && Number.isFinite((value as { right: unknown }).right);\nconst isTab = (value: unknown): value is Tab => value === \"structure\" || value === \"preview\" || value === \"settings\";\n\n/** The root's own width (a window can be narrow on a wide screen). */\nfunction useNarrow(ref: React.RefObject<HTMLElement | null>): boolean {\n const [narrow, setNarrow] = React.useState(() => typeof window !== \"undefined\" && window.innerWidth < MOBILE_WIDTH);\n React.useLayoutEffect(() => {\n const node = ref.current;\n if (!node) return;\n const measure = () => {\n const width = node.getBoundingClientRect().width || window.innerWidth;\n setNarrow(width < MOBILE_WIDTH);\n };\n measure();\n if (typeof ResizeObserver === \"undefined\") {\n window.addEventListener(\"resize\", measure);\n return () => window.removeEventListener(\"resize\", measure);\n }\n const observer = new ResizeObserver(measure);\n observer.observe(node);\n return () => observer.disconnect();\n });\n return narrow;\n}\n\n/**\n * The read-only preview: the sealed text in line-aligned chunks the browser skips laying out when\n * off screen (`content-visibility: auto`), so a megabyte of transcript scrolls without a long\n * main-thread task. Concatenated, the chunks are exactly the sealed text — marks (a selected node's\n * span, search matches, removed text) wrap ranges of it and never add a character.\n */\nfunction PreviewText({ text, id, marks = EMPTY_MARKS, label = \"Prepared output\" }: { text: string; id?: string; marks?: readonly Mark[]; label?: string }) {\n const chunks = React.useMemo(() => {\n const out: { start: number; text: string }[] = [];\n let start = 0;\n let lines = 0;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) === 10 && ++lines === PREVIEW_CHUNK_LINES) {\n out.push({ start, text: text.slice(start, i + 1) });\n start = i + 1;\n lines = 0;\n }\n }\n if (start < text.length || out.length === 0) out.push({ start, text: text.slice(start) });\n return out;\n }, [text]);\n const ref = React.useRef<HTMLDivElement>(null);\n const focusStart = marks.find((mark) => mark.kind === \"focus\")?.start ?? -1;\n React.useEffect(() => {\n if (focusStart < 0) return;\n ref.current?.querySelector<HTMLElement>(\"[data-mark~='focus']\")?.scrollIntoView?.({ block: \"center\" });\n }, [focusStart]);\n return (\n <div ref={ref} id={id} className=\"matrx-alchemy-preview matrx-alchemy-prep-preview\" role=\"region\" aria-label={label} tabIndex={0} data-chars={text.length}>\n {chunks.map((chunk, index) => <pre key={index} className=\"matrx-alchemy-prep-chunk\">{marked(chunk.text, chunk.start, marks)}</pre>)}\n </div>\n );\n}\nconst EMPTY_MARKS: readonly Mark[] = [];\n/** One chunk's text with every overlapping mark as a `<mark>` (overlaps carry every kind). */\nfunction marked(text: string, offset: number, marks: readonly Mark[]): React.ReactNode {\n const end = offset + text.length;\n const inside = marks.filter((mark) => mark.end > offset && mark.start < end && mark.end > mark.start);\n if (!inside.length) return text;\n const cuts = new Set<number>([offset, end]);\n for (const mark of inside) { cuts.add(Math.max(offset, mark.start)); cuts.add(Math.min(end, mark.end)); }\n const points = [...cuts].sort((a, b) => a - b);\n const out: React.ReactNode[] = [];\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]!;\n const b = points[i + 1]!;\n const piece = text.slice(a - offset, b - offset);\n const kinds = [...new Set(inside.filter((mark) => mark.start <= a && mark.end >= b).map((mark) => mark.kind))];\n out.push(kinds.length ? <mark key={a} className=\"matrx-alchemy-mark\" data-mark={kinds.join(\" \")}>{piece}</mark> : piece);\n }\n return out;\n}\n\n/** \"Formatted\" is rich HTML on the clipboard: the preview shows that HTML rendered, sandboxed (no scripts). */\nfunction PreviewHtml({ html }: { html: string }) {\n return <iframe className=\"matrx-alchemy-preview matrx-alchemy-prep-html\" title=\"Prepared output (formatted)\" sandbox=\"\" srcDoc={html} />;\n}\n\nfunction ShareBar({ part, whole }: { part: number; whole: number }) {\n const share = whole > 0 ? Math.min(1, part / whole) : 0;\n return <span className=\"matrx-alchemy-prep-share\" aria-hidden=\"true\"><span style={{ width: `${(share * 100).toFixed(1)}%` }} /></span>;\n}\nfunction SizeNote({ chars, whole }: { chars: number | null; whole: number }) {\n if (chars === null) return null;\n return <span className=\"matrx-alchemy-prep-size\"><ShareBar part={chars} whole={whole} /><span>{sizeLabel(chars)}</span></span>;\n}\n\n/** Plain-text labels from the host's one plain-text projection (\"plain\" engine); raw text until it answers. */\nfunction useProjectedLabels(labels: readonly string[], adapters: readonly FormatAdapter[]): readonly string[] {\n const engine = hostEngineFor(adapters, \"plain\");\n const key = labels.join(\"\\u0000\");\n const [projected, setProjected] = React.useState<{ key: string; labels: readonly string[] } | null>(null);\n React.useEffect(() => {\n if (!engine || !labels.some((label) => /[#*_`[\\]>~|]/.test(label))) return;\n const controller = new AbortController();\n void Promise.all(\n labels.map(async (label) => {\n const artifact = await buildWithAdapter(\n engine,\n // A label is Markdown flattened onto one line (\"2. Assistant: ### Claim …\"): a heading\n // marker mid-line is only a heading again at a line start, so give it one first.\n { snapshotId: \"label\", sourceId: \"label\", sourceRevision: \"label\", revision: 0, payload: { kind: \"markdown\", text: label.replace(/\\s+(#{1,6}\\s)/g, \"\\n$1\") }, omissions: [], manuallyEdited: false, provenance: [] },\n controller.signal,\n );\n return artifact.plainText.replace(/\\s+/g, \" \").trim() || label;\n }),\n ).then((result) => { if (!controller.signal.aborted) setProjected({ key, labels: result }); }).catch(() => undefined);\n return () => controller.abort();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [engine, key]);\n return projected?.key === key ? projected.labels : labels;\n}\n\n/** A segmented control: one pressed button per choice (PP-03 preset buttons, PP-05 levels). */\nfunction Segmented<T extends string | number>({ label, value, choices, onChange }: { label: string; value: T; choices: readonly { value: T; label: string; title?: string }[]; onChange: (value: T) => void }) {\n return (\n <div className=\"matrx-alchemy-prep-segmented\" role=\"group\" aria-label={label}>\n {choices.map((choice) => (\n <button key={String(choice.value)} type=\"button\" aria-pressed={choice.value === value} title={choice.title} onClick={() => onChange(choice.value)}>{choice.label}</button>\n ))}\n </div>\n );\n}\n\n/** One host lever, drawn as the rich control its kind deserves (PP-03). */\nfunction LeverControl({ option, value, onChange }: { option: AlchemySourceOption; value: boolean | number; onChange: (value: boolean | number) => void }) {\n const hint = \"hint\" in option && option.hint ? <small className=\"matrx-alchemy-prep-hint\">{option.hint}</small> : null;\n if (option.kind === \"toggle\") {\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <button type=\"button\" role=\"switch\" aria-checked={Boolean(value)} className=\"matrx-alchemy-prep-switch\" onClick={() => onChange(!value)}>\n <span className=\"matrx-alchemy-prep-switch-track\" aria-hidden=\"true\"><span /></span>\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n </button>\n {hint}\n </div>\n );\n }\n if (option.kind === \"preset\") {\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n <Segmented label={option.label} value={Number(value)} choices={option.options.map((choice) => ({ value: choice.value, label: choice.label }))} onChange={onChange} />\n </div>\n );\n }\n if (option.kind === \"slider\") {\n const index = Math.max(0, option.stops.indexOf(Number(value)));\n return (\n <label className=\"matrx-alchemy-prep-lever\">\n <span className=\"matrx-alchemy-prep-lever-row\"><span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span><output className=\"matrx-alchemy-prep-value\">{option.formatValue(Number(value))}</output></span>\n <input type=\"range\" aria-label={option.label} min={0} max={Math.max(0, option.stops.length - 1)} step={1} value={index} aria-valuetext={option.formatValue(Number(value))} onChange={(event) => onChange(option.stops[Number(event.target.value)]!)} />\n {hint}\n </label>\n );\n }\n return (\n <div className=\"matrx-alchemy-prep-lever\">\n <label className=\"matrx-alchemy-prep-lever-row\">\n <span className=\"matrx-alchemy-prep-lever-label\">{option.label}</span>\n <input type=\"number\" aria-label={option.label} min={option.min} step={option.step} value={Number(value)} onChange={(event) => { if (!Number.isNaN(event.target.valueAsNumber)) onChange(event.target.valueAsNumber); }} />\n </label>\n {option.presets?.length ? <Segmented label={`${option.label} presets`} value={Number(value)} choices={option.presets.map((preset) => ({ value: preset.value, label: preset.label }))} onChange={onChange} /> : null}\n {hint}\n </div>\n );\n}\n\nconst LEVEL_NAMES: Record<SectionLevel, string> = { full: \"Full\", compact: \"Compact\", brief: \"Brief\", off: \"Off\" };\n\nfunction GroomerSection({ section, level, size, whole, onChange }: { section: AlchemyGroomerSection; level: SectionLevel; size: number; whole: number; onChange: (level: SectionLevel) => void }) {\n const levels: SectionLevel[] = section.cuttable ? [\"full\", \"compact\", \"brief\", \"off\"] : [\"full\", \"compact\", \"brief\"];\n return (\n <div className=\"matrx-alchemy-prep-node\" data-level={level}>\n <div className=\"matrx-alchemy-prep-node-head\">\n <span className=\"matrx-alchemy-prep-node-title\">{section.title}{section.cuttable ? <span className=\"matrx-alchemy-prep-cut\" title=\"Safe to cut\">✂</span> : null}</span>\n <SizeNote chars={size} whole={whole} />\n </div>\n {section.description ? <small className=\"matrx-alchemy-prep-hint\">{section.description}</small> : null}\n <Segmented label={`${section.title} detail`} value={level} choices={levels.map((value) => ({ value, label: LEVEL_NAMES[value], ...(value !== \"off\" && section.levelLabels?.[value] ? { title: section.levelLabels[value] } : {}) }))} onChange={onChange} />\n {level !== \"off\" && section.levelLabels?.[level] ? <small className=\"matrx-alchemy-prep-hint\">{section.levelLabels[level]}</small> : null}\n </div>\n );\n}\n\nexport interface PreparationWorkspaceProps {\n restoreFocus: () => void;\n open: boolean;\n frame: Frame;\n /** Host frame only: the node the host's window gave this session. */\n windowNode?: HTMLElement | null;\n state: WorkspaceState;\n scopes: TransferScope[];\n scopeLabels?: Partial<Record<TransferScope, string>> | undefined;\n onClose: () => void;\n onChange: (next: WorkspaceState) => void;\n transport: Transport;\n ai?: AiPreparation;\n adapters: FormatAdapter[];\n actions: PageAction[];\n onOutcome: (outcome: TransferOutcome) => void;\n captureScope: (scope: TransferScope, signal: AbortSignal) => Promise<CaptureResult>;\n /** Bumped by \"Copy with prompt…\": the AI envelope turns on and the instructions box takes focus. */\n promptFocus?: number;\n}\n\nexport function PreparationWorkspace({ restoreFocus, open, frame, windowNode, state, scopes, scopeLabels, onClose, onChange, transport, ai, adapters, actions, onOutcome, captureScope, promptFocus = 0 }: PreparationWorkspaceProps) {\n const fence = useFence();\n const latest = React.useRef(state); latest.current = state;\n const aiSession = React.useRef<AiPreparation | undefined>(undefined);\n if (!aiSession.current && ai) aiSession.current = ai.fork?.() ?? ai;\n const [controls, setControls] = React.useState(() => initialControls(state));\n const [controlsHistory, setControlsHistory] = React.useState<Controls[]>([]);\n const [pending, setPending] = React.useState<Pending | null>(null);\n const requestedFormat = state.preferences.initialFormat;\n // The payload's own format first (JSON for JSON, the sheet for rows, Markdown for Markdown), then palette order.\n const firstOffered = () => {\n const kind = state.draft.payload.kind;\n const natural: (typeof COPIES)[number] = kind === \"json\" || kind === \"registered\" ? \"json\" : kind === \"rows\" ? \"tsv\" : kind === \"markdown\" ? \"markdown\" : \"plain\";\n return [natural, ...COPIES].find((f) => offersFormat(f, state.draft.payload, adapters)) ?? \"plain\";\n };\n const [format, setFormat] = React.useState<string>(() => isBuiltInFormat(requestedFormat) ? (offersFormat(requestedFormat, state.draft.payload, adapters) ? requestedFormat : firstOffered()) : adapters.some((adapter) => adapter.id === requestedFormat && adapter.supports(state.draft.payload)) ? requestedFormat : firstOffered());\n const [envelopeOn, setEnvelopeOn] = React.useState(state.preferences.initialEnvelope !== \"text\");\n const [instructions, setInstructions] = React.useState(\"\");\n const instructionsRef = React.useRef<HTMLTextAreaElement>(null);\n const [sealedInstructions, setSealedInstructions] = React.useState(\"\");\n const [formatArtifact, setFormatArtifact] = React.useState<Artifact | null>(null);\n const [formatError, setFormatError] = React.useState<string | null>(null);\n const [editing, setEditing] = React.useState(false);\n const [buffer, setBuffer] = React.useState(\"\");\n const [bufferError, setBufferError] = React.useState<string | null>(null);\n const [aiInstruction, setAiInstruction] = React.useState(\"\");\n const [busy, setBusy] = React.useState<\"ai\" | \"capture\" | \"copy\" | \"download\" | \"action\" | null>(null);\n const [aiFailed, setAiFailed] = React.useState(false);\n const [biggestFirst, setBiggestFirst] = React.useState(false);\n // The node whose span the preview highlights (PP-06b–d), the data search (PP-08), the JSON\n // tree's open nodes, and \"Show what was removed\" (PP-07).\n const [focus, setFocus] = React.useState<{ kind: \"json\" | \"section\" | \"row\" | \"column\"; id: string; key: string } | null>(null);\n const [treeQuery, setTreeQuery] = React.useState(\"\");\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set([\"\"]));\n const [showRemoved, setShowRemoved] = React.useState(false);\n const [removedView, setRemovedView] = React.useState<{ text: string; marks: Mark[]; summary: string } | { error: string } | null>(null);\n const [panes, setPanes] = React.useState(() => readStored(PANE_KEY, DEFAULT_PANES, isPanes));\n const [tab, setTab] = React.useState<Tab>(() => readStored(TAB_KEY, \"preview\" as Tab, isTab));\n React.useEffect(() => {\n if (!promptFocus || !open) return;\n setEnvelopeOn(true);\n setTab(\"settings\");\n const timer = setTimeout(() => instructionsRef.current?.focus(), 50);\n return () => clearTimeout(timer);\n }, [promptFocus, open]);\n const root = React.useRef<HTMLDivElement>(null);\n const narrow = useNarrow(root);\n React.useEffect(() => { setAiFailed(false); }, [state.snapshot.id, state.draft.revision]);\n const handingOff = React.useRef(false);\n React.useEffect(() => { if (open) handingOff.current = false; }, [open]);\n const activeAi = React.useRef<AbortController | null>(null);\n const activeCapture = React.useRef<AbortController | null>(null);\n\n // Instructions are sealed a beat after typing stops, so each keystroke never reseals a megabyte.\n React.useEffect(() => {\n const timer = setTimeout(() => setSealedInstructions(instructions), 200);\n return () => clearTimeout(timer);\n }, [instructions]);\n\n // Build the chosen format's bytes. Toggling the envelope or typing instructions never rebuilds them.\n React.useEffect(() => {\n if (state.buildError) { setFormatArtifact(null); setFormatError(null); return; }\n if (bufferError) return;\n const adapter = adapters.find((candidate) => candidate.id === format);\n const controller = new AbortController();\n const snapshotId = state.snapshot.id; const revision = state.draft.revision;\n setFormatError(null);\n const artifactPromise = isBuiltInFormat(format) ? buildFormat(state.draft, format, state.snapshot.label, adapters, controller.signal) : adapter ? buildWithAdapter(adapter, state.draft, controller.signal) : buildArtifact(state.draft, \"plain\", state.snapshot.label);\n void artifactPromise.then((artifact) => {\n if (!controller.signal.aborted && artifact.snapshotId === snapshotId && artifact.draftRevision === revision) setFormatArtifact(artifact);\n }).catch((error) => { if (!controller.signal.aborted) setFormatError(errorMessage(error, \"Format preview failed\")); });\n return () => controller.abort();\n }, [adapters, bufferError, format, state.buildError, state.draft, state.snapshot.id, state.snapshot.label]);\n // The ONE artifact: the format's bytes, or (For AI) those bytes sealed in the envelope with the\n // instructions first. The preview shows exactly `shown`; Copy and Download deliver exactly `shown`.\n const sealed = React.useMemo((): { artifact: Artifact | null; error: string | null } => {\n if (state.buildError || !formatArtifact || formatArtifact.snapshotId !== state.snapshot.id || formatArtifact.draftRevision !== state.draft.revision) return { artifact: null, error: null };\n const dataFormat = envelopeDataFormat(format, formatArtifact);\n if (!envelopeOn || !dataFormat) return { artifact: formatArtifact, error: null };\n try {\n return { artifact: sealForAi(formatArtifact, dataFormat, state.envelope ?? defaultEnvelope(state.snapshot), sealedInstructions, state.snapshot.label), error: null };\n } catch (cause) {\n return { artifact: null, error: errorMessage(cause, \"The AI envelope could not be sealed.\") };\n }\n }, [envelopeOn, format, formatArtifact, sealedInstructions, state.buildError, state.draft.revision, state.envelope, state.snapshot]);\n const shown = sealed.artifact;\n\n const close = React.useCallback(() => { activeAi.current?.abort(); activeCapture.current?.abort(); activeAi.current = null; activeCapture.current = null; fence.abortAll(); setBusy(null); onClose(); }, [fence, onClose]);\n\n // ── Levers (PP-02): the host builder is the capture; a lever change rebuilds from it. ──\n const applyLevers = (values: LeverValues, base: WorkspaceState = latest.current, withControls: Controls = controls) => {\n const levers = base.levers;\n if (!levers) return;\n try {\n const built = levers.build(values);\n const snapshot = leverSnapshot(built.payload, base.snapshot.sourceId, base.snapshot.label);\n const original = createDraft(snapshot);\n const next: WorkspaceState = { ...base, snapshot, original, draft: original, leverValues: values, leverMeta: built.meta, leverSizes: built.sectionSizes, envelope: built.envelope, buildError: undefined, error: undefined };\n onChange({ ...next, draft: rebuild(next, withControls) });\n } catch (cause) {\n onChange({ ...base, leverValues: values, buildError: errorMessage(cause, \"This source could not be prepared with these options.\") });\n }\n };\n const changeLevers = (values: LeverValues) => {\n if (state.draft.manuallyEdited) { setPending({ kind: \"levers\", values }); return; }\n React.startTransition(() => applyLevers(values));\n };\n const leverTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n React.useEffect(() => () => { if (leverTimer.current) clearTimeout(leverTimer.current); }, []);\n const [typedLevers, setTypedLevers] = React.useState<LeverValues | null>(null);\n const leverValues = typedLevers ?? state.leverValues ?? state.levers?.initial ?? {};\n const setLever = (key: string, value: boolean | number | string, debounce = false) => {\n const next = { ...leverValues, [key]: value };\n if (!debounce) { setTypedLevers(null); changeLevers(next); return; }\n setTypedLevers(next);\n if (leverTimer.current) clearTimeout(leverTimer.current);\n leverTimer.current = setTimeout(() => { setTypedLevers(null); changeLevers(next); }, 150);\n };\n\n const changeControls = (next: Controls) => {\n if (state.draft.manuallyEdited) { setPending({ kind: \"controls\", controls: next }); return; }\n setControlsHistory((history) => [...history, controls]); setControls(next);\n React.startTransition(() => onChange({ ...latest.current, draft: rebuild(latest.current, next), error: undefined }));\n };\n const applyPending = () => {\n if (!pending) return;\n setBufferError(null); setEditing(false);\n if (pending.kind === \"controls\") {\n setControlsHistory((history) => [...history, controls]); setControls(pending.controls);\n onChange({ ...state, draft: rebuild(state, pending.controls), error: undefined });\n } else applyLevers(pending.values, state);\n setPending(null);\n };\n const rebuildFromSource = () => {\n setBufferError(null); setEditing(false); setPending(null);\n if (state.levers) applyLevers(state.leverValues ?? state.levers.initial, state);\n else onChange({ ...state, draft: rebuild(state, controls), error: undefined });\n };\n\n const startEditing = () => { setBuffer(formatArtifact?.plainText ?? \"\"); setEditing(true); };\n const editBuffer = (text: string) => {\n setBuffer(text);\n setFormatError(null);\n const payload = state.draft.payload;\n if (payload.kind === \"json\" || payload.kind === \"registered\") {\n try {\n const value = JSON.parse(text) as Json;\n const next: Payload = payload.kind === \"json\" ? { kind: \"json\", value } : { kind: \"registered\", format: payload.format, value };\n setBufferError(null); onChange({ ...state, draft: editDraft(state.draft, next), error: undefined });\n } catch { setBufferError(\"JSON is incomplete or invalid. Fix it before copying or downloading.\"); }\n return;\n }\n setBufferError(null);\n const kind = payload.kind === \"markdown\" || format === \"markdown\" ? \"markdown\" : \"text\";\n if (payload.kind === \"rows\" || !isBuiltInFormat(format)) setFormat(\"plain\");\n onChange({ ...state, draft: editDraft(state.draft, { kind, text }), error: undefined });\n };\n\n const requestCapture = async (scope: TransferScope) => {\n activeCapture.current?.abort();\n const { controller, id } = fence.begin(); activeCapture.current = controller; const revision = state.draft.revision; setBusy(\"capture\");\n try {\n const result = await captureScope(scope, controller.signal);\n if (fence.valid(id, controller) && latest.current.draft.revision === revision) onChange({ ...latest.current, pending: { ...result, scope }, sourceStale: false, error: result.collectionError });\n } catch (error) { if (fence.valid(id, controller)) onChange({ ...latest.current, error: errorMessage(error, \"Refresh failed\") }); }\n finally { fence.finish(controller); if (activeCapture.current === controller) activeCapture.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const resolveCapture = (choice: \"keep\" | \"regenerate\") => {\n if (!state.pending) return;\n if (choice === \"keep\") { const { pending: _pending, ...kept } = state; onChange({ ...kept, error: undefined }); return; }\n const fresh = state.pending;\n const preferences = resolveTransferPreferences({}, state.preferences, fresh.snapshot.limits);\n const base: WorkspaceState = { ...fresh, key: state.key, original: createDraft(fresh.snapshot), draft: createDraft(fresh.snapshot), scope: fresh.scope, preferences, ...(fresh.collectionError ? { error: fresh.collectionError } : {}), ...(state.envelope ? { envelope: state.envelope } : {}) };\n const nextControls = initialControls(base); setControls(nextControls); setControlsHistory([]); setPending(null); setBufferError(null); setEditing(false);\n onChange({ ...base, draft: rebuild(base, nextControls) });\n };\n\n const runAi = async (recover = false) => {\n const adapter = aiSession.current;\n if (!adapter || !adapter.supports(state.snapshot) || (!recover && !aiInstruction.trim()) || (recover && !adapter.recover)) return;\n activeAi.current?.abort();\n const { controller, id } = fence.begin(); activeAi.current = controller;\n const snapshotId = state.snapshot.id; const revision = state.draft.revision; setBusy(\"ai\"); setAiFailed(false);\n try {\n const next = recover ? await adapter.recover!({ snapshot: state.snapshot, draft: state.draft, signal: controller.signal }) : await adapter.run({ snapshot: state.snapshot, draft: state.draft, instruction: aiInstruction, signal: controller.signal });\n const current = latest.current;\n if (!fence.valid(id, controller) || current.snapshot.id !== snapshotId || current.draft.revision !== revision || next.snapshotId !== snapshotId || next.sourceId !== state.draft.sourceId || next.sourceRevision !== state.draft.sourceRevision || next.revision <= revision) return;\n try { serialize(next, \"plain\"); } catch { onChange({ ...current, error: \"AI returned an invalid transfer draft.\" }); setAiFailed(true); return; }\n onChange({ ...current, draft: next, error: undefined }); setBufferError(null);\n } catch (error) {\n if (!isAbort(error) && fence.valid(id, controller)) { setAiFailed(true); onChange({ ...latest.current, error: errorMessage(error, \"AI preparation failed\") }); }\n } finally { fence.finish(controller); if (activeAi.current === controller) activeAi.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const cancelAi = async () => {\n const aiController = activeAi.current;\n const { controller, id } = fence.begin();\n try { await aiSession.current?.cancel?.(); }\n catch (error) { if (fence.valid(id, controller)) onChange({ ...latest.current, error: errorMessage(error, \"AI cancellation failed\") }); }\n finally { aiController?.abort(); fence.finish(controller); if (activeAi.current === aiController) activeAi.current = null; if (fence.valid(id, controller)) setBusy(null); }\n };\n const [deliveryNotice, setDeliveryNotice] = React.useState<string | null>(null);\n React.useEffect(() => { setDeliveryNotice(null); }, [state.draft.revision]);\n const reportDelivery = (outcome: TransferOutcome) => { setDeliveryNotice(outcomeMessage(outcome)); onOutcome(outcome); };\n const deliver = async (download: boolean) => {\n if (bufferError) return;\n const { controller, id } = fence.begin(); const snapshotId = state.snapshot.id; const revision = state.draft.revision; setBusy(download ? \"download\" : \"copy\");\n try {\n if (!shown) throw new Error(\"Wait for the preview before delivery.\");\n const artifact = shown;\n const current = latest.current;\n if (!fence.valid(id, controller) || current.snapshot.id !== snapshotId || current.draft.revision !== revision || artifact.snapshotId !== snapshotId || artifact.draftRevision !== revision) return;\n const result = await transport[download ? \"download\" : \"copy\"](artifact, controller.signal);\n if (fence.valid(id, controller)) reportDelivery(result);\n } catch (error) { if (fence.valid(id, controller)) reportDelivery({ status: \"error\", code: \"prepare-failed\", message: errorMessage(error, \"Preparation failed\"), retryable: true }); }\n finally { fence.finish(controller); if (fence.valid(id, controller)) setBusy(null); }\n };\n const deliverAction = async (action: PageAction) => {\n if (busy || bufferError || formatError || !shown) return;\n const { controller, id } = fence.begin();\n const current = latest.current;\n setBusy(\"action\");\n try {\n if (!action.supports(current.snapshot, current.draft)) throw new Error(`${action.label} is unavailable for this prepared content.`);\n // Release the preparation focus trap before a host opens its destination.\n handingOff.current = true;\n flushSync(() => onClose());\n const result = await action.run({ snapshot: current.snapshot, draft: current.draft, signal: controller.signal });\n if (fence.valid(id, controller)) reportDelivery(result);\n } catch (error) {\n if (fence.valid(id, controller)) reportDelivery({ status: \"error\", code: \"destination-failed\", message: errorMessage(error, \"Could not deliver prepared content\"), retryable: false });\n } finally { fence.finish(controller); if (fence.valid(id, controller)) setBusy(null); }\n };\n const eligibleActions = state.buildError ? [] : actions.filter((action) => action.supports(state.snapshot, state.draft));\n\n // ── Derived view ──\n const rows = state.original.payload.kind === \"rows\" ? state.original.payload : null;\n const formats = COPIES.filter((f) => offersFormat(f, state.draft.payload, adapters));\n const workspaceAdapters = adapters.filter((adapter) => !isBuiltInFormat(adapter.id) && adapter.supports(state.draft.payload));\n const displayedOmissions = shown?.omissions ?? state.draft.omissions;\n const shownText = shown?.plainText ?? \"\";\n const chars = shownText.length;\n const bytes = React.useMemo(() => new TextEncoder().encode(shownText).length, [shownText]);\n const envelopeOffered = formatArtifact ? envelopeDataFormat(format, formatArtifact) !== null : format !== \"html\" && format !== \"xlsx\";\n const snapshotSections = state.snapshot.sections;\n const sectionLabels = useProjectedLabels(snapshotSections.map((section) => section.label), adapters);\n const sectionRows = snapshotSections.map((section, index) => ({ section, label: sectionLabels[index] ?? section.label, size: sectionSize(state.original.payload, section.path) }));\n const sectionWhole = sectionRows.reduce((sum, row) => sum + (row.size ?? 0), 0);\n const orderedSections = biggestFirst ? [...sectionRows].sort((a, b) => (b.size ?? 0) - (a.size ?? 0)) : sectionRows;\n const groomer = state.levers?.sections ?? null;\n const groomerWhole = Object.values(state.leverSizes ?? {}).reduce((sum, size) => sum + size, 0);\n const orderedGroomer = groomer ? (biggestFirst ? [...groomer].sort((a, b) => (state.leverSizes?.[b.id] ?? 0) - (state.leverSizes?.[a.id] ?? 0)) : groomer) : null;\n const activePreset = groomer ? activeGroomerPreset(leverValues, groomer) : null;\n const options = state.levers?.options ?? null;\n const jsonRoot = !groomer && (state.original.payload.kind === \"json\" || state.original.payload.kind === \"registered\") ? state.original.payload.value : undefined;\n const hasStructure = Boolean(rows || snapshotSections.length || groomer || jsonRoot !== undefined);\n const editHeld = state.draft.manuallyEdited;\n const meta = Object.entries(state.leverMeta ?? {}).filter(([, value]) => value !== undefined && value !== \"\");\n const title = `Prepare ${state.snapshot.label}`;\n const copyVisible = !state.buildError && !formatError && !bufferError && !sealed.error && !showRemoved;\n\n // ── Spans, highlight and search (PP-06a–d, PP-08) ──\n const spans = React.useMemo(() => (shown && formatArtifact && formatArtifact.snapshotId === state.snapshot.id && formatArtifact.draftRevision === state.draft.revision ? shownSpans(state.draft, formatArtifact, shown) : null), [formatArtifact, shown, state.draft, state.snapshot.id]);\n // A host engine that rewrites the text (Markdown → plain) moves every section: find each one by\n // projecting it alone through the same engine (PP-06d), for this draft and this format.\n const [projectedSections, setProjectedSections] = React.useState<{ artifact: Artifact; ranges: Record<string, { start: number; end: number }> } | null>(null);\n React.useEffect(() => {\n const engine = hostEngineFor(adapters, format);\n const layout = draftLayout(state.draft);\n const payload = state.draft.payload;\n if (!engine || !formatArtifact || !layout.sectionRanges || (payload.kind !== \"text\" && payload.kind !== \"markdown\") || formatArtifact.draftRevision !== state.draft.revision) { setProjectedSections(null); return; }\n const controller = new AbortController();\n const pieces = Object.entries(layout.sectionRanges).sort((a, b) => a[1].start - b[1].start).map(([id, range]) => ({ id, text: payload.text.slice(range.start, range.end) }));\n void locateProjectedSections(formatArtifact.plainText, pieces, engine, controller.signal)\n .then((ranges) => { if (!controller.signal.aborted) setProjectedSections({ artifact: formatArtifact, ranges }); })\n .catch(() => { if (!controller.signal.aborted) setProjectedSections(null); });\n return () => controller.abort();\n }, [adapters, format, formatArtifact, state.draft]);\n const focusResult = React.useMemo((): { marks: Mark[]; note: string | null } => {\n if (!focus || !shown) return { marks: [], note: null };\n if (!spans) return { marks: [], note: \"This format has no highlight map. Choose JSON, Markdown, CSV, Google Sheets or plain text to see where it lands.\" };\n const byPath = new Map(spans.map((span) => [span.path, span]));\n let found: { start: number; end: number }[] = [];\n if (focus.kind === \"json\" && jsonRoot !== undefined) {\n const pointers = focus.id.includes(\"*\") ? concretePointers(jsonRoot, focus.id).slice(0, 500) : [focus.id];\n found = pointers.map((pointer) => outputPointer(jsonRoot, controls.structure, pointer)).flatMap((pointer) => (pointer === null ? [] : [byPath.get(pointer)].filter((span): span is NonNullable<typeof span> => Boolean(span))));\n } else if (focus.kind === \"section\") {\n const section = snapshotSections.find((candidate) => candidate.id === focus.id);\n let span = section ? sectionSpan(state.draft, spans, shownText, section.id) ?? byPath.get(section.path) : undefined;\n const projected = section && projectedSections?.artifact === formatArtifact ? projectedSections.ranges[section.id] : undefined;\n const whole = byPath.get(\"\");\n if (!span && projected && whole) span = { path: `/sections/${section!.id}`, start: whole.start + projected.start, end: whole.start + projected.end };\n if (span) found = [span];\n } else if (focus.kind === \"row\") {\n const position = draftLayout(state.draft).rowOrder?.indexOf(Number(focus.id)) ?? -1;\n const span = position >= 0 ? byPath.get(`/rows/${position}`) : undefined;\n if (span) found = [span];\n } else {\n const span = byPath.get(`/columns/${encodePointer(focus.id)}`);\n if (span) found = [span];\n }\n if (!found.length) {\n const included = focus.kind === \"section\" ? controls.sections.includes(focus.id) : focus.kind === \"row\" ? !controls.excludedRows.includes(Number(focus.id)) : true;\n return { marks: [], note: included && focus.kind === \"section\" ? \"This format rewrites the text, so this section's place cannot be pointed at yet. Choose Markdown to see exactly where it lands.\" : \"Not in the output: it is left out, or a limit trimmed it.\" };\n }\n return { marks: found.map((span) => ({ start: span.start, end: span.end, kind: \"focus\" as const })), note: null };\n }, [controls.excludedRows, controls.sections, controls.structure, focus, formatArtifact, jsonRoot, projectedSections, shown, shownText, snapshotSections, spans, state.draft]);\n const searchQuery = rows ? controls.search : treeQuery;\n const matches = React.useMemo(() => findMatches(shownText, searchQuery, rows ? controls.searchMode : \"contains\"), [controls.searchMode, rows, searchQuery, shownText]);\n const previewMarks = React.useMemo(() => [...focusResult.marks, ...matches.marks], [focusResult.marks, matches.marks]);\n\n const copyText = (text: string, what: string) => {\n const artifact = sealTransferArtifact({ snapshotId: state.draft.snapshotId, draftRevision: state.draft.revision, format: \"plain\", plainText: text, omissions: [] });\n void transport.copy(artifact, new AbortController().signal)\n .then((outcome) => { setDeliveryNotice(outcome.status === \"success\" ? `${what} copied` : outcomeMessage(outcome)); onOutcome(outcome); })\n .catch((error: unknown) => setDeliveryNotice(errorMessage(error, `${what} could not be copied`)));\n };\n\n // ── \"Show what was removed\" (PP-07): Full in this format, removals marked through its span map ──\n React.useEffect(() => {\n if (!showRemoved) { setRemovedView(null); return; }\n if (!isBuiltInFormat(format) || format === \"xlsx\" || format === \"html\") { setRemovedView({ error: \"Choose JSON, Markdown, CSV, Google Sheets or plain text to see what was removed.\" }); return; }\n const controller = new AbortController();\n const full = resetDraft(state.snapshot);\n void buildFormat(full, format, state.snapshot.label, adapters, controller.signal).then(async (artifact) => {\n if (controller.signal.aborted) return;\n const engine = hostEngineFor(adapters, format);\n const payload = full.payload;\n const prose = (payload.kind === \"text\" || payload.kind === \"markdown\") && snapshotSections.length > 0 && snapshotSections.every((section) => /^\\/text\\/\\d+-\\d+$/.test(section.path));\n const projected = engine && prose\n ? await locateProjectedSections(artifact.plainText, snapshotSections.map((section) => { const [, a, b] = /^\\/text\\/(\\d+)-(\\d+)$/.exec(section.path)!; return { id: section.id, text: payload.text.slice(Number(a), Number(b)) }; }), engine, controller.signal)\n : undefined;\n if (controller.signal.aborted) return;\n const result = removedMarks(state, controls, full, artifact, projected);\n setRemovedView(result\n ? { text: artifact.plainText, marks: result.marks, summary: `${formatCount(result.removed)} removed · ${formatCount(result.changed)} shortened · ${formatCount(result.chars)} chars left out` }\n : { error: \"This format has no span map, so its removals cannot be pointed at.\" });\n }).catch((error: unknown) => { if (!controller.signal.aborted) setRemovedView({ error: errorMessage(error, \"Full could not be built in this format.\") }); });\n return () => controller.abort();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [adapters, controls, format, showRemoved, state.draft, state.snapshot]);\n\n // ── The JSON tree (PP-06b) ──\n const jsonItems = React.useMemo(() => (jsonRoot === undefined ? [] : treeQuery.trim() ? jsonSearchItems(jsonRoot, controls.structure, treeQuery) : jsonTreeItems(jsonRoot, controls.structure, expanded)), [controls.structure, expanded, jsonRoot, treeQuery]);\n const jsonWhole = jsonItems.find((item) => item.key === \"#root\")?.chars ?? jsonItems.reduce((max, item) => Math.max(max, item.chars ?? 0), 0);\n const setStructure = (structure: Controls[\"structure\"]) => changeControls({ ...controls, structure });\n const jsonHandlers: TreeHandlers = {\n toggle: (item) => setStructure(toggleNode(controls.structure, itemPattern(item))),\n includeAgain: (item) => {\n const pattern = itemPattern(item);\n const cover = controls.structure.exclude.find((candidate) => candidate !== pattern && patternCovers(candidate, pattern));\n if (cover !== undefined) setStructure({ ...controls.structure, exclude: controls.structure.exclude.filter((candidate) => candidate !== cover) });\n },\n expand: (item) => setExpanded((current) => { const next = new Set(current); const pattern = itemPattern(item); if (next.has(pattern)) next.delete(pattern); else next.add(pattern); return next; }),\n focus: (item) => setFocus({ kind: \"json\", id: itemPattern(item), key: item.key }),\n limit: (item, value) => {\n const pattern = itemPattern(item);\n const limits: Record<string, NodeLimit> = { ...controls.structure.limits };\n const limit = decodeLimit(value);\n if (limit) limits[pattern] = limit; else delete limits[pattern];\n setStructure({ ...controls.structure, limits });\n },\n copyPath: (path) => copyText(path, \"Path\"),\n };\n\n // ── The sections tree (PP-06d) ──\n const sectionText = (path: string) => { const m = /^\\/text\\/(\\d+)-(\\d+)$/.exec(path); const payload = state.original.payload; return m && (payload.kind === \"text\" || payload.kind === \"markdown\") ? payload.text.slice(Number(m[1]), Number(m[2])) : \"\"; };\n const sectionQuery = treeQuery.trim().toLocaleLowerCase();\n const sectionItems: TreeItem[] = orderedSections\n .filter(({ section, label }) => !sectionQuery || label.toLocaleLowerCase().includes(sectionQuery) || sectionText(section.path).toLocaleLowerCase().includes(sectionQuery))\n .map(({ section, label, size }) => ({ key: `section:${section.id}`, depth: 0, label, chars: size, state: controls.sections.includes(section.id) ? \"on\" : \"off\", limitChoices: TEXT_LIMITS, limit: encodeLimit(controls.sectionLimits[section.id]) }));\n const sectionId = (item: TreeItem) => item.key.slice(\"section:\".length);\n const sectionHandlers: TreeHandlers = {\n toggle: (item) => { const id = sectionId(item); changeControls({ ...controls, sections: controls.sections.includes(id) ? controls.sections.filter((value) => value !== id) : [...controls.sections, id] }); },\n focus: (item) => setFocus({ kind: \"section\", id: sectionId(item), key: item.key }),\n limit: (item, value) => { const id = sectionId(item); const limits = { ...controls.sectionLimits }; const limit = decodeLimit(value); if (limit) limits[id] = limit; else delete limits[id]; changeControls({ ...controls, sectionLimits: limits }); },\n };\n\n // ── Panes (PP-01b): draggable dividers, widths remembered per viewer (storage may be blocked). ──\n const drag = React.useRef<{ side: \"left\" | \"right\"; startX: number; start: number } | null>(null);\n const clampPane = (width: number) => {\n const total = root.current?.getBoundingClientRect().width || 1600;\n return Math.round(Math.min(Math.max(width, MIN_PANE), Math.max(MIN_PANE, total * 0.45)));\n };\n const setPane = (side: \"left\" | \"right\", width: number, persist: boolean) => {\n setPanes((current) => {\n const next = { ...current, [side]: clampPane(width) };\n if (persist) writeStored(PANE_KEY, next);\n return next;\n });\n };\n const divider = (side: \"left\" | \"right\") => (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label={side === \"left\" ? \"Resize structure pane\" : \"Resize settings pane\"}\n aria-valuenow={panes[side]}\n aria-valuemin={MIN_PANE}\n tabIndex={0}\n className=\"matrx-alchemy-prep-divider\"\n onPointerDown={(event) => { drag.current = { side, startX: event.clientX, start: panes[side] }; event.currentTarget.setPointerCapture?.(event.pointerId); }}\n onPointerMove={(event) => { const d = drag.current; if (!d || d.side !== side) return; const delta = event.clientX - d.startX; setPane(side, side === \"left\" ? d.start + delta : d.start - delta, false); }}\n onPointerUp={(event) => { if (!drag.current) return; drag.current = null; event.currentTarget.releasePointerCapture?.(event.pointerId); setPanes((current) => { writeStored(PANE_KEY, current); return current; }); }}\n onKeyDown={(event) => {\n const step = event.shiftKey ? 64 : 16;\n if (event.key === \"ArrowLeft\") { event.preventDefault(); setPane(side, panes[side] + (side === \"left\" ? -step : step), true); }\n if (event.key === \"ArrowRight\") { event.preventDefault(); setPane(side, panes[side] + (side === \"left\" ? step : -step), true); }\n }}\n />\n );\n const chooseTab = (next: Tab) => { setTab(next); writeStored(TAB_KEY, next); };\n\n // ── Regions ──\n const topBar = (\n <div className=\"matrx-alchemy-prep-top\">\n {scopes.length > 1 ? <label className=\"matrx-alchemy-prep-field\">Scope<select aria-label=\"Transfer scope\" value={state.scope} disabled={busy !== null} onChange={(e) => void requestCapture(e.target.value as TransferScope)}>{scopes.map((scope) => <option key={scope} value={scope}>{scopeLabels?.[scope] ?? SCOPE_LABEL[scope]}</option>)}</select></label> : null}\n <label className=\"matrx-alchemy-prep-field\">Detail<select aria-label=\"Detail preset\" value={controls.preset} onChange={(e) => changeControls({ ...controls, preset: e.target.value as Preset })}><option value=\"full\">Full</option><option value=\"compact\">Compact</option><option value=\"brief\">Brief</option><option value=\"custom\">Custom</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">Format<select aria-label=\"Output format\" value={format} onChange={(e) => { setFormat(e.target.value); setEditing(false); }}>{formats.map((f) => <option key={f} value={f}>{LABEL[f]}</option>)}{state.draft.payload.kind === \"rows\" ? <option value=\"xlsx\">Excel workbook</option> : null}{workspaceAdapters.map((adapter) => <option key={adapter.id} value={adapter.id}>{adapter.label}</option>)}</select></label>\n {envelopeOffered ? <Segmented label=\"Copy as\" value={envelopeOn ? \"ai\" : \"text\"} choices={[{ value: \"text\", label: \"Text\", title: \"The format's bytes alone\" }, { value: \"ai\", label: \"For AI\", title: \"Inside the AI envelope, with your instructions first\" }]} onChange={(value) => setEnvelopeOn(value === \"ai\")} /> : null}\n <span className=\"matrx-alchemy-prep-totals\" aria-live=\"polite\">{shown ? <>{formatCount(chars)} chars · {formatCount(bytes)} bytes · ≈{formatCount(Math.ceil(chars / 4))} tokens <small>(estimate)</small></> : state.buildError ? \"Nothing to copy\" : \"Preparing…\"}</span>\n {meta.length ? <span className=\"matrx-alchemy-prep-meta\">{meta.map(([key, value]) => `${key.replace(/_/g, \" \")} ${String(value)}`).join(\" · \")}</span> : null}\n </div>\n );\n\n const structure = hasStructure ? (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-structure\" aria-label=\"Structure\">\n <div className=\"matrx-alchemy-prep-pane-head\"><h3>Structure</h3>{(snapshotSections.length > 1 || (groomer?.length ?? 0) > 1) ? <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={biggestFirst} onClick={() => setBiggestFirst(!biggestFirst)}>Biggest first</button> : null}</div>\n {editHeld ? <p className=\"matrx-alchemy-prep-held\">Editing — rebuild from source to change the structure.</p> : null}\n {focusResult.note ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{focusResult.note}</p> : null}\n {groomer && orderedGroomer ? (\n <div className=\"matrx-alchemy-prep-group\">\n <div className=\"matrx-alchemy-prep-lever-row\"><span className=\"matrx-alchemy-prep-lever-label\">Sections</span><span className=\"matrx-alchemy-prep-hint\">{activePreset ? `${activePreset[0]!.toUpperCase()}${activePreset.slice(1)}` : \"Custom\"}</span></div>\n <Segmented label=\"Section preset\" value={activePreset ?? \"custom\"} choices={[{ value: \"everything\", label: \"Everything\" }, { value: \"balanced\", label: \"Balanced\" }, { value: \"minimal\", label: \"Minimal\" }, ...(activePreset ? [] : [{ value: \"custom\" as const, label: \"Custom\" }])]} onChange={(value) => { if (value === \"custom\") return; const levels = applyGroomerPreset(value, groomer); changeLevers({ ...leverValues, ...Object.fromEntries(Object.entries(levels).map(([id, level]) => [sectionLeverKey(id), level])) }); }} />\n {orderedGroomer.map((section) => <GroomerSection key={section.id} section={section} level={(leverValues[sectionLeverKey(section.id)] ?? \"full\") as SectionLevel} size={state.leverSizes?.[section.id] ?? 0} whole={groomerWhole} onChange={(level) => setLever(sectionLeverKey(section.id), level)} />)}\n </div>\n ) : null}\n {jsonRoot !== undefined ? (\n <div className=\"matrx-alchemy-prep-group\">\n <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label=\"Find in data\" placeholder=\"Find a key or value\" value={treeQuery} onChange={(e) => setTreeQuery(e.target.value)} />\n {treeQuery.trim() ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{jsonItems.length >= 500 ? \"500+\" : formatCount(jsonItems.length)} {jsonItems.length === 1 ? \"node matches\" : \"nodes match\"} · {formatCount(matches.total)} in the preview</small> : null}\n <StructureTreeList label=\"Data\" items={jsonItems} whole={jsonWhole} focusKey={focus?.key ?? null} handlers={jsonHandlers} maxHeight=\"calc(92dvh - 16rem)\" />\n </div>\n ) : null}\n {snapshotSections.length ? (\n <fieldset className=\"matrx-alchemy-prep-group\" aria-label=\"Included sections\">\n <legend className=\"matrx-alchemy-prep-legend\">{controls.sections.length.toLocaleString()} of {snapshotSections.length.toLocaleString()} {countNoun(state.snapshot.coverage.unit ?? \"section\", snapshotSections.length)} included</legend>\n {snapshotSections.length > 6 ? <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label={`Find a ${state.snapshot.coverage.unit ?? \"section\"}`} placeholder=\"Find by name or text\" value={treeQuery} onChange={(e) => setTreeQuery(e.target.value)} /> : null}\n {sectionQuery ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{formatCount(sectionItems.length)} {sectionItems.length === 1 ? \"matches\" : \"match\"} · {formatCount(matches.total)} in the preview</small> : null}\n <StructureTreeList label=\"Sections\" items={sectionItems} whole={sectionWhole} focusKey={focus?.key ?? null} handlers={sectionHandlers} maxHeight=\"calc(92dvh - 16rem)\" />\n </fieldset>\n ) : null}\n {rows ? <RowsStructure rows={rows} controls={controls} change={changeControls} draft={state.draft} focusKey={focus?.key ?? null} matchesInPreview={matches.total} onFocus={(kind, id) => setFocus({ kind, id, key: `${kind}:${id}` })} onCopyRow={(text) => copyText(text, \"Row\")} /> : null}\n </section>\n ) : null;\n\n const previewPane = (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-center\" aria-label=\"Preview\">\n <div className=\"matrx-alchemy-prep-pane-head\">\n <h3>{editing ? \"Editing\" : showRemoved ? \"Removed compared with Full\" : envelopeOn && envelopeOffered ? \"Preview — for AI\" : \"Preview\"}</h3>\n {searchQuery.trim() && shown && !showRemoved ? <span className=\"matrx-alchemy-prep-hint\" role=\"status\" aria-label=\"Matches in the preview\">{matches.total.toLocaleString()} {matches.total === 1 ? \"match\" : \"matches\"}</span> : null}\n {hasStructure && !editing && !state.buildError ? <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>{showRemoved ? \"Back to preview\" : \"Show what was removed\"}</button> : null}\n {!state.buildError && !showRemoved && (formatArtifact || editing) ? (editing\n ? <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={() => setEditing(false)}>Done</Button>\n : <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={startEditing}>Edit</Button>) : null}\n </div>\n {editHeld && !editing && !pending ? <div className=\"matrx-alchemy-prep-held\" role=\"status\"><span>Editing — rebuild from source to change the structure.</span><Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={rebuildFromSource}>Rebuild from source</Button></div> : null}\n {pending ? <div className=\"matrx-alchemy-decision\" role=\"alert\"><p>This control would replace your manual edit.</p><Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => setPending(null)}>Keep edited draft</Button><Button className=\"matrx-alchemy-workspace-primary\" type=\"button\" onClick={applyPending}>Rebuild from source</Button></div> : null}\n {state.buildError ? (\n <div className=\"matrx-alchemy-preview matrx-alchemy-prep-preview matrx-alchemy-prep-failed\" role=\"alert\" aria-label=\"Prepared output\">\n <p><strong>This source could not be prepared.</strong></p>\n <p>{state.buildError}</p>\n <p className=\"matrx-alchemy-prep-hint\">Change an option to try again; nothing was copied.</p>\n </div>\n ) : editing ? (\n <>\n {envelopeOn && envelopeOffered ? <p className=\"matrx-alchemy-prep-hint\">Copy wraps this text in the AI envelope{sealedInstructions.trim() ? \" with your instructions first\" : \"\"}.</p> : null}\n <textarea className=\"matrx-alchemy-preview matrx-alchemy-prep-editor\" aria-label=\"Edit prepared output\" aria-invalid={bufferError ? true : undefined} aria-describedby={bufferError ? \"alchemy-buffer-error\" : undefined} value={buffer} onChange={(e) => editBuffer(e.target.value)} autoFocus />\n </>\n ) : showRemoved ? (\n removedView === null ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">Building Full to compare…</p>\n : \"error\" in removedView ? <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{removedView.error}</p>\n : <>\n <p className=\"matrx-alchemy-prep-hint\" role=\"status\">{removedView.summary}. Full, before your structure choices — this is not what you copy.</p>\n <PreviewText text={removedView.text} marks={removedView.marks} label=\"Removed compared with Full\" />\n </>\n ) : shown ? (\n shown.html !== undefined && !(envelopeOn && envelopeOffered) ? <PreviewHtml html={shown.html} /> : <PreviewText text={shownText} marks={previewMarks} />\n ) : formatError ? null : <p className=\"matrx-alchemy-prep-hint\" role=\"status\">Preparing preview…</p>}\n {bufferError ? <p id=\"alchemy-buffer-error\" role=\"alert\" className=\"matrx-alchemy-error\">{bufferError}</p> : null}\n {formatError ? <p role=\"alert\" className=\"matrx-alchemy-error\">{formatError}</p> : null}\n {sealed.error ? <p role=\"alert\" className=\"matrx-alchemy-error\">{sealed.error}</p> : null}\n {bufferError ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" disabled={busy !== null} onClick={() => { const fallback = editDraft(state.draft, { kind: \"text\", text: buffer }); setBufferError(null); onChange({ ...state, draft: fallback, error: undefined }); setFormat(\"plain\"); }}>Use invalid JSON as plain text</Button> : null}\n <div className=\"matrx-alchemy-coverage\">\n <span>{snapshotSections.length ? `${formatCount(controls.sections.length)} of ${formatCount(snapshotSections.length)} ${countNoun(state.snapshot.coverage.unit ?? \"section\", snapshotSections.length)} included` : `${formatCount(state.snapshot.coverage.included)} included${state.snapshot.coverage.total == null ? \"\" : ` of ${formatCount(state.snapshot.coverage.total)}`}`} · {state.snapshot.coverage.status}</span>\n {state.snapshot.coverage.reason ? <span>{state.snapshot.coverage.reason}</span> : null}\n {displayedOmissions.length ? <details><summary>{displayedOmissions.length} omissions or adjustments</summary><ul>{displayedOmissions.map((o, i) => <li key={`${o.path}-${o.reason}-${i}`}>{o.label ? `${o.label}: ${o.reason}` : `${o.path || \"/\"}: ${o.reason}`}{o.count == null ? \"\" : ` (${o.count})`}</li>)}</ul></details> : null}\n </div>\n </section>\n );\n\n const settings = (\n <section className=\"matrx-alchemy-prep-pane matrx-alchemy-prep-settings\" aria-label=\"Settings\">\n <div className=\"matrx-alchemy-prep-pane-head\"><h3>Settings</h3></div>\n {options?.length ? (\n <div className=\"matrx-alchemy-prep-group\" role=\"group\" aria-label=\"Source options\">\n <h4>Source options</h4>\n {options.map((option) => <LeverControl key={option.key} option={option} value={(leverValues[option.key] ?? option.default) as boolean | number} onChange={(value) => setLever(option.key, value, option.kind === \"number\")} />)}\n </div>\n ) : null}\n {controls.preset === \"custom\" ? <fieldset className=\"matrx-alchemy-prep-group\"><legend className=\"matrx-alchemy-prep-legend\">{state.draft.payload.kind === \"json\" || state.draft.payload.kind === \"registered\" ? \"JSON limits\" : \"Content limits\"}</legend>{([[\"maxDepth\", \"Maximum depth\"], [\"maxStringChars\", state.draft.payload.kind === \"rows\" ? \"Maximum characters per cell\" : \"Maximum string characters\"], [\"maxArrayItems\", \"Maximum array items\"]] as const).filter(([key]) => key === \"maxStringChars\" || state.draft.payload.kind === \"json\" || state.draft.payload.kind === \"registered\").map(([key, text]) => <label key={key} className=\"matrx-alchemy-prep-lever-row\"><span>{text}</span><input type=\"number\" min=\"0\" value={controls[key] ?? \"\"} onChange={(e) => changeControls({ ...controls, [key]: Number.isNaN(e.target.valueAsNumber) ? null : e.target.valueAsNumber })} /></label>)}</fieldset> : null}\n {envelopeOn && envelopeOffered ? (\n <label className=\"matrx-alchemy-prep-group\">\n <h4>Instructions for the model</h4>\n <textarea ref={instructionsRef} aria-label=\"Instructions for the model\" value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder=\"e.g. Review this conversation for tool errors\" />\n <small className=\"matrx-alchemy-prep-hint\">Sealed first in what you copy, and counted in the total.</small>\n </label>\n ) : null}\n {ai ? (\n <div className=\"matrx-alchemy-prep-group\">\n <h4>Prepare with AI</h4>\n <label className=\"matrx-alchemy-prep-field\">Start with<select aria-label=\"AI preparation recipe\" defaultValue=\"\" onChange={(event) => { if (event.target.value) setAiInstruction(event.target.value); }}><option value=\"\">Choose an instruction</option><option value=\"Summarize this content concisely. Preserve important facts, names, decisions, and source references.\">Summarize</option><option value=\"Extract decisions, action items, owners, and due dates. Mark missing details as unspecified.\">Extract action items</option><option value=\"Prepare a complete handoff for another assistant. Include the objective, relevant facts, constraints, decisions, and unresolved questions.\">Assistant handoff</option><option value=\"Condense this content by removing repetition and formatting noise. Preserve every unique fact and all identifiers.\">Condense without losing facts</option><option value=\"Turn this content into a clear structured outline. Keep the original meaning and explicitly flag uncertainty.\">Create an outline</option><option value=\"Analyze this data. Identify patterns, anomalies, and useful comparisons. Distinguish observations from inferences.\">Analyze the data</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">AI instruction<textarea value={aiInstruction} onChange={(e) => setAiInstruction(e.target.value)} placeholder=\"Tell AI how to prepare this content\" /></label>\n <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" disabled={!aiSession.current || !aiInstruction.trim() || busy !== null || !aiSession.current.supports(state.snapshot)} onClick={() => void runAi(false)}>Generate preview</Button>\n {busy === \"ai\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => void cancelAi()}>{aiSession.current?.cancel ? \"Cancel AI\" : \"Stop waiting\"}</Button> : null}\n {aiFailed && aiSession.current?.recover && busy !== \"ai\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => void runAi(true)}>Retry or rejoin AI run</Button> : null}\n <p className=\"matrx-alchemy-meta\">AI updates the preview; copy it when you are ready. Closing this window lets the AI run continue.</p>\n </div>\n ) : null}\n {!options?.length && controls.preset !== \"custom\" && !(envelopeOn && envelopeOffered) && !ai && !eligibleActions.length ? <p className=\"matrx-alchemy-prep-hint\">{envelopeOffered ? \"Choose For AI to seal instructions for the model with what you copy.\" : \"This format has no further settings.\"}</p> : null}\n {busy === \"capture\" ? <Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => { activeCapture.current?.abort(); activeCapture.current = null; setBusy(null); }}>Stop loading rows</Button> : null}\n {state.error ? <p role=\"alert\" className=\"matrx-alchemy-error\">{state.error}</p> : null}\n {eligibleActions.length ? <details className=\"matrx-alchemy-prep-group matrx-alchemy-destinations\"><summary>Use prepared content · {eligibleActions.length} {eligibleActions.length === 1 ? \"destination\" : \"destinations\"}</summary><div className=\"matrx-alchemy-destination-grid\">{eligibleActions.map((action) => <button key={action.id} type=\"button\" className=\"matrx-alchemy-palette-row\" disabled={busy !== null || Boolean(bufferError || formatError) || !shown} onClick={() => void deliverAction(action)}><DestinationPresentation action={action} /></button>)}</div></details> : null}\n </section>\n );\n\n const footer = (\n <div className=\"matrx-alchemy-prep-footer\">\n {state.sourceStale ? <p role=\"alert\" className=\"matrx-alchemy-decision\">The source changed since this draft. Use Refresh source to review the latest data.</p> : null}\n {state.pending ? <div className=\"matrx-alchemy-decision\" role=\"alert\"><p>A fresh source snapshot is ready.</p>{state.pending.scope !== state.scope ? <p>Switch from {scopeLabels?.[state.scope] ?? SCOPE_LABEL[state.scope]} to {scopeLabels?.[state.pending.scope] ?? SCOPE_LABEL[state.pending.scope]} by regenerating. Your current draft is retained until you choose.</p> : null}<Button className=\"matrx-alchemy-workspace-secondary\" type=\"button\" variant=\"outline\" onClick={() => resolveCapture(\"keep\")}>Keep current snapshot and draft</Button><Button className=\"matrx-alchemy-workspace-primary\" type=\"button\" onClick={() => resolveCapture(\"regenerate\")}>Regenerate from fresh source</Button></div> : null}\n <div className=\"matrx-alchemy-prep-actions\">\n {deliveryNotice ? <p role=\"status\" className=\"matrx-alchemy-meta\">{deliveryNotice}</p> : null}\n {showRemoved ? <Button type=\"button\" size=\"sm\" className=\"matrx-alchemy-workspace-primary\" onClick={() => setShowRemoved(false)}>Back to preview to copy</Button> : null}\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={(!state.draft.history?.length && !controlsHistory.length) || busy !== null} onClick={() => { setBufferError(null); if (controlsHistory.length) { const next = controlsHistory[controlsHistory.length - 1]!; setControls(next); setControlsHistory((history) => history.slice(0, -1)); onChange({ ...state, draft: rebuild(state, next), error: undefined }); } else onChange({ ...state, draft: undoDraft(state.draft), error: undefined }); }}>Undo</Button>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={busy !== null} onClick={() => { const next = initialControls(state); setControls(next); setControlsHistory([]); setPending(null); setBufferError(null); setEditing(false); if (state.levers) applyLevers(state.levers.initial, state, next); else onChange({ ...state, draft: rebuild(state, next), error: undefined }); }}>Reset</Button>\n {state.levers ? null : <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" disabled={busy !== null} onClick={() => void requestCapture(state.scope)}>Refresh source</Button>}\n {frame === \"dialog\" ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={close}>Close</Button> : null}\n {copyVisible ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" aria-label=\"Download prepared output\" disabled={busy !== null || !shown} onClick={() => void deliver(true)}>Download</Button> : null}\n {copyVisible ? <Button type=\"button\" className=\"matrx-alchemy-workspace-primary\" aria-label=\"Copy prepared output\" disabled={busy !== null || !shown} onClick={() => void deliver(false)}>{shown ? (envelopeOn && envelopeOffered ? \"Copy for AI\" : \"Copy\") : \"Preparing…\"}</Button> : null}\n </div>\n </div>\n );\n\n const layout = narrow ? (\n <>\n <div className=\"matrx-alchemy-prep-tabs\" role=\"tablist\" aria-label=\"Workspace sections\">\n {([...(hasStructure ? [[\"structure\", \"Structure\"]] : []), [\"preview\", \"Preview\"], [\"settings\", \"Settings\"]] as [Tab, string][]).map(([id, label]) => (\n <button key={id} type=\"button\" role=\"tab\" aria-selected={(hasStructure || tab !== \"structure\" ? tab : \"preview\") === id} onClick={() => chooseTab(id)}>{label}</button>\n ))}\n </div>\n <div className=\"matrx-alchemy-prep-tabpanel\" role=\"tabpanel\">\n {(hasStructure || tab !== \"structure\" ? tab : \"preview\") === \"structure\" ? structure : tab === \"settings\" ? settings : previewPane}\n </div>\n </>\n ) : (\n <div className=\"matrx-alchemy-prep-panes\" style={{ gridTemplateColumns: hasStructure ? `${panes.left}px 8px minmax(0, 1fr) 8px ${panes.right}px` : `minmax(0, 1fr) 8px ${panes.right}px` }}>\n {structure}\n {hasStructure ? divider(\"left\") : null}\n {previewPane}\n {divider(\"right\")}\n {settings}\n </div>\n );\n\n const body = (\n <div ref={root} className={cn(\"matrx-alchemy-prep\", narrow && \"matrx-alchemy-prep-narrow\")} data-frame={frame} aria-busy={busy !== null}>\n {frame === \"host\" && state.snapshot.unsavedChanges ? <p className=\"matrx-alchemy-prep-hint\">Includes your unsaved changes.</p> : null}\n {topBar}\n {layout}\n {footer}\n </div>\n );\n\n if (frame === \"host\") return open && windowNode ? createPortal(body, windowNode) : null;\n return <Dialog open={open} onOpenChange={(next) => { if (!next) close(); }}><DialogContent onCloseAutoFocus={(event) => { event.preventDefault(); if (!handingOff.current) restoreFocus(); }} className=\"matrx-alchemy-workspace matrx-alchemy-prep-dialog\" aria-busy={busy !== null}>\n <DialogHeader><DialogTitle>{title}</DialogTitle><DialogDescription>{state.snapshot.unsavedChanges ? \"Includes your unsaved changes. \" : \"\"}Review and edit this copy. Your original stays unchanged.</DialogDescription></DialogHeader>\n {body}\n </DialogContent></Dialog>;\n}\n\n\n/**\n * The rows tree (PP-06c) with copy-subset parity (PP-08): search every shown column (contains or\n * whole words), per-column and layered filters, sort, top N; every column with its own include\n * box, size, filter and per-cell limit; every matching row with its include box, size and span\n * highlight; right-click a row to copy just that row's shown columns. Hiding a column drops its\n * filter, its layered rules, its sort and its limit — the table cannot show a filter on a column\n * it does not show. The captured rows are only ever read.\n */\nfunction RowsStructure({ rows, controls, change, draft, focusKey, matchesInPreview, onFocus, onCopyRow }: {\n rows: Extract<Payload, { kind: \"rows\" }>;\n controls: Controls;\n change: (next: Controls) => void;\n draft: Draft;\n focusKey: string | null;\n matchesInPreview: number;\n onFocus: (kind: \"row\" | \"column\", id: string) => void;\n onCopyRow: (text: string) => void;\n}) {\n const [columnSearch, setColumnSearch] = React.useState(\"\");\n const [menuRow, setMenuRow] = React.useState<number | null>(null);\n const shown = React.useMemo(() => new Set(controls.visibleColumns), [controls.visibleColumns]);\n const filterCount = Object.values(controls.filters).filter(Boolean).length + controls.layeredFilters.length;\n const sizes = React.useMemo(() => Object.fromEntries(rows.columns.map((column) => [column.id, columnSize(rows, column.id)])), [rows]);\n const whole = Object.values(sizes).reduce((sum, size) => sum + size, 0);\n const shownColumns = rows.columns.filter((column) => !columnSearch.trim() || column.label.toLowerCase().includes(columnSearch.trim().toLowerCase()));\n const visibleDefs = rows.columns.filter((column) => shown.has(column.id) && exportableColumn(column));\n const matched = draftLayout(draft).matchedRows ?? rows.rows.map((_, index) => index);\n const left = React.useMemo(() => new Set(controls.excludedRows), [controls.excludedRows]);\n const included = matched.filter((index) => !left.has(index)).length;\n const rowText = React.useCallback((index: number) => visibleDefs.map((column) => cellText(readTransferCell(rows.rows[index]!, column))), [rows, visibleDefs]);\n const rowItems = React.useMemo((): TreeItem[] => matched.map((index) => {\n const cells = rowText(index);\n const summary = cells.slice(0, 2).filter(Boolean).join(\" · \");\n return { key: `row:${index}`, depth: 0, label: `Row ${index + 1}${summary ? ` — ${summary}` : \"\"}`, chars: cells.reduce((sum, cell) => sum + cell.length, 0), state: left.has(index) ? \"off\" : \"on\", rowIndex: index };\n }), [left, matched, rowText]);\n const rowWhole = rowItems.reduce((sum, item) => sum + (item.chars ?? 0), 0);\n const setRowIncluded = (index: number, include: boolean) => change({ ...controls, excludedRows: include ? controls.excludedRows.filter((value) => value !== index) : [...controls.excludedRows, index] });\n const rowHandlers: TreeHandlers = {\n toggle: (item) => setRowIncluded(item.rowIndex!, left.has(item.rowIndex!)),\n focus: (item) => onFocus(\"row\", String(item.rowIndex)),\n };\n const everyRow: \"on\" | \"off\" | \"mixed\" = included === matched.length ? \"on\" : included === 0 ? \"off\" : \"mixed\";\n const toggleEveryRow = () => {\n const inView = new Set(matched);\n change({ ...controls, excludedRows: everyRow === \"off\" ? controls.excludedRows.filter((index) => !inView.has(index)) : [...new Set([...controls.excludedRows, ...matched])] });\n };\n /** Hiding a column drops its filter, layered rules, sort and limit with it. */\n const setColumnShown = (column: Column, visible: boolean) => {\n if (visible) { change({ ...controls, visibleColumns: [...controls.visibleColumns, column.id] }); return; }\n const { [column.id]: _filter, ...filters } = controls.filters;\n const { [column.id]: _limit, ...columnLimits } = controls.columnLimits;\n change({\n ...controls,\n visibleColumns: controls.visibleColumns.filter((id) => id !== column.id),\n filters,\n columnLimits,\n layeredFilters: controls.layeredFilters.filter((rule) => rule.field !== column.id),\n ...(controls.sort === column.id ? { sort: \"\", direction: \"asc\" as const } : {}),\n });\n };\n const layeredFields: LayeredFilterField[] = visibleDefs.map((column) => column.schema?.dataType === \"number\" || column.schema?.dataType === \"integer\" ? { id: column.id, label: column.label, kind: \"number\" } : { id: column.id, label: column.label, kind: \"text\" });\n const rowCopy = (index: number) => visibleDefs.map((column) => `${column.label}: ${cellText(readTransferCell(rows.rows[index]!, column))}`).join(\"\\n\");\n return <div className=\"matrx-alchemy-prep-group\">\n <div className=\"matrx-alchemy-prep-rowbar\">\n <label className=\"matrx-alchemy-prep-field\">Search<input type=\"search\" aria-label=\"Search\" value={controls.search} placeholder=\"Every shown column\" onChange={(e) => change({ ...controls, search: e.target.value })} /></label>\n <button type=\"button\" className=\"matrx-alchemy-prep-chip\" aria-pressed={controls.searchMode === \"whole_words\"} title=\"Match whole words only: “are” finds “we are ready”, never “hardware”\" onClick={() => change({ ...controls, searchMode: controls.searchMode === \"whole_words\" ? \"contains\" : \"whole_words\" })}>Whole words</button>\n <label className=\"matrx-alchemy-prep-field\">Sort<select aria-label=\"Sort\" value={controls.sort} onChange={(e) => change({ ...controls, sort: e.target.value })}><option value=\"\">None</option>{visibleDefs.map((column) => <option key={column.id} value={column.id}>{column.label}</option>)}</select></label>\n <label className=\"matrx-alchemy-prep-field\">Direction<select aria-label=\"Direction\" value={controls.direction} disabled={!controls.sort} onChange={(e) => change({ ...controls, direction: e.target.value as \"asc\" | \"desc\" })}><option value=\"asc\">Ascending</option><option value=\"desc\">Descending</option></select></label>\n <label className=\"matrx-alchemy-prep-field\">Top rows<input type=\"number\" aria-label=\"Top rows\" min=\"0\" value={controls.top ?? \"\"} onChange={(e) => change({ ...controls, top: Number.isNaN(e.target.valueAsNumber) ? null : e.target.valueAsNumber })} /></label>\n <LayeredFilterBuilder fields={layeredFields} rules={controls.layeredFilters} onChange={(layeredFilters) => change({ ...controls, layeredFilters })} label=\"Advanced row filters\" />\n </div>\n {controls.search.trim() ? <small className=\"matrx-alchemy-prep-hint\" role=\"status\">{formatCount(matched.length)} of {formatCount(rows.rows.length)} rows match · {formatCount(matchesInPreview)} in the preview</small> : null}\n <fieldset className=\"matrx-alchemy-prep-group\" aria-label=\"Columns and filters\">\n <legend className=\"matrx-alchemy-prep-legend\">{visibleDefs.length} of {rows.columns.length} columns{filterCount ? ` · ${filterCount} filter${filterCount === 1 ? \"\" : \"s\"}` : \"\"}</legend>\n {rows.columns.length > 6 ? <input className=\"matrx-alchemy-prep-search\" type=\"search\" aria-label=\"Find a column\" placeholder=\"Find a column\" value={columnSearch} onChange={(e) => setColumnSearch(e.target.value)} /> : null}\n {shownColumns.map((column) => {\n const exportable = exportableColumn(column);\n const on = exportable && shown.has(column.id);\n return <div className=\"matrx-alchemy-prep-node matrx-alchemy-column\" key={column.id} data-focused={focusKey === `column:${column.id}` || undefined}>\n <div className=\"matrx-alchemy-tree-row matrx-alchemy-column-head\">\n {exportable\n ? <input type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label={column.label} checked={on} onChange={(e) => setColumnShown(column, e.target.checked)} />\n : <span className=\"matrx-alchemy-tree-lock\" role=\"img\" aria-label={`${column.label} is declared ${column.classification === \"secret\" || column.classification === \"credential\" ? column.classification : \"not exportable\"} and never leaves this page`} title=\"Declared not exportable — it never leaves this page\"><LockGlyph /></span>}\n <button type=\"button\" className=\"matrx-alchemy-tree-label\" aria-label={`Highlight ${column.label}`} aria-pressed={focusKey === `column:${column.id}`} onClick={() => onFocus(\"column\", column.id)}><span className=\"matrx-alchemy-tree-name\">{column.label}</span></button>\n {on ? <select className=\"matrx-alchemy-tree-limit\" aria-label={`Limit ${column.label}`} value={encodeLimit(controls.columnLimits[column.id])} onChange={(e) => { const limit = decodeLimit(e.target.value); const { [column.id]: _old, ...rest } = controls.columnLimits; change({ ...controls, columnLimits: limit && e.target.value !== KEEP ? { ...rest, [column.id]: limit } : rest }); }}>{CELL_LIMITS.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select> : null}\n </div>\n <div className=\"matrx-alchemy-column-meta\">\n <SizeNote chars={sizes[column.id] ?? 0} whole={whole} />\n {on ? <input aria-label={`Filter ${column.label}`} placeholder=\"Filter\" value={controls.filters[column.id] ?? \"\"} onChange={(e) => change({ ...controls, filters: { ...controls.filters, [column.id]: e.target.value } })} /> : null}\n </div>\n </div>;\n })}\n </fieldset>\n <div className=\"matrx-alchemy-prep-group\" role=\"group\" aria-label=\"Rows\">\n <div className=\"matrx-alchemy-tree-row matrx-alchemy-rows-head\">\n <RowsCheckbox state={everyRow} onChange={toggleEveryRow} />\n <span className=\"matrx-alchemy-prep-legend\">Rows — {formatCount(included)} of {formatCount(matched.length)} included{matched.length < rows.rows.length ? ` (${formatCount(rows.rows.length)} captured)` : \"\"}</span>\n </div>\n <ContextMenu>\n <ContextMenuTrigger asChild>\n <div onContextMenu={(event) => { const index = (event.target as HTMLElement).closest(\"[data-row-index]\")?.getAttribute(\"data-row-index\"); setMenuRow(index == null ? null : Number(index)); }}>\n <StructureTreeList label=\"Rows\" items={rowItems} whole={rowWhole} focusKey={focusKey} handlers={rowHandlers} maxHeight=\"min(24rem, 50dvh)\" />\n </div>\n </ContextMenuTrigger>\n <ContextMenuContent>\n {menuRow === null ? <ContextMenuLabel>Right-click a row to copy it</ContextMenuLabel> : <>\n <ContextMenuLabel>Row {menuRow + 1}</ContextMenuLabel>\n <ContextMenuItem onSelect={() => onCopyRow(rowCopy(menuRow))}>Copy this row’s shown columns</ContextMenuItem>\n <ContextMenuItem onSelect={() => setRowIncluded(menuRow, left.has(menuRow))}>{left.has(menuRow) ? \"Include this row\" : \"Leave this row out\"}</ContextMenuItem>\n </>}\n </ContextMenuContent>\n </ContextMenu>\n </div>\n </div>;\n}\nfunction RowsCheckbox({ state, onChange }: { state: \"on\" | \"off\" | \"mixed\"; onChange: () => void }) {\n const ref = React.useRef<HTMLInputElement>(null);\n React.useEffect(() => { if (ref.current) ref.current.indeterminate = state === \"mixed\"; }, [state]);\n return <input ref={ref} type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label=\"Include every matching row\" checked={state === \"on\"} aria-checked={state === \"mixed\" ? \"mixed\" : state === \"on\"} onChange={onChange} />;\n}\n\n/** A cell as one line of text: objects (including prototype-less JSON) as JSON, never `String(object)`. */\nfunction cellText(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value) ?? \"\";\n}\n\n/**\n * Which workspace sessions still hold their content. A host window can outlive the page that\n * opened it (a restored or kept window); its slot then says so, with the remedy, instead of\n * standing empty (PP-08, the copy-subset \"rows were released\" message).\n */\nconst liveSessions = new Set<string>();\nconst sessionListeners = new Set<() => void>();\nexport function setWorkspaceSessionLive(key: string, live: boolean) {\n if (live) liveSessions.add(key); else liveSessions.delete(key);\n sessionListeners.forEach((listener) => listener());\n}\nconst subscribeSessions = (listener: () => void) => { sessionListeners.add(listener); return () => { sessionListeners.delete(listener); }; };\n\n/** The node a host window gives a session (its content is portalled in by the session). */\nexport function WorkspaceWindowSlot({ onNode, sessionKey, onClose }: { onNode: (node: HTMLDivElement | null) => void; sessionKey?: string; onClose?: () => void }) {\n const live = React.useSyncExternalStore(subscribeSessions, () => sessionKey === undefined || liveSessions.has(sessionKey), () => true);\n if (!live) {\n return (\n <div className=\"matrx-alchemy-prep-released\" role=\"status\">\n <p><strong>The rows this held were released.</strong></p>\n <p>The page that opened this preparation closed or reloaded, so what it captured is gone. Reopen Prepare from the table or page to start again.</p>\n {onClose ? <Button type=\"button\" variant=\"outline\" className=\"matrx-alchemy-workspace-secondary\" onClick={onClose}>Close</Button> : null}\n </div>\n );\n }\n return <div className=\"matrx-alchemy-prep-slot\" ref={onNode} />;\n}\n","/**\n * Host levers (Preparation parity PP-02, PP-03, PP-05): the controls a screen declares for its own\n * data — \"tool results\", \"last N messages\", \"per-message cap\", a groomer section's Full / Compact /\n * Brief / Off — and how a lever value becomes the payload the workspace prepares.\n *\n * The levers live INSIDE the one preparation workspace, beside the preview: changing one rebuilds\n * the payload from the host builder and the preview follows. There is no second dialog and no\n * \"Prepare in Alchemy\" handoff that loses them.\n *\n * Text stays text (PP-09): a builder that returns text becomes a text payload whose AI envelope\n * carries it as `<data format=\"text\">`, never one escaped JSON string.\n */\nimport {\n directSource,\n normalizeTransferJson,\n projectSnapshot,\n type AgentPayloadInput,\n type Payload,\n type Snapshot,\n} from \"@ai-matrx/alchemy/operate\";\n\nexport type AlchemyOptionValues = Record<string, boolean | number>;\nexport type AlchemySourceOption =\n | {\n kind: \"toggle\";\n key: string;\n label: string;\n hint?: string;\n default: boolean;\n }\n | {\n kind: \"preset\";\n key: string;\n label: string;\n options: { label: string; value: number }[];\n default: number;\n }\n | {\n kind: \"slider\";\n key: string;\n label: string;\n hint?: string;\n stops: number[];\n default: number;\n formatValue: (value: number) => string;\n }\n | {\n kind: \"number\";\n key: string;\n label: string;\n hint?: string;\n min?: number;\n step?: number;\n presets?: { label: string; value: number }[];\n default: number;\n };\nexport type LeverMeta = Record<string, string | number | boolean | undefined>;\nexport interface AlchemyCustomSource {\n label?: string;\n hint?: string;\n options: AlchemySourceOption[];\n build(values: AlchemyOptionValues): {\n text: string;\n meta?: LeverMeta;\n };\n wrap(\n text: string,\n values: AlchemyOptionValues,\n meta?: LeverMeta,\n ): AgentPayloadInput;\n dialogTitle?: string;\n dialogDescription?: string;\n}\nexport type AlchemyDetail = \"full\" | \"compact\" | \"brief\";\nexport interface AlchemyGroomerSection {\n id: string;\n title: string;\n description?: string;\n cuttable?: boolean;\n levelLabels?: Partial<Record<AlchemyDetail, string>>;\n build(level: AlchemyDetail): unknown;\n defaultSelection?: AlchemyDetail | \"off\";\n}\nexport interface AlchemyGroomerConfig {\n label: string;\n kind: string;\n location: string;\n description: string;\n attributes?: AgentPayloadInput[\"attributes\"];\n context?: AgentPayloadInput[\"context\"];\n summary?: string;\n sections: AlchemyGroomerSection[];\n}\n\n/** Who a piece of content is, for the AI envelope — everything but the body. */\nexport type EnvelopeMeta = Omit<AgentPayloadInput, \"data\" | \"dataFormat\" | \"instructions\">;\nexport type LeverValue = boolean | number | string;\nexport type LeverValues = Record<string, LeverValue>;\nexport type SectionLevel = AlchemyDetail | \"off\";\n\nexport interface LeverBuild {\n payload: Payload;\n envelope: EnvelopeMeta;\n meta?: LeverMeta;\n /** Per groomer section: its size in the prepared JSON at its current level (PP-04). */\n sectionSizes?: Record<string, number>;\n}\n/** The levers one workspace session carries: the host's controls and the one builder they feed. */\nexport interface WorkspaceLevers {\n /** Source options (custom levers), shown in Settings. */\n options?: readonly AlchemySourceOption[];\n /** Groomer sections, shown in Structure with their level control. */\n sections?: readonly AlchemyGroomerSection[];\n initial: LeverValues;\n build(values: LeverValues): LeverBuild;\n}\n\nexport const sectionLeverKey = (id: string) => `section:${id}`;\n\n/**\n * A payload for text the host built: Markdown when the host said so (`dataFormat: \"markdown\"`),\n * else plain text. A JSON body stays JSON. Never a text body wrapped as a JSON string (PP-09).\n */\nexport function payloadForEnvelope(value: AgentPayloadInput | string): { payload: Payload; envelope?: EnvelopeMeta } {\n if (typeof value === \"string\") return { payload: { kind: \"markdown\", text: value } };\n const { data, dataFormat, instructions: _instructions, ...envelope } = value;\n const clean = (record?: AgentPayloadInput[\"context\"]) =>\n Object.fromEntries(Object.entries(record ?? {}).filter(([, entry]) => entry !== undefined));\n const meta: EnvelopeMeta = {\n ...envelope,\n attributes: clean(envelope.attributes),\n context: clean(envelope.context),\n };\n if (typeof data === \"string\") {\n return { payload: dataFormat === \"markdown\" ? { kind: \"markdown\", text: data } : { kind: \"text\", text: data }, envelope: meta };\n }\n return {\n payload: { kind: \"json\", value: normalizeTransferJson(data, { omitUndefinedObjectProperties: true }) },\n envelope: meta,\n };\n}\n\n/** The custom levers of `aiCustom`: option values → the host's text → a TEXT payload. */\nexport function customLevers(custom: AlchemyCustomSource): WorkspaceLevers {\n return {\n options: custom.options,\n initial: Object.fromEntries(custom.options.map((option) => [option.key, option.default])),\n build(values) {\n const optionValues = values as AlchemyOptionValues;\n const result = custom.build(optionValues);\n // The wrap decides what travels: text data stays text (PP-09), structured data stays JSON.\n const { payload, envelope } = payloadForEnvelope(custom.wrap(result.text, optionValues, result.meta));\n return { payload, envelope: envelope!, ...(result.meta ? { meta: result.meta } : {}) };\n },\n };\n}\n\n/** Pretty JSON of `value` exactly as it sits one level inside the prepared object. */\nfunction nestedJsonLength(key: string, value: unknown): number {\n const text = JSON.stringify(value, null, 2);\n if (text === undefined) return 0;\n // ` \"key\": <value with every line indented two more>,\\n`\n return 2 + JSON.stringify(key).length + 2 + text.replace(/\\n/g, \"\\n \").length + 2;\n}\n\n/** The groomer levers: a level per section → the JSON object of the included sections. */\nexport function groomerLevers(config: AlchemyGroomerConfig): WorkspaceLevers {\n return {\n sections: config.sections,\n initial: Object.fromEntries(config.sections.map((section) => [sectionLeverKey(section.id), section.defaultSelection ?? \"full\"])),\n build(values) {\n const data: Record<string, unknown> = {};\n const dropped: string[] = [];\n const sectionSizes: Record<string, number> = {};\n for (const section of config.sections) {\n const level = (values[sectionLeverKey(section.id)] ?? \"full\") as SectionLevel;\n if (level === \"off\") {\n dropped.push(section.id);\n sectionSizes[section.id] = 0;\n continue;\n }\n const value = section.build(level);\n if (value !== undefined && value !== null) {\n data[section.id] = value;\n sectionSizes[section.id] = nestedJsonLength(section.id, normalizeTransferJson(value, { omitUndefinedObjectProperties: true }));\n } else sectionSizes[section.id] = 0;\n }\n return {\n payload: { kind: \"json\", value: normalizeTransferJson(data, { omitUndefinedObjectProperties: true }) },\n envelope: {\n kind: config.kind,\n location: config.location,\n description: config.description,\n ...(config.summary !== undefined ? { summary: config.summary } : {}),\n attributes: { ...config.attributes, ...(dropped.length ? { dropped_sections: dropped.join(\",\") } : {}) },\n ...(config.context ? { context: config.context } : {}),\n },\n sectionSizes,\n };\n },\n };\n}\n\n/** Presets over groomer sections (O4's Everything / Balanced / Minimal). */\nexport type AlchemyGroomerPreset = \"everything\" | \"balanced\" | \"minimal\";\nexport function applyGroomerPreset(\n preset: AlchemyGroomerPreset,\n sections: readonly AlchemyGroomerSection[],\n): Record<string, SectionLevel> {\n return Object.fromEntries(\n sections.map((section) => [\n section.id,\n preset === \"everything\" ? \"full\" : preset === \"balanced\" ? \"compact\" : section.cuttable ? \"off\" : \"brief\",\n ]),\n );\n}\n/** The preset these levels are, or null when hand-tuned (\"Custom\") — PP-05 active-preset detection. */\nexport function activeGroomerPreset(\n values: LeverValues,\n sections: readonly AlchemyGroomerSection[],\n): AlchemyGroomerPreset | null {\n for (const preset of [\"everything\", \"balanced\", \"minimal\"] as const) {\n const levels = applyGroomerPreset(preset, sections);\n if (sections.every((section) => (values[sectionLeverKey(section.id)] ?? \"full\") === levels[section.id])) return preset;\n }\n return null;\n}\n\n/** A snapshot of a lever build, synchronously (the builder is the capture). */\nexport function leverSnapshot(payload: Payload, sourceId: string, label: string): Snapshot {\n const raw = directSource(payload, { sourceId, label });\n return projectSnapshot(raw.snapshot, raw.projection);\n}\n","\"use client\";\n\n/**\n * The preparation workspace's Structure trees (Preparation parity PP-06b JSON, PP-06c rows,\n * PP-06d sections, PP-07 per-node limits, PP-08 search).\n *\n * One row shape for every tree: an include checkbox (tri-state for parents), the node's name,\n * its size (chars · ≈tokens) with a share bar, a per-node limit (Keep / Stub / Max …), and — for a\n * JSON node — copy-path. Selecting a node's name highlights its span in the preview through the\n * serializer span map. Lists are windowed (only the rows on screen are drawn), so a 5,000-row\n * table or a thousand-message conversation stays responsive.\n *\n * A node the person cannot include is honest about it: a declared non-exportable column shows a\n * lock and its sentence (no checkbox at all), and a node excluded by a broader pattern offers\n * \"Include … again\" by name rather than a dead checkbox.\n */\nimport * as React from \"react\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport { computeWindow } from \"@ai-matrx/design-system/data-table\";\nimport { displayPath, jsonSize, nodeChars, patternBelow, patternCovers, pointerSegments, type Json, type NodeLimit, type StructureRecipe } from \"@ai-matrx/alchemy/operate\";\nimport { sizeLabel } from \"./workspace-core\";\n\nexport type NodeState = \"on\" | \"off\" | \"mixed\";\nexport interface LimitChoice { value: string; label: string }\nexport interface TreeItem {\n key: string;\n depth: number;\n label: string;\n detail?: string | undefined;\n chars: number | null;\n /** Absent: the node has no include choice of its own (the root). */\n state?: NodeState | undefined;\n /** Why this node cannot be included (declared non-exportable / secret). Shown instead of a checkbox. */\n locked?: string | undefined;\n /** The broader pattern that excludes this node; its control includes that pattern again. */\n coveredBy?: string | undefined;\n expandable?: boolean | undefined;\n expanded?: boolean | undefined;\n limitChoices?: readonly LimitChoice[] | undefined;\n limit?: string | undefined;\n copyPath?: string | undefined;\n /** Rows tree: the captured row position, for the row menu. */\n rowIndex?: number | undefined;\n}\nexport interface TreeHandlers {\n toggle(item: TreeItem): void;\n focus(item: TreeItem): void;\n expand?(item: TreeItem): void;\n limit?(item: TreeItem, value: string): void;\n includeAgain?(item: TreeItem): void;\n copyPath?(path: string): void;\n}\n\nexport const KEEP = \"keep\";\nexport const TEXT_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" },\n { value: \"chars:200\", label: \"Max 200 chars\" }, { value: \"chars:1000\", label: \"Max 1,000 chars\" }, { value: \"chars:4000\", label: \"Max 4,000 chars\" },\n];\nexport const LIST_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" },\n { value: \"items:5\", label: \"First 5 items\" }, { value: \"items:25\", label: \"First 25 items\" }, { value: \"items:100\", label: \"First 100 items\" },\n];\nexport const OBJECT_LIMITS: readonly LimitChoice[] = [{ value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" }, { value: \"chars:1000\", label: \"Max 1,000 chars per text\" }];\nexport const CELL_LIMITS: readonly LimitChoice[] = [\n { value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub cells\" },\n { value: \"chars:100\", label: \"Max 100 chars\" }, { value: \"chars:500\", label: \"Max 500 chars\" }, { value: \"chars:2000\", label: \"Max 2,000 chars\" },\n];\nexport function encodeLimit(limit: NodeLimit | undefined): string {\n if (!limit) return KEEP;\n return limit.kind === \"stub\" ? \"stub\" : limit.kind === \"maxChars\" ? `chars:${limit.value}` : `items:${limit.value}`;\n}\nexport function decodeLimit(value: string): NodeLimit | null {\n if (value === \"stub\") return { kind: \"stub\" };\n const m = /^(chars|items):(\\d+)$/.exec(value);\n if (!m) return null;\n return m[1] === \"chars\" ? { kind: \"maxChars\", value: Number(m[2]) } : { kind: \"maxItems\", value: Number(m[2]) };\n}\n\n// ── The windowed list ────────────────────────────────────────────────────────────────────────\n\nfunction useRowHeight(): number {\n const [coarse, setCoarse] = React.useState(() => typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" && window.matchMedia(\"(pointer: coarse)\").matches);\n React.useEffect(() => {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n const query = window.matchMedia(\"(pointer: coarse)\");\n const update = () => setCoarse(query.matches);\n query.addEventListener?.(\"change\", update);\n return () => query.removeEventListener?.(\"change\", update);\n }, []);\n // 44px targets on a coarse pointer (touch), a compact row with a mouse.\n // Two lines (name, then size and value) — 44px targets on a coarse pointer (touch).\n return coarse ? 48 : 40;\n}\n\nfunction Checkbox({ state, label, onChange }: { state: NodeState; label: string; onChange: () => void }) {\n const ref = React.useRef<HTMLInputElement>(null);\n React.useEffect(() => { if (ref.current) ref.current.indeterminate = state === \"mixed\"; }, [state]);\n return <input ref={ref} type=\"checkbox\" className=\"matrx-alchemy-tree-check\" aria-label={label} checked={state === \"on\"} aria-checked={state === \"mixed\" ? \"mixed\" : state === \"on\"} onChange={onChange} />;\n}\n\nexport const LockGlyph = () => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"5\" y=\"11\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 11V7a4 4 0 0 1 8 0v4\"/></svg>;\nconst CopyGlyph = () => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"9\" y=\"9\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1\"/></svg>;\nconst Chevron = ({ open }: { open: boolean }) => <svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" style={{ transform: open ? \"rotate(90deg)\" : undefined, transition: \"transform 120ms\" }}><path d=\"m9 6 6 6-6 6\"/></svg>;\n\nfunction TreeRow({ item, whole, focused, height, handlers }: { item: TreeItem; whole: number; focused: boolean; height: number; handlers: TreeHandlers }) {\n const share = whole > 0 && item.chars !== null ? Math.min(1, item.chars / whole) : 0;\n return (\n <div\n role=\"treeitem\"\n aria-level={item.depth + 1}\n aria-expanded={item.expandable ? Boolean(item.expanded) : undefined}\n aria-selected={focused}\n data-row-index={item.rowIndex}\n className=\"matrx-alchemy-tree-row\"\n data-state={item.state ?? \"root\"}\n style={{ height, paddingLeft: `${0.25 + item.depth * 0.875}rem` }}\n >\n {item.expandable ? (\n <button type=\"button\" className=\"matrx-alchemy-tree-twisty\" aria-label={`${item.expanded ? \"Collapse\" : \"Expand\"} ${item.label}`} onClick={() => handlers.expand?.(item)}><Chevron open={Boolean(item.expanded)} /></button>\n ) : <span className=\"matrx-alchemy-tree-twisty\" aria-hidden=\"true\" />}\n {item.locked ? (\n <span className=\"matrx-alchemy-tree-lock\" role=\"img\" aria-label={item.locked} title={item.locked}><LockGlyph /></span>\n ) : item.coveredBy ? (\n <button type=\"button\" className=\"matrx-alchemy-tree-covered\" aria-label={`Left out by ${item.coveredBy} — include it again`} title={`Left out by ${item.coveredBy}. Include it again.`} onClick={() => handlers.includeAgain?.(item)}>\n <input type=\"checkbox\" tabIndex={-1} aria-hidden=\"true\" checked={false} readOnly />\n </button>\n ) : item.state ? <Checkbox state={item.state} label={item.label} onChange={() => handlers.toggle(item)} /> : <span className=\"matrx-alchemy-tree-twisty\" aria-hidden=\"true\" />}\n <button type=\"button\" className=\"matrx-alchemy-tree-label\" aria-label={`Highlight ${item.label}`} aria-pressed={focused} onClick={() => handlers.focus(item)} title={item.detail ? `${item.label} — ${item.detail}` : item.label}>\n <span className=\"matrx-alchemy-tree-name\">{item.label}</span>\n <span className=\"matrx-alchemy-tree-meta\">\n {item.chars !== null ? <span className=\"matrx-alchemy-prep-size matrx-alchemy-tree-size\" title={sizeLabel(item.chars)}><span className=\"matrx-alchemy-prep-share\" aria-hidden=\"true\"><span style={{ width: `${(share * 100).toFixed(1)}%` }} /></span><span>{compactSize(item.chars)}</span></span> : null}\n {item.detail ? <small className=\"matrx-alchemy-tree-detail\">{item.detail}</small> : null}\n </span>\n </button>\n {item.limitChoices && handlers.limit && item.state !== \"off\" && !item.locked && !item.coveredBy ? (\n <select className=\"matrx-alchemy-tree-limit\" aria-label={`Limit ${item.label}`} value={item.limit ?? KEEP} onChange={(event) => handlers.limit!(item, event.target.value)}>\n {item.limitChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}\n </select>\n ) : null}\n {item.copyPath && handlers.copyPath ? <button type=\"button\" className=\"matrx-alchemy-tree-icon\" aria-label={`Copy path ${item.copyPath}`} title={`Copy ${item.copyPath}`} onClick={() => handlers.copyPath!(item.copyPath!)}><CopyGlyph /></button> : null}\n </div>\n );\n}\n\n/** \"1.2k chars · ≈300 tok\" — compact enough for a tree row; the full figure is the title. */\nfunction compactSize(chars: number): string {\n const short = (value: number) => formatCount(value, { style: \"compact\" });\n return `${short(chars)} · ≈${short(Math.ceil(chars / 4))} tok`;\n}\n\n/** A windowed tree: only the rows in view (plus a few) are in the DOM. */\nexport function StructureTreeList({ label, items, whole, focusKey, handlers, maxHeight = \"24rem\", onContextMenu }: {\n label: string;\n items: readonly TreeItem[];\n whole: number;\n focusKey: string | null;\n handlers: TreeHandlers;\n maxHeight?: string;\n onContextMenu?: (event: React.MouseEvent<HTMLDivElement>) => void;\n}) {\n const height = useRowHeight();\n const ref = React.useRef<HTMLDivElement>(null);\n const [offset, setOffset] = React.useState(0);\n const [viewport, setViewport] = React.useState(0);\n React.useLayoutEffect(() => {\n const node = ref.current;\n if (!node) return;\n const measure = () => setViewport(node.clientHeight);\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(node);\n return () => observer.disconnect();\n }, []);\n // An unmeasured list (first paint, a test DOM) draws a screenful rather than nothing.\n const view = computeWindow({ count: items.length, itemSize: height, viewport: viewport || 640, offset });\n const rows: React.ReactNode[] = [];\n for (let index = view.start; index < view.end; index++) {\n const item = items[index]!;\n rows.push(<TreeRow key={item.key} item={item} whole={whole} focused={item.key === focusKey} height={height} handlers={handlers} />);\n }\n return (\n <div ref={ref} role=\"tree\" aria-label={label} className=\"matrx-alchemy-tree\" style={{ maxHeight }} onScroll={(event) => setOffset(event.currentTarget.scrollTop)} onContextMenu={onContextMenu}>\n <div style={{ height: view.padStart }} aria-hidden=\"true\" />\n {rows}\n <div style={{ height: view.padEnd }} aria-hidden=\"true\" />\n </div>\n );\n}\n\n// ── JSON tree (PP-06b) ───────────────────────────────────────────────────────────────────────\n\ninterface JsonNode { pattern: string; label: string; values: Json[]; concrete: boolean }\nconst isRecord = (value: Json): value is { [key: string]: Json } => value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst enc = (segment: string) => segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nfunction jsonChildren(node: JsonNode): JsonNode[] {\n const values = node.values;\n if (values.length && values.every(Array.isArray)) {\n const items = (values as Json[][]).flat();\n const out: JsonNode[] = [];\n // `[*]` — every item at once: unticking `messages[*].metadata` reaches all messages.\n if (items.length > 1) out.push({ pattern: `${node.pattern}/*`, label: \"[*] every item\", values: items, concrete: false });\n if (node.concrete) (values[0] as Json[]).forEach((item, index) => out.push({ pattern: `${node.pattern}/${index}`, label: `[${index}]`, values: [item], concrete: true }));\n return out;\n }\n const objects = values.filter(isRecord);\n if (!objects.length) return [];\n const keys: string[] = [];\n const seen = new Set<string>();\n for (const object of objects) for (const key of Object.keys(object)) if (!seen.has(key)) { seen.add(key); keys.push(key); }\n return keys.map((key) => ({ pattern: `${node.pattern}/${enc(key)}`, label: key, values: objects.filter((object) => Object.prototype.hasOwnProperty.call(object, key)).map((object) => object[key]!), concrete: node.concrete }));\n}\nconst hasChildren = (node: JsonNode) => node.values.some((value) => (Array.isArray(value) && value.length > 0) || (isRecord(value) && Object.keys(value).length > 0));\nfunction preview(value: Json): string {\n if (typeof value === \"string\") return value.length > 60 ? `\"${value.slice(0, 60).replace(/\\s+/g, \" \")}…\"` : JSON.stringify(value);\n if (Array.isArray(value)) return `[${formatCount(value.length)} items]`;\n if (isRecord(value)) return `{${formatCount(Object.keys(value).length)} keys}`;\n return String(value);\n}\nfunction limitChoicesFor(node: JsonNode): readonly LimitChoice[] {\n if (node.values.every(Array.isArray)) return LIST_LIMITS;\n if (node.values.every((value) => typeof value === \"string\")) return TEXT_LIMITS;\n if (node.values.every(isRecord)) return OBJECT_LIMITS;\n return [{ value: KEEP, label: \"Keep\" }, { value: \"stub\", label: \"Stub\" }];\n}\n\n/** Two patterns name overlapping nodes at the same depth (`/a/*\\/m` and `/a/2/m`). */\nfunction overlaps(a: string, b: string): boolean {\n const x = pointerSegments(a);\n const y = pointerSegments(b);\n return x.length === y.length && x.every((segment, index) => segment === y[index] || segment === \"*\" || y[index] === \"*\");\n}\nexport function nodeState(pattern: string, exclude: readonly string[]): { state: NodeState; coveredBy?: string } {\n if (exclude.includes(pattern)) return { state: \"off\" };\n const cover = exclude.find((candidate) => patternCovers(candidate, pattern));\n if (cover !== undefined) return { state: \"off\", coveredBy: cover };\n return exclude.some((candidate) => patternBelow(candidate, pattern) || overlaps(candidate, pattern)) ? { state: \"mixed\" } : { state: \"on\" };\n}\n/** The recipe after ticking or unticking one node (a parent's choice replaces its descendants'). */\nexport function toggleNode(recipe: StructureRecipe, pattern: string): StructureRecipe {\n const { state } = nodeState(pattern, recipe.exclude);\n if (state === \"off\") return { ...recipe, exclude: recipe.exclude.filter((candidate) => candidate !== pattern) };\n const limits = Object.fromEntries(Object.entries(recipe.limits).filter(([candidate]) => !patternCovers(pattern, candidate)));\n return { exclude: [...recipe.exclude.filter((candidate) => !patternCovers(pattern, candidate)), pattern], limits };\n}\n\nexport function jsonTreeItems(root: Json, recipe: StructureRecipe, expanded: ReadonlySet<string>): TreeItem[] {\n const items: TreeItem[] = [];\n const visit = (node: JsonNode, depth: number) => {\n const expandable = hasChildren(node);\n const isOpen = expandable && expanded.has(node.pattern);\n const chars = node.values.reduce<number>((sum, value) => sum + (node.pattern === \"\" ? jsonSize(value) : nodeChars(value)), 0);\n const { state, coveredBy } = node.pattern === \"\" ? { state: undefined, coveredBy: undefined } : nodeState(node.pattern, recipe.exclude);\n items.push({\n key: node.pattern || \"#root\",\n depth,\n label: node.label,\n detail: node.concrete ? preview(node.values[0] ?? null) : `in ${formatCount(node.values.length)} items`,\n chars,\n state,\n coveredBy: coveredBy === undefined ? undefined : displayPath(coveredBy),\n expandable,\n expanded: isOpen,\n ...(node.pattern ? { limitChoices: limitChoicesFor(node), limit: encodeLimit(recipe.limits[node.pattern]), copyPath: displayPath(node.pattern) } : { copyPath: \"data\" }),\n });\n if (isOpen && state !== \"off\") for (const child of jsonChildren(node)) visit(child, depth + 1);\n };\n visit({ pattern: \"\", label: \"data\", values: [root], concrete: true }, 0);\n return items;\n}\n\n/** Search the data by key and value (PP-08): every concrete node whose key or text holds the query. */\nexport function jsonSearchItems(root: Json, recipe: StructureRecipe, query: string, cap = 500): TreeItem[] {\n const q = query.trim().toLocaleLowerCase();\n if (!q) return [];\n const items: TreeItem[] = [];\n const walk = (value: Json, segments: string[]) => {\n if (items.length >= cap) return;\n const key = segments[segments.length - 1] ?? \"\";\n const scalar = value === null || typeof value !== \"object\";\n const hit = key.toLocaleLowerCase().includes(q) || (scalar && String(value).toLocaleLowerCase().includes(q));\n if (hit && segments.length) {\n const pattern = segments.map((segment) => `/${enc(segment)}`).join(\"\");\n const { state, coveredBy } = nodeState(pattern, recipe.exclude);\n const node: JsonNode = { pattern, label: key, values: [value], concrete: true };\n items.push({ key: `search:${pattern}`, depth: 0, label: displayPath(pattern), detail: preview(value), chars: nodeChars(value), state, coveredBy: coveredBy === undefined ? undefined : displayPath(coveredBy), limitChoices: limitChoicesFor(node), limit: encodeLimit(recipe.limits[pattern]), copyPath: displayPath(pattern) });\n }\n if (Array.isArray(value)) value.forEach((item, index) => walk(item, [...segments, String(index)]));\n else if (isRecord(value)) for (const [child, item] of Object.entries(value)) walk(item, [...segments, child]);\n };\n walk(root, []);\n return items;\n}\n/** The pointer a tree item stands for (search results carry a prefix). */\nexport const itemPattern = (item: TreeItem) => (item.key.startsWith(\"search:\") ? item.key.slice(7) : item.key === \"#root\" ? \"\" : item.key);\n","import {\n ContentTransferError,\n readTransferCell,\n sealTransferArtifact,\n serialize,\n type Artifact,\n type Draft,\n type FormatAdapter,\n type FormatOptions,\n type Json,\n type PageAction,\n type Payload,\n type TransferOutcome,\n} from \"@ai-matrx/alchemy/operate\";\n\n/** The table copy contract declares it (design-system sits below alchemy); one definition. */\nexport type { ContentTransferReference } from \"@ai-matrx/design-system/data-table/host\";\nimport type { ContentTransferReference } from \"@ai-matrx/design-system/data-table/host\";\n\nexport type ContentTransferReferencePort = {\n supports(reference: ContentTransferReference): boolean;\n build(reference: ContentTransferReference): string | Promise<string>;\n};\n\nexport type ContentTransferEmailPort = {\n send(\n artifact: Artifact,\n context: { label: string; signal: AbortSignal },\n ): Promise<TransferOutcome>;\n};\n\n/** The host's HTML preview (a window or overlay that renders the document); Alchemy only decides when to offer it. */\nexport type ContentTransferHtmlPreviewPort = {\n open(request: { content: string; title: string }): void | Promise<void>;\n};\n\nconst exportableColumns = (payload: Extract<Payload, { kind: \"rows\" }>) =>\n payload.columns.filter(\n (column) =>\n column.visible &&\n column.exportable !== false &&\n column.classification !== \"secret\" &&\n column.classification !== \"credential\",\n );\n\n/** A sealed, projection-safe representation of a tabular draft's declared schema and values. */\nexport const tableSchemaFormat: FormatAdapter = {\n id: \"table-schema\",\n label: \"Schema\",\n supports: (payload) => payload.kind === \"rows\",\n extension: \"json\",\n mime: \"application/json\",\n modes: [\"copy\", \"download\"],\n runsOn: \"client\",\n load: async () => ({ async build(draft: Draft, _options: FormatOptions, signal: AbortSignal): Promise<Artifact> {\n if (signal.aborted) throw new DOMException(\"Cancelled\", \"AbortError\");\n if (draft.payload.kind !== \"rows\")\n throw new ContentTransferError(\n \"unsupported-format\",\n \"Schema + rows requires tabular content; manually edited text cannot carry a table schema.\",\n );\n const rowColumns = exportableColumns(draft.payload);\n const columns = rowColumns.map((column) => ({\n id: column.id,\n label: column.label,\n path: column.path,\n ...(column.schema === undefined ? {} : { schema: column.schema }),\n }));\n const body = {\n sourceId: draft.sourceId,\n columns,\n rows: draft.payload.rows.map((row) =>\n Object.fromEntries(rowColumns.map((column) => [column.id, readTransferCell(row, column) ?? null])),\n ),\n } satisfies Json;\n const plainText = JSON.stringify(body, null, 2);\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"table-schema\",\n plainText,\n file: {\n filename: \"table-schema.json\",\n mime: \"application/json\",\n bytes: new TextEncoder().encode(plainText),\n },\n omissions: [...draft.omissions],\n });\n } }),\n};\n\nfunction displayLabels(payload: Extract<Payload, { kind: \"rows\" }>): [string, typeof payload.columns[number]][] {\n const columns = exportableColumns(payload);\n const counts = new Map<string, number>();\n for (const column of columns) counts.set(column.label, (counts.get(column.label) ?? 0) + 1);\n const used = new Set<string>();\n return columns.map((column) => {\n const base = counts.get(column.label) === 1 ? column.label : `${column.label} [${column.id}]`;\n let label = base;\n for (let suffix = 2; used.has(label); suffix += 1) label = `${base} (${suffix})`;\n used.add(label);\n return [label, column];\n });\n}\n\n/** Flat row JSON keyed by user-facing display labels, never raw table records. */\nexport const tableDataFormat: FormatAdapter = {\n id: \"table-data\",\n label: \"Table JSON\",\n supports: (payload) => payload.kind === \"rows\",\n extension: \"json\",\n mime: \"application/json;charset=utf-8\",\n modes: [\"copy\", \"download\"],\n runsOn: \"client\",\n load: async () => ({ async build(draft: Draft, _options: FormatOptions, signal: AbortSignal): Promise<Artifact> {\n if (signal.aborted) throw new DOMException(\"Cancelled\", \"AbortError\");\n if (draft.payload.kind !== \"rows\")\n throw new ContentTransferError(\"unsupported-format\", \"Display-label JSON requires tabular content.\");\n const columns = displayLabels(draft.payload);\n const plainText = JSON.stringify(\n draft.payload.rows.map((row) =>\n Object.fromEntries(columns.map(([label, column]) => [label, readTransferCell(row, column) ?? null])),\n ),\n null,\n 2,\n );\n return sealTransferArtifact({\n snapshotId: draft.snapshotId,\n draftRevision: draft.revision,\n format: \"json\",\n plainText,\n file: {\n filename: \"data.json\",\n mime: \"application/json;charset=utf-8\",\n bytes: new TextEncoder().encode(plainText),\n },\n omissions: [...draft.omissions],\n });\n } }),\n};\n\ntype EmailFormat = \"csv\" | \"json\" | \"markdown\";\nexport type TransferHtmlPreviewAction = PageAction;\nexport type TransferEmailAction = PageAction & { prepared: true; group: \"email\" };\n\nconst emailArtifact = (draft: Draft, format: EmailFormat, signal: AbortSignal, jsonFormat?: FormatAdapter): Promise<Artifact> =>\n format === \"json\" && jsonFormat?.supports(draft.payload)\n ? jsonFormat.load().then((engine) => engine.build(draft, {}, signal))\n : Promise.resolve(serialize(draft, format));\n\n/** Prepared-only delivery actions always serialize the current draft, never a host source. */\nexport function createTransferEmailActions(\n email: ContentTransferEmailPort,\n options: { jsonFormat?: FormatAdapter } = {},\n): TransferEmailAction[] {\n return ([\"csv\", \"json\", \"markdown\"] as const).map((format) => ({\n id: `email-${format}`,\n label: `Email ${format === \"csv\" ? \"CSV\" : format === \"json\" ? \"JSON\" : \"Markdown\"}`,\n prepared: true,\n group: \"email\",\n supports: (_snapshot, draft) => Boolean(draft) && (format !== \"csv\" || draft?.payload.kind === \"rows\"),\n async run({ draft, signal, snapshot }) {\n if (signal.aborted) return { status: \"cancelled\" };\n const artifact = await emailArtifact(draft, format, signal, options.jsonFormat);\n return email.send(artifact, { label: snapshot.label, signal });\n },\n }));\n}\n\n/**\n * \"HTML preview\": opens the host's preview on the PREPARED text (what the person would copy, edits\n * and thinking-strip included). Offered for Markdown and text drafts only — a table has no document.\n */\nexport function createTransferHtmlPreviewAction(port: ContentTransferHtmlPreviewPort): TransferHtmlPreviewAction {\n return {\n id: \"html-preview\",\n label: \"HTML preview\",\n supports: (snapshot, draft) => {\n const kind = (draft?.payload ?? snapshot.payload).kind;\n return kind === \"markdown\" || kind === \"text\";\n },\n async run({ draft, snapshot, signal }) {\n if (signal.aborted) return { status: \"cancelled\" };\n if (draft.payload.kind !== \"markdown\" && draft.payload.kind !== \"text\")\n throw new ContentTransferError(\"unsupported-format\", \"HTML preview requires text.\");\n await port.open({ content: draft.payload.text, title: snapshot.label });\n return { status: \"success\", delivered: \"action\", mimeTypes: [], message: \"HTML preview opened\" };\n },\n };\n}\n","\"use client\";\n\nimport * as React from \"react\";\nimport {\n buildAgentPayload,\n capture,\n createBrowserTransport,\n createDraft,\n serialize,\n directSource,\n hasThinking,\n stripThinking,\n normalizeTransferJson,\n sealTransferArtifact,\n type AgentPayloadInput,\n type PageAction,\n type Payload,\n type TransferOutcome,\n} from \"@ai-matrx/alchemy/operate\";\nimport {\n ContentTransferMenu,\n useContentTransferCapabilities,\n type RichCopyFlavor,\n type ContentTransferController,\n type ContentTransferReference,\n type ContentTransferReferenceAction,\n type ShapedSource,\n type SourceShape,\n type TransferMenuPresentation,\n} from \"./index\";\nimport { markdownRichArtifact } from \"./workspace-core\";\nimport type { TableCopyController } from \"@ai-matrx/design-system/data-table/host\";\nimport type { AlchemyIcon } from \"@ai-matrx/design-system/content-transfer/icon\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport {\n applyGroomerPreset,\n customLevers,\n groomerLevers,\n payloadForEnvelope,\n type AlchemyCustomSource,\n type AlchemyDetail,\n type AlchemyGroomerConfig,\n type AlchemyGroomerPreset,\n type AlchemyGroomerSection,\n type EnvelopeMeta,\n} from \"./levers\";\n\nexport type {\n AlchemyCustomSource,\n AlchemyDetail,\n AlchemyGroomerConfig,\n AlchemyGroomerPreset,\n AlchemyGroomerSection,\n AlchemyOptionValues,\n AlchemySourceOption,\n} from \"./levers\";\nexport { applyGroomerPreset } from \"./levers\";\nexport interface AlchemyCopyVariant {\n id: string;\n label: string;\n hint?: string;\n icon?: React.ComponentType<{ className?: string }>;\n section?: \"copy\" | \"ai\";\n ariaLabel?: string;\n successMessage?: string;\n build?: () =>\n AgentPayloadInput | string | Promise<AgentPayloadInput | string>;\n onSelect?: () => void | Promise<void>;\n modal?: (props: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n }) => React.ReactNode;\n /** Opens THE preparation workspace on this content (the rows tree for rows, PP-08). */\n prepare?: () => { payload: Payload; label: string; envelope?: EnvelopeMeta };\n}\nexport interface AlchemyExportItem {\n id: string;\n label: string;\n build?: () => {\n content: BlobPart;\n extension: string;\n mime: string;\n /** Optional exact safe basename captured with bytes; omission derives a default, invalid values error. */\n filename?: string;\n };\n onSelect?: () => void | Promise<void>;\n}\ntype Resolvable<T> = T | (() => T);\nexport interface MatrxCopyMenuProps {\n label: string;\n /** Stable record identity when this mounted control can switch between records. */\n sourceId?: string;\n references?: readonly ContentTransferReference[];\n referenceActions?: readonly ContentTransferReferenceAction[];\n /** Prepare the tabular view while keeping raw JSON and human copy formats. */\n primarySource?: \"table\";\n human?: Resolvable<string>;\n /**\n * What `human` is. \"markdown\" makes it rich text: the main Copy click writes text/plain = the\n * markdown plus text/html = formatted, and the panel leads with \"Copy as Markdown\", \"Copy content\" and \"Copy formatted\".\n * Default \"plain\": a plain string, the existing Text / Markdown tiles.\n */\n contentFlavor?: \"plain\" | \"markdown\";\n /**\n * The host's own rich copy, so one implementation serves every surface (matrx-frontend injects\n * `copyRichContent`). Absent: the package writes the main click and Copy markdown through the session\n * transport and offers no Copy content tile (readable text is the host's one projection).\n */\n richCopy?: (markdown: string, flavor: RichCopyFlavor) => Promise<TransferOutcome | boolean | void> | TransferOutcome | boolean | void;\n /**\n * Which of the three rich-copy tiles the panel leads with when `richCopy` is on. A host that\n * already shows those two choices itself (the split Copy's own menu rows) passes `[]` so the panel\n * carries only what is unique to it (Formatted, download, AI). Default: every flavor the host has.\n */\n richCopyFlavors?: readonly (\"markdown\" | \"text\" | \"formatted\")[];\n /**\n * Model output: every copy of `human` leaves out its reasoning blocks (`<thinking>`, `<think>`,\n * `<reasoning>`), and when it held any the panel offers \"Copy including thinking\" with the full text.\n * A function `human` is never read to decide this (opening the menu prepares nothing), so the\n * variant is offered for a string `human` only.\n */\n stripThinking?: boolean;\n /**\n * Offer \"HTML preview\" for `human` (markdown) when the host bound `capabilities.htmlPreview`.\n * Default true for `contentFlavor=\"markdown\"`; pass false where the host's editable preview is the one action.\n */\n htmlPreview?: boolean;\n json?: Resolvable<unknown>;\n agent?: Resolvable<AgentPayloadInput | string>;\n aiVariants?: AlchemyCopyVariant[];\n aiCustom?: AlchemyCustomSource;\n groomer?: () => AlchemyGroomerConfig;\n agentVariant?: {\n id?: string;\n label?: string;\n hint?: string;\n position?: \"first\" | \"last\";\n };\n export?: {\n items: AlchemyExportItem[];\n /** May be async: a server-paged host hands its whole selected result, read when a format is picked. */\n sheetRows?: () => Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>;\n sheetColumns?: () => Array<{ id: string; label: string }>;\n };\n /** Host-owned authenticated destination, not a second export serializer. */\n sendToSheet?: (\n rows: Array<Record<string, unknown>>,\n label: string,\n ) => Promise<TransferOutcome>;\n hide?: Array<\"copy\" | \"ai\" | \"export\">;\n disabled?: boolean;\n className?: string;\n stopPropagation?: boolean;\n size?: \"xs\" | \"icon\" | \"sm\" | \"toolbar\";\n appearance?: \"bare\" | \"segmented\";\n unified?: boolean;\n grouped?: boolean;\n icon?: AlchemyIcon;\n triggerVariant?: \"transparent\" | \"glass\" | \"outline\";\n /** The full controller, or the table's subset (`TableCopyController`, design-system's copy contract). */\n controllerRef?: React.Ref<ContentTransferController> | React.Ref<TableCopyController>;\n triggerHidden?: boolean;\n}\n/** The longest already-built text the twin check (PP-09) builds when the menu opens. */\nconst TWIN_CHECK_MAX_CHARS = 20_000;\nconst resolve = <T,>(value: Resolvable<T>): T =>\n typeof value === \"function\" ? (value as () => T)() : value;\nconst asPayload = (value: AgentPayloadInput | string): Payload => ({\n kind: \"markdown\",\n text: typeof value === \"string\" ? value : buildAgentPayload(value),\n});\n/** PP-09: a text body stays text (its envelope says so); structured data stays JSON. */\nconst structuredPayload = (value: AgentPayloadInput | string) => payloadForEnvelope(value);\nconst actionDone = (message: string): TransferOutcome => ({\n status: \"success\",\n delivered: \"action\",\n mimeTypes: [],\n message,\n});\nconst isSafeFilename = (filename: string) =>\n filename === filename.trim() &&\n filename.length > 0 &&\n !/^\\.+$/.test(filename) &&\n !/[\\\\/\\x00-\\x1F\\x7F]/.test(filename);\nconst sourceFor = (\n id: string,\n label: string,\n build: () => Payload | Promise<Payload>,\n shape?: SourceShape,\n): ShapedSource => ({\n id,\n label,\n ...(shape ? { shape } : {}),\n capture: async ({ signal }) => {\n signal.throwIfAborted();\n const payload = await build();\n signal.throwIfAborted();\n return directSource(payload, { sourceId: id, label });\n },\n});\n\n/** Opinionated bridge for Matrx's existing content builders, with one transfer UI. */\nexport function MatrxCopyMenu(props: MatrxCopyMenuProps) {\n const inherited = useContentTransferCapabilities();\n return (\n <MatrxCopyMenuSession\n key={JSON.stringify([\n inherited.identityKey ?? null,\n props.sourceId ?? props.label,\n ])}\n {...props}\n />\n );\n}\n\nfunction MatrxCopyMenuSession(props: MatrxCopyMenuProps) {\n const instance = React.useId();\n const controller = React.useRef<ContentTransferController>(null);\n const capabilities = useContentTransferCapabilities();\n const transport = capabilities.transport ?? createBrowserTransport();\n const [modal, setModal] = React.useState<AlchemyCopyVariant | null>(null);\n const copyVisible = !props.hide?.includes(\"copy\");\n const humanSource = (): string => {\n const text = resolve(props.human!);\n return props.stripThinking ? stripThinking(text) : text;\n };\n const richText = props.contentFlavor === \"markdown\" && props.human !== undefined && copyVisible;\n const richCopy = richText\n ? async (flavor: RichCopyFlavor) => {\n const markdown = humanSource();\n if (props.richCopy) return props.richCopy(markdown, flavor);\n const signal = new AbortController().signal;\n const { snapshot } = await capture({ kind: \"markdown\", text: markdown }, signal);\n const draft = createDraft(snapshot);\n // No host projection for \"text\": the package does not invent a second readable-text implementation.\n const artifact = flavor === \"default\" || flavor === \"formatted\" ? await markdownRichArtifact(draft) : serialize(draft, \"markdown\");\n return transport.copy(artifact, signal);\n }\n : undefined;\n const aiVisible = !props.hide?.includes(\"ai\");\n const exportVisible = !props.hide?.includes(\"export\");\n const make = (\n suffix: string,\n build: () => Payload | Promise<Payload>,\n label = props.label,\n shape?: SourceShape,\n ) =>\n sourceFor(\n `${props.sourceId ?? `${instance}:${props.label}`}:${suffix}`,\n label,\n build,\n shape,\n );\n // The menu inspects these by their kind alone, so opening it builds nothing (sec_8f1a9be1…). Only a\n // short, already-built string is cheap enough for the twin check (PP-09) to build it on open.\n const humanCheap =\n typeof props.human === \"string\" && props.human.length <= TWIN_CHECK_MAX_CHARS;\n const human =\n copyVisible && props.human !== undefined\n ? make(\"human\", () => ({ kind: \"text\", text: humanSource() }), props.label, { kind: \"text\", cheap: humanCheap })\n : undefined;\n const humanMarkdown =\n copyVisible && props.human !== undefined\n ? make(\"human-markdown\", () => ({\n kind: \"markdown\",\n text: humanSource(),\n }), props.label, { kind: \"markdown\", cheap: humanCheap })\n : undefined;\n // \"Text\" of Markdown-style text is the host's one plain-text projection of that Markdown (no \"##\",\n // no \"**\"); where that projection is only an echo, the menu offers one of the twins, never both.\n const humanText =\n copyVisible && props.human !== undefined\n ? make(\"human-text\", () => ({\n kind: \"markdown\",\n text: humanSource(),\n }), props.label, { kind: \"markdown\", cheap: humanCheap })\n : undefined;\n const json =\n aiVisible && props.json !== undefined\n ? make(\"json\", () => ({\n kind: \"json\",\n value: normalizeTransferJson(resolve(props.json!), {\n omitUndefinedObjectProperties: true,\n }),\n }), props.label, { kind: \"json\" })\n : undefined;\n const agent =\n aiVisible && props.agent !== undefined\n ? make(\"agent\", () => asPayload(resolve(props.agent!)))\n : undefined;\n const structuredAgent =\n aiVisible && props.agent !== undefined\n ? make(\"structured-agent\", () => structuredPayload(resolve(props.agent!)).payload)\n : undefined;\n const table =\n (exportVisible || props.primarySource === \"table\") &&\n props.export?.sheetRows\n ? make(\"rows\", async () => {\n const value = normalizeTransferJson(await props.export!.sheetRows!(), {\n omitUndefinedObjectProperties: true,\n });\n if (\n !Array.isArray(value) ||\n value.some(\n (row) =>\n row === null || typeof row !== \"object\" || Array.isArray(row),\n )\n )\n throw new Error(\"Sheet rows must be JSON objects.\");\n const rows = value as Array<\n Record<string, import(\"@ai-matrx/alchemy/operate\").Json>\n >;\n const suppliedColumns = props.export!.sheetColumns?.();\n const columns = suppliedColumns ?? [...new Set(rows.flatMap((row) => Object.keys(row)))].map((id) => ({ id, label: id }));\n const ids = new Set<string>();\n for (const column of columns) {\n if (!column.id || !column.label || ids.has(column.id)) throw new Error(\"Sheet columns require unique nonempty ids and labels.\");\n ids.add(column.id);\n }\n for (const row of rows) for (const key of Object.keys(row)) if (!ids.has(key)) throw new Error(\"Table data contains a field outside its declared columns.\");\n return {\n kind: \"rows\",\n rows,\n columns: columns.map((column) => ({\n id: column.id,\n label: column.label,\n path: `/${column.id.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`,\n visible: true,\n })),\n };\n })\n : undefined;\n const builderVariants = aiVisible\n ? (props.aiVariants ?? [])\n .filter(\n (variant) => variant.build && !variant.onSelect && !variant.modal && !variant.prepare,\n )\n .map((variant) => ({\n ...variant,\n copyLabel: variant.label,\n source: make(\n `variant:${variant.id}`,\n async () => asPayload(await variant.build!()),\n variant.label,\n ),\n }))\n : [];\n const faithful = agent\n ? [\n {\n id: props.agentVariant?.id ?? \"faithful\",\n label: props.agentVariant?.label ?? \"Full AI context\",\n source: agent,\n copyLabel: props.agentVariant?.label ?? \"Copy for AI\",\n ...(props.agentVariant?.hint\n ? { hint: props.agentVariant.hint }\n : {}),\n },\n ]\n : [];\n // The full text is its own source: it never passes through the strip.\n const thinkingVariants =\n copyVisible && props.stripThinking && typeof props.human === \"string\" && hasThinking(props.human)\n ? [\n {\n id: \"include-thinking\",\n label: \"Including thinking\",\n copyLabel: \"Copy including thinking\",\n hint: \"Includes the original reasoning content\",\n section: \"copy\" as const,\n source: make(\"include-thinking\", () => ({ kind: \"markdown\", text: props.human as string }), props.label, { kind: \"markdown\", cheap: false }),\n },\n ]\n : [];\n const variants =\n props.agentVariant?.position === \"last\"\n ? [...thinkingVariants, ...builderVariants, ...faithful]\n : [...thinkingVariants, ...faithful, ...builderVariants];\n const actions: (PageAction & TransferMenuPresentation)[] = [];\n if (aiVisible)\n for (const variant of props.aiVariants ?? []) {\n if (!variant.onSelect && !variant.modal && !variant.prepare) continue;\n actions.push({\n ...variant,\n id: `variant-action:${variant.id}`,\n label: variant.label,\n // A door into THE preparation workspace sits in \"Edit and prepare\" (never a heading of its own).\n ...(variant.prepare ? { placement: \"prepare\" as const } : {}),\n supports: () => true,\n run: async () => {\n if (variant.prepare) {\n // PP-08: the door opens THE preparation workspace (the rows tree), not a second dialog.\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n const prepared = variant.prepare();\n await controller.current.prepare(prepared.payload, { id: `${instance}:${variant.id}`, label: prepared.label, ...(prepared.envelope ? { envelope: prepared.envelope } : {}) });\n } else if (variant.onSelect) await variant.onSelect();\n else setModal(variant);\n return actionDone(`Opened ${variant.label}`);\n },\n });\n }\n if (aiVisible && props.aiCustom)\n actions.push({\n id: \"configure-source\",\n label: props.aiCustom.label ?? \"Customize source\",\n ...(props.aiCustom.hint ? { hint: props.aiCustom.hint } : {}),\n supports: () => true,\n run: async () => {\n // PP-02: the levers open INSIDE the one workspace, beside the preview.\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n await controller.current.prepareLevers(customLevers(props.aiCustom!), {\n id: `${instance}:custom`,\n label: props.aiCustom!.dialogTitle ?? props.label,\n });\n return actionDone(\"Source options opened\");\n },\n });\n if (aiVisible && props.groomer)\n actions.push({\n id: \"groom-source\",\n label: \"Customize sections\",\n supports: () => true,\n run: async () => {\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n const config = props.groomer!();\n await controller.current.prepareLevers(groomerLevers(config), {\n id: `${instance}:groomer`,\n label: config.label,\n });\n return actionDone(\"Section options opened\");\n },\n });\n if (exportVisible)\n for (const item of props.export?.items ?? [])\n actions.push({\n id: `export:${item.id}`,\n label: item.label,\n supports: () => true,\n ...(item.build && !item.onSelect\n ? {\n placement: \"download\" as const,\n source: make(\n `export:${item.id}`,\n async () => {\n const file = item.build!();\n const bytes = new Uint8Array(\n await new Blob([file.content], {\n type: file.mime,\n }).arrayBuffer(),\n );\n return {\n kind: \"registered\",\n format: \"matrx-file\",\n value: {\n bytes: Array.from(bytes),\n mime: file.mime,\n extension: file.extension,\n ...(file.filename !== undefined\n ? { filename: file.filename }\n : {}),\n },\n };\n },\n item.label,\n ),\n }\n : {}),\n run: async ({ snapshot, draft, signal }) => {\n if (item.onSelect) {\n await item.onSelect();\n return actionDone(`Opened ${item.label}`);\n }\n const value =\n draft.payload.kind === \"registered\" ? draft.payload.value : null;\n if (\n !value ||\n Array.isArray(value) ||\n typeof value !== \"object\" ||\n !Array.isArray(value.bytes) ||\n typeof value.mime !== \"string\" ||\n typeof value.extension !== \"string\" ||\n value.bytes.some(\n (byte) =>\n typeof byte !== \"number\" ||\n !Number.isInteger(byte) ||\n byte < 0 ||\n byte > 255,\n )\n )\n throw new Error(`${item.label} did not capture a valid file.`);\n if (\n value.filename !== undefined &&\n (typeof value.filename !== \"string\" ||\n !isSafeFilename(value.filename))\n )\n throw new Error(\n `${item.label} has an unsafe filename. Use a nonempty basename without leading or trailing whitespace, dots only, path separators, or control characters.`,\n );\n if (\n draft.omissions.some((omission) => omission.reason !== \"duplicate\")\n )\n throw new Error(\n \"This custom file exceeds the configured export limits or contains excluded content. Use a standard format or revise the source options.\",\n );\n const bytes = new Uint8Array(value.bytes as number[]);\n const filename =\n typeof value.filename === \"string\"\n ? value.filename\n : `${\n props.label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\") || \"export\"\n }.${value.extension.replace(/[^a-zA-Z0-9.-]/g, \"\") || \"bin\"}`;\n return transport.download(\n sealTransferArtifact({\n snapshotId: snapshot.id,\n draftRevision: draft.revision,\n format: `export:${item.id}`,\n plainText: \"\",\n file: { filename, mime: value.mime, bytes },\n omissions: [...draft.omissions],\n }),\n signal,\n );\n },\n });\n if (exportVisible && table && props.sendToSheet)\n actions.push({\n id: \"send-google-sheet\",\n label: \"Send to Google Sheet\",\n source: table,\n supports: () => true,\n run: async ({ draft }) => {\n if (draft.payload.kind !== \"rows\")\n throw new Error(\"Google Sheets requires captured rows.\");\n return props.sendToSheet!(draft.payload.rows, props.label);\n },\n });\n const source =\n (props.primarySource === \"table\" ? table : undefined) ??\n json ??\n table ??\n structuredAgent ??\n human ??\n builderVariants[0]?.source;\n if (!source && !actions.length) return null;\n // Action-only targets carry an explicit description, never invented record data.\n const target =\n source ?? make(\"actions\", () => ({ kind: \"text\", text: props.label }));\n return (\n <>\n <ContentTransferMenu\n triggerSize={props.size === \"xs\" || props.size === \"toolbar\" ? \"compact\" : \"default\"}\n source={target}\n {...(source && source === structuredAgent\n ? { envelope: () => structuredPayload(resolve(props.agent!)).envelope }\n : {})}\n {...(props.references ? { references: props.references } : {})}\n {...(props.referenceActions ? { referenceActions: props.referenceActions } : {})}\n {...(props.icon !== undefined ? { icon: props.icon } : {})}\n {...(props.triggerVariant !== undefined\n ? { triggerVariant: props.triggerVariant }\n : {})}\n controllerRef={(value) => {\n controller.current = value;\n if (typeof props.controllerRef === \"function\") props.controllerRef(value);\n else if (props.controllerRef) (props.controllerRef as React.MutableRefObject<ContentTransferController | null>).current = value;\n }}\n {...(props.triggerHidden ? { triggerHidden: true } : {})}\n {...(richCopy ? { richCopy, ...(props.richCopyFlavors ? { richCopyFlavors: props.richCopyFlavors } : props.richCopy ? {} : { richCopyFlavors: [\"markdown\" as const] }) } : {})}\n label={props.label}\n {...(aiVisible && props.aiCustom\n ? {\n copyWithPrompt: async () => {\n if (!controller.current) throw new Error(\"Alchemy is no longer mounted.\");\n await controller.current.prepareLevers(customLevers(props.aiCustom!), {\n id: `${instance}:custom`,\n label: props.aiCustom!.dialogTitle ?? props.label,\n });\n },\n }\n : {})}\n variants={variants}\n actions={actions}\n {...(richText && props.htmlPreview !== false ? { htmlPreview: true } : {})}\n sourceFormats={Boolean(source)}\n hide={[\n ...(!copyVisible || !source ? [\"copy\" as const] : []),\n ...(!aiVisible || !source ? [\"prepare\" as const] : []),\n ...(!exportVisible ? [\"download\" as const] : []),\n ]}\n formatSources={{\n ...(human\n ? { plain: humanText!, markdown: humanMarkdown!, html: humanMarkdown! }\n : {}),\n ...(json ? { json, \"compact-json\": json } : {}),\n ...(table && exportVisible ? { csv: table, tsv: table } : {}),\n }}\n {...(props.disabled !== undefined ? { disabled: props.disabled } : {})}\n className={cn(\n props.className,\n props.size === \"xs\" && \"matrx-alchemy-xs\",\n props.size === \"sm\" && \"matrx-alchemy-sm\",\n props.size === \"toolbar\" && \"matrx-alchemy-toolbar-target\",\n )}\n {...(props.stopPropagation !== undefined\n ? { stopPropagation: props.stopPropagation }\n : {})}\n />\n {modal?.modal?.({\n open: true,\n onOpenChange: (open) => {\n if (!open) setModal(null);\n },\n })}\n </>\n );\n}\n\nexport const GROOMER_LEVELS: AlchemyDetail[] = [\"full\", \"compact\", \"brief\"];\nexport function defaultGroomerSelections(\n sections: AlchemyGroomerSection[],\n): Record<string, AlchemyDetail | \"off\"> {\n return Object.fromEntries(\n sections.map((section) => [section.id, section.defaultSelection ?? \"full\"]),\n );\n}\nexport function buildGroomerPresetPayload(\n config: AlchemyGroomerConfig,\n preset: AlchemyGroomerPreset,\n): AgentPayloadInput {\n const selections = applyGroomerPreset(preset, config.sections);\n const data: Record<string, unknown> = {};\n const dropped: string[] = [];\n for (const section of config.sections) {\n const selection = selections[section.id] ?? \"full\";\n if (selection === \"off\") {\n dropped.push(section.id);\n continue;\n }\n const value = section.build(selection);\n if (value !== undefined && value !== null) data[section.id] = value;\n }\n return {\n kind: config.kind,\n location: config.location,\n description:\n preset === \"everything\"\n ? config.description\n : `${config.description} (${preset} detail)`,\n data,\n ...(config.summary !== undefined ? { summary: config.summary } : {}),\n attributes: {\n ...config.attributes,\n detail: preset,\n ...(dropped.length ? { dropped_sections: dropped.join(\",\") } : {}),\n },\n ...(config.context ? { context: config.context } : {}),\n };\n}\nexport function groomerPresetVariants(\n getConfig: () => AlchemyGroomerConfig,\n): AlchemyCopyVariant[] {\n return [\n {\n id: \"balanced\",\n label: \"Balanced\",\n hint: \"Compact sections\",\n build: () => buildGroomerPresetPayload(getConfig(), \"balanced\"),\n },\n {\n id: \"minimal\",\n label: \"Minimal\",\n hint: \"Brief sections with optional detail excluded\",\n build: () => buildGroomerPresetPayload(getConfig(), \"minimal\"),\n },\n ];\n}\n","\"use client\";\n\nimport type { CopyControlProps } from \"@ai-matrx/design-system/data-table/host\";\nimport { MatrxCopyMenu } from \"./matrx-copy\";\n\n/**\n * THE table copy control (ALC-16): what a host binds as `MatrxDataTableHost.CopyControls`.\n * design-system's table sits below alchemy, so it speaks only the copy contract\n * (`CopyControlProps`); this answers it with the one Alchemy menu.\n */\nexport function AlchemyTableCopyControls(props: CopyControlProps) {\n return <MatrxCopyMenu {...props} />;\n}\n"],"mappings":";aAEA,UAAY,UAAW,QAEvB,OAAS,WAAc,0BACvB,OAAS,OAAQ,cAAe,kBAAmB,aAAc,aAAc,gBAAmB,0BAkG1F,WACA,SADA,oBAxFR,IAAM,UAAY,KAAwB,CAAE,OAAQ,WAAY,GAC1D,OAAU,QAAqC,CACnD,OAAQ,QACR,KAAM,eACN,QAAS,iBAAiB,MAAQ,MAAM,QAAU,wBAClD,UAAW,EACb,GAGO,SAAS,yBAAyB,MAGvC,CACA,GAAM,CAAC,QAAS,UAAU,EAAU,eAA8B,IAAI,EAChE,CAAC,QAAS,UAAU,EAAU,eAAS,EAAK,EAC5C,WAAmB,aAA4B,IAAI,EACnD,WAAmB,aAAO,EAAK,EAE/B,OAAe,kBAAY,CAAC,QAAuB,QAA0B,OAAS,KAAS,CAC/F,WAAW,UAAY,UAC3B,WAAW,QAAU,KACrB,QAAQ,QAAQ,OAAO,oBAAoB,QAAS,QAAQ,OAAO,EACnE,QAAQ,QAAQ,OAAO,EACvB,WAAW,QAAU,GACjB,SACF,WAAW,EAAK,EAChB,WAAW,IAAI,GAEnB,EAAG,CAAC,CAAC,EAEC,gBACJ,IAAM,IAAM,CACV,IAAM,QAAU,WAAW,QACtB,UACL,WAAW,QAAU,KACrB,QAAQ,QAAQ,OAAO,oBAAoB,QAAS,QAAQ,OAAO,EACnE,QAAQ,QAAQ,UAAU,CAAC,EAC3B,WAAW,QAAU,GACvB,EACA,CAAC,CACH,EAEA,IAAM,SAAiB,cA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AC,sBAAqB,YAAa,eAAiB,MAAM,IAAM,YAAc,EAAG,aAAc,IAAM,gBAAgB,UAAU,GAAK,WAAW,SAAS,MAAM,EAAmB,MAAO,WAAa,OAAS,SAAU,WAAY,YAAY,MAAM,GAAG,GAAK,KAAM,KAAM,eAAiB,eAAiB,MAAM,IAAK,MAAO,MAAO,OAAgB,YAAa,OAAO,YAAa,QAAS,IAAM,iBAAiB,EAAK,EAAG,SAAW,MAAS,cAAe,UAAa,CAAE,GAAG,QAAS,CAAC,MAAM,GAAG,EAAG,IAAK,EAAE,EAAG,UAAsB,SAAoB,QAAS,gBAAiB,aAAc,kBAAkB,QAAQ,IAAI,MAAM,GAAG,GAAK,eAAiB,GAAI,GAAK,CAAE,EAAG,EAAI,CAAC,EAAI,UAAW,QAA9f,MAAM,GAA+f,CAAE,EACttB,aACH,CACF","names":["resolve","React","createPortal","applyTransferLimits","capture","buildAgentPayload","createBrowserTransport","createDraft","directSource","projectSnapshot","resolveTransferPreferences","sealTransferArtifact","serialize","Button","cn","React","jsx","jsxs","React","formatCount","concretePointers","patternCovers","readTransferCell","resetDraft","sealTransferArtifact","serialize","Button","Dialog","DialogContent","DialogDescription","DialogHeader","DialogTitle","React","formatCount","pointerSegments","jsx","jsxs","formatCount","pointerSegments","Fragment","jsx","jsxs","serialize","layout","concretePointers","sealTransferArtifact","resetDraft","formatCount","structure","patternCovers","Button","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","readTransferCell","readTransferCell","sealTransferArtifact","serialize","useContentTransferSurface","React","createDraft","serialize","directSource","normalizeTransferJson","sealTransferArtifact","cn","Fragment","jsx","jsxs","directSource","createDraft","serialize","normalizeTransferJson","sealTransferArtifact","cn","jsx","Fragment","jsx","jsxs","cn","createBrowserTransport","resolveTransferPreferences","directSource","capture","projectSnapshot","createDraft","applyTransferLimits","handle","label","sealTransferArtifact","serialize","buildAgentPayload","Button","createPortal"]}
|