@ai-matrx/sharing 0.1.4 → 0.1.5

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/access/react/env.tsx","../src/access/react/AccessDenied.tsx","../src/access/react/RequestAccessPanel.tsx","../src/access/react/BlindAccessAsk.tsx","../src/access/react/useAccessGate.ts","../src/access/react/AccessGate.tsx","../src/access/react/SlugAccessGate.tsx","../src/access/react/SettingAccessGate.tsx","../src/access/react/ForbiddenSurface.tsx","../src/access/react/RequestAccess.tsx","../src/access/react/useRequestAccess.ts","../src/access/react/UnresolvedEntityRef.tsx","../src/access/react/ServerReadRecheck.tsx","../src/access/react/GovernedActionDialog.tsx","../src/access/react/useHiddenByMe.ts","../src/access/react/HiddenByMeButton.tsx","../src/access/react/HiddenFilter.tsx","../src/access/react/ResourceActionRequestButtons.tsx","../src/access/react/SettingRequestActionButtons.tsx","../src/access/react/AccessRequestsSurface.tsx","../src/access/react/useAccessStates.ts","../src/access/react/cantRemoveOpener.ts"],"sourcesContent":["\"use client\";\n\n/**\n * @ai-matrx/sharing/access/react — the app inputs the access SCREENS cannot own.\n *\n * The screens import nothing from the host app (no `@/…`, no `next/*`). What a\n * screen needs from the app is injected here, ONCE at boot:\n *\n * configureAccessUi({ useLoginHref, useCurrentUser, toast, Link, … });\n *\n * (The pure half — the Supabase client, `ensureOrgId`, the CMS entity tokens —\n * is injected separately through `configureAccess` from `@ai-matrx/data/access`.)\n *\n * ONE MECHANISM: a module-level `configureAccessUi(env)` that MERGES over any\n * earlier call, plus an optional `<AccessUiProvider env>` that overrides fields\n * for one subtree (a Storybook, a test, a second host). Components read the\n * merged, defaulted result with `useAccessUi()`.\n *\n * THREE KINDS OF FIELD\n * - REQUIRED (`useLoginHref`, `useCurrentUser`, `toast`): there is no honest\n * default — a wrong sign-in link, a guessed identity or a swallowed message\n * is a lie on the screen that exists to stop lies. Reading one that was\n * never supplied THROWS an error naming `configureAccessUi` and the field.\n * - OPTIONAL WITH A WORKING DEFAULT (`Link`, `router`, `confirm`, `Textarea`,\n * `renderUserIdentity`, `renderEntityRef`, `renderErrorMenu`,\n * `navItemClasses`, `searchParam`): the screen renders its documented\n * default (a plain anchor, the browser history, the kit confirm, a plain\n * name) — never nothing.\n * - OPTIONAL APP FEATURES (`entityRegistry`, `trash`, `recordUnavailableCapture`,\n * `settingRequestActions`, `resourceActionRequests`, `cms`, `settingDoorHref`,\n * `reportFeedback`, `presentOrganizationRefusal`, `overlays`):\n * messaging / settings / cms / trash coupling the gate does not own. Absent,\n * the component renders its documented default for the absence (no door\n * link, an unrecognised-action notice, a visible \"not wired\" failure when\n * the person presses the button) — it never hides a feature.\n *\n * Hook-valued fields (`useLoginHref`, `useCurrentUser`) are called inside\n * components: they must be stable for the life of the app (set at boot).\n */\n\nimport {\n createContext,\n forwardRef,\n useContext,\n useMemo,\n type AnchorHTMLAttributes,\n type ComponentType,\n type ReactNode,\n type RefAttributes,\n} from \"react\";\nimport { Avatar, AvatarFallback, AvatarImage, Textarea } from \"@ai-matrx/design-system\";\nimport { getInitials } from \"@ai-matrx/kit/format\";\nimport { confirm as kitConfirm, type ConfirmOptions } from \"@ai-matrx/kit/confirm-opener\";\nimport type { JsonObject } from \"@ai-matrx/kit/json-format\";\nimport type { RecordUnavailableResolution } from \"@ai-matrx/data/db\";\nimport type { AccessRequestCreated } from \"@ai-matrx/data/access\";\n\n/* ─── shapes ─────────────────────────────────────────────────────────────── */\n\nexport interface AccessUiLinkProps\n extends AnchorHTMLAttributes<HTMLAnchorElement> {\n href: string;\n}\n\n/** The person using the screen. Any field may be null while the session boots. */\nexport interface AccessUiCurrentUser {\n id: string | null;\n displayName: string | null;\n email: string | null;\n}\n\nexport interface AccessUiToast {\n success(message: string): void;\n error(message: string): void;\n warning(message: string): void;\n info?(message: string): void;\n}\n\nexport interface AccessUiRouter {\n push(href: string): void;\n back(): void;\n /** Re-render the current URL from the server (Next `router.refresh()`). */\n refresh(): void;\n}\n\n/** What the gate needs to know about an entity token to link to a record. */\nexport interface AccessUiEntityInfo {\n hrefFor?: (id: string) => string | null | undefined;\n}\n\nexport interface AccessUiEntityRefProps {\n token: string;\n id: string;\n name: string;\n showIcon?: boolean;\n className?: string;\n}\n\nexport interface AccessUiUserIdentityProps {\n user: {\n id?: string | null | undefined;\n displayName?: string | null | undefined;\n avatarUrl?: string | null | undefined;\n };\n size?: \"sm\" | \"md\";\n subtitle?: boolean;\n avatarOnly?: boolean;\n}\n\nexport interface AccessUiErrorMenuProps {\n size?: \"icon\" | \"default\";\n className?: string;\n /** The error text (or error) the menu should offer to copy. */\n error?: unknown;\n /** Structured description of what failed (title, message, operation, records…). */\n input?: Record<string, unknown>;\n}\n\nexport interface AccessUiTextareaProps {\n className?: string;\n value: string;\n onChange: (event: { target: { value: string } }) => void;\n placeholder?: string;\n maxLength?: number;\n rows?: number;\n autoFocus?: boolean;\n \"aria-label\"?: string;\n}\n\n/** A setting-change action an admin completes from a request (messaging registry). */\nexport interface AccessSettingRequestAction {\n label: string;\n completedLabel: string;\n execute(payload: JsonObject, context: { organizationId: string }): Promise<void>;\n}\n\n/** A resource action (e.g. delete) an owner completes from a request. */\nexport interface AccessResourceActionRequestAction {\n label: string;\n completedLabel: string;\n confirmTitle(name: string): string;\n confirmDescription: string;\n execute(context: { resourceType: string; resourceId: string }): Promise<void>;\n}\n\nexport interface AccessUiFeedbackInput {\n feedback_type: \"request\";\n route: string;\n organization_id: string;\n description: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface AccessUiEnv {\n /* REQUIRED */\n /** The sign-in URL that returns the person to where they are. Hook-shaped. */\n useLoginHref(): string;\n /** The current person (replaces the app's redux selectors). Hook-shaped. */\n useCurrentUser(): AccessUiCurrentUser;\n /** User-visible notices. */\n toast: AccessUiToast;\n\n /* OPTIONAL, WITH A WORKING DEFAULT */\n /** Client-side navigation link. Default: a plain `<a href>` (full page load). */\n Link?: ComponentType<AccessUiLinkProps & RefAttributes<HTMLAnchorElement>>;\n /** Default: `history.back()` / `location.reload()` / `location.assign`. */\n router?: AccessUiRouter;\n /** Read one URL query parameter. Default: `window.location.search`. */\n searchParam?(name: string): string | null;\n /** Default: the kit's imperative `confirm()` (needs the design-system ConfirmDialogHost mounted). */\n confirm?(options: ConfirmOptions): Promise<boolean>;\n /** Default: the design-system `Textarea`. An app may pass its voice-enabled textarea. */\n Textarea?: ComponentType<AccessUiTextareaProps>;\n /** Default: avatar + name from the design-system Avatar. */\n renderUserIdentity?(props: AccessUiUserIdentityProps): ReactNode;\n /** Default: the plain name — NOT a door. Pass the app's EntityRef to make it one. */\n renderEntityRef?(props: AccessUiEntityRefProps): ReactNode;\n /** The error-copy menu slot. Default: renders nothing (it is a convenience, not a feature). */\n renderErrorMenu?(props: AccessUiErrorMenuProps): ReactNode;\n /** Classes of the selected / unselected inbox tab. Default: the app-shell nav CSS variables. */\n navItemClasses?: { selected: string; unselected: string };\n\n /* OPTIONAL APP FEATURES */\n /** Label/route lookup per entity token. Absent: owners and records render as plain names. */\n entityRegistry?: { tryGetEntityInfo(token: string): AccessUiEntityInfo | null };\n /** Restore from Trash. Absent: pressing Restore fails visibly naming this field. */\n trash?: { restore(token: string, id: string): Promise<void> };\n /** Reconcile the diagnostics row of a captured read. Absent: no-op. */\n recordUnavailableCapture?: {\n resolve(error: unknown, resolution: RecordUnavailableResolution): void;\n };\n /** Setting-change actions by key. Absent: requests render without the primary action button. */\n settingRequestActions?: { get(key: string): AccessSettingRequestAction | undefined };\n /** The action key the \"request access\" flows file. Default `request_access.manual`. */\n manualRequestActionKey?: string;\n /** Resource actions by key. Absent: requests render without the primary action button. */\n resourceActionRequests?: {\n get(key: string): AccessResourceActionRequestAction | undefined;\n };\n /** CMS-resolved tokens file through the host's CMS door. Absent: asking fails visibly. */\n cms?: {\n createAccessRequest(args: {\n token: string;\n resourceId: string;\n message?: string;\n currentUserId?: string | null;\n }): Promise<AccessRequestCreated>;\n };\n /** The URL of an organization setting's door. Absent: asking for a setting change fails visibly. */\n settingDoorHref?(target: {\n scope: \"organization\";\n organizationSlugOrId: string;\n controlId: string;\n }): string;\n /** File a feedback item (system-owned access requests). Absent: asking the platform team fails visibly. */\n reportFeedback?(\n input: AccessUiFeedbackInput,\n ): Promise<{ success: boolean; error?: string }>;\n /** Show \"choose an organization first\". Returns true when it handled the error. Default: false. */\n presentOrganizationRefusal?(\n error: unknown,\n options: { act: string; subject: string },\n ): boolean;\n /**\n * The host's overlay doors (AI Matrx: dispatch summon `openOverlay` / `closeOverlay` on its store). The\n * \"can't remove it\" screen is the overlay `CANT_REMOVE_DIALOG` opened through them. Absent: that screen\n * cannot open and says so on the console (the caller gets \"closed\").\n */\n overlays?: {\n open(overlayId: string, instanceId: string, data: unknown): void;\n close(overlayId: string, instanceId: string): void;\n };\n}\n\n/** The documented default for `manualRequestActionKey`. */\nexport const REQUEST_ACCESS_MANUAL_ACTION = \"request_access.manual\";\n\nconst DEFAULT_NAV_ITEM_CLASSES = {\n selected:\n \"bg-[var(--shell-nav-selected-bg)] text-[var(--shell-nav-selected-text)] shadow-[var(--shell-nav-selected-shadow)] font-semibold\",\n unselected:\n \"text-[var(--shell-nav-unselected-text)] hover:text-[var(--shell-nav-text-hover)] hover:bg-[var(--matrx-glass-bg-hover)]\",\n};\n\n/* ─── defaults ───────────────────────────────────────────────────────────── */\n\nconst DefaultLink = forwardRef<HTMLAnchorElement, AccessUiLinkProps>(\n function DefaultLink(props, ref) {\n // eslint-disable-next-line @next/next/no-html-link-for-pages -- the package has no router; the host's Link replaces this\n return <a ref={ref} {...props} />;\n },\n);\n\n/** The host's `Link`, resolved at render. Components import this as `Link`. */\nexport const AccessLink = forwardRef<HTMLAnchorElement, AccessUiLinkProps>(\n function AccessLink(props, ref) {\n const { Link } = useAccessUi();\n return <Link ref={ref} {...props} />;\n },\n);\n\nconst DEFAULT_ROUTER: AccessUiRouter = {\n push: (href) => {\n if (typeof window !== \"undefined\") window.location.assign(href);\n },\n back: () => {\n if (typeof window !== \"undefined\") window.history.back();\n },\n refresh: () => {\n if (typeof window !== \"undefined\") window.location.reload();\n },\n};\n\nfunction defaultSearchParam(name: string): string | null {\n if (typeof window === \"undefined\") return null;\n return new URLSearchParams(window.location.search).get(name);\n}\n\nfunction DefaultTextarea(props: AccessUiTextareaProps) {\n return <Textarea {...props} />;\n}\n\nfunction DefaultUserIdentity({ user, size = \"md\", avatarOnly }: AccessUiUserIdentityProps) {\n const name = user.displayName ?? \"Someone\";\n const box = size === \"sm\" ? \"h-7 w-7\" : \"h-9 w-9\";\n return (\n <span className=\"inline-flex min-w-0 items-center gap-2\">\n <Avatar className={box}>\n {user.avatarUrl ? <AvatarImage src={user.avatarUrl} alt={name} /> : null}\n <AvatarFallback className=\"text-[11px]\">{getInitials(user.displayName)}</AvatarFallback>\n </Avatar>\n {avatarOnly ? null : <span className=\"min-w-0 truncate text-sm\">{name}</span>}\n </span>\n );\n}\n\nfunction DefaultEntityRef({ name, className }: AccessUiEntityRefProps) {\n return <span className={className}>{name}</span>;\n}\n\n/* ─── configure / resolve ────────────────────────────────────────────────── */\n\nlet moduleEnv: Partial<AccessUiEnv> = {};\nlet moduleVersion = 0;\n\n/**\n * Inject the app inputs the access screens need. Call once at boot. Later\n * calls MERGE over earlier ones, so a host can configure in two steps.\n */\nexport function configureAccessUi(env: Partial<AccessUiEnv>): void {\n moduleEnv = { ...moduleEnv, ...env };\n moduleVersion += 1;\n}\n\n/** True once every REQUIRED field has been supplied. */\nexport function isAccessUiConfigured(): boolean {\n return Boolean(moduleEnv.useLoginHref && moduleEnv.useCurrentUser && moduleEnv.toast);\n}\n\n/** The resolved environment: required fields throw when missing, the rest are defaulted. */\nexport interface AccessUi {\n useLoginHref(): string;\n useCurrentUser(): AccessUiCurrentUser;\n toast: AccessUiToast;\n Link: ComponentType<AccessUiLinkProps & RefAttributes<HTMLAnchorElement>>;\n router: AccessUiRouter;\n searchParam(name: string): string | null;\n confirm(options: ConfirmOptions): Promise<boolean>;\n Textarea: ComponentType<AccessUiTextareaProps>;\n renderUserIdentity(props: AccessUiUserIdentityProps): ReactNode;\n renderEntityRef(props: AccessUiEntityRefProps): ReactNode;\n renderErrorMenu(props: AccessUiErrorMenuProps): ReactNode;\n navItemClasses: { selected: string; unselected: string };\n manualRequestActionKey: string;\n tryGetEntityInfo(token: string): AccessUiEntityInfo | null;\n restoreFromTrash(token: string, id: string): Promise<void>;\n resolveRecordUnavailableCapture(error: unknown, resolution: RecordUnavailableResolution): void;\n getSettingRequestAction(key: string): AccessSettingRequestAction | undefined;\n getResourceActionRequestAction(key: string): AccessResourceActionRequestAction | undefined;\n /** Whether the host wired the CMS door (cms.createAccessRequest). */\n createCmsAccessRequest(args: {\n token: string;\n resourceId: string;\n message?: string;\n currentUserId?: string | null;\n }): Promise<AccessRequestCreated>;\n settingDoorHref(target: {\n scope: \"organization\";\n organizationSlugOrId: string;\n controlId: string;\n }): string;\n reportFeedback(input: AccessUiFeedbackInput): Promise<{ success: boolean; error?: string }>;\n presentOrganizationRefusal(error: unknown, options: { act: string; subject: string }): boolean;\n /** Open an overlay through the host's doors; throws `notConfigured(\"overlays\")` without them. */\n openOverlay(overlayId: string, instanceId: string, data: unknown): void;\n closeOverlay(overlayId: string, instanceId: string): void;\n}\n\nfunction notConfigured(field: string): Error {\n return new Error(\n `[@ai-matrx/sharing/access/react] \\`${field}\\` was not supplied: add it to configureAccessUi({ ${field} }) once at app boot.`,\n );\n}\n\nfunction resolveAccessUi(\n base: Partial<AccessUiEnv>,\n override: Partial<AccessUiEnv> | null,\n): AccessUi {\n const env: Partial<AccessUiEnv> = { ...base, ...(override ?? {}) };\n const required = <K extends \"useLoginHref\" | \"useCurrentUser\" | \"toast\">(\n key: K,\n ): NonNullable<AccessUiEnv[K]> => {\n const value = env[key];\n if (value === undefined || value === null) throw notConfigured(key);\n return value as NonNullable<AccessUiEnv[K]>;\n };\n const ui: AccessUi = {\n // Required fields are getters so a screen that never reads one still renders.\n get useLoginHref() {\n return required(\"useLoginHref\");\n },\n get useCurrentUser() {\n return required(\"useCurrentUser\");\n },\n get toast() {\n return required(\"toast\");\n },\n Link: env.Link ?? DefaultLink,\n router: env.router ?? DEFAULT_ROUTER,\n searchParam: env.searchParam ?? defaultSearchParam,\n confirm: env.confirm ?? kitConfirm,\n Textarea: env.Textarea ?? DefaultTextarea,\n renderUserIdentity: env.renderUserIdentity ?? ((p) => <DefaultUserIdentity {...p} />),\n renderEntityRef: env.renderEntityRef ?? ((p) => <DefaultEntityRef {...p} />),\n renderErrorMenu: env.renderErrorMenu ?? (() => null),\n navItemClasses: env.navItemClasses ?? DEFAULT_NAV_ITEM_CLASSES,\n manualRequestActionKey: env.manualRequestActionKey ?? REQUEST_ACCESS_MANUAL_ACTION,\n tryGetEntityInfo: (token) => env.entityRegistry?.tryGetEntityInfo(token) ?? null,\n restoreFromTrash: async (token, id) => {\n if (!env.trash) throw notConfigured(\"trash\");\n await env.trash.restore(token, id);\n },\n resolveRecordUnavailableCapture: (error, resolution) =>\n env.recordUnavailableCapture?.resolve(error, resolution),\n getSettingRequestAction: (key) => env.settingRequestActions?.get(key),\n getResourceActionRequestAction: (key) => env.resourceActionRequests?.get(key),\n createCmsAccessRequest: async (args) => {\n if (!env.cms) throw notConfigured(\"cms\");\n return env.cms.createAccessRequest(args);\n },\n settingDoorHref: (target) => {\n if (!env.settingDoorHref) throw notConfigured(\"settingDoorHref\");\n return env.settingDoorHref(target);\n },\n reportFeedback: async (input) => {\n if (!env.reportFeedback) throw notConfigured(\"reportFeedback\");\n return env.reportFeedback(input);\n },\n presentOrganizationRefusal: (error, options) =>\n env.presentOrganizationRefusal?.(error, options) ?? false,\n openOverlay: (overlayId, instanceId, data) => {\n if (!env.overlays) throw notConfigured(\"overlays\");\n env.overlays.open(overlayId, instanceId, data);\n },\n closeOverlay: (overlayId, instanceId) => env.overlays?.close(overlayId, instanceId),\n };\n return ui;\n}\n\n/** The module-level environment, for code that is not a component (openers, stores). */\nexport function getAccessUi(): AccessUi {\n return resolveAccessUi(moduleEnv, null);\n}\n\nconst AccessUiContext = createContext<Partial<AccessUiEnv> | null>(null);\n\n/** Override fields for one subtree (tests, a second host). Merges over `configureAccessUi`. */\nexport function AccessUiProvider({\n env,\n children,\n}: {\n env: Partial<AccessUiEnv>;\n children: ReactNode;\n}) {\n return <AccessUiContext.Provider value={env}>{children}</AccessUiContext.Provider>;\n}\n\n/** The merged, defaulted environment. Stable while neither the provider value nor the configuration changes. */\nexport function useAccessUi(): AccessUi {\n const override = useContext(AccessUiContext);\n return useMemo(\n () => resolveAccessUi(moduleEnv, override),\n // `moduleVersion` is read on purpose: configuring after first render is picked up by the next mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [override, moduleVersion],\n );\n}\n","\"use client\";\n\n/**\n * AccessDenied — THE screen a user sees when they can't open something.\n *\n * One component covers every case, because the platform (not the surface) knows\n * which case it is: no access, deleted, never existed, signed out, or a\n * transient fault on something they CAN open. Before this existed, each surface\n * guessed, and the guess was usually wrong — the incident that produced this\n * feature told a signed-out user their data had been deleted.\n *\n * WHAT IT PROMISES\n * - Human words only. Never a token, a uuid, an RLS error, a schema name, or a\n * PostgREST code. The kind is a pretty label from the entity registry.\n * - A real next step, always: request access, sign in, or a door to something\n * the user CAN open. Never a Retry button that cannot succeed.\n * - A LANDING, not a cul-de-sac. A surface may hand it `suggestions` — the\n * two or three things a person in this feature actually wants when the\n * thing they clicked isn't there (\"your websites\", \"create one\"). Without\n * them the screen is technically honest and practically a dead end: it says\n * what went wrong and leaves you to find your own way back.\n * - Every identity it names is a door (THE DOOR LAW) — the owner, the\n * organization, and the nearest reachable ancestor are all reachable.\n *\n * A feature that genuinely earns its own branded version composes the exported\n * `AccessDeniedView` at its own call site; it does not fork this file.\n */\n\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport { useState } from \"react\";\nimport {\n ArrowLeft,\n Building2,\n Lock,\n LogIn,\n RefreshCw,\n RotateCcw,\n SearchX,\n Trash2,\n TriangleAlert,\n} from \"lucide-react\";\nimport { Avatar, AvatarFallback, AvatarImage, Button } from \"@ai-matrx/design-system\";\nimport { RequestAccessPanel } from \"./RequestAccessPanel\";\nimport { BlindAccessAsk } from \"./BlindAccessAsk\";\n// THE EMERGENCY DOOR'S ONE ENTRANCE (DD-137a). It renders NOTHING unless this\n// viewer can actually get through — see the component's header. The ordinary\n// request panel above it is unchanged and stays for everyone.\nimport { useAccessGate } from \"./useAccessGate\";\nimport type {\n AccessDeniedContext,\n AccessRequestability,\n} from \"@ai-matrx/data/access\";\n// THE package initials formatter (`@ai-matrx/kit/format`, census H1\n// 2026-09-07). Recorded display decision: a multi-part name takes FIRST +\n// LAST, so \"Ana Maria Rivera\" is AR — this surface previously took first +\n// second and printed \"AM\".\nimport { getInitials } from \"@ai-matrx/kit/format\";\nimport { ErrorNotice } from \"@ai-matrx/design-system\";\nimport {\n archivedExplanation,\n archivedHeadline,\n archivedOrganizationExplanation,\n archivedOrganizationHeadline,\n mayRestoreArchived,\n} from \"@ai-matrx/data/access\";\n\n/**\n * Restore an archived record in place, through the ONE generic door\n * (`entity_undelete`, the same call /trash makes). On success the surface\n * re-reads: its own retry when it has one, otherwise a server re-render of this\n * same URL — which is what a server page's gate needs.\n */\nfunction RestoreArchived({\n token,\n id,\n kind,\n onRestored,\n}: {\n token: string;\n id: string;\n kind: string;\n onRestored: () => void;\n}) {\n const ui = useAccessUi();\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<unknown>(null);\n return (\n <>\n <Button\n size=\"sm\"\n disabled={busy}\n onClick={async () => {\n setBusy(true);\n setFailure(null);\n try {\n await ui.restoreFromTrash(token, id);\n ui.toast.success(`Restored the ${kind}.`);\n onRestored();\n } catch (error) {\n setFailure(error);\n } finally {\n setBusy(false);\n }\n }}\n >\n <RotateCcw className=\"mr-1.5 h-4 w-4\" aria-hidden />\n {busy ? \"Restoring…\" : \"Restore\"}\n </Button>\n {failure ? (\n <ErrorNotice\n size=\"inline\"\n className=\"basis-full text-sm\"\n title=\"Not restored\"\n error={failure}\n operation={`Restore this ${kind}`}\n records={[{ type: token, id }]}\n />\n ) : null}\n </>\n );\n}\n\n/**\n * One concrete way forward, offered by the surface that knows the feature.\n * The gate cannot invent these — only the CMS knows that \"create a website\" is\n * the useful thing to offer someone whose website link went nowhere.\n */\nexport interface AccessDeniedSuggestion {\n /** Short imperative label — \"Your websites\", \"Create a website\". */\n title: string;\n /** One line on what they will get. Optional. */\n description?: string;\n /** Where it goes. Must be a route this viewer can actually open (THE DOOR LAW). */\n href: string;\n icon?: React.ComponentType<{ className?: string }>;\n}\n\nexport interface AccessDeniedProps {\n /** Canonical entity token of the thing the user tried to open. */\n token: string;\n /** Its id. */\n id: string;\n /** The original failed read, so the resolver can reconcile its capture. */\n readError?: unknown | undefined;\n /**\n * Where \"go back to what I can see\" should land when the platform can't find\n * a reachable ancestor — usually the feature's own list route.\n */\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n /** Retry the surface's own read, offered only where retrying can work. */\n onRetry?: (() => void) | undefined;\n /** Concrete next steps in THIS feature. See AccessDeniedSuggestion. */\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /**\n * Whether asking is a real option here. Defaults to `\"requestable\"` — the\n * behavior every existing caller already has. Pass `\"absolute\"` when the\n * door is closed by law and the ask itself would leak. See\n * `AccessRequestability`.\n */\n requestability?: AccessRequestability | undefined;\n /**\n * The surface's own worded reason, shown in place of the generic explanation.\n * On an `absolute` door this sentence must not confirm the record exists.\n */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /** The surface's own trailing disclosure (a reference code, an audit id). */\n footer?: React.ReactNode | undefined;\n}\n\n/** The full sentence: \"Site · AI Matrx\" or just \"Site\" when we may not say. */\nfunction headline(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\":\n if (context.organizationArchived) return archivedOrganizationHeadline(context);\n return `You don't have access to this ${kind}`;\n case \"deleted\":\n // Archived, in Trash, restorable — never \"deleted\" (archivedWords.ts).\n return archivedHeadline(context);\n case \"missing\":\n return `We couldn't find this ${kind}`;\n case \"anonymous\":\n return `Sign in to open this ${kind}`;\n case \"ok\":\n return `We couldn't load this ${kind}`;\n default:\n return \"Something went wrong\";\n }\n}\n\nfunction explanation(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\": {\n if (context.organizationArchived) return archivedOrganizationExplanation(context);\n const owner =\n context.organization\n ? context.organization.name\n : context.owner?.displayName;\n // Only promise the panel when it will actually render. `canRequest` is\n // false for rows with neither an owner nor an org (platform catalogs),\n // where \"ask below\" pointed at nothing. (Adversarial pass, 2026-08-11.)\n if (!context.canRequest && context.request?.status !== \"pending\") {\n return owner\n ? `It belongs to ${owner}, and there's no one for us to pass a request to.`\n : `It belongs to someone else, and there's no one for us to pass a request to.`;\n }\n return owner\n ? `It belongs to ${owner}. You can ask for access below.`\n : `It belongs to someone else. You can ask for access below.`;\n }\n case \"deleted\":\n return archivedExplanation(context);\n case \"missing\":\n // THE SAME SENTENCE FOR A STRANGER AND A RANDOM ID (V24-TAILS, chair ruling 2026-09-25):\n // the resolver answers a stranger to an unshared object exactly as it answers a missing id,\n // so this page can never say which it is, whose it is, or where it lives.\n return `If someone shared a link with you, you can ask for access.`;\n case \"anonymous\":\n return `We can't tell you anything about it until we know who you are.`;\n case \"ok\":\n // The honest one nobody used to write: they DO have access.\n return `You do have access to it — something went wrong on our side. Try again.`;\n default:\n return `We couldn't work out what happened. Try again in a moment.`;\n }\n}\n\nfunction StatusIcon({ status }: { status: AccessDeniedContext[\"status\"] }) {\n const className = \"h-7 w-7 text-muted-foreground\";\n if (status === \"denied\") return <Lock className={className} aria-hidden />;\n if (status === \"deleted\") return <Trash2 className={className} aria-hidden />;\n if (status === \"missing\")\n return <SearchX className={className} aria-hidden />;\n if (status === \"anonymous\")\n return <LogIn className={className} aria-hidden />;\n return <TriangleAlert className={className} aria-hidden />;\n}\n\n/**\n * One identity — owner or organization — rendered as a door when we know the\n * viewer can walk through it, and as plain text when we don't. Rendering a\n * `<Link>` to a route this viewer cannot open (or that doesn't exist) is the\n * dead end THE DOOR LAW is about; a name with no link is honest.\n */\nfunction IdentityBlock({\n label,\n name,\n href,\n avatar,\n}: {\n label: string;\n name: string;\n href: string | null;\n avatar: React.ReactNode;\n}) {\n const body = (\n <>\n {avatar}\n <span className=\"min-w-0\">\n <span className=\"block text-[11px] uppercase tracking-wide text-muted-foreground\">\n {label}\n </span>\n <span className=\"block truncate text-foreground\">{name}</span>\n </span>\n </>\n );\n\n if (!href) {\n return (\n <span className=\"flex min-w-0 items-center gap-2 text-sm\">{body}</span>\n );\n }\n return (\n <Link\n href={href}\n className=\"flex min-w-0 items-center gap-2 text-sm hover:underline\"\n >\n {body}\n </Link>\n );\n}\n\n/**\n * The resolved surface. Split from the loader so a bespoke variant can reuse\n * the same body with different chrome.\n */\nexport function AccessDeniedView({\n context,\n id,\n fallbackHref,\n fallbackLabel,\n onRetry,\n onChanged,\n suggestions = [],\n requestability = \"requestable\",\n reason,\n headline: headlineOverride,\n footer,\n}: {\n context: AccessDeniedContext;\n id: string;\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n onRetry?: (() => void) | undefined;\n onChanged: () => void;\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /** See `AccessRequestability`. `absolute` removes the request affordance entirely. */\n requestability?: AccessRequestability | undefined;\n /** The surface's own worded reason, in place of the generic explanation. */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /**\n * The surface's own trailing disclosure — a reference code, an audit id, the\n * things a feature earned the right to show and the frame cannot know about.\n * Rendered above the doors. Machine tokens belong in here behind a\n * `<details>`, never in the body: that rule predates this slot and outlives it.\n */\n footer?: React.ReactNode | undefined;\n}) {\n const ui = useAccessUi();\n const router = ui.router;\n const signInHref = ui.useLoginHref();\n const tryGetEntityInfo = ui.tryGetEntityInfo;\n const showOrg = Boolean(context.organization);\n const ancestor = context.ancestor;\n const ancestorInfo = ancestor ? tryGetEntityInfo(ancestor.token) : null;\n const ancestorHref = ancestorInfo?.hrefFor?.(ancestor?.id ?? \"\") ?? null;\n const selfInfo = tryGetEntityInfo(context.entity.token);\n const selfHref = selfInfo?.hrefFor?.(id) ?? null;\n\n /*\n AN ABSOLUTE DOOR SAYS LESS, ON PURPOSE.\n\n The generic headline names the KIND (\"You don't have access to this\n employee\") and the generic explanation names the OWNER and offers to pass a\n request along. On a door closed by law all three are disclosure: the kind,\n the owner, and the very offer to ask. So an absolute denial falls back to a\n headline that claims nothing, and says only what the surface chose to say.\n */\n const absolute =\n requestability === \"absolute\" && context.status === \"denied\";\n const title =\n headlineOverride?.trim() ||\n (absolute ? \"You can't open this here\" : headline(context));\n const body = reason?.trim() || (absolute ? \"\" : explanation(context));\n\n return (\n <div className=\"matrx-touch-targets flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-xl\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-border bg-muted\">\n <StatusIcon status={context.status} />\n </div>\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex items-start gap-2\">\n <h1 className=\"min-w-0 flex-1 text-xl font-semibold tracking-tight text-foreground\">\n {title}\n </h1>\n {/* What stopped the person, copyable for AI (RC-B12). It says no\n more than the page does: an absolute door and a missing/stranger\n record name no kind, owner or id. */}\n {ui.renderErrorMenu({\n size: \"icon\",\n input: {\n title,\n message: body || title,\n operation:\n absolute || context.status === \"missing\"\n ? \"Open this record\"\n : `Open this ${context.entity.label.toLowerCase()}`,\n ...(absolute || context.status === \"missing\"\n ? {}\n : { records: [{ type: context.entity.token, id }] }),\n details: { access_status: context.status },\n source: \"route-boundary\",\n },\n })}\n </div>\n\n {context.entity.title ? (\n <p className=\"mt-1 truncate text-sm text-muted-foreground\">\n {context.entity.label} &middot;{\" \"}\n <span className=\"text-foreground\">{context.entity.title}</span>\n </p>\n ) : null}\n\n {/* The surface's own sentence wins when it has one. A feature that\n knows WHY (a legal veto, a confidentiality tier) says it better\n than the generic copy — and the generic denied copy would be an\n outright lie on an absolute door, since it offers to pass along\n a request that will never be offered. */}\n {body ? (\n <p className=\"mt-2 text-sm text-muted-foreground\">{body}</p>\n ) : null}\n </div>\n </div>\n\n {/* Who has it.\n THE DOOR LAW cuts both ways here: a link the viewer cannot open is a\n worse dead end than no link. A denied viewer is, by definition,\n usually outside the owning org — so each identity is a door only when\n we know it actually opens. */}\n {!absolute && (context.owner || showOrg) ? (\n <div className=\"mt-5 flex flex-wrap items-center gap-4 rounded-lg border border-border bg-muted/30 px-4 py-3\">\n {context.owner ? (\n <IdentityBlock\n label=\"Owner\"\n name={context.owner.displayName ?? \"Someone else\"}\n href={\n context.owner.creatorHandle\n ? `/c/${context.owner.creatorHandle}`\n : null\n }\n avatar={\n <Avatar className=\"h-7 w-7\">\n {context.owner.avatarUrl ? (\n <AvatarImage\n src={context.owner.avatarUrl}\n alt={context.owner.displayName ?? \"Owner\"}\n />\n ) : null}\n <AvatarFallback className=\"text-[11px]\">\n {getInitials(context.owner.displayName)}\n </AvatarFallback>\n </Avatar>\n }\n />\n ) : null}\n\n {showOrg && context.organization ? (\n <IdentityBlock\n label=\"Organization\"\n name={context.organization.name ?? \"An organization\"}\n href={\n context.organization.viewerIsMember\n ? `/organizations/${context.organization.id}`\n : null\n }\n avatar={\n <span className=\"flex h-7 w-7 items-center justify-center rounded-full bg-background\">\n <Building2\n className=\"h-3.5 w-3.5 text-muted-foreground\"\n aria-hidden\n />\n </span>\n }\n />\n ) : null}\n </div>\n ) : null}\n\n {/* 🚨 ABSOLUTE DOORS GET NO ASK. Some refusals are dead ends by law —\n an accused person may never request the case against them, because\n the ASK ITSELF confirms the case exists. `canRequest` cannot express\n this: it only knows whether somebody exists to receive a request. */}\n {context.status === \"denied\" && !absolute && !context.organizationArchived ? (\n <div className=\"mt-4\">\n <RequestAccessPanel\n context={context}\n resourceId={id}\n href={selfHref}\n onChanged={onChanged}\n />\n </div>\n ) : null}\n\n {/* THE ONE ASK ON THE NOT-FOUND PAGE (V24-TAILS). It files for a real object and files\n nothing for a missing id, and says the same sentence either way. An absolute door\n (requestability \"absolute\") offers no ask here either. */}\n {context.status === \"missing\" && requestability !== \"absolute\" ? (\n <div className=\"mt-4\">\n <BlindAccessAsk token={context.entity.token} id={id} href={selfHref} />\n </div>\n ) : null}\n\n {/* WHERE TO GO INSTEAD. The buttons below get you OUT; these get you\n somewhere useful. A screen that only says \"back\" makes the user\n re-navigate from scratch to do the thing they came to do. */}\n {suggestions.length > 0 ? (\n <div className=\"mt-5 grid gap-2 sm:grid-cols-2\">\n {suggestions.map((s) => {\n const Icon = s.icon;\n return (\n <Link\n key={s.href + s.title}\n href={s.href}\n data-tap-target\n className=\"group flex items-start gap-3 rounded-lg border border-border bg-card px-4 py-3 transition-colors hover:border-foreground/20 hover:bg-accent\"\n >\n {Icon ? (\n <span className=\"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground group-hover:text-foreground\">\n <Icon className=\"h-4 w-4\" />\n </span>\n ) : null}\n <span className=\"min-w-0\">\n <span className=\"block text-sm font-medium text-foreground\">\n {s.title}\n </span>\n {s.description ? (\n <span className=\"mt-0.5 block text-xs leading-snug text-muted-foreground\">\n {s.description}\n </span>\n ) : null}\n </span>\n </Link>\n );\n })}\n </div>\n ) : null}\n\n {footer ? <div className=\"mt-4\">{footer}</div> : null}\n\n {/* Always a real way forward. */}\n <div className=\"mt-5 flex flex-wrap items-center gap-2\">\n {context.status === \"anonymous\" ? (\n <Button asChild size=\"sm\">\n <Link href={signInHref} data-tap-target>\n <LogIn className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Sign in\n </Link>\n </Button>\n ) : null}\n\n {mayRestoreArchived(context) ? (\n <RestoreArchived\n token={context.entity.token}\n id={id}\n kind={context.entity.label.toLowerCase()}\n onRestored={() => {\n onChanged();\n if (onRetry) onRetry();\n else router.refresh();\n }}\n />\n ) : null}\n\n {(context.status === \"ok\" || context.status === \"error\") &&\n onRetry ? (\n <Button size=\"sm\" onClick={onRetry}>\n <RefreshCw className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Try again\n </Button>\n ) : null}\n\n {ancestor && ancestorHref ? (\n <Button asChild size=\"sm\" variant=\"outline\">\n <Link href={ancestorHref} data-tap-target>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Open {ancestor.title ?? ancestor.label.toLowerCase()}\n </Link>\n </Button>\n ) : fallbackHref ? (\n <Button asChild size=\"sm\" variant=\"outline\">\n <Link href={fallbackHref} data-tap-target>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n {fallbackLabel ?? \"Back to what you can see\"}\n </Link>\n </Button>\n ) : (\n <Button size=\"sm\" variant=\"outline\" onClick={() => router.back()}>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Go back\n </Button>\n )}\n </div>\n </div>\n </div>\n );\n}\n\n/**\n * The loader. Resolves why the record couldn't be opened, then renders it.\n *\n * A feature that genuinely earns a bespoke screen composes `AccessDeniedView`\n * (exported above) at its own call site — it does NOT register a variant here.\n * A token→component registry consulted during render is a dynamic component\n * boundary (react-hooks/static-components) for an extension point that has\n * exactly zero users, which is the speculative abstraction docs/reuse-first\n * bans. Passing your own component down is simpler and has no such hazard.\n */\nexport function AccessDenied({\n token,\n id,\n readError,\n fallbackHref,\n fallbackLabel,\n onRetry,\n suggestions,\n requestability,\n reason,\n headline,\n footer,\n}: AccessDeniedProps) {\n const { context, isLoading, refresh } = useAccessGate(token, id, {\n readError,\n });\n\n if (isLoading || !context) {\n // Deliberately quiet: this renders in a failure path that usually resolves\n // in well under a second, and a spinner-with-copy here would flash.\n return (\n <div className=\"flex h-full min-h-64 items-center justify-center p-6\">\n <div className=\"h-8 w-8 animate-pulse rounded-full bg-muted\" />\n </div>\n );\n }\n\n return (\n <AccessDeniedView\n context={context}\n id={id}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n onRetry={onRetry}\n onChanged={refresh}\n suggestions={suggestions}\n requestability={requestability}\n reason={reason}\n headline={headline}\n footer={footer}\n />\n );\n}\n","\"use client\";\n\n/**\n * RequestAccessPanel — the ask, and everything that happens after it.\n *\n * Three states in one place, because they are the same conversation:\n * ask → level choice + an optional note + Send\n * pending → who it went to, and a way to take it back\n * answered → what they said\n *\n * Deliberately NOT a dialog. The user is already stuck on a wall; making them\n * open a modal to knock on the door adds a step to the worst moment in the app.\n */\n\nimport { useState } from \"react\";\nimport { Check, Loader2, Send, Undo2 } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport { getAccessEnv } from \"@ai-matrx/data/access\";\nimport {\n createAccessRequest,\n withdrawAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type {\n AccessDeniedContext,\n RequestedLevel,\n} from \"@ai-matrx/data/access\";\n\ninterface RequestAccessPanelProps {\n context: AccessDeniedContext;\n /**\n * The record's id. It is NOT on the context — the RPC never echoes back an id\n * the caller already had, so the surface that knows it passes it through.\n */\n resourceId: string;\n /** Where the record lives, passed to the recipient's DM chip. */\n href?: string | null;\n onChanged: () => void;\n}\n\n/** \"AI Matrx Admin\", or an honest generic when the owner has no profile name. */\nfunction ownerName(context: AccessDeniedContext): string {\n return context.owner?.displayName ?? \"the owner\";\n}\n\nexport function RequestAccessPanel({\n context,\n resourceId,\n href,\n onChanged,\n}: RequestAccessPanelProps) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const currentUserId = ui.useCurrentUser().id;\n const [level, setLevel] = useState<RequestedLevel>(\"viewer\");\n const [note, setNote] = useState(\"\");\n const [busy, setBusy] = useState(false);\n /** Null until we've sent one; 0 means the row saved but nobody was reached. */\n const [delivered, setDelivered] = useState<number | null>(null);\n /** The user chose to ask again after a decline. */\n const [reasking, setReasking] = useState(false);\n\n const request = context.request;\n const kind = context.entity.label.toLowerCase();\n const cmsToken = getAccessEnv().entityTokens?.isCmsAccessGateToken(context.entity.token)\n ? context.entity.token\n : null;\n // A review cycle is decided by the organization's HR, never by whoever created it: the ask names that group.\n const hrToken = context.entity.token === \"hr_review_cycle\";\n const requestRecipientName = cmsToken\n ? (context.organization?.name ?? \"the organization’s admins\")\n : hrToken\n ? \"HR\"\n : ownerName(context);\n\n async function send() {\n setBusy(true);\n try {\n const result = cmsToken\n ? await ui.createCmsAccessRequest({\n token: cmsToken,\n resourceId,\n message: note,\n currentUserId,\n })\n : await createAccessRequest({\n resourceType: context.entity.token,\n resourceId,\n level,\n message: note,\n currentUserId,\n href: href ?? null,\n });\n if (result.blindAnswer) {\n toast.success(result.blindAnswer);\n } else if (result.already) {\n toast.success(\"You've already asked — they haven't answered yet.\");\n } else if (result.delivered === 0) {\n // The request row landed, but nobody was actually reached. Saying\n // \"sent\" here would be the same unverified claim this whole feature\n // exists to stop.\n toast.warning(\n \"Your request is saved, but we couldn't message them just now.\",\n );\n } else {\n toast.success(\n `Request sent to ${\n (hrToken ? null : result.recipients[0]?.displayName) ?? requestRecipientName\n }.`,\n );\n }\n setDelivered(result.already ? null : (result.delivered ?? null));\n onChanged();\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't send that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function withdraw() {\n if (!request) return;\n setBusy(true);\n try {\n await withdrawAccessRequest(request.id);\n toast.success(\"Request withdrawn.\");\n onChanged();\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't withdraw that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n if (request?.status === \"pending\") {\n return (\n <div className=\"rounded-lg border border-border bg-muted/40 p-4\">\n <p className=\"text-sm text-foreground\">\n <Check className=\"mr-1.5 inline h-4 w-4 text-primary\" aria-hidden />\n Waiting on {requestRecipientName}.\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {cmsToken\n ? \"Your request is saved. Once an owner adds you to the organization, this site will open.\"\n : delivered === 0\n ? \"We couldn't reach them with a message, but your request is saved and they'll see it.\"\n : \"They’ve been messaged. You’ll get a message back the moment they answer, and this page will open.\"}\n {ui.renderErrorMenu({})}\n </p>\n <Button\n className=\"mt-3 h-8\"\n size=\"sm\"\n variant=\"outline\"\n disabled={busy}\n onClick={() => void withdraw()}\n >\n {busy ? (\n <Loader2 className=\"mr-1.5 h-3.5 w-3.5 animate-spin\" aria-hidden />\n ) : (\n <Undo2 className=\"mr-1.5 h-3.5 w-3.5\" aria-hidden />\n )}\n Withdraw request\n </Button>\n </div>\n );\n }\n\n // A declined ask used to end in \"reach out to them directly\" with no way to\n // do it — a dead end inside the No Dead Ends primitive. The database happily\n // accepts a fresh request (declined is neither pending nor reported), so the\n // door is real; it just wasn't rendered.\n if (request?.status === \"declined\" && !reasking) {\n return (\n <div className=\"rounded-lg border border-border bg-muted/40 p-4\">\n <p className=\"text-sm text-foreground\">\n {requestRecipientName} declined this request.\n </p>\n {request.decisionNote ? (\n <p className=\"mt-1 text-xs text-muted-foreground\">\n &ldquo;{request.decisionNote}&rdquo;\n </p>\n ) : null}\n <Button\n className=\"mt-3 h-8\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setReasking(true)}\n >\n <Send className=\"mr-1.5 h-3.5 w-3.5\" aria-hidden />\n Ask again\n </Button>\n </div>\n );\n }\n\n if (request?.status === \"reported\" || !context.canRequest) {\n return null;\n }\n\n return (\n <div className=\"rounded-lg border border-border bg-card p-4\">\n <p className=\"text-sm font-medium text-foreground\">\n Ask {requestRecipientName} for access\n </p>\n\n {!cmsToken ? (\n <div className=\"mt-3 flex flex-wrap gap-2\">\n <LevelChoice\n active={level === \"viewer\"}\n label=\"Just to view\"\n onClick={() => setLevel(\"viewer\")}\n />\n <LevelChoice\n active={level === \"editor\"}\n label=\"To view and make changes\"\n onClick={() => setLevel(\"editor\")}\n />\n </div>\n ) : null}\n\n <ProTextarea\n className=\"mt-3 min-h-16 text-base md:text-sm\"\n placeholder={`Why you need this ${kind} (optional)`}\n value={note}\n maxLength={500}\n onChange={(event) => setNote(event.target.value)}\n />\n\n <Button\n className=\"mt-3\"\n size=\"sm\"\n disabled={busy}\n onClick={() => void send()}\n >\n {busy ? (\n <Loader2 className=\"mr-1.5 h-4 w-4 animate-spin\" aria-hidden />\n ) : (\n <Send className=\"mr-1.5 h-4 w-4\" aria-hidden />\n )}\n Request access\n </Button>\n </div>\n );\n}\n\nfunction LevelChoice({\n active,\n label,\n onClick,\n}: {\n active: boolean;\n label: string;\n onClick: () => void;\n}) {\n return (\n <button\n type=\"button\"\n aria-pressed={active}\n onClick={onClick}\n className={[\n \"whitespace-nowrap rounded-full border px-3 py-1 text-xs font-medium transition-colors\",\n active\n ? \"border-primary bg-primary/10 text-primary-ink\"\n : \"border-border bg-background text-muted-foreground hover:bg-accent\",\n ].join(\" \")}\n >\n {label}\n </button>\n );\n}\n","\"use client\";\n\n/**\n * BlindAccessAsk — the one \"Ask for access\" on the not-found page (lane V24-TAILS, chair ruling\n * 2026-09-25).\n *\n * A stranger who opens an unshared object and a person who opens a random id see the SAME page:\n * \"We couldn't find this <kind>. If someone shared a link with you, you can ask for access.\" and\n * this one control. Pressing it calls `public.access_request_blind`, which files the ordinary\n * request (the owner's /user-settings/access-requests inbox and an in-app notice) for a real object and\n * nothing for a missing one. The asker is told the same sentence either way and never who owns it.\n */\n\nimport { useState } from \"react\";\nimport { KeyRound } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { askForAccessBlind, BLIND_ASK_ANSWER } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\n\nexport function BlindAccessAsk({\n token,\n id,\n href,\n}: {\n token: string;\n id: string;\n href?: string | null;\n}) {\n const ui = useAccessUi();\n const [state, setState] = useState<\n { kind: \"idle\" } | { kind: \"asking\" } | { kind: \"asked\"; says: string } | { kind: \"failed\"; why: string }\n >({ kind: \"idle\" });\n\n if (state.kind === \"asked\") {\n return (\n <p className=\"text-sm text-foreground\" role=\"status\" data-blind-ask=\"asked\">\n {state.says || BLIND_ASK_ANSWER}\n </p>\n );\n }\n\n return (\n <div className=\"flex flex-col items-start gap-2\" data-blind-ask={state.kind}>\n <Button\n size=\"sm\"\n disabled={state.kind === \"asking\"}\n aria-busy={state.kind === \"asking\"}\n onClick={() => {\n setState({ kind: \"asking\" });\n void askForAccessBlind({\n resourceType: token,\n resourceId: id,\n href: href ?? (typeof window !== \"undefined\" ? window.location.pathname : null),\n }).then(\n (says) => setState({ kind: \"asked\", says }),\n (e: unknown) =>\n setState({\n kind: \"failed\",\n why: e instanceof Error ? e.message : \"We could not send that just now.\",\n }),\n );\n }}\n data-tap-target\n >\n <KeyRound className=\"mr-1.5 h-4 w-4\" aria-hidden />\n {state.kind === \"asking\" ? \"Asking…\" : \"Ask for access\"}\n </Button>\n {state.kind === \"failed\" ? (\n <p className=\"text-xs text-destructive\" role=\"alert\">\n {state.why} Try again.\n {ui.renderErrorMenu({ className: \"ml-auto\" })}\n </p>\n ) : null}\n </div>\n );\n}\n","\"use client\";\n\n/**\n * useAccessGate — one hook, one honest answer.\n *\n * A surface whose read came back empty calls this with the entity it was trying\n * to open, and gets back the ONE status it should branch on: `denied`,\n * `deleted`, `missing`, `anonymous`, `ok` (the read failed for some other\n * reason), or `error`. No surface has to know about RLS, PostgREST codes, or\n * the four different meanings of a null row.\n *\n * `ok` is the one people forget: it means the caller CAN open the record, so\n * whatever failed was transient. Rendering a denial there would be a fresh lie.\n */\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport { fetchAccessDeniedContext } from \"@ai-matrx/data/access\";\nimport { classifyDataError } from \"@ai-matrx/data/access\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\nimport type { RecordUnavailableResolution } from \"@ai-matrx/data/db\";\nimport { useAccessUi } from \"./env\";\n\nexport interface UseAccessGateResult {\n context: AccessDeniedContext | null;\n status: AccessDeniedContext[\"status\"] | \"loading\";\n isLoading: boolean;\n /** Re-resolve — used after a request is sent, granted, or withdrawn. */\n refresh: () => void;\n}\n\nexport function useAccessGate(\n token: string | null | undefined,\n id: string | null | undefined,\n options: { enabled?: boolean; readError?: unknown } = {},\n): UseAccessGateResult {\n const resolveRecordUnavailableCapture = useAccessUi().resolveRecordUnavailableCapture;\n const [nonce, setNonce] = useState(0);\n\n // ONE key identifies \"which question is currently being asked\". Both the\n // freshness check and the loading state derive from it, so the effect never\n // has to call setState synchronously to reset itself when the target changes\n // (that pattern cascades renders — react-hooks/set-state-in-effect).\n const enabled = options.enabled !== false && Boolean(token && id);\n const key = enabled ? `${token}:${id}:${nonce}` : null;\n\n const [resolved, setResolved] = useState<{\n key: string;\n context: AccessDeniedContext;\n } | null>(null);\n\n useEffect(() => {\n if (!key || !token || !id) return;\n\n // An answer must never be applied to a different record — the user can\n // navigate between two denied ids faster than the RPC returns.\n let active = true;\n // WHAT THE SURFACE'S OWN READ DID is half the answer, and only the surface\n // knows it. A genuine fault leaves room for \"you can open this, that was\n // transient\"; a read that returned nothing is itself an access answer and\n // must not be overruled by a level claim (V-XT-2/N2 — see `deriveStatus`).\n const read =\n classifyDataError(options.readError) === \"fault\"\n ? \"fault\"\n : \"access-question\";\n void fetchAccessDeniedContext(token, id, read).then((next) => {\n if (!active) return;\n\n // `recordUnavailable()` had to capture immediately while the read was\n // still ambiguous. Now the platform resolver knows the truth, reconcile\n // that SAME inspector row before rendering the handled state. A resolver\n // `error` deliberately does nothing: unknown access gaps stay loud.\n const resolution: RecordUnavailableResolution | null =\n next.status === \"anonymous\"\n ? \"signed-out\"\n : next.status === \"denied\" ||\n next.status === \"deleted\" ||\n next.status === \"missing\" ||\n next.status === \"ok\"\n ? next.status\n : null;\n if (resolution) {\n resolveRecordUnavailableCapture(options.readError, resolution);\n }\n setResolved({ key, context: next });\n });\n return () => {\n active = false;\n };\n }, [key, token, id, options.readError, resolveRecordUnavailableCapture]);\n\n // Stale answers are discarded by comparing keys, not by clearing state.\n const context = resolved && resolved.key === key ? resolved.context : null;\n const isLoading = key !== null && context === null;\n\n const refresh = useCallback(() => setNonce((n) => n + 1), []);\n\n return {\n context,\n status: isLoading ? \"loading\" : (context?.status ?? \"error\"),\n isLoading,\n refresh,\n };\n}\n","\"use client\";\n\n/**\n * AccessGate — the drop-in that replaces a hand-rolled \"couldn't load it\" branch.\n *\n * if (site.isError || !site.data) {\n * return <AccessGate token=\"web_site\" id={siteId} error={site.error}\n * onRetry={site.refetch} fallbackHref=\"/marketing/sites\" />;\n * }\n *\n * It decides between a REAL error (a timeout, a broken query — show the error,\n * offer retry) and an ACCESS state (denied, deleted, missing, signed out — show\n * the explanation and the way forward). Surfaces stop having to know the\n * difference, which is the whole reason they kept getting it wrong.\n *\n * 🚨 AND WHEN THE SERVER REFUSED IN WORDS, THOSE WORDS WIN. A door that\n * answered `{code, user_message}` has already said the true thing; the gate\n * prints it verbatim, discloses the code, and offers no retry — it never\n * replaces it with a sentence composed here about what it believes the\n * viewer's access to be. That substitution is V-XT-2/N2: a conversation the\n * server refused with `404 conversation_not_found` was rendered as \"You do\n * have access to it — something went wrong on our side. Try again.\"\n * (`service/serverRefusal.ts`).\n */\n\nimport {\n AccessDenied,\n type AccessDeniedSuggestion,\n} from \"./AccessDenied\";\nimport { classifyDataError } from \"@ai-matrx/data/access\";\nimport { readServerRefusal } from \"@ai-matrx/data/access\";\nimport { useAccessGate } from \"./useAccessGate\";\nimport type { AccessRequestability } from \"@ai-matrx/data/access\";\n\nexport interface AccessGateProps {\n /** Canonical entity token of the record the surface tried to open. */\n token: string;\n id: string;\n /**\n * The error the read produced, if any. A null-row read (no error at all) is\n * the common case and is exactly what this gate is for.\n */\n error?: unknown | undefined;\n onRetry?: (() => void) | undefined;\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n /**\n * Parallel failed reads hidden by this gate's early return. Each is resolved\n * independently for truthful diagnostics; none renders a second surface.\n */\n relatedReads?: ReadonlyArray<{\n token: string;\n id: string;\n error: unknown;\n }>;\n /**\n * Render this instead when the failure was a genuine fault rather than an\n * access state. Defaults to the access surface, which handles faults with an\n * honest \"something went wrong on our side\" + retry.\n */\n renderFault?: (error: unknown) => React.ReactNode;\n /**\n * Two or three concrete things to do instead, in THIS feature — \"your\n * websites\", \"create one\". Without them the gate is honest and still a dead\n * end: it says what went wrong and leaves the user to re-navigate.\n */\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /**\n * `\"absolute\"` removes the request affordance entirely — for a door closed by\n * law, where the ask itself would leak. Defaults to `\"requestable\"`.\n */\n requestability?: AccessRequestability | undefined;\n /** The surface's own worded reason, in place of the generic explanation. */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /** The surface's own trailing disclosure (a reference code, an audit id). */\n footer?: React.ReactNode | undefined;\n}\n\nexport function AccessGate({\n token,\n id,\n error,\n onRetry,\n fallbackHref,\n fallbackLabel,\n relatedReads = [],\n renderFault,\n suggestions,\n requestability,\n reason,\n headline,\n footer,\n}: AccessGateProps) {\n // A hard fault (network, timeout, malformed query) is not an access story.\n // Surfaces with a good error component keep using it; everyone else gets the\n // access surface, whose `ok`/`error` states already say the honest thing.\n if (error && classifyDataError(error) === \"fault\" && renderFault) {\n return <>{renderFault(error)}</>;\n }\n\n // The server's own refusal, when there was one. It outranks BOTH the generic\n // copy and a `reason` the surface composed: the door already said the true\n // thing, in words the person can report.\n const refusal = readServerRefusal(error);\n\n return (\n <>\n {relatedReads.map((read) => (\n <AccessGateCaptureResolver\n key={`${read.token}:${read.id}`}\n token={read.token}\n id={read.id}\n error={read.error}\n />\n ))}\n <AccessDenied\n token={token}\n id={id}\n readError={error}\n // A refused door is not a retry: offering one is the \"Try again\" that\n // can never succeed.\n onRetry={refusal ? undefined : onRetry}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n suggestions={suggestions}\n requestability={requestability}\n reason={refusal?.message ?? reason}\n headline={headline}\n footer={\n refusal?.code ? (\n <>\n {footer}\n <ServerRefusalCode code={refusal.code} issues={refusal.issues} />\n </>\n ) : (\n footer\n )\n }\n />\n </>\n );\n}\n\n/** Resolves diagnostics for a parallel read without rendering another gate. */\nfunction AccessGateCaptureResolver({\n token,\n id,\n error,\n}: {\n token: string;\n id: string;\n error: unknown;\n}) {\n // This hook owns both the authoritative resolver call and capture\n // reconciliation. Its visual context is deliberately consumed by the one\n // primary AccessDenied above, never by a second competing surface.\n useAccessGate(token, id, { readError: error });\n return null;\n}\n\n/**\n * The refusal's machine code, disclosed where machine tokens belong: a closed\n * `<details>` under the body, never in the sentence a person reads. It is the\n * thing that makes a refusal reportable — \"it said conversation_not_found\" is\n * actionable, \"it wouldn't open\" is not.\n */\nfunction ServerRefusalCode({\n code,\n issues,\n}: {\n code: string;\n issues: string[];\n}) {\n return (\n <details className=\"text-[11px] text-muted-foreground\">\n <summary className=\"cursor-pointer select-none\">\n What the server said\n </summary>\n <p className=\"mt-1 font-mono\">{code}</p>\n {issues.length > 0 ? (\n <ul className=\"mt-1 list-disc pl-4\">\n {issues.map((issue) => (\n <li key={issue}>{issue}</li>\n ))}\n </ul>\n ) : null}\n </details>\n );\n}\n","\"use client\";\n\n/**\n * SlugAccessGate — the canonical access gate for a SLUG-addressed page.\n *\n * `<AccessGate>` is keyed on the record's uuid, but pages like `/shapes/[kind]`,\n * `/education/learn/[...slug]`, `/podcast/[slug]` and `/applets/[slug]` address their\n * item by slug. When their read comes back empty they cannot know the uuid —\n * RLS hid the very row that would say it. `access_gate_resolve_slug` (signed-in\n * only, existence-level disclosure; see migrations/access_gate_slug_resolver.sql)\n * asks the platform, and a resolved slug gets the full gate.\n *\n * `tokens` is tried in order and the first that resolves wins — `/podcast/[slug]`\n * is an episode OR a show, resolved the same way the page does (episode first).\n *\n * PUBLIC, PUBLISH-FILTERED PAGES (`publishFiltered`). Those pages 404 a row the\n * viewer CAN read but that is not published — the owner opening their own draft,\n * or anyone on a public-visibility episode not yet released. Showing that person\n * a denial would be a lie, so the gate asks the platform whether the viewer can\n * read the row at all; if they can, the honest answer is \"not published\", said\n * plainly.\n *\n * A slug nothing resolves (or a signed-out visitor, to whom the resolver says\n * nothing) gets exactly the truth we hold — \"this address doesn't match a\n * <thing> you can open\" — never upgraded to \"doesn't exist\" or \"no permission\".\n * Same contract as OrganizationAccessGate, generalised.\n */\n\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport { useEffect, useState } from \"react\";\nimport { ArrowLeft, Link2Off } from \"lucide-react\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { AccessGate } from \"./AccessGate\";\nimport {\n fetchAccessDeniedContext,\n resolveAccessGateSlug,\n} from \"@ai-matrx/data/access\";\n\nexport interface SlugAccessGateProps {\n /** Entity tokens to try, in the page's own resolution order. */\n tokens: readonly string[];\n /** The raw route slug (already decoded by the App Router). */\n slug: string;\n /** What the thing is called in the \"didn't match\" sentence, e.g. \"shape\". */\n noun: string;\n fallbackHref: string;\n fallbackLabel: string;\n /**\n * The page also filters by publication state (not just RLS), so a miss can\n * be a row the viewer may read that simply is not published.\n */\n publishFiltered?: boolean;\n}\n\nexport function SlugAccessGate({\n tokens,\n slug,\n noun,\n fallbackHref,\n fallbackLabel,\n publishFiltered = false,\n}: SlugAccessGateProps) {\n const tokenKey = tokens.join(\"|\");\n const [resolved, setResolved] = useState<{\n key: string;\n token: string | null;\n id: string | null;\n /** The viewer can read the row: the page's miss was publication. */\n readable: boolean;\n } | null>(null);\n const key = `${tokenKey}::${slug}`;\n\n useEffect(() => {\n let active = true;\n const list = tokenKey ? tokenKey.split(\"|\") : [];\n void (async () => {\n for (const token of list) {\n const id = slug ? await resolveAccessGateSlug(token, slug) : null;\n if (!active) return;\n if (id) {\n // `fault` lets the resolver report the viewer's real level: `ok`\n // means they can read the row, so only publication hid it.\n const readable = publishFiltered\n ? (await fetchAccessDeniedContext(token, id, \"fault\")).status ===\n \"ok\"\n : false;\n if (active) setResolved({ key, token, id, readable });\n return;\n }\n }\n // An id-shaped address names the record directly: the full gate (with\n // its request-access door) answers it, never \"doesn't match\".\n if (active && list.length && isUuidShape(slug)) {\n setResolved({ key, token: list[0] ?? null, id: slug, readable: false });\n return;\n }\n if (active) setResolved({ key, token: null, id: null, readable: false });\n })();\n return () => {\n active = false;\n };\n }, [key, tokenKey, slug, publishFiltered]);\n\n // Still asking — render nothing rather than flash a \"didn't match\" claim\n // that may be about to become the full gate. Keyed so a navigation never\n // applies a stale answer to the wrong slug.\n if (!resolved || resolved.key !== key) return null;\n\n if (resolved.token && resolved.id && resolved.readable) {\n return (\n <Notice\n title={`This ${noun} isn't published`}\n body={`It exists and you can open it, but it has no public page until it's published.`}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n }\n\n if (resolved.token && resolved.id) {\n return (\n <AccessGate\n token={resolved.token}\n id={resolved.id}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n }\n\n return (\n <Notice\n title={`This address doesn't match ${/^[aeiou]/i.test(noun) ? \"an\" : \"a\"} ${noun} you can open`}\n body=\"Check the link, or sign in with the account it was shared with.\"\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n}\n\nfunction Notice({\n title,\n body,\n fallbackHref,\n fallbackLabel,\n}: {\n title: string;\n body: string;\n fallbackHref: string;\n fallbackLabel: string;\n}) {\n return (\n <div className=\"flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-lg\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-muted\">\n <Link2Off className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n </div>\n <div className=\"min-w-0 flex-1\">\n <h1 className=\"text-lg font-semibold text-foreground\">{title}</h1>\n <p className=\"mt-2 text-sm text-muted-foreground\">{body}</p>\n </div>\n </div>\n <div className=\"mt-5\">\n <Button asChild variant=\"outline\">\n <Link href={fallbackHref}>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n {fallbackLabel}\n </Link>\n </Button>\n </div>\n </div>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * SettingAccessGate — the settings variant of the existing access gate.\n * Admins see the control. Other org members see a gentle, pre-filled request\n * that lands in the same durable ledger and actionable DM system.\n */\n\nimport { useState } from \"react\";\nimport { Check, Loader2, Lock, Send } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { useAccessUi } from \"./env\";\nimport { createSettingAccessRequest } from \"@ai-matrx/data/access\";\nimport type { JsonObject } from \"@ai-matrx/kit/json-format\";\n\nexport function SettingAccessGate({\n canManage,\n organizationId,\n organizationSlugOrId,\n settingKey,\n settingLabel,\n actionKey,\n actionPayload,\n defaultMessage,\n requestReady = true,\n children,\n}: {\n canManage: boolean;\n organizationId: string;\n organizationSlugOrId: string;\n settingKey: string;\n settingLabel: string;\n actionKey: string;\n actionPayload: JsonObject;\n defaultMessage: string;\n requestReady?: boolean;\n children: React.ReactNode;\n}) {\n const ui = useAccessUi();\n const currentUserId = ui.useCurrentUser().id;\n const ProTextarea = ui.Textarea;\n const toast = ui.toast;\n const [customMessage, setCustomMessage] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [pending, setPending] = useState(false);\n const message = customMessage ?? defaultMessage;\n\n if (canManage) return <>{children}</>;\n\n async function send() {\n setBusy(true);\n try {\n const result = await createSettingAccessRequest({\n organizationId,\n settingKey,\n settingLabel,\n href: ui.settingDoorHref({\n scope: \"organization\",\n organizationSlugOrId,\n controlId: settingKey,\n }),\n actionKey,\n actionPayload,\n message,\n currentUserId,\n });\n setPending(true);\n if (result.already) {\n toast.success(\"Your request is already waiting for an admin.\");\n } else if (result.delivered === 0) {\n toast.warning(\n \"Your request is saved, but we couldn't message an admin just now.\",\n );\n } else {\n toast.success(\"Request sent to your organization admins.\");\n }\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't send that request.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <div className=\"rounded-lg border border-border bg-muted/30 p-4\">\n <div className=\"flex items-start gap-3\">\n <span className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-background\">\n {pending ? (\n <Check className=\"h-4 w-4 text-primary\" aria-hidden />\n ) : (\n <Lock className=\"h-4 w-4 text-muted-foreground\" aria-hidden />\n )}\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium text-foreground\">\n {pending\n ? \"Your request is waiting\"\n : \"An organization admin controls this setting\"}\n </p>\n <p className=\"mt-1 text-xs leading-5 text-muted-foreground\">\n {pending\n ? \"It is saved in Access requests, even if the direct message could not be delivered.\"\n : \"Tell them what you need. The request is filled with this setting and includes an action they can complete inside the message.\"}\n </p>\n </div>\n </div>\n\n {!pending ? (\n <div className=\"mt-3 space-y-2\">\n <ProTextarea\n value={message}\n onChange={(event) => setCustomMessage(event.target.value)}\n rows={3}\n maxLength={1000}\n aria-label=\"Message to organization admins\"\n />\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Send aria-hidden />\n )}\n variant=\"primary\"\n disabled={busy || !message.trim() || !requestReady}\n onClick={() => void send()}\n >\n Request this change\n </Button>\n </div>\n ) : null}\n </div>\n );\n}\n","/**\n * ForbiddenSurface — the SERVER-side face of the access gate.\n *\n * Rendered by every `forbidden.tsx` boundary, i.e. whenever a Server Component\n * calls Next's `forbidden()` (see `requireAccess(..., { forbid: true })`). It\n * says the one thing we can actually prove — you're signed in and this page\n * isn't yours to open, or you're signed out — and hands over real doors. It\n * never claims a deletion, an absence, or a wrong link.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY THIS DOESN'T NAME THE RECORD, AND WHY YOU SHOULDN'T TRY (2026-08-11)\n *\n * The obvious idea is to have `requireAccess` stash `{token, id}` somewhere\n * request-scoped right before it throws, and let this component read it back\n * and render the full `<AccessGate>` — kind, name, owner, \"Request access\".\n * It was built that way (a `React.cache()` holder) and it DOES NOT WORK, for a\n * structural reason rather than a fixable bug:\n *\n * Next renders the `forbidden.tsx` fallback EAGERLY, as part of building the\n * loader tree — BEFORE the page component runs and throws. Instrumented in\n * the browser, the order is literally GET → GET → SET. Whatever the page\n * sets, the fallback has already rendered without it.\n *\n * So no request-scoped channel of any kind (cache, ALS, module global) can\n * carry the target here; the write always loses the race, and a module global\n * would additionally risk naming one user's record to another. Do not\n * reintroduce it.\n *\n * THE PATTERN THAT WORKS: a route that wants the record-specific gate must not\n * call `forbidden()` at all — it renders `<AccessGate token id/>` itself and\n * returns it. `AccessGate` is a client component, so a Server Component can\n * return it directly; `app/(core)/pick-lists/[id]/page.tsx` is the live example.\n * ─────────────────────────────────────────────────────────────────────────────\n */\nimport { AccessLink as Link } from \"./env\";\nimport { ArrowLeft, Lock, LogIn, RotateCw } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\n\n/**\n * WHAT THE APP'S SERVER BOUNDARY READS AND HANDS DOWN. The package cannot call\n * `headers()` or the session verdict (no `next/*`, no app imports, and an async\n * Server Component cannot live in a client entry). The app's `forbidden.tsx`\n * keeps a ~10-line server wrapper: read the verdict + the stamped request path,\n * build `signInHref`, and render `<ForbiddenSurfaceView …/>`.\n */\nexport interface ForbiddenSurfaceViewProps {\n /** `unverified` = the session could not be confirmed (neither \"no access\" nor \"sign in\"). */\n state: \"authenticated\" | \"anonymous\" | \"unverified\";\n isAuthenticated: boolean;\n /** The path the person was trying to open (the app stamps it on the request). */\n pathname: string;\n search?: string;\n /** Sign-in URL that returns to `pathname`+`search`. */\n signInHref: string;\n /** Where \"Back to what you can see\" goes. Default `/dashboard`. */\n homeHref?: string;\n}\n\nexport function ForbiddenSurfaceView({\n state,\n isAuthenticated,\n pathname,\n search = \"\",\n signInHref,\n homeHref = \"/dashboard\",\n}: ForbiddenSurfaceViewProps) {\n // A boundary answers IN PLACE (a redirect would lose the page), so it reads\n // the three-state verdict. \"Could not verify\" is neither \"no access\" nor\n // \"sign in\": it gets its own sentence and a way back to the same page.\n const unverified = state === \"unverified\";\n\n return (\n <div className=\"flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-lg\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-muted\">\n <Lock className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n </div>\n <div className=\"min-w-0 flex-1\">\n <h1 className=\"text-lg font-semibold text-foreground\">\n {unverified\n ? \"We could not confirm who you are just now\"\n : isAuthenticated\n ? \"You don't have access to this page\"\n : \"Sign in to open this page\"}\n </h1>\n <p className=\"mt-2 text-sm text-muted-foreground\">\n {unverified\n ? \"You have not been signed out. This usually clears in a few seconds — open the page again.\"\n : isAuthenticated\n ? \"Your account can't open it. If someone shared it with you, ask them to share it with this account.\"\n : \"We can't tell you anything about it until we know who you are.\"}\n </p>\n </div>\n </div>\n\n <div className=\"mt-5 flex flex-wrap items-center gap-2\">\n {unverified ? (\n <Button variant=\"primary\" asChild>\n <Link href={`${pathname}${search}`}>\n <RotateCw className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Open it again\n </Link>\n </Button>\n ) : isAuthenticated ? null : (\n <Button variant=\"primary\" asChild>\n <Link href={signInHref}>\n <LogIn className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Sign in\n </Link>\n </Button>\n )}\n <Button asChild variant=\"outline\">\n <Link href={homeHref}>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Back to what you can see\n </Link>\n </Button>\n </div>\n </div>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * RequestAccess — the platform's answer to a control the viewer cannot use.\n *\n * Owner ruling (Arman, 2026-09-25): the control is ABSENT; where the person\n * would plausibly want it, render this instead. One line + \"Ask for access\"\n * (or a key icon where space is tight) → a compact dialog with a note box and\n * the context we already know → organization admins (access-request ledger +\n * DM) or the platform team (user feedback). See `features/access-gate/FEATURE.md`.\n */\n\nimport { useState } from \"react\";\nimport { Check, KeyRound, Loader2, Send } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { useRequestAccess } from \"./useRequestAccess\";\nimport {\n contextLines,\n type RequestAccessTarget,\n} from \"@ai-matrx/data/access\";\n\nexport type { RequestAccessTarget } from \"@ai-matrx/data/access\";\n\nexport function RequestAccess({\n target,\n variant = \"inline\",\n reason,\n className,\n}: {\n target: RequestAccessTarget;\n /** `inline` = one line + button; `icon` = key icon only (tight headers). */\n variant?: \"inline\" | \"icon\";\n /** Inline only: the one-line why. Defaults from the owner. */\n reason?: string;\n className?: string;\n}) {\n const [open, setOpen] = useState(false);\n const request = useRequestAccess(target);\n const label = `Ask for access to ${target.action.toLowerCase()}`;\n const why =\n reason ??\n (request.owner.kind === \"system\"\n ? \"Only the platform team can change this.\"\n : `Only ${request.destination} can change this.`);\n\n return (\n <>\n {variant === \"icon\" ? (\n <button\n type=\"button\"\n aria-label={label}\n title={label}\n onClick={() => setOpen(true)}\n className={cn(\n \"inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n className,\n )}\n >\n {request.sent ? (\n <Check className=\"size-3.5 text-primary\" aria-hidden=\"true\" />\n ) : (\n <KeyRound className=\"size-3.5\" aria-hidden=\"true\" />\n )}\n </button>\n ) : (\n <div\n className={cn(\n \"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground\",\n className,\n )}\n >\n <span>{request.sent ? \"Request sent.\" : why}</span>\n {request.sent ? null : (\n <Button\n icon={<KeyRound aria-hidden=\"true\" />}\n variant=\"outline\"\n onClick={() => setOpen(true)}\n >\n Ask for access\n </Button>\n )}\n </div>\n )}\n {open ? (\n <RequestAccessDialog\n target={target}\n request={request}\n onOpenChange={setOpen}\n />\n ) : null}\n </>\n );\n}\n\nfunction RequestAccessDialog({\n target,\n request,\n onOpenChange,\n}: {\n target: RequestAccessTarget;\n request: ReturnType<typeof useRequestAccess>;\n onOpenChange: (open: boolean) => void;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const [note, setNote] = useState(\"\");\n const lines = contextLines(target, request.context());\n\n async function send() {\n try {\n const result = await request.send(note);\n if (result.undelivered) toast.warning(result.message);\n else toast.success(result.message);\n onOpenChange(false);\n } catch (error: unknown) {\n // Declining the organization picker is an answer, not a failure.\n if (ui.presentOrganizationRefusal(error, { act: \"sent\", subject: \"Your request\" })) return;\n toast.error(\n error instanceof Error ? error.message : \"We couldn't send that request.\",\n );\n }\n }\n\n return (\n <Dialog open onOpenChange={onOpenChange}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>Ask for access</DialogTitle>\n <DialogDescription>Goes to {request.destination}.</DialogDescription>\n </DialogHeader>\n <dl className=\"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs\">\n {lines.map(([label, value]) => (\n <div key={label} className=\"contents\">\n <dt className=\"text-muted-foreground\">{label}</dt>\n <dd className=\"min-w-0 text-foreground [overflow-wrap:anywhere]\">\n {value}\n </dd>\n </div>\n ))}\n </dl>\n <ProTextarea\n className=\"min-h-20 text-base md:text-sm\"\n value={note}\n maxLength={1000}\n autoFocus\n placeholder=\"What do you need, and why? (optional)\"\n aria-label=\"Note\"\n onChange={(event) => setNote(event.target.value)}\n />\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n Cancel\n </Button>\n <Button icon={request.sending ? (\n <Loader2 className=\"animate-spin\" aria-hidden=\"true\" />\n ) : (\n <Send aria-hidden=\"true\" />\n )} variant=\"primary\" disabled={request.sending} onClick={() => void send()}>\n Send request\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n","\"use client\";\n\n/**\n * useRequestAccess — send a `RequestAccessTarget` ask through the system that\n * owns it (see `service/requestAccess.ts`). Organization → the access-request\n * ledger + DM to its admins; system → a user-feedback item. Nothing new stored.\n */\n\nimport { useState } from \"react\";\nimport { requireAccessEnvField } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\nimport { createSettingAccessRequest } from \"@ai-matrx/data/access\";\nimport {\n destinationLabel,\n feedbackMetadata,\n orgActionPayload,\n orgManageHref,\n orgSettingKey,\n requestBody,\n requestTitle,\n resolveRequestOwner,\n type RequestAccessTarget,\n type RequestContext,\n} from \"@ai-matrx/data/access\";\n\nexport interface RequestAccessResult {\n /** A pending ask already existed — nothing new was sent. */\n already: boolean;\n /** Sentence for the confirmation toast. */\n message: string;\n /** Warning, not success: the ask is saved but no admin was messaged. */\n undelivered: boolean;\n}\n\nexport function useRequestAccess(target: RequestAccessTarget) {\n const ui = useAccessUi();\n const { id: userId, displayName, email } = ui.useCurrentUser();\n const owner = resolveRequestOwner(target.owner);\n const [sending, setSending] = useState(false);\n const [sent, setSent] = useState(false);\n\n const context = (): RequestContext => ({\n pageUrl: typeof window === \"undefined\" ? \"\" : window.location.href,\n requesterName: displayName,\n requesterEmail: email,\n });\n\n async function send(note: string): Promise<RequestAccessResult> {\n setSending(true);\n try {\n const ctx = context();\n if (owner.kind === \"system\") {\n // The request is filed under an organization; with none selected yet, ASK and continue\n // (ensureOrganizationContext waits for boot and opens the picker) — never a refusal\n // spelled from a nullable id while boot is still resolving (check:org-three-states).\n const organizationId = await requireAccessEnvField(\"ensureOrgId\", \"useRequestAccess\")(null);\n const result = await ui.reportFeedback({\n // The feedback vocabulary's access-request type; `metadata` carries\n // the structured target (FEATURE.md, RequestAccess).\n feedback_type: \"request\",\n route: typeof window === \"undefined\" ? \"\" : window.location.pathname,\n organization_id: organizationId,\n description: `Access request: ${requestTitle(target)}\\n\\n${requestBody(target, ctx, note)}`,\n metadata: feedbackMetadata(target, ctx),\n });\n if (!result.success) {\n throw new Error(result.error ?? \"We couldn't send that request.\");\n }\n setSent(true);\n return {\n already: false,\n undelivered: false,\n message: `Request sent to ${destinationLabel(owner)}.`,\n };\n }\n\n const result = await createSettingAccessRequest({\n organizationId: owner.organizationId,\n settingKey: orgSettingKey(target),\n settingLabel: requestTitle(target),\n href: orgManageHref(target, owner),\n actionKey: ui.manualRequestActionKey,\n actionPayload: orgActionPayload(target, owner),\n message: requestBody(target, ctx, note),\n currentUserId: userId,\n });\n setSent(true);\n if (result.already) {\n return {\n already: true,\n undelivered: false,\n message: \"Your request is already waiting for an answer.\",\n };\n }\n if (result.delivered === 0) {\n return {\n already: false,\n undelivered: true,\n message:\n \"Your request is saved in Access requests, but we couldn't message an admin just now.\",\n };\n }\n return {\n already: false,\n undelivered: false,\n message: `Request sent to ${destinationLabel(owner)}.`,\n };\n } finally {\n setSending(false);\n }\n }\n\n return {\n owner,\n destination: destinationLabel(owner),\n context,\n send,\n sending,\n sent,\n };\n}\n","\"use client\";\n\n/**\n * UnresolvedEntityRef — the inline sibling of `EntityRef`.\n *\n * `EntityRef` is THE DOOR LAW for a record you CAN read: name → route, new tab,\n * peek. This is the same law for the record you cannot. A list that joins to\n * another table always has rows whose embed came back null, and every one of\n * them is ambiguous for the four reasons `features/access-gate` exists to\n * disambiguate. Printing \"(record unavailable)\" is the surface asserting a\n * cause it never checked, offering no door and no repair.\n *\n * This renders the RESOLVED state in the cell — \"No access · Steven Wax\" — and\n * puts the whole explanation plus the one-click fix one click away: the owner,\n * the organization, and the canonical `RequestAccessPanel` for a denial, the\n * destination-preserving sign-in link when the session lapsed, a real Try again\n * when the caller actually HAS access and the read merely failed.\n *\n * The caller resolves the state with `useAccessStates` (one hook for the whole\n * page) and passes it down, so the row's action menu can branch on exactly the\n * same answer instead of resolving it a second time.\n */\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Ban,\n HelpCircle,\n Loader2,\n LogIn,\n RefreshCw,\n Trash2,\n TriangleAlert,\n} from \"lucide-react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@ai-matrx/design-system\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { RequestAccessPanel } from \"./RequestAccessPanel\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\n\nexport interface UnresolvedEntityRefProps {\n /** The record's id — the resolver never echoes back an id the caller had. */\n id: string;\n /**\n * The resolved answer, or null while `useAccessStates` is still asking.\n * Never synthesize one: a guessed state is the defect this component fixes.\n */\n context: AccessDeniedContext | null;\n /** Re-resolve after the owner grants, so the row heals in place. */\n onChanged?: () => void;\n /**\n * The surface's own repair for a record it cannot resolve — \"Remove from\n * outreach list\", \"Detach\", \"Replace\". Rendered inside the popover under the\n * platform's own actions. THE DOOR LAW's third corollary: a problem you can\n * detect ships with its fix.\n */\n repairAction?: React.ReactNode;\n className?: string;\n}\n\n/** The one-line label the cell shows. Short enough for a dense table row. */\nfunction chipLabel(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n // The state has to be readable WITHOUT opening the popover — a bare name in\n // a roster reads as an ordinary row, which is the lie all over again.\n case \"denied\":\n return context.entity.title\n ? `${context.entity.title} — no access`\n : `A ${kind} you can't open`;\n case \"deleted\":\n return context.entity.title\n ? `${context.entity.title} — deleted`\n : `Deleted ${kind}`;\n case \"missing\":\n return `This ${kind} no longer exists`;\n case \"anonymous\":\n return \"Sign in to see this\";\n case \"ok\":\n return context.entity.title ?? `This ${kind} didn't load`;\n default:\n return \"Couldn't check this record\";\n }\n}\n\n/** The honest sentence, in the popover. */\nfunction explanation(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\":\n return `This ${kind} exists, but it isn't shared with you. You can ask for access — the row stays in the list either way.`;\n case \"deleted\":\n return `This ${kind} was moved to the trash. Whoever deleted it can restore it; until then there is nothing here to open.`;\n case \"missing\":\n return `There is no ${kind} with this id. The reference is stale.`;\n case \"anonymous\":\n return \"Your session ended, so we can't tell you anything about this record. Sign in and it will load.\";\n case \"ok\":\n return `You DO have access to this ${kind} — the read failed for some other reason. Trying again should work.`;\n default:\n return \"We couldn't work out why this didn't load. That's a fault on our side, not a permission problem.\";\n }\n}\n\nfunction StatusIcon({ status }: { status: AccessDeniedContext[\"status\"] }) {\n const className = \"h-3.5 w-3.5 shrink-0\";\n switch (status) {\n case \"denied\":\n return <Ban className={className} aria-hidden />;\n case \"deleted\":\n return <Trash2 className={className} aria-hidden />;\n case \"missing\":\n return <HelpCircle className={className} aria-hidden />;\n case \"anonymous\":\n return <LogIn className={className} aria-hidden />;\n case \"ok\":\n return <RefreshCw className={className} aria-hidden />;\n default:\n return <TriangleAlert className={className} aria-hidden />;\n }\n}\n\nexport function UnresolvedEntityRef({\n id,\n context,\n onChanged,\n repairAction,\n className,\n}: UnresolvedEntityRefProps) {\n const [open, setOpen] = useState(false);\n const signInHref = useAccessUi().useLoginHref();\n\n if (!context) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 text-sm text-muted-foreground\",\n className,\n )}\n >\n <Loader2 className=\"h-3.5 w-3.5 animate-spin\" aria-hidden />\n Checking…\n </span>\n );\n }\n\n const label = chipLabel(context);\n // A denial is expected authorization, not a fault — muted. A resolver failure\n // and a stale reference are real problems and read as warnings.\n const tone =\n context.status === \"error\" || context.status === \"missing\"\n ? \"text-amber-700 dark:text-amber-400\"\n : \"text-muted-foreground\";\n const showOrg = Boolean(context.organization);\n\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n // Inside a clickable row: this opens the explanation, not the record.\n onClick={(e) => e.stopPropagation()}\n className={cn(\n \"inline-flex min-w-0 items-center gap-1.5 rounded-md border border-dashed border-border px-1.5 py-0.5 text-sm italic transition-colors hover:bg-muted\",\n tone,\n className,\n )}\n title=\"Why can't I see this?\"\n >\n <StatusIcon status={context.status} />\n <span className=\"truncate\">{label}</span>\n </button>\n </PopoverTrigger>\n <PopoverContent\n sizing=\"content\"\n align=\"start\"\n className=\"p-3\"\n onClick={(e) => e.stopPropagation()}\n >\n <p className=\"text-sm font-medium text-foreground\">\n {context.entity.title ?? context.entity.label}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {explanation(context)}\n </p>\n\n {/* Who has it. Each identity is a door only when it actually opens —\n a denied viewer is usually outside the owning org, and a link into a\n second locked door is a worse dead end than plain text. */}\n {context.owner || showOrg ? (\n <dl className=\"mt-2 space-y-0.5 rounded-md bg-muted/50 px-2 py-1.5 text-xs\">\n {context.owner ? (\n <div className=\"flex gap-1.5\">\n <dt className=\"text-muted-foreground\">Owner</dt>\n <dd className=\"min-w-0 truncate text-foreground\">\n {context.owner.creatorHandle ? (\n <Link\n href={`/c/${context.owner.creatorHandle}`}\n className=\"underline underline-offset-2\"\n >\n {context.owner.displayName ?? \"Someone else\"}\n </Link>\n ) : (\n (context.owner.displayName ?? \"Someone else\")\n )}\n </dd>\n </div>\n ) : null}\n {showOrg && context.organization ? (\n <div className=\"flex gap-1.5\">\n <dt className=\"text-muted-foreground\">Organization</dt>\n <dd className=\"min-w-0 truncate text-foreground\">\n {context.organization.viewerIsMember ? (\n <Link\n href={`/organizations/${context.organization.id}`}\n className=\"underline underline-offset-2\"\n >\n {context.organization.name ?? \"An organization\"}\n </Link>\n ) : (\n (context.organization.name ?? \"An organization\")\n )}\n </dd>\n </div>\n ) : null}\n </dl>\n ) : null}\n\n {context.status === \"denied\" ? (\n <div className=\"mt-2\">\n <RequestAccessPanel\n context={context}\n resourceId={id}\n onChanged={() => onChanged?.()}\n />\n </div>\n ) : null}\n\n {context.status === \"anonymous\" ? (\n <Button variant=\"primary\" asChild className=\"mt-2 w-full\">\n <Link href={signInHref}>\n <LogIn className=\"mr-1.5 h-3.5 w-3.5\" aria-hidden />\n Sign in\n </Link>\n </Button>\n ) : null}\n\n {(context.status === \"ok\" || context.status === \"error\") && onChanged ? (\n <Button\n icon={<RefreshCw aria-hidden />}\n variant=\"primary\"\n className=\"mt-2 w-full\"\n onClick={() => onChanged()}\n >\n Try again\n </Button>\n ) : null}\n\n {repairAction ? <div className=\"mt-2\">{repairAction}</div> : null}\n </PopoverContent>\n </Popover>\n );\n}\n","\"use client\";\n\n/**\n * Wraps a record page's `<AccessGate>` after an EMPTY SSR read: the browser\n * re-reads the row with its own (refreshed) session first. Readable → the\n * server page re-renders once with the fresh cookie and the record opens.\n * Not readable → the gate renders and answers honestly.\n * Why: `service/serverReadRecheck.ts`.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { getClaimsUser } from \"@ai-matrx/auth/claims\";\nimport { getAccessEnv, type AccessSupabaseClient } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\nimport { decideServerReadRecheck } from \"@ai-matrx/data/access\";\n\ntype BrowserClient = AccessSupabaseClient;\n\n/** Row readers per canonical entity token. Add a token when a page adopts this. */\nconst ROW_READERS = {\n conversation: async (supabase: BrowserClient, id: string) => {\n const { data, error } = await supabase\n .schema(\"chat\")\n .from(\"conversation\")\n .select(\"id\")\n .eq(\"id\", id)\n .is(\"deleted_at\", null)\n .maybeSingle();\n return !error && Boolean(data);\n },\n} satisfies Record<string, (supabase: BrowserClient, id: string) => Promise<boolean>>;\n\nexport type ServerReadRecheckToken = keyof typeof ROW_READERS;\n\n/** Records this tab already re-rendered for — a second SSR miss shows the gate. */\nconst refreshedOnce = new Set<string>();\n\nexport function ServerReadRecheck({\n token,\n id,\n children,\n pending,\n}: {\n token: ServerReadRecheckToken;\n id: string;\n /** The access gate. */\n children: ReactNode;\n /** What shows while the browser re-reads. */\n pending?: ReactNode;\n}) {\n const router = useAccessUi().router;\n const key = `${token}:${id}`;\n const [showGate, setShowGate] = useState(false);\n\n useEffect(() => {\n let active = true;\n void (async () => {\n let signedIn = false;\n let rowReadable = false;\n try {\n const supabase = getAccessEnv().getClient();\n const { data } = await getClaimsUser(supabase as unknown as Parameters<typeof getClaimsUser>[0]);\n signedIn = Boolean(data.user);\n if (signedIn) rowReadable = await ROW_READERS[token](supabase, id);\n } catch (error) {\n console.error(`[ServerReadRecheck] ${key}: browser re-read failed`, error);\n }\n if (!active) return;\n const verdict = decideServerReadRecheck({\n signedIn,\n rowReadable,\n alreadyRefreshed: refreshedOnce.has(key),\n });\n if (verdict === \"refresh\") {\n console.warn(\n `[ServerReadRecheck] ${key}: the server read came back empty but this browser can read it — re-rendering with the refreshed session`,\n );\n refreshedOnce.add(key);\n router.refresh();\n return;\n }\n setShowGate(true);\n })();\n return () => {\n active = false;\n };\n }, [key, token, id, router]);\n\n return <>{showGate ? children : (pending ?? null)}</>;\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n Archive,\n Check,\n EyeOff,\n KeyRound,\n Loader2,\n Send,\n ShieldCheck,\n Trash2,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport { useAccessGate } from \"./useAccessGate\";\nimport {\n createAccessRequest,\n createDeleteRequest,\n} from \"@ai-matrx/data/access\";\nimport { useHideForMe } from \"./useHiddenByMe\";\n\n/**\n * THE screen for \"you can see this, but removing it is not yours to do\"\n * (platform primitive, 2026-10-14). Any record a person can view but may not\n * archive or delete opens this instead of a refusal: ask the owner/admins to\n * do it, ask for full access, or hide it for yourself (it leaves your lists and\n * waits in that list's Hidden view). Open it BEFORE trying the write when\n * `useRemovalRights` says `canRemove: false`, and after a governed refusal\n * (`isGovernedActionDenial`).\n */\ntype RequestChoice = \"delete\" | \"hide\" | \"full\";\n\nexport function GovernedActionDialog({\n open,\n onOpenChange,\n resourceType,\n resourceId,\n itemName,\n itemLabel = \"site\",\n href,\n action = \"delete\",\n onHidden,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n resourceType: string;\n resourceId: string;\n itemName: string;\n itemLabel?: string;\n href?: string | null;\n /** The word for the removal the person tried: \"archive\" or \"delete\". */\n action?: \"archive\" | \"delete\";\n /** Called after the person hid the item (re-read a list that narrows server-side). */\n onHidden?: () => void;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const currentUserId = ui.useCurrentUser().id;\n const { context, isLoading } = useAccessGate(resourceType, resourceId, {\n enabled: open,\n });\n const [choice, setChoice] = useState<RequestChoice>(\"delete\");\n const [note, setNote] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [sent, setSent] = useState<RequestChoice | null>(null);\n const { hide } = useHideForMe(resourceType);\n const verb = action === \"archive\" ? \"archive\" : \"delete\";\n const ActionIcon = action === \"archive\" ? Archive : Trash2;\n\n const ownerName =\n context?.owner?.displayName ??\n (context?.organization ? context.organization.name : null) ??\n \"the owner\";\n\n async function hideIt() {\n setBusy(true);\n try {\n await hide.mutateAsync({ id: resourceId, label: itemName });\n toast.success(`Hidden for you. Find ${itemName} under Hidden.`);\n onHidden?.();\n onOpenChange(false);\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't hide that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function sendRequest() {\n if (choice === \"hide\") return hideIt();\n setBusy(true);\n try {\n const result =\n choice === \"delete\"\n ? await createDeleteRequest({\n resourceType,\n resourceId,\n message: note,\n currentUserId,\n href: href ?? null,\n })\n : await createAccessRequest({\n resourceType,\n resourceId,\n level: \"admin\",\n message: note,\n currentUserId,\n href: href ?? null,\n });\n setSent(choice);\n if (result.blindAnswer) {\n toast.success(result.blindAnswer);\n } else if (result.already) {\n toast.success(\"Your request is already waiting for an answer.\");\n } else if (result.delivered === 0) {\n toast.warning(\n \"Your request is saved, but we couldn't message them just now.\",\n );\n } else {\n toast.success(\n `Request sent to ${result.recipients[0]?.displayName ?? ownerName}.`,\n );\n }\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't send that request.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-xl\">\n <DialogHeader>\n <div className=\"mb-2 flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10\">\n <ActionIcon className=\"h-5 w-5 text-destructive\" aria-hidden />\n </div>\n <DialogTitle>\n Ask {ownerName} to {verb} this {itemLabel}\n </DialogTitle>\n <DialogDescription>\n You can work on{\" \"}\n <span className=\"font-medium text-foreground\">{itemName}</span>, but\n removing it is up to them. Ask them, or hide it just for you.\n </DialogDescription>\n </DialogHeader>\n\n {isLoading ? (\n <div className=\"flex items-center gap-2 rounded-lg border border-border bg-muted/30 p-4 text-sm text-muted-foreground\">\n <Loader2 className=\"h-4 w-4 animate-spin\" aria-hidden />\n Finding the person who can help…\n </div>\n ) : context?.status === \"error\" || context?.status === \"anonymous\" ? (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive-ink\">\n We couldn't find the right person to contact. Try again after\n refreshing.\n {ui.renderErrorMenu({})}\n </div>\n ) : sent ? (\n <div className=\"rounded-lg border border-primary/30 bg-primary/5 p-4\">\n <p className=\"flex items-center gap-2 text-sm font-medium text-foreground\">\n <Check className=\"h-4 w-4 text-primary\" aria-hidden />\n {sent === \"delete\"\n ? action === \"archive\"\n ? \"Archive requested\"\n : \"Deletion requested\"\n : \"Full access requested\"}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n The request is saved in Access requests and sent to {ownerName} in\n Messages.\n </p>\n </div>\n ) : (\n <>\n <div className=\"grid gap-2 sm:grid-cols-3\">\n <RequestChoiceButton\n active={choice === \"delete\"}\n icon={<ActionIcon className=\"h-4 w-4\" aria-hidden />}\n title={`Ask them to ${verb} it`}\n detail=\"They approve it from your message.\"\n onClick={() => setChoice(\"delete\")}\n />\n <RequestChoiceButton\n active={choice === \"hide\"}\n icon={<EyeOff className=\"h-4 w-4\" aria-hidden />}\n title=\"Hide it for me\"\n detail=\"Only you stop seeing it; undo under Hidden.\"\n onClick={() => setChoice(\"hide\")}\n />\n <RequestChoiceButton\n active={choice === \"full\"}\n icon={<ShieldCheck className=\"h-4 w-4\" aria-hidden />}\n title=\"Request full access\"\n detail={`Then you can ${verb} it yourself.`}\n onClick={() => setChoice(\"full\")}\n />\n </div>\n {choice === \"hide\" ? null : (\n <ProTextarea\n className=\"min-h-20 text-base md:text-sm\"\n value={note}\n maxLength={500}\n placeholder=\"Add a note for the owner (optional)\"\n onChange={(event) => setNote(event.target.value)}\n />\n )}\n </>\n )}\n\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n {sent ? \"Done\" : \"Cancel\"}\n </Button>\n {!sent &&\n context?.status !== \"error\" &&\n context?.status !== \"anonymous\" ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : choice === \"hide\" ? (\n <EyeOff aria-hidden />\n ) : choice === \"delete\" ? (\n <Send aria-hidden />\n ) : (\n <KeyRound aria-hidden />\n )}\n variant=\"primary\"\n disabled={busy || isLoading}\n onClick={() => void sendRequest()}\n >\n {choice === \"hide\" ? \"Hide for me\" : \"Send request\"}\n </Button>\n ) : null}\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nfunction RequestChoiceButton({\n active,\n icon,\n title,\n detail,\n onClick,\n}: {\n active: boolean;\n icon: React.ReactNode;\n title: string;\n detail: string;\n onClick: () => void;\n}) {\n return (\n <button\n type=\"button\"\n aria-pressed={active}\n onClick={onClick}\n className={`rounded-lg border p-3 text-left transition-colors ${\n active\n ? \"border-primary bg-primary/5\"\n : \"border-border hover:bg-muted/40\"\n }`}\n >\n <span className=\"flex items-center gap-2 text-sm font-medium text-foreground\">\n {icon}\n {title}\n </span>\n <span className=\"mt-1 block text-xs text-muted-foreground\">{detail}</span>\n </button>\n );\n}\n","\"use client\";\n\n/**\n * Hooks over THE per-person hide (`features/access-gate/service/hiddenByMe.ts`).\n *\n * The hidden ids live in ONE small module store per token (no React Query): the\n * list shell (`lib/entity-list`) reads them, and it renders in hosts and tests\n * that have no query client. Hide/unhide refresh the store, so every list of\n * that kind re-renders at once.\n *\n * `useHiddenByMe(token)` — the person's hidden ids for one record type.\n * `useHiddenItems(token)` — the same, with the names they saw (for the panel).\n * `useHideForMe(token)` — hide / unhide; `onChanged` re-reads a list that\n * narrows server-side (Marketing › Brands).\n * `useRemovalRights(token, id)` — the pre-check run BEFORE an archive/delete\n * confirm (own small state — no query client needed).\n */\n\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport {\n fetchRemovalRights,\n hideForMe,\n listHiddenItems,\n unhideForMe,\n type HiddenItem,\n type RemovalRights,\n} from \"@ai-matrx/data/access\";\nimport { getAccessEnv } from \"@ai-matrx/data/access\";\n\ninterface Slot {\n items: HiddenItem[] | undefined;\n /** Stable ids array for `items` (lists memoise on it). */\n ids: string[] | undefined;\n loading: Promise<void> | null;\n /** The last read failed: the next mount retries instead of trusting []. */\n failed: boolean;\n}\n\nconst slots = new Map<string, Slot>();\nconst listeners = new Set<() => void>();\nlet version = 0;\nlet watchingAuth = false;\n\nfunction emit() {\n version += 1;\n listeners.forEach((listener) => listener());\n}\n\n/** A sign-in, sign-out or account switch empties the store: hides belong to one person. */\nfunction watchAuth() {\n if (watchingAuth || typeof window === \"undefined\") return;\n watchingAuth = true;\n try {\n getAccessEnv().getClient().auth.onAuthStateChange((event) => {\n if (event === \"SIGNED_IN\" || event === \"SIGNED_OUT\" || event === \"USER_UPDATED\") {\n slots.clear();\n emit();\n }\n });\n } catch {\n // No auth client in this host (tests): nothing to watch.\n }\n}\n\nfunction slotFor(token: string): Slot {\n let slot = slots.get(token);\n if (!slot) {\n slot = { items: undefined, ids: undefined, loading: null, failed: false };\n slots.set(token, slot);\n }\n return slot;\n}\n\nfunction settle(slot: Slot, items: HiddenItem[], failed: boolean) {\n slot.items = items;\n slot.ids = items.map((item) => item.id);\n slot.failed = failed;\n}\n\n/** (Re)read one token's hidden items into the store. Signed out → nothing is hidden. */\nexport function refreshHiddenByMe(token: string): Promise<void> {\n watchAuth();\n const slot = slotFor(token);\n const loading = (async () => {\n try {\n const { data } = await getAccessEnv().getClient().auth.getSession();\n if (!data.session) {\n settle(slot, [], true);\n return;\n }\n settle(slot, await listHiddenItems(token), false);\n } catch {\n // An unreadable answer hides nothing: the list stays whole, never wrongly short.\n settle(slot, slot.items ?? [], true);\n }\n })().finally(() => {\n slot.loading = null;\n emit();\n });\n slot.loading = loading;\n return loading;\n}\n\nfunction useHiddenSlot(token: string, enabled: boolean): Slot | undefined {\n useSyncExternalStore(\n (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n () => version,\n () => version,\n );\n const active = enabled && Boolean(token);\n const slot = active ? slotFor(token) : undefined;\n useEffect(() => {\n if (!active) return;\n const current = slotFor(token);\n if ((current.items === undefined || current.failed) && !current.loading) void refreshHiddenByMe(token);\n }, [active, token]);\n return slot;\n}\n\nexport function useHiddenByMe(token: string, enabled = true) {\n const slot = useHiddenSlot(token, enabled);\n return {\n data: slot?.ids,\n isPending: enabled && Boolean(token) && slot?.ids === undefined,\n };\n}\n\nexport function useHiddenItems(token: string, enabled = true) {\n const slot = useHiddenSlot(token, enabled);\n return { data: slot?.items, isPending: enabled && slot?.items === undefined };\n}\n\nexport function useRemovalRights(token: string, id: string | null) {\n const [nonce, setNonce] = useState(0);\n const key = id ? `${token}:${id}:${nonce}` : null;\n const [settled, setSettled] = useState<{\n key: string;\n data?: RemovalRights;\n error?: unknown;\n } | null>(null);\n\n // Always re-read on mount / target change (the old query had staleTime 0).\n useEffect(() => {\n if (!key || !id) return;\n let active = true;\n fetchRemovalRights(token, id).then(\n (data) => active && setSettled({ key, data }),\n (error: unknown) => active && setSettled({ key, error }),\n );\n return () => {\n active = false;\n };\n }, [key, token, id]);\n\n // Stale answers are discarded by comparing keys, never by clearing state.\n const current = key && settled?.key === key ? settled : null;\n const isLoading = key !== null && current === null;\n return {\n data: current?.data,\n error: current?.error,\n isLoading,\n isPending: isLoading,\n isError: current?.error !== undefined,\n refetch: () => setNonce((n) => n + 1),\n };\n}\n\ntype HideArgs = string | { id: string; label?: string | null };\n\n/** Hide / unhide for the person. `onChanged` runs after the store refreshed. */\nexport function useHideForMe(token: string, onChanged?: () => void | Promise<void>) {\n const [busy, setBusy] = useState(false);\n const run = async (work: () => Promise<void>) => {\n setBusy(true);\n try {\n await work();\n await refreshHiddenByMe(token);\n await onChanged?.();\n } finally {\n setBusy(false);\n }\n };\n return {\n hide: {\n isPending: busy,\n mutateAsync: (args: HideArgs) =>\n run(() =>\n typeof args === \"string\" ? hideForMe(token, args) : hideForMe(token, args.id, args.label),\n ),\n },\n unhide: {\n isPending: busy,\n mutateAsync: (id: string) => run(() => unhideForMe(token, id)),\n },\n };\n}\n","\"use client\";\n\n/**\n * HiddenByMeButton — the one-click \"Hidden by me\" place for ANY list\n * (2026-10-14, the archived-items law's sibling). The list shell renders it in\n * its toolbar with the list's entity token; it is absent until the person has\n * hidden something of that kind. It opens a panel naming each hidden record\n * (each one opens — no dead ends) with \"Show again\".\n *\n * Lists whose own query narrows hidden rows server-side (Marketing › Brands)\n * use `HiddenFilter` + `applyHiddenView` instead.\n */\n\nimport { useState } from \"react\";\nimport { Eye, EyeOff } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport {\n useHiddenByMe,\n useHiddenItems,\n useHideForMe,\n} from \"./useHiddenByMe\";\n\nexport function HiddenByMeButton({\n token,\n pluralLabel,\n}: {\n /** Platform entity token of the list (`note`, `transcript`, …). */\n token: string;\n /** \"notes\" — the list's own word for its records. */\n pluralLabel: string;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const [open, setOpen] = useState(false);\n const ids = useHiddenByMe(token);\n const items = useHiddenItems(token, open);\n const { unhide } = useHideForMe(token);\n const count = ids.data?.length ?? 0;\n if (count === 0 && !open) return null;\n\n const showAgain = async (id: string, name: string) => {\n try {\n await unhide.mutateAsync(id);\n toast.success(`${name} is back in your list`);\n if (count <= 1) setOpen(false);\n } catch (error) {\n toast.error(error instanceof Error ? error.message : \"We couldn't show that again.\");\n }\n };\n\n return (\n <>\n <Button\n type=\"button\"\n variant=\"quiet\"\n icon={<EyeOff />}\n title={`${pluralLabel} you hid`}\n onClick={() => setOpen(true)}\n >\n {`Hidden ${count}`}\n </Button>\n <Dialog open={open} onOpenChange={setOpen}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>Hidden by me</DialogTitle>\n <DialogDescription>\n Only you stopped seeing these {pluralLabel}.\n </DialogDescription>\n </DialogHeader>\n <ul className=\"flex max-h-[60dvh] flex-col divide-y divide-border overflow-y-auto\">\n {(items.data ?? []).map((item) => {\n const name = item.label ?? \"Untitled\";\n return (\n <li key={item.id} className=\"flex items-center gap-2 py-2\">\n <div className=\"min-w-0 flex-1\">\n {ui.renderEntityRef({ token: item.token, id: item.id, name })}\n </div>\n <Button\n type=\"button\"\n variant=\"outline\"\n icon={<Eye />}\n disabled={unhide.isPending}\n onClick={() => void showAgain(item.id, name)}\n >\n Show again\n </Button>\n </li>\n );\n })}\n </ul>\n </DialogContent>\n </Dialog>\n </>\n );\n}\n","\"use client\";\n\n/**\n * HiddenFilter — the one-click way into a list's \"Hidden by me\" view (platform\n * primitive, 2026-10-14; sits beside `ArchiveFilter`). Absent until the person\n * has hidden something in this list, so it adds nothing to a clean list.\n */\n\nimport { EyeOff } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport type { HiddenView } from \"@ai-matrx/data/access\";\n\nexport function HiddenFilter({\n count,\n value,\n onValueChange,\n}: {\n /** How many items of this list the person has hidden. */\n count: number;\n value: HiddenView;\n onValueChange: (value: HiddenView) => void;\n}) {\n if (count === 0 && value === \"visible\") return null;\n const showing = value === \"hidden\";\n return (\n <Button\n type=\"button\"\n variant={showing ? \"outline\" : \"quiet\"}\n icon={<EyeOff />}\n aria-pressed={showing}\n title={showing ? \"Back to the list\" : \"Items you hid\"}\n onClick={() => onValueChange(showing ? \"visible\" : \"hidden\")}\n >\n {`Hidden ${count}`}\n </Button>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Check,\n CircleSlash,\n ExternalLink,\n Flag,\n KeyRound,\n Loader2,\n Trash2,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n decideAccessRequest,\n getResourceActionRequestForDecision,\n reportAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type { AccessRequestStatus } from \"@ai-matrx/data/access\";\n\nexport function ResourceActionRequestButtons({\n requestId,\n actionKey,\n href,\n itemName,\n isOwn = false,\n compact = false,\n onDone,\n}: {\n requestId: string;\n actionKey: string;\n href?: string | null;\n itemName: string;\n isOwn?: boolean;\n compact?: boolean;\n onDone?: (status: AccessRequestStatus) => void;\n}) {\n const ui = useAccessUi();\n const { toast, confirm, getResourceActionRequestAction } = ui;\n const currentUserId = ui.useCurrentUser().id;\n const [busy, setBusy] = useState(false);\n const [done, setDone] = useState<AccessRequestStatus | null>(null);\n const action = getResourceActionRequestAction(actionKey);\n const safeHref =\n href?.startsWith(\"/\") && !href.startsWith(\"//\") ? href : null;\n const size = compact ? \"h-7 px-2 text-[11px]\" : \"h-11 sm:h-8\";\n\n if (isOwn) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-inherit\">\n <Trash2 className=\"h-3 w-3\" aria-hidden />\n Deletion requested\n </span>\n );\n }\n if (done) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-muted-foreground\">\n <Check className=\"h-3 w-3\" aria-hidden />\n {done === \"granted\"\n ? \"Completed\"\n : done === \"reported\"\n ? \"Reported\"\n : \"Declined\"}\n </span>\n );\n }\n\n async function completeAction() {\n if (!action) {\n toast.error(\"This request uses an action the app does not recognize.\");\n return;\n }\n const ok = await confirm({\n title: action.confirmTitle(itemName),\n description: action.confirmDescription,\n confirmLabel: action.label,\n variant: \"destructive\",\n });\n if (!ok) return;\n setBusy(true);\n try {\n const request = await getResourceActionRequestForDecision(requestId);\n const durableAction = getResourceActionRequestAction(\n request.resourceAction.actionKey,\n );\n if (!durableAction) {\n throw new Error(\n \"This request uses an action the app does not recognize.\",\n );\n }\n await durableAction.execute({\n resourceType: request.resourceType,\n resourceId: request.resourceId,\n });\n const result = await decideAccessRequest({\n requestId,\n decision: \"complete\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(durableAction.completedLabel);\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't complete that action.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function grantFullAccess() {\n setBusy(true);\n try {\n const result = await decideAccessRequest({\n requestId,\n decision: \"grant\",\n level: \"admin\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Full access granted.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't grant access.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function decline() {\n setBusy(true);\n try {\n const result = await decideAccessRequest({\n requestId,\n decision: \"decline\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Request declined.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't decline that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function report() {\n const ok = await confirm({\n title: \"Report this request?\",\n description:\n \"This ends the conversation for good. They won't be able to ask about this item again.\",\n confirmLabel: \"Report\",\n variant: \"destructive\",\n });\n if (!ok) return;\n setBusy(true);\n try {\n await reportAccessRequest(requestId);\n setDone(\"reported\");\n onDone?.(\"reported\");\n toast.success(\"Request reported.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't report that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <div className=\"flex flex-wrap gap-2\">\n {action ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Trash2 aria-hidden />\n )}\n variant=\"primary\"\n className={size}\n disabled={busy}\n onClick={() => void completeAction()}\n >\n {action.label}\n </Button>\n ) : null}\n <Button\n icon={<KeyRound aria-hidden />}\n className={size}\n variant=\"outline\"\n disabled={busy}\n onClick={() => void grantFullAccess()}\n >\n Give full access\n </Button>\n {safeHref ? (\n <Button asChild className={size} variant=\"outline\">\n <Link href={safeHref} target=\"_blank\" rel=\"noopener noreferrer\">\n <ExternalLink className=\"h-3.5 w-3.5\" aria-hidden />\n Open item\n </Link>\n </Button>\n ) : null}\n <Button\n icon={<CircleSlash aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void decline()}\n >\n Decline\n </Button>\n <Button\n icon={<Flag aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void report()}\n >\n Report\n </Button>\n </div>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Check,\n CircleSlash,\n ExternalLink,\n Loader2,\n Settings,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n decideSettingAccessRequest,\n getSettingAccessRequestForDecision,\n} from \"@ai-matrx/data/access\";\nimport type { AccessRequestStatus } from \"@ai-matrx/data/access\";\n\nexport function SettingRequestActionButtons({\n requestId,\n href,\n actionKey,\n isOwn = false,\n compact = false,\n onDone,\n}: {\n requestId: string;\n href: string;\n actionKey: string;\n isOwn?: boolean;\n compact?: boolean;\n onDone?: (status: AccessRequestStatus) => void;\n}) {\n const ui = useAccessUi();\n const toast = ui.toast;\n const getSettingRequestAction = ui.getSettingRequestAction;\n const [busy, setBusy] = useState(false);\n const [done, setDone] = useState<AccessRequestStatus | null>(null);\n const action = getSettingRequestAction(actionKey);\n const safeHref = href.startsWith(\"/\") && !href.startsWith(\"//\") ? href : null;\n\n if (isOwn) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-inherit\">\n <Settings className=\"h-3 w-3\" aria-hidden />\n Setting change requested\n </span>\n );\n }\n\n if (done) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-muted-foreground\">\n <Check className=\"h-3 w-3\" aria-hidden />\n {done === \"granted\" ? \"Change completed\" : \"Declined\"}\n </span>\n );\n }\n\n async function apply() {\n if (!action) {\n toast.error(\"This request uses an action the app does not recognize.\");\n return;\n }\n setBusy(true);\n try {\n const request = await getSettingAccessRequestForDecision(requestId);\n const durableAction = getSettingRequestAction(\n request.settingRequest.actionKey,\n );\n if (!durableAction) {\n throw new Error(\n \"This request uses an action the app does not recognize.\",\n );\n }\n await durableAction.execute(request.settingRequest.actionPayload, {\n organizationId: request.resourceId,\n });\n const result = await decideSettingAccessRequest({\n requestId,\n decision: \"complete\",\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(durableAction.completedLabel);\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't make that change.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function decline() {\n setBusy(true);\n try {\n const result = await decideSettingAccessRequest({\n requestId,\n decision: \"decline\",\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Request declined.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't decline that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n const size = compact ? \"h-7 px-2 text-[11px]\" : \"h-11 sm:h-8\";\n return (\n <div className=\"flex flex-wrap gap-2\">\n {action ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Check aria-hidden />\n )}\n variant=\"primary\"\n className={size}\n disabled={busy}\n onClick={() => void apply()}\n >\n {action.label}\n </Button>\n ) : null}\n {safeHref ? (\n <Button asChild className={size} variant=\"outline\">\n <Link href={safeHref} target=\"_blank\" rel=\"noopener noreferrer\">\n <ExternalLink className=\"h-3.5 w-3.5\" aria-hidden />\n Open setting\n </Link>\n </Button>\n ) : null}\n <Button\n icon={<CircleSlash aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void decline()}\n >\n Decline\n </Button>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * AccessRequestsSurface — the inbox for `iam.access_requests`, both directions.\n *\n * Why it exists: the request row is the durable fact and the DM is only how it\n * gets NOTICED. Until this page, the DM was the only place an ask was ever\n * visible — so a request whose delivery failed, or one filed while the sender\n * had no signed-in session to message from, became a row nobody on earth could\n * see or answer. This is the surface that makes the row reachable.\n *\n * It deliberately does NOT reimplement the decision: the same\n * `decideAccessRequest` / `reportAccessRequest` / `withdrawAccessRequest` the DM\n * chips call are called here, so grant-and-notify behaves identically in both\n * places and can never drift.\n *\n * Not built on `lib/entity-list`: that shell's contract is a server-side\n * scoped/sorted/filtered/faceted RPC over the five-scope vocabulary\n * (mine/orgs/shared/public). `access_request_list(p_box)` is a two-box,\n * unpaged, authorization-derived list — an inbox, not an entity list — and\n * satisfying the shell would mean inventing an `access_request_list_scoped`\n * family for a set that is small by construction.\n *\n * Where it lives (2026-10-01): a settings tab — `General › Access requests`,\n * `ACCESS_REQUESTS_HREF` — rendered by the ONE settings core, so the route,\n * the Preferences window and the phone drawer all show it. It therefore owns\n * no route chrome: the two boxes and Refresh sit in an inline bar, and the box\n * is local state (seeded once from `?box=sent`, which old DM links and the\n * `/settings/access-requests` redirect still carry), because pushing a URL\n * from inside the window would navigate the page out from under it. The old\n * standalone route is a config redirect in `next.config.js`.\n */\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n CircleCheck,\n CircleSlash,\n Flag,\n Inbox,\n KeyRound,\n PenLine,\n Send,\n Undo2,\n} from \"lucide-react\";\nimport { Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { Button, SegmentedControl } from \"@ai-matrx/design-system/controls\";\nimport { SettingRequestActionButtons } from \"./SettingRequestActionButtons\";\nimport { ResourceActionRequestButtons } from \"./ResourceActionRequestButtons\";\nimport { RefreshCwTapButton } from \"@ai-matrx/design-system/tap-target/buttons\";\nimport { formatRelativeTime } from \"@ai-matrx/kit/format\";\nimport {\n decideAccessRequest,\n listAccessRequests,\n reportAccessRequest,\n withdrawAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type {\n AccessRequestRow,\n AccessRequestStatus,\n RequestedLevel,\n} from \"@ai-matrx/data/access\";\n\ntype Box = \"inbox\" | \"sent\";\n\n/** The one address of this inbox: the settings tab `accessRequests`. */\nexport const ACCESS_REQUESTS_HREF = \"/user-settings/access-requests\";\n\nconst STATUS_LABEL: Record<AccessRequestStatus, string> = {\n pending: \"Pending\",\n granted: \"Granted\",\n declined: \"Declined\",\n withdrawn: \"Withdrawn\",\n reported: \"Reported\",\n};\n\nconst STATUS_TONE: Record<AccessRequestStatus, string> = {\n pending: \"bg-muted text-muted-foreground\",\n granted: \"bg-primary/10 text-primary-ink\",\n declined: \"bg-muted text-muted-foreground\",\n withdrawn: \"bg-muted text-muted-foreground\",\n reported: \"bg-destructive/10 text-destructive-ink\",\n};\n\nfunction statusLabel(row: AccessRequestRow): string {\n return row.requestKind === \"resource_action\" && row.status === \"granted\"\n ? \"Completed\"\n : STATUS_LABEL[row.status];\n}\n\nfunction boxFromParam(value: string | null): Box {\n return value === \"sent\" ? \"sent\" : \"inbox\";\n}\n\n/**\n * BOTH boxes, every time. The tab the user is not standing on still has to\n * show an honest count — a badge that only becomes true once you click the tab\n * is exactly the kind of small lie this feature exists to stop.\n *\n * Module-level and state-free on purpose: the mount effect can then await it\n * and set state in the callback, instead of calling a setState-bearing helper\n * synchronously inside the effect body (React Compiler's\n * `react-hooks/set-state-in-effect`).\n */\nasync function fetchBoxes(): Promise<{\n rows: Record<Box, AccessRequestRow[]>;\n error: string | null;\n}> {\n try {\n const [inbox, sent] = await Promise.all([\n listAccessRequests(\"inbox\"),\n listAccessRequests(\"sent\"),\n ]);\n return { rows: { inbox, sent }, error: null };\n } catch (e) {\n return {\n rows: { inbox: [], sent: [] },\n error:\n e instanceof Error\n ? e.message\n : \"We couldn't load your access requests.\",\n };\n }\n}\n\n/** The record the ask is about. A door where one resolves, plain text where not. */\nfunction EntityCell({ row }: { row: AccessRequestRow }) {\n const ui = useAccessUi();\n const label = row.entityLabel ?? \"Item\";\n if (row.requestKind === \"setting\" && row.settingRequest) {\n return (\n <span className=\"flex min-w-0 items-center gap-1.5 text-sm\">\n <span className=\"shrink-0 text-xs uppercase tracking-wide text-muted-foreground\">\n Setting\n </span>\n <Link\n href={row.settingRequest.href}\n className=\"min-w-0 truncate font-medium text-primary hover:underline\"\n >\n {row.settingRequest.settingLabel}\n </Link>\n </span>\n );\n }\n if (!row.entityTitle) {\n // No title to show, and an 8-character uuid stem is not a name. Say the\n // kind and stop — never print an id the user cannot open.\n return (\n <span className=\"text-sm text-muted-foreground\">\n Untitled {label.toLowerCase()}\n </span>\n );\n }\n return (\n <span className=\"flex min-w-0 items-center gap-1.5 text-sm\">\n <span className=\"shrink-0 text-xs uppercase tracking-wide text-muted-foreground\">\n {label}\n </span>\n {/* Renders as plain text when no route resolves for this token — the\n component decides, so this surface can never invent a dead link. */}\n {ui.renderEntityRef({\n token: row.resourceType,\n id: row.resourceId,\n name: row.entityTitle,\n showIcon: false,\n className: \"min-w-0 font-medium\",\n })}\n </span>\n );\n}\n\nfunction RowShell({ children }: { children: React.ReactNode }) {\n return (\n <li className=\"rounded-lg border border-border bg-card p-3 sm:p-4\">\n {children}\n </li>\n );\n}\n\nfunction LoadingRows() {\n return (\n <ul className=\"space-y-2\">\n {[0, 1, 2].map((i) => (\n <RowShell key={i}>\n <div className=\"flex items-start gap-3\">\n <Skeleton className=\"h-8 w-8 shrink-0 rounded-full\" />\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Skeleton className=\"h-4 w-1/3\" />\n <Skeleton className=\"h-3 w-2/3\" />\n </div>\n </div>\n </RowShell>\n ))}\n </ul>\n );\n}\n\nfunction EmptyState({ box }: { box: Box }) {\n const Icon = box === \"inbox\" ? Inbox : Send;\n return (\n <div className=\"flex flex-col items-center gap-2 rounded-lg border border-dashed border-border px-6 py-12 text-center\">\n <Icon className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n <p className=\"text-sm font-medium text-foreground\">\n {box === \"inbox\"\n ? \"Nothing waiting on you\"\n : \"You haven't asked for anything\"}\n </p>\n <p className=\"max-w-sm text-xs text-muted-foreground\">\n {box === \"inbox\"\n ? \"When someone asks to open something you own, it lands here — and in your messages.\"\n : \"When you open something you don't have access to yet, you can ask the owner from there. Your request shows up here.\"}\n </p>\n </div>\n );\n}\n\nexport function AccessRequestsSurface() {\n const ui = useAccessUi();\n const { toast, confirm } = ui;\n const [box, setBox] = useState<Box>(() => boxFromParam(ui.searchParam(\"box\")));\n const currentUserId = ui.useCurrentUser().id;\n\n const [rows, setRows] = useState<Record<Box, AccessRequestRow[] | null>>({\n inbox: null,\n sent: null,\n });\n const [error, setError] = useState<string | null>(null);\n const [busyId, setBusyId] = useState<string | null>(null);\n const [refreshing, setRefreshing] = useState(false);\n\n const refresh = useCallback(async () => {\n setRefreshing(true);\n const result = await fetchBoxes();\n setRows(result.rows);\n setError(result.error);\n setRefreshing(false);\n }, []);\n\n useEffect(() => {\n let alive = true;\n void (async () => {\n const result = await fetchBoxes();\n if (!alive) return;\n setRows(result.rows);\n setError(result.error);\n })();\n return () => {\n alive = false;\n };\n }, []);\n\n const current = rows[box];\n // The inbox RPC returns ONLY pending asks I am entitled to answer, so its\n // length IS the count of things waiting on me.\n const inboxCount = rows.inbox?.length ?? 0;\n const sentPending =\n rows.sent?.filter((r) => r.status === \"pending\").length ?? 0;\n\n async function run(id: string, work: () => Promise<void>, done: string) {\n setBusyId(id);\n try {\n await work();\n toast.success(done);\n await refresh();\n } catch (e) {\n toast.error(e instanceof Error ? e.message : \"We couldn't do that.\");\n } finally {\n setBusyId(null);\n }\n }\n\n function decide(row: AccessRequestRow, level: RequestedLevel) {\n void run(\n row.id,\n async () => {\n await decideAccessRequest({\n requestId: row.id,\n decision: \"grant\",\n level,\n currentUserId,\n });\n },\n `Access granted${row.entityTitle ? ` to ${row.entityTitle}` : \"\"}.`,\n );\n }\n\n async function decline(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Decline this request?\",\n description:\n \"They'll be told you said no. They can ask again later if something changes.\",\n confirmLabel: \"Decline\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await decideAccessRequest({\n requestId: row.id,\n decision: \"decline\",\n currentUserId,\n });\n },\n \"Request declined.\",\n );\n }\n\n async function report(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Report this request?\",\n description:\n \"This ends the conversation for good — they won't be able to ask about this again.\",\n confirmLabel: \"Report\",\n variant: \"destructive\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await reportAccessRequest(row.id);\n },\n \"Reported. They can't ask about this again.\",\n );\n }\n\n async function withdraw(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Withdraw your request?\",\n description: \"The owner will no longer see it waiting for an answer.\",\n confirmLabel: \"Withdraw\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await withdrawAccessRequest(row.id);\n },\n \"Request withdrawn.\",\n );\n }\n\n const tabLabel = (target: Box, label: string) => (\n <span className=\"inline-flex items-center gap-1.5\">\n {target === \"inbox\" ? (\n <Inbox className=\"h-3.5 w-3.5\" aria-hidden />\n ) : (\n <Send className=\"h-3.5 w-3.5\" aria-hidden />\n )}\n {label}\n </span>\n );\n\n return (\n <div className=\"mx-auto w-full max-w-3xl\">\n <div className=\"mb-3 flex items-center justify-between gap-2\">\n {/* The host (settings breadcrumb, drawer header) already names the\n page on a phone; the title steps out there so the pill fits. */}\n <span className=\"hidden items-center gap-1.5 text-sm font-medium sm:inline-flex\">\n <KeyRound className=\"h-4 w-4\" aria-hidden />\n Access requests\n </span>\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n <SegmentedControl<Box>\n aria-label=\"Request box\"\n value={box}\n onValueChange={setBox}\n data={[\n { value: \"inbox\", label: tabLabel(\"inbox\", \"To me\"), count: inboxCount > 0 ? inboxCount : null },\n { value: \"sent\", label: tabLabel(\"sent\", \"I sent\"), count: sentPending > 0 ? sentPending : null },\n ]}\n />\n <RefreshCwTapButton\n ariaLabel=\"Refresh access requests\"\n disabled={refreshing}\n onClick={() => void refresh()}\n />\n </div>\n </div>\n\n <div>\n {error && (\n <div className=\"mb-3 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink\">\n {error}\n {ui.renderErrorMenu({ error })}\n </div>\n )}\n\n {/* An error is never dressed up as an empty inbox: \"nothing waiting\n on you\" when the read failed is the same class of lie this whole\n feature exists to kill. */}\n {error ? null : current === null ? (\n <LoadingRows />\n ) : current.length === 0 ? (\n <EmptyState box={box} />\n ) : (\n <ul className=\"space-y-2\">\n {current.map((row) => (\n <RowShell key={row.id}>\n <div className=\"flex min-w-0 flex-col gap-3\">\n <div className=\"flex min-w-0 flex-wrap items-start justify-between gap-2\">\n <div className=\"flex min-w-0 items-start gap-3\">\n {box === \"inbox\" && (\n ui.renderUserIdentity({\n user: {\n id: row.requester?.userId,\n displayName: row.requester?.displayName,\n avatarUrl: row.requester?.avatarUrl,\n },\n size: \"sm\",\n subtitle: false,\n avatarOnly: true,\n })\n )}\n <div className=\"min-w-0 space-y-1\">\n <p className=\"text-sm text-foreground\">\n {box === \"inbox\" ? (\n <span className=\"font-medium\">\n {row.requester?.displayName ?? \"Someone\"}\n </span>\n ) : (\n <span className=\"font-medium\">You</span>\n )}{\" \"}\n {row.requestKind === \"setting\"\n ? \"asked for a setting change\"\n : row.requestKind === \"resource_action\"\n ? \"asked you to delete\"\n : `asked to ${\n row.requestedLevel === \"admin\"\n ? \"give full access to\"\n : row.requestedLevel === \"editor\"\n ? \"edit\"\n : \"view\"\n }`}\n </p>\n <EntityCell row={row} />\n </div>\n </div>\n <div className=\"flex shrink-0 items-center gap-2\">\n {box === \"sent\" && (\n <span\n className={cn(\n \"rounded-full px-2 py-0.5 text-[11px] font-medium\",\n STATUS_TONE[row.status],\n )}\n >\n {statusLabel(row)}\n </span>\n )}\n {row.createdAt && (\n <span\n className=\"text-xs tabular-nums text-muted-foreground\"\n title={new Date(row.createdAt).toLocaleString()}\n >\n {formatRelativeTime(row.createdAt)}\n </span>\n )}\n </div>\n </div>\n\n {row.message && (\n <p className=\"whitespace-pre-line rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground [overflow-wrap:anywhere]\">\n {row.message}\n </p>\n )}\n\n {box === \"sent\" && row.decisionNote && (\n <p className=\"text-xs text-muted-foreground\">\n <span className=\"font-medium text-foreground\">\n Their note:\n </span>{\" \"}\n {row.decisionNote}\n </p>\n )}\n\n {box === \"inbox\" &&\n row.requestKind === \"resource_action\" &&\n row.resourceAction ? (\n <ResourceActionRequestButtons\n requestId={row.id}\n actionKey={row.resourceAction.actionKey}\n itemName={\n row.entityTitle ?? row.entityLabel ?? \"this item\"\n }\n onDone={() => void refresh()}\n />\n ) : box === \"inbox\" &&\n row.requestKind === \"setting\" &&\n row.settingRequest ? (\n <SettingRequestActionButtons\n requestId={row.id}\n href={row.settingRequest.href}\n actionKey={row.settingRequest.actionKey}\n onDone={() => void refresh()}\n />\n ) : box === \"inbox\" ? (\n <div className=\"flex flex-wrap gap-2\">\n <Button\n icon={<CircleCheck aria-hidden />}\n variant=\"primary\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"viewer\")}\n >\n Let them view\n </Button>\n <Button\n icon={<PenLine aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"editor\")}\n >\n Let them edit\n </Button>\n <Button\n icon={<KeyRound aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"admin\")}\n >\n Give full access\n </Button>\n <Button\n icon={<CircleSlash aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => void decline(row)}\n >\n Decline\n </Button>\n <Button\n icon={<Flag aria-hidden />}\n variant=\"quiet\"\n disabled={busyId === row.id}\n onClick={() => void report(row)}\n >\n Report\n </Button>\n </div>\n ) : (\n row.status === \"pending\" && (\n <div className=\"flex flex-wrap gap-2\">\n <Button\n icon={<Undo2 aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => void withdraw(row)}\n >\n Withdraw\n </Button>\n </div>\n )\n )}\n </div>\n </RowShell>\n ))}\n </ul>\n )}\n </div>\n </div>\n );\n}\n\nexport default AccessRequestsSurface;\n","\"use client\";\n\n/**\n * useAccessStates — the LIST counterpart of `useAccessGate`.\n *\n * `useAccessGate` answers \"why can't I open THIS record\" for a whole page. A\n * table is the other shape of the same question: a roster joins to another\n * table, some of those embeds come back null, and every one of them is\n * ambiguous for the same four reasons (denied / deleted / missing / signed\n * out). Rendering \"(record unavailable)\" is the surface guessing — the exact\n * thing `features/access-gate` exists to stop.\n *\n * One hook resolves every unresolved id on the page at once and hands the\n * answers back as a map, so BOTH halves of the fix read the same truth:\n * - the cell renders the real state (`<UnresolvedEntityRef>`), and\n * - the row's action menu suppresses the actions that state cannot satisfy.\n *\n * Answers are cached module-wide by `token:id` because a denial does not change\n * while the user pages back and forth, and because the same party can appear in\n * several lists. `refresh()` clears the ids it owns — that is what makes the\n * \"Request access\" loop close in place once the owner grants.\n */\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { fetchAccessDeniedContext } from \"@ai-matrx/data/access\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\n\n/** Resolved answers, shared across surfaces. A denial is stable; re-asking is waste. */\nconst CACHE = new Map<string, AccessDeniedContext>();\n/** In-flight promises, so ten rows naming one party issue ONE rpc. */\nconst INFLIGHT = new Map<string, Promise<AccessDeniedContext>>();\n\nfunction cacheKey(token: string, id: string): string {\n return `${token}:${id}`;\n}\n\nfunction resolveOne(token: string, id: string): Promise<AccessDeniedContext> {\n const key = cacheKey(token, id);\n const cached = CACHE.get(key);\n if (cached) return Promise.resolve(cached);\n\n const existing = INFLIGHT.get(key);\n if (existing) return existing;\n\n // `fetchAccessDeniedContext` never throws — it degrades to `status: \"error\"`,\n // which the UI renders as a retry-able fault rather than as a denial.\n const promise = fetchAccessDeniedContext(token, id).then((context) => {\n INFLIGHT.delete(key);\n // A resolver fault is not an answer — caching it would freeze a transient\n // outage into a permanent \"we couldn't check\" for the rest of the session.\n if (context.status !== \"error\") CACHE.set(key, context);\n return context;\n });\n INFLIGHT.set(key, promise);\n return promise;\n}\n\nexport interface UseAccessStatesResult {\n /** Resolved answers by record id. An absent id is still resolving. */\n states: ReadonlyMap<string, AccessDeniedContext>;\n /** True while at least one id on this page has no answer yet. */\n isLoading: boolean;\n /** Drop the cached answers for these ids and ask again. */\n refresh: () => void;\n}\n\n/**\n * Resolve the true access state of every id in `ids` for one entity token.\n *\n * Pass ONLY the ids that actually failed to resolve. Asking about records the\n * caller can already read is a wasted round trip per row, and the resolver is\n * deliberately a per-record call.\n */\nexport function useAccessStates(\n token: string,\n ids: readonly string[],\n): UseAccessStatesResult {\n const [nonce, setNonce] = useState(0);\n const [resolved, setResolved] = useState<\n ReadonlyMap<string, AccessDeniedContext>\n >(() => new Map());\n\n // A stable identity for \"which ids are we asking about\", so the effect does\n // not re-run on every render just because the caller rebuilt the array.\n const idKey = useMemo(() => Array.from(new Set(ids)).sort().join(\",\"), [ids]);\n\n useEffect(() => {\n const wanted = idKey ? idKey.split(\",\") : [];\n if (wanted.length === 0) return;\n\n let active = true;\n void Promise.all(\n wanted.map((id) =>\n resolveOne(token, id).then(\n (context) => [id, context] as const,\n ),\n ),\n ).then((entries) => {\n if (active) setResolved(new Map(entries));\n });\n return () => {\n active = false;\n };\n // `nonce` is the refresh trigger: bumping it re-runs the same question.\n }, [token, idKey, nonce]);\n\n const refresh = useCallback(() => {\n for (const id of idKey ? idKey.split(\",\") : []) {\n CACHE.delete(cacheKey(token, id));\n }\n setNonce((n) => n + 1);\n }, [token, idKey]);\n\n // What we publish is DERIVED, never cleared by the effect: an answer for an id\n // the page no longer shows is stale, not wrong, and clearing it with a\n // synchronous setState inside the effect is exactly the cascading-render\n // pattern React Compiler lint rejects.\n const wanted = useMemo(() => (idKey ? idKey.split(\",\") : []), [idKey]);\n const states = useMemo(() => {\n const out = new Map<string, AccessDeniedContext>();\n for (const id of wanted) {\n const context = resolved.get(id);\n if (context) out.set(id, context);\n }\n return out;\n }, [wanted, resolved]);\n\n return {\n states,\n isLoading: states.size < wanted.length,\n refresh,\n };\n}\n","/**\n * THE imperative door to \"you can't remove this: ask the owner, or hide it for me\" (2026-10-14). Any code\n * that tried to archive or delete a record the person may not remove calls `offerOwnerChoices(...)`.\n * The screen is the summon overlay `CANT_REMOVE_DIALOG` (render: `./cantRemoveDialog.render`), opened\n * through the host's overlay doors (`configureAccessUi({ overlays })`) and answered through summon's\n * one-shot request (`requestOverlay`, `@ai-matrx/summon/request`, loaded on the first ask).\n */\n\nimport { getAccessUi } from \"./env\";\nimport { isGovernedActionDenial } from \"@ai-matrx/data/access\";\nimport { fetchRemovalRights } from \"@ai-matrx/data/access\";\n\nexport interface CantRemoveRequest {\n /** Platform entity token (`web_brand`, `note`, …). */\n token: string;\n id: string;\n /** The record as a person says it (\"Kiln log\"). */\n itemName: string;\n /** The kind as a person says it (\"note\"). */\n itemLabel: string;\n action: \"archive\" | \"delete\";\n href?: string | null;\n}\n\n/** \"hidden\" when the person hid it for themselves; \"closed\" otherwise. */\nexport type CantRemoveOutcome = \"hidden\" | \"closed\";\n\n/** The overlay id a host registers with `./cantRemoveDialog.render` as its render. */\nexport const CANT_REMOVE_DIALOG = \"cantRemoveDialog\";\n\n/**\n * Open the owner-choices screen and await it: \"hidden\" when the person hid the record for themselves,\n * \"closed\" otherwise (also when the host has no overlay doors). One screen per record at a time.\n */\nexport async function requestCantRemove(request: CantRemoveRequest): Promise<CantRemoveOutcome> {\n const { requestOverlay } = await import(\"@ai-matrx/summon/request\");\n const ui = getAccessUi();\n return requestOverlay<CantRemoveRequest, CantRemoveOutcome>(CANT_REMOVE_DIALOG, request, {\n cancel: \"closed\",\n dedupeKey: `${request.token}:${request.id}`,\n open: ({ instanceId, data }) => ui.openOverlay(CANT_REMOVE_DIALOG, instanceId, data),\n close: ({ instanceId }) => ui.closeOverlay(CANT_REMOVE_DIALOG, instanceId),\n });\n}\n\n/** Thrown by a removal path that checked first and found the record isn't the person's to remove. */\nexport class RemovalNotYoursError extends Error {\n readonly token: string;\n readonly id: string;\n constructor(token: string, id: string) {\n super(\"Removing this is up to its owner.\");\n this.name = \"RemovalNotYoursError\";\n this.token = token;\n this.id = id;\n }\n}\n\n/** True for a check-first refusal or the database's governed refusal. */\nexport function isRemovalNotYours(error: unknown): boolean {\n return error instanceof RemovalNotYoursError || isGovernedActionDenial(error);\n}\n\nfunction openOnce(request: CantRemoveRequest) {\n void requestCantRemove(request);\n}\n\n/**\n * When `error` means \"not yours to remove\", open the owner-choices screen and\n * answer true (the caller shows nothing else). Otherwise answer false.\n */\nexport function offerOwnerChoices(\n error: unknown,\n request: CantRemoveRequest,\n): boolean {\n if (!isRemovalNotYours(error)) return false;\n openOnce(request);\n return true;\n}\n\n/**\n * CHECK FIRST, before any archive/delete confirm: answers true when the person\n * may remove the record (show your confirm), or opens the owner-choices screen\n * and answers false. An unreadable answer is true — the write's own refusal\n * still lands on `offerOwnerChoices`.\n */\nexport async function ensureRemovable(request: CantRemoveRequest): Promise<boolean> {\n const rights = await fetchRemovalRights(request.token, request.id).catch(() => null);\n if (rights?.canView && !rights.canRemove) {\n openOnce(request);\n return false;\n }\n return true;\n}\n"],"mappings":";;;AAwCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,E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OAAO;AAChB,SAAO;AACT;AAQA,eAAsB,gBAAgB,SAA8C;AAClF,QAAM,SAAS,MAAMA,oBAAmB,QAAQ,OAAO,QAAQ,EAAE,EAAE,MAAM,MAAM,IAAI;AACnF,MAAI,QAAQ,WAAW,CAAC,OAAO,WAAW;AACxC,aAAS,OAAO;AAChB,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["DefaultLink","AccessLink","useState","Avatar","AvatarFallback","AvatarImage","Button","jsx","jsxs","useState","Button","jsx","jsxs","useState","Button","useState","useState","getInitials","jsx","jsxs","useState","Button","Avatar","AvatarImage","AvatarFallback","headline","classifyDataError","Fragment","jsx","jsxs","headline","classifyDataError","useEffect","useState","ArrowLeft","Button","fetchAccessDeniedContext","jsx","jsxs","useState","useEffect","Button","ArrowLeft","useState","Check","Loader2","Lock","Send","Button","Fragment","jsx","jsxs","useState","Check","Lock","Button","Loader2","Send","ArrowLeft","Lock","LogIn","Button","jsx","jsxs","useState","Check","KeyRound","Loader2","Send","Button","useState","createSettingAccessRequest","useState","result","Fragment","jsx","jsxs","useState","Check","KeyRound","Button","Loader2","Send","useState","Loader2","LogIn","RefreshCw","Trash2","TriangleAlert","Button","cn","jsx","jsxs","explanation","StatusIcon","Trash2","LogIn","RefreshCw","TriangleAlert","useState","cn","Loader2","Button","useEffect","useState","getAccessEnv","Fragment","jsx","useState","useEffect","getAccessEnv","useState","Check","KeyRound","Loader2","Send","Trash2","Button","Dialog","DialogContent","DialogDescription","DialogFooter","DialogHeader","DialogTitle","createAccessRequest","useEffect","useState","getAccessEnv","Fragment","jsx","jsxs","useState","Trash2","ownerName","createAccessRequest","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","Loader2","Check","DialogFooter","Button","Send","KeyRound","useState","EyeOff","Button","Dialog","DialogContent","DialogDescription","DialogHeader","DialogTitle","Fragment","jsx","jsxs","useState","Button","EyeOff","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","EyeOff","Button","jsx","useState","Check","KeyRound","Loader2","Trash2","Button","jsx","jsxs","useState","useState","Check","CircleSlash","ExternalLink","Loader2","Button","jsx","jsxs","useState","useCallback","useEffect","useState","CircleSlash","Flag","KeyRound","Send","Undo2","cn","Button","decideAccessRequest","reportAccessRequest","withdrawAccessRequest","jsx","jsxs","Send","useState","useCallback","useEffect","KeyRound","cn","Button","CircleSlash","Flag","Undo2","useCallback","useEffect","useMemo","useState","fetchAccessDeniedContext","wanted","fetchRemovalRights"]}
1
+ {"version":3,"sources":["../src/access/react/env.tsx","../src/access/react/AccessDenied.tsx","../src/access/react/RequestAccessPanel.tsx","../src/access/react/BlindAccessAsk.tsx","../src/access/react/useAccessGate.ts","../src/access/react/AccessGate.tsx","../src/access/react/SlugAccessGate.tsx","../src/access/react/SettingAccessGate.tsx","../src/access/react/ForbiddenSurface.tsx","../src/access/react/RequestAccess.tsx","../src/access/react/useRequestAccess.ts","../src/access/react/UnresolvedEntityRef.tsx","../src/access/react/ServerReadRecheck.tsx","../src/access/react/GovernedActionDialog.tsx","../src/access/react/useHiddenByMe.ts","../src/access/react/HiddenByMeButton.tsx","../src/access/react/HiddenFilter.tsx","../src/access/react/ResourceActionRequestButtons.tsx","../src/access/react/SettingRequestActionButtons.tsx","../src/access/react/AccessRequestsSurface.tsx","../src/access/react/useAccessStates.ts","../src/access/react/cantRemoveOpener.ts"],"sourcesContent":["\"use client\";\n\n/**\n * @ai-matrx/sharing/access/react — the app inputs the access SCREENS cannot own.\n *\n * The screens import nothing from the host app (no `@/…`, no `next/*`). What a\n * screen needs from the app is injected here, ONCE at boot:\n *\n * configureAccessUi({ useLoginHref, useCurrentUser, toast, Link, … });\n *\n * (The pure half — the Supabase client, `ensureOrgId`, the CMS entity tokens —\n * is injected separately through `configureAccess` from `@ai-matrx/data/access`.)\n *\n * ONE MECHANISM: a module-level `configureAccessUi(env)` that MERGES over any\n * earlier call, plus an optional `<AccessUiProvider env>` that overrides fields\n * for one subtree (a Storybook, a test, a second host). Components read the\n * merged, defaulted result with `useAccessUi()`.\n *\n * THREE KINDS OF FIELD\n * - REQUIRED (`useLoginHref`, `useCurrentUser`, `toast`): there is no honest\n * default — a wrong sign-in link, a guessed identity or a swallowed message\n * is a lie on the screen that exists to stop lies. Reading one that was\n * never supplied THROWS an error naming `configureAccessUi` and the field.\n * - OPTIONAL WITH A WORKING DEFAULT (`Link`, `router`, `confirm`, `Textarea`,\n * `renderUserIdentity`, `renderEntityRef`, `renderErrorMenu`,\n * `navItemClasses`, `searchParam`): the screen renders its documented\n * default (a plain anchor, the browser history, the kit confirm, a plain\n * name) — never nothing.\n * - OPTIONAL APP FEATURES (`entityRegistry`, `trash`, `recordUnavailableCapture`,\n * `settingRequestActions`, `resourceActionRequests`, `cms`, `settingDoorHref`,\n * `reportFeedback`, `presentOrganizationRefusal`, `overlays`):\n * messaging / settings / cms / trash coupling the gate does not own. Absent,\n * the component renders its documented default for the absence (no door\n * link, an unrecognised-action notice, a visible \"not wired\" failure when\n * the person presses the button) — it never hides a feature.\n *\n * Hook-valued fields (`useLoginHref`, `useCurrentUser`) are called inside\n * components: they must be stable for the life of the app (set at boot).\n */\n\nimport {\n createContext,\n forwardRef,\n useContext,\n useMemo,\n type AnchorHTMLAttributes,\n type ComponentType,\n type ReactNode,\n type RefAttributes,\n} from \"react\";\nimport { Avatar, AvatarFallback, AvatarImage, Textarea } from \"@ai-matrx/design-system\";\nimport { getInitials } from \"@ai-matrx/kit/format\";\nimport { confirm as kitConfirm, type ConfirmOptions } from \"@ai-matrx/kit/confirm-opener\";\nimport type { JsonObject } from \"@ai-matrx/kit/json-format\";\nimport type { RecordUnavailableResolution } from \"@ai-matrx/data/db\";\nimport type { AccessRequestCreated } from \"@ai-matrx/data/access\";\n\n/* ─── shapes ─────────────────────────────────────────────────────────────── */\n\nexport interface AccessUiLinkProps\n extends AnchorHTMLAttributes<HTMLAnchorElement> {\n href: string;\n}\n\n/** The person using the screen. Any field may be null while the session boots. */\nexport interface AccessUiCurrentUser {\n id: string | null;\n displayName: string | null;\n email: string | null;\n}\n\nexport interface AccessUiToast {\n success(message: string): void;\n error(message: string): void;\n warning(message: string): void;\n info?(message: string): void;\n}\n\nexport interface AccessUiRouter {\n push(href: string): void;\n back(): void;\n /** Re-render the current URL from the server (Next `router.refresh()`). */\n refresh(): void;\n}\n\n/** What the gate needs to know about an entity token to link to a record. */\nexport interface AccessUiEntityInfo {\n hrefFor?: (id: string) => string | null | undefined;\n}\n\nexport interface AccessUiEntityRefProps {\n token: string;\n id: string;\n name: string;\n showIcon?: boolean;\n className?: string;\n}\n\nexport interface AccessUiUserIdentityProps {\n user: {\n id?: string | null | undefined;\n displayName?: string | null | undefined;\n avatarUrl?: string | null | undefined;\n };\n size?: \"sm\" | \"md\";\n subtitle?: boolean;\n avatarOnly?: boolean;\n}\n\nexport interface AccessUiErrorMenuProps {\n size?: \"icon\" | \"default\";\n className?: string;\n /** The error text (or error) the menu should offer to copy. */\n error?: unknown;\n /** Structured description of what failed (title, message, operation, records…). */\n input?: Record<string, unknown>;\n}\n\nexport interface AccessUiTextareaProps {\n className?: string;\n value: string;\n onChange: (event: { target: { value: string } }) => void;\n placeholder?: string;\n maxLength?: number;\n rows?: number;\n autoFocus?: boolean;\n \"aria-label\"?: string;\n}\n\n/** A setting-change action an admin completes from a request (messaging registry). */\nexport interface AccessSettingRequestAction {\n label: string;\n completedLabel: string;\n execute(payload: JsonObject, context: { organizationId: string }): Promise<void>;\n}\n\n/** A resource action (e.g. delete) an owner completes from a request. */\nexport interface AccessResourceActionRequestAction {\n label: string;\n completedLabel: string;\n confirmTitle(name: string): string;\n confirmDescription: string;\n execute(context: { resourceType: string; resourceId: string }): Promise<void>;\n}\n\nexport interface AccessUiFeedbackInput {\n feedback_type: \"request\";\n route: string;\n organization_id: string;\n description: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface AccessUiEnv {\n /* REQUIRED */\n /** The sign-in URL that returns the person to where they are. Hook-shaped. */\n useLoginHref(): string;\n /** The current person (replaces the app's redux selectors). Hook-shaped. */\n useCurrentUser(): AccessUiCurrentUser;\n /** User-visible notices. */\n toast: AccessUiToast;\n\n /* OPTIONAL, WITH A WORKING DEFAULT */\n /** Client-side navigation link. Default: a plain `<a href>` (full page load). */\n Link?: ComponentType<AccessUiLinkProps & RefAttributes<HTMLAnchorElement>>;\n /** Default: `history.back()` / `location.reload()` / `location.assign`. */\n router?: AccessUiRouter;\n /** Read one URL query parameter. Default: `window.location.search`. */\n searchParam?(name: string): string | null;\n /** Default: the kit's imperative `confirm()` (needs the design-system ConfirmDialogHost mounted). */\n confirm?(options: ConfirmOptions): Promise<boolean>;\n /** Default: the design-system `Textarea`. An app may pass its voice-enabled textarea. */\n Textarea?: ComponentType<AccessUiTextareaProps>;\n /** Default: avatar + name from the design-system Avatar. */\n renderUserIdentity?(props: AccessUiUserIdentityProps): ReactNode;\n /** Default: the plain name — NOT a door. Pass the app's EntityRef to make it one. */\n renderEntityRef?(props: AccessUiEntityRefProps): ReactNode;\n /** The error-copy menu slot. Default: renders nothing (it is a convenience, not a feature). */\n renderErrorMenu?(props: AccessUiErrorMenuProps): ReactNode;\n /** Classes of the selected / unselected inbox tab. Default: the app-shell nav CSS variables. */\n navItemClasses?: { selected: string; unselected: string };\n\n /* OPTIONAL APP FEATURES */\n /** Label/route lookup per entity token. Absent: owners and records render as plain names. */\n entityRegistry?: { tryGetEntityInfo(token: string): AccessUiEntityInfo | null };\n /** Restore from Trash. Absent: pressing Restore fails visibly naming this field. */\n trash?: { restore(token: string, id: string): Promise<void> };\n /** Reconcile the diagnostics row of a captured read. Absent: no-op. */\n recordUnavailableCapture?: {\n resolve(error: unknown, resolution: RecordUnavailableResolution): void;\n };\n /** Setting-change actions by key. Absent: requests render without the primary action button. */\n settingRequestActions?: { get(key: string): AccessSettingRequestAction | undefined };\n /** The action key the \"request access\" flows file. Default `request_access.manual`. */\n manualRequestActionKey?: string;\n /** Resource actions by key. Absent: requests render without the primary action button. */\n resourceActionRequests?: {\n get(key: string): AccessResourceActionRequestAction | undefined;\n };\n /** CMS-resolved tokens file through the host's CMS door. Absent: asking fails visibly. */\n cms?: {\n createAccessRequest(args: {\n token: string;\n resourceId: string;\n message?: string;\n currentUserId?: string | null;\n }): Promise<AccessRequestCreated>;\n };\n /** The URL of an organization setting's door. Absent: asking for a setting change fails visibly. */\n settingDoorHref?(target: {\n scope: \"organization\";\n organizationSlugOrId: string;\n controlId: string;\n }): string;\n /** File a feedback item (system-owned access requests). Absent: asking the platform team fails visibly. */\n reportFeedback?(\n input: AccessUiFeedbackInput,\n ): Promise<{ success: boolean; error?: string }>;\n /** Show \"choose an organization first\". Returns true when it handled the error. Default: false. */\n presentOrganizationRefusal?(\n error: unknown,\n options: { act: string; subject: string },\n ): boolean;\n /**\n * The host's overlay doors (AI Matrx: dispatch summon `openOverlay` / `closeOverlay` on its store). The\n * \"can't remove it\" screen is the overlay `CANT_REMOVE_DIALOG` opened through them. Absent: that screen\n * cannot open and says so on the console (the caller gets \"closed\").\n */\n overlays?: {\n open(overlayId: string, instanceId: string, data: unknown): void;\n close(overlayId: string, instanceId: string): void;\n };\n}\n\n/** The documented default for `manualRequestActionKey`. */\nexport const REQUEST_ACCESS_MANUAL_ACTION = \"request_access.manual\";\n\nconst DEFAULT_NAV_ITEM_CLASSES = {\n selected:\n \"bg-[var(--shell-nav-selected-bg)] text-[var(--shell-nav-selected-text)] shadow-[var(--shell-nav-selected-shadow)] font-semibold\",\n unselected:\n \"text-[var(--shell-nav-unselected-text)] hover:text-[var(--shell-nav-text-hover)] hover:bg-[var(--matrx-glass-bg-hover)]\",\n};\n\n/* ─── defaults ───────────────────────────────────────────────────────────── */\n\nconst DefaultLink = forwardRef<HTMLAnchorElement, AccessUiLinkProps>(\n function DefaultLink(props, ref) {\n // eslint-disable-next-line @next/next/no-html-link-for-pages -- the package has no router; the host's Link replaces this\n return <a ref={ref} {...props} />;\n },\n);\n\n/** The host's `Link`, resolved at render. Components import this as `Link`. */\nexport const AccessLink = forwardRef<HTMLAnchorElement, AccessUiLinkProps>(\n function AccessLink(props, ref) {\n const { Link } = useAccessUi();\n return <Link ref={ref} {...props} />;\n },\n);\n\nconst DEFAULT_ROUTER: AccessUiRouter = {\n push: (href) => {\n if (typeof window !== \"undefined\") window.location.assign(href);\n },\n back: () => {\n if (typeof window !== \"undefined\") window.history.back();\n },\n refresh: () => {\n if (typeof window !== \"undefined\") window.location.reload();\n },\n};\n\nfunction defaultSearchParam(name: string): string | null {\n if (typeof window === \"undefined\") return null;\n return new URLSearchParams(window.location.search).get(name);\n}\n\nfunction DefaultTextarea(props: AccessUiTextareaProps) {\n return <Textarea {...props} />;\n}\n\nfunction DefaultUserIdentity({ user, size = \"md\", avatarOnly }: AccessUiUserIdentityProps) {\n const name = user.displayName ?? \"Someone\";\n const box = size === \"sm\" ? \"h-7 w-7\" : \"h-9 w-9\";\n return (\n <span className=\"inline-flex min-w-0 items-center gap-2\">\n <Avatar className={box}>\n {user.avatarUrl ? <AvatarImage src={user.avatarUrl} alt={name} /> : null}\n <AvatarFallback className=\"text-[11px]\">{getInitials(user.displayName)}</AvatarFallback>\n </Avatar>\n {avatarOnly ? null : <span className=\"min-w-0 truncate text-sm\">{name}</span>}\n </span>\n );\n}\n\nfunction DefaultEntityRef({ name, className }: AccessUiEntityRefProps) {\n return <span className={className}>{name}</span>;\n}\n\n/* ─── configure / resolve ────────────────────────────────────────────────── */\n\nlet moduleEnv: Partial<AccessUiEnv> = {};\nlet moduleVersion = 0;\n\n/**\n * Inject the app inputs the access screens need. Call once at boot. Later\n * calls MERGE over earlier ones, so a host can configure in two steps.\n */\nexport function configureAccessUi(env: Partial<AccessUiEnv>): void {\n moduleEnv = { ...moduleEnv, ...env };\n moduleVersion += 1;\n}\n\n/** True once every REQUIRED field has been supplied. */\nexport function isAccessUiConfigured(): boolean {\n return Boolean(moduleEnv.useLoginHref && moduleEnv.useCurrentUser && moduleEnv.toast);\n}\n\n/** The resolved environment: required fields throw when missing, the rest are defaulted. */\nexport interface AccessUi {\n useLoginHref(): string;\n useCurrentUser(): AccessUiCurrentUser;\n toast: AccessUiToast;\n Link: ComponentType<AccessUiLinkProps & RefAttributes<HTMLAnchorElement>>;\n router: AccessUiRouter;\n searchParam(name: string): string | null;\n confirm(options: ConfirmOptions): Promise<boolean>;\n Textarea: ComponentType<AccessUiTextareaProps>;\n renderUserIdentity(props: AccessUiUserIdentityProps): ReactNode;\n renderEntityRef(props: AccessUiEntityRefProps): ReactNode;\n renderErrorMenu(props: AccessUiErrorMenuProps): ReactNode;\n navItemClasses: { selected: string; unselected: string };\n manualRequestActionKey: string;\n tryGetEntityInfo(token: string): AccessUiEntityInfo | null;\n restoreFromTrash(token: string, id: string): Promise<void>;\n resolveRecordUnavailableCapture(error: unknown, resolution: RecordUnavailableResolution): void;\n getSettingRequestAction(key: string): AccessSettingRequestAction | undefined;\n getResourceActionRequestAction(key: string): AccessResourceActionRequestAction | undefined;\n /** Whether the host wired the CMS door (cms.createAccessRequest). */\n createCmsAccessRequest(args: {\n token: string;\n resourceId: string;\n message?: string;\n currentUserId?: string | null;\n }): Promise<AccessRequestCreated>;\n settingDoorHref(target: {\n scope: \"organization\";\n organizationSlugOrId: string;\n controlId: string;\n }): string;\n reportFeedback(input: AccessUiFeedbackInput): Promise<{ success: boolean; error?: string }>;\n presentOrganizationRefusal(error: unknown, options: { act: string; subject: string }): boolean;\n /** Open an overlay through the host's doors; throws `notConfigured(\"overlays\")` without them. */\n openOverlay(overlayId: string, instanceId: string, data: unknown): void;\n closeOverlay(overlayId: string, instanceId: string): void;\n}\n\nfunction notConfigured(field: string): Error {\n return new Error(\n `[@ai-matrx/sharing/access/react] \\`${field}\\` was not supplied: add it to configureAccessUi({ ${field} }) once at app boot.`,\n );\n}\n\nfunction resolveAccessUi(\n base: Partial<AccessUiEnv>,\n override: Partial<AccessUiEnv> | null,\n): AccessUi {\n const env: Partial<AccessUiEnv> = { ...base, ...(override ?? {}) };\n const required = <K extends \"useLoginHref\" | \"useCurrentUser\" | \"toast\">(\n key: K,\n ): NonNullable<AccessUiEnv[K]> => {\n const value = env[key];\n if (value === undefined || value === null) throw notConfigured(key);\n return value as NonNullable<AccessUiEnv[K]>;\n };\n const ui: AccessUi = {\n // Required fields are getters so a screen that never reads one still renders.\n get useLoginHref() {\n return required(\"useLoginHref\");\n },\n get useCurrentUser() {\n return required(\"useCurrentUser\");\n },\n get toast() {\n return required(\"toast\");\n },\n Link: env.Link ?? DefaultLink,\n router: env.router ?? DEFAULT_ROUTER,\n searchParam: env.searchParam ?? defaultSearchParam,\n confirm: env.confirm ?? kitConfirm,\n Textarea: env.Textarea ?? DefaultTextarea,\n renderUserIdentity: env.renderUserIdentity ?? ((p) => <DefaultUserIdentity {...p} />),\n renderEntityRef: env.renderEntityRef ?? ((p) => <DefaultEntityRef {...p} />),\n renderErrorMenu: env.renderErrorMenu ?? (() => null),\n navItemClasses: env.navItemClasses ?? DEFAULT_NAV_ITEM_CLASSES,\n manualRequestActionKey: env.manualRequestActionKey ?? REQUEST_ACCESS_MANUAL_ACTION,\n tryGetEntityInfo: (token) => env.entityRegistry?.tryGetEntityInfo(token) ?? null,\n restoreFromTrash: async (token, id) => {\n if (!env.trash) throw notConfigured(\"trash\");\n await env.trash.restore(token, id);\n },\n resolveRecordUnavailableCapture: (error, resolution) =>\n env.recordUnavailableCapture?.resolve(error, resolution),\n getSettingRequestAction: (key) => env.settingRequestActions?.get(key),\n getResourceActionRequestAction: (key) => env.resourceActionRequests?.get(key),\n createCmsAccessRequest: async (args) => {\n if (!env.cms) throw notConfigured(\"cms\");\n return env.cms.createAccessRequest(args);\n },\n settingDoorHref: (target) => {\n if (!env.settingDoorHref) throw notConfigured(\"settingDoorHref\");\n return env.settingDoorHref(target);\n },\n reportFeedback: async (input) => {\n if (!env.reportFeedback) throw notConfigured(\"reportFeedback\");\n return env.reportFeedback(input);\n },\n presentOrganizationRefusal: (error, options) =>\n env.presentOrganizationRefusal?.(error, options) ?? false,\n openOverlay: (overlayId, instanceId, data) => {\n if (!env.overlays) throw notConfigured(\"overlays\");\n env.overlays.open(overlayId, instanceId, data);\n },\n closeOverlay: (overlayId, instanceId) => env.overlays?.close(overlayId, instanceId),\n };\n return ui;\n}\n\n/** The module-level environment, for code that is not a component (openers, stores). */\nexport function getAccessUi(): AccessUi {\n return resolveAccessUi(moduleEnv, null);\n}\n\nconst AccessUiContext = createContext<Partial<AccessUiEnv> | null>(null);\n\n/** Override fields for one subtree (tests, a second host). Merges over `configureAccessUi`. */\nexport function AccessUiProvider({\n env,\n children,\n}: {\n env: Partial<AccessUiEnv>;\n children: ReactNode;\n}) {\n return <AccessUiContext.Provider value={env}>{children}</AccessUiContext.Provider>;\n}\n\n/** The merged, defaulted environment. Stable while neither the provider value nor the configuration changes. */\nexport function useAccessUi(): AccessUi {\n const override = useContext(AccessUiContext);\n return useMemo(\n () => resolveAccessUi(moduleEnv, override),\n // `moduleVersion` is read on purpose: configuring after first render is picked up by the next mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [override, moduleVersion],\n );\n}\n","\"use client\";\n\n/**\n * AccessDenied — THE screen a user sees when they can't open something.\n *\n * One component covers every case, because the platform (not the surface) knows\n * which case it is: no access, deleted, never existed, signed out, or a\n * transient fault on something they CAN open. Before this existed, each surface\n * guessed, and the guess was usually wrong — the incident that produced this\n * feature told a signed-out user their data had been deleted.\n *\n * WHAT IT PROMISES\n * - Human words only. Never a token, a uuid, an RLS error, a schema name, or a\n * PostgREST code. The kind is a pretty label from the entity registry.\n * - A real next step, always: request access, sign in, or a door to something\n * the user CAN open. Never a Retry button that cannot succeed.\n * - A LANDING, not a cul-de-sac. A surface may hand it `suggestions` — the\n * two or three things a person in this feature actually wants when the\n * thing they clicked isn't there (\"your websites\", \"create one\"). Without\n * them the screen is technically honest and practically a dead end: it says\n * what went wrong and leaves you to find your own way back.\n * - Every identity it names is a door (THE DOOR LAW) — the owner, the\n * organization, and the nearest reachable ancestor are all reachable.\n *\n * A feature that genuinely earns its own branded version composes the exported\n * `AccessDeniedView` at its own call site; it does not fork this file.\n */\n\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport { useState } from \"react\";\nimport {\n ArrowLeft,\n Building2,\n Lock,\n LogIn,\n RefreshCw,\n RotateCcw,\n SearchX,\n Trash2,\n TriangleAlert,\n} from \"lucide-react\";\nimport { Avatar, AvatarFallback, AvatarImage } from \"@ai-matrx/design-system\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { RequestAccessPanel } from \"./RequestAccessPanel\";\nimport { BlindAccessAsk } from \"./BlindAccessAsk\";\n// THE EMERGENCY DOOR'S ONE ENTRANCE (DD-137a). It renders NOTHING unless this\n// viewer can actually get through — see the component's header. The ordinary\n// request panel above it is unchanged and stays for everyone.\nimport { useAccessGate } from \"./useAccessGate\";\nimport type {\n AccessDeniedContext,\n AccessRequestability,\n} from \"@ai-matrx/data/access\";\n// THE package initials formatter (`@ai-matrx/kit/format`, census H1\n// 2026-09-07). Recorded display decision: a multi-part name takes FIRST +\n// LAST, so \"Ana Maria Rivera\" is AR — this surface previously took first +\n// second and printed \"AM\".\nimport { getInitials } from \"@ai-matrx/kit/format\";\nimport { ErrorNotice } from \"@ai-matrx/design-system\";\nimport {\n archivedExplanation,\n archivedHeadline,\n archivedOrganizationExplanation,\n archivedOrganizationHeadline,\n mayRestoreArchived,\n} from \"@ai-matrx/data/access\";\n\n/**\n * Restore an archived record in place, through the ONE generic door\n * (`entity_undelete`, the same call /trash makes). On success the surface\n * re-reads: its own retry when it has one, otherwise a server re-render of this\n * same URL — which is what a server page's gate needs.\n */\nfunction RestoreArchived({\n token,\n id,\n kind,\n onRestored,\n}: {\n token: string;\n id: string;\n kind: string;\n onRestored: () => void;\n}) {\n const ui = useAccessUi();\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<unknown>(null);\n return (\n <>\n <Button\n icon={<RotateCcw aria-hidden />}\n variant=\"primary\"\n disabled={busy}\n onClick={async () => {\n setBusy(true);\n setFailure(null);\n try {\n await ui.restoreFromTrash(token, id);\n ui.toast.success(`Restored the ${kind}.`);\n onRestored();\n } catch (error) {\n setFailure(error);\n } finally {\n setBusy(false);\n }\n }}\n >\n {busy ? \"Restoring…\" : \"Restore\"}\n </Button>\n {failure ? (\n <ErrorNotice\n size=\"inline\"\n className=\"basis-full text-sm\"\n title=\"Not restored\"\n error={failure}\n operation={`Restore this ${kind}`}\n records={[{ type: token, id }]}\n />\n ) : null}\n </>\n );\n}\n\n/**\n * One concrete way forward, offered by the surface that knows the feature.\n * The gate cannot invent these — only the CMS knows that \"create a website\" is\n * the useful thing to offer someone whose website link went nowhere.\n */\nexport interface AccessDeniedSuggestion {\n /** Short imperative label — \"Your websites\", \"Create a website\". */\n title: string;\n /** One line on what they will get. Optional. */\n description?: string;\n /** Where it goes. Must be a route this viewer can actually open (THE DOOR LAW). */\n href: string;\n icon?: React.ComponentType<{ className?: string }>;\n}\n\nexport interface AccessDeniedProps {\n /** Canonical entity token of the thing the user tried to open. */\n token: string;\n /** Its id. */\n id: string;\n /** The original failed read, so the resolver can reconcile its capture. */\n readError?: unknown | undefined;\n /**\n * Where \"go back to what I can see\" should land when the platform can't find\n * a reachable ancestor — usually the feature's own list route.\n */\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n /** Retry the surface's own read, offered only where retrying can work. */\n onRetry?: (() => void) | undefined;\n /** Concrete next steps in THIS feature. See AccessDeniedSuggestion. */\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /**\n * Whether asking is a real option here. Defaults to `\"requestable\"` — the\n * behavior every existing caller already has. Pass `\"absolute\"` when the\n * door is closed by law and the ask itself would leak. See\n * `AccessRequestability`.\n */\n requestability?: AccessRequestability | undefined;\n /**\n * The surface's own worded reason, shown in place of the generic explanation.\n * On an `absolute` door this sentence must not confirm the record exists.\n */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /** The surface's own trailing disclosure (a reference code, an audit id). */\n footer?: React.ReactNode | undefined;\n}\n\n/** The full sentence: \"Site · AI Matrx\" or just \"Site\" when we may not say. */\nfunction headline(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\":\n if (context.organizationArchived) return archivedOrganizationHeadline(context);\n return `You don't have access to this ${kind}`;\n case \"deleted\":\n // Archived, in Trash, restorable — never \"deleted\" (archivedWords.ts).\n return archivedHeadline(context);\n case \"missing\":\n return `We couldn't find this ${kind}`;\n case \"anonymous\":\n return `Sign in to open this ${kind}`;\n case \"ok\":\n return `We couldn't load this ${kind}`;\n default:\n return \"Something went wrong\";\n }\n}\n\nfunction explanation(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\": {\n if (context.organizationArchived) return archivedOrganizationExplanation(context);\n const owner =\n context.organization\n ? context.organization.name\n : context.owner?.displayName;\n // Only promise the panel when it will actually render. `canRequest` is\n // false for rows with neither an owner nor an org (platform catalogs),\n // where \"ask below\" pointed at nothing. (Adversarial pass, 2026-08-11.)\n if (!context.canRequest && context.request?.status !== \"pending\") {\n return owner\n ? `It belongs to ${owner}, and there's no one for us to pass a request to.`\n : `It belongs to someone else, and there's no one for us to pass a request to.`;\n }\n return owner\n ? `It belongs to ${owner}. You can ask for access below.`\n : `It belongs to someone else. You can ask for access below.`;\n }\n case \"deleted\":\n return archivedExplanation(context);\n case \"missing\":\n // THE SAME SENTENCE FOR A STRANGER AND A RANDOM ID (V24-TAILS, chair ruling 2026-09-25):\n // the resolver answers a stranger to an unshared object exactly as it answers a missing id,\n // so this page can never say which it is, whose it is, or where it lives.\n return `If someone shared a link with you, you can ask for access.`;\n case \"anonymous\":\n return `We can't tell you anything about it until we know who you are.`;\n case \"ok\":\n // The honest one nobody used to write: they DO have access.\n return `You do have access to it — something went wrong on our side. Try again.`;\n default:\n return `We couldn't work out what happened. Try again in a moment.`;\n }\n}\n\nfunction StatusIcon({ status }: { status: AccessDeniedContext[\"status\"] }) {\n const className = \"h-7 w-7 text-muted-foreground\";\n if (status === \"denied\") return <Lock className={className} aria-hidden />;\n if (status === \"deleted\") return <Trash2 className={className} aria-hidden />;\n if (status === \"missing\")\n return <SearchX className={className} aria-hidden />;\n if (status === \"anonymous\")\n return <LogIn className={className} aria-hidden />;\n return <TriangleAlert className={className} aria-hidden />;\n}\n\n/**\n * One identity — owner or organization — rendered as a door when we know the\n * viewer can walk through it, and as plain text when we don't. Rendering a\n * `<Link>` to a route this viewer cannot open (or that doesn't exist) is the\n * dead end THE DOOR LAW is about; a name with no link is honest.\n */\nfunction IdentityBlock({\n label,\n name,\n href,\n avatar,\n}: {\n label: string;\n name: string;\n href: string | null;\n avatar: React.ReactNode;\n}) {\n const body = (\n <>\n {avatar}\n <span className=\"min-w-0\">\n <span className=\"block text-[11px] uppercase tracking-wide text-muted-foreground\">\n {label}\n </span>\n <span className=\"block truncate text-foreground\">{name}</span>\n </span>\n </>\n );\n\n if (!href) {\n return (\n <span className=\"flex min-w-0 items-center gap-2 text-sm\">{body}</span>\n );\n }\n return (\n <Link\n href={href}\n className=\"flex min-w-0 items-center gap-2 text-sm hover:underline\"\n >\n {body}\n </Link>\n );\n}\n\n/**\n * The resolved surface. Split from the loader so a bespoke variant can reuse\n * the same body with different chrome.\n */\nexport function AccessDeniedView({\n context,\n id,\n fallbackHref,\n fallbackLabel,\n onRetry,\n onChanged,\n suggestions = [],\n requestability = \"requestable\",\n reason,\n headline: headlineOverride,\n footer,\n}: {\n context: AccessDeniedContext;\n id: string;\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n onRetry?: (() => void) | undefined;\n onChanged: () => void;\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /** See `AccessRequestability`. `absolute` removes the request affordance entirely. */\n requestability?: AccessRequestability | undefined;\n /** The surface's own worded reason, in place of the generic explanation. */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /**\n * The surface's own trailing disclosure — a reference code, an audit id, the\n * things a feature earned the right to show and the frame cannot know about.\n * Rendered above the doors. Machine tokens belong in here behind a\n * `<details>`, never in the body: that rule predates this slot and outlives it.\n */\n footer?: React.ReactNode | undefined;\n}) {\n const ui = useAccessUi();\n const router = ui.router;\n const signInHref = ui.useLoginHref();\n const tryGetEntityInfo = ui.tryGetEntityInfo;\n const showOrg = Boolean(context.organization);\n const ancestor = context.ancestor;\n const ancestorInfo = ancestor ? tryGetEntityInfo(ancestor.token) : null;\n const ancestorHref = ancestorInfo?.hrefFor?.(ancestor?.id ?? \"\") ?? null;\n const selfInfo = tryGetEntityInfo(context.entity.token);\n const selfHref = selfInfo?.hrefFor?.(id) ?? null;\n\n /*\n AN ABSOLUTE DOOR SAYS LESS, ON PURPOSE.\n\n The generic headline names the KIND (\"You don't have access to this\n employee\") and the generic explanation names the OWNER and offers to pass a\n request along. On a door closed by law all three are disclosure: the kind,\n the owner, and the very offer to ask. So an absolute denial falls back to a\n headline that claims nothing, and says only what the surface chose to say.\n */\n const absolute =\n requestability === \"absolute\" && context.status === \"denied\";\n const title =\n headlineOverride?.trim() ||\n (absolute ? \"You can't open this here\" : headline(context));\n const body = reason?.trim() || (absolute ? \"\" : explanation(context));\n\n return (\n <div className=\"matrx-touch-targets flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-xl\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-border bg-muted\">\n <StatusIcon status={context.status} />\n </div>\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex items-start gap-2\">\n <h1 className=\"min-w-0 flex-1 text-xl font-semibold tracking-tight text-foreground\">\n {title}\n </h1>\n {/* What stopped the person, copyable for AI (RC-B12). It says no\n more than the page does: an absolute door and a missing/stranger\n record name no kind, owner or id. */}\n {ui.renderErrorMenu({\n size: \"icon\",\n input: {\n title,\n message: body || title,\n operation:\n absolute || context.status === \"missing\"\n ? \"Open this record\"\n : `Open this ${context.entity.label.toLowerCase()}`,\n ...(absolute || context.status === \"missing\"\n ? {}\n : { records: [{ type: context.entity.token, id }] }),\n details: { access_status: context.status },\n source: \"route-boundary\",\n },\n })}\n </div>\n\n {context.entity.title ? (\n <p className=\"mt-1 truncate text-sm text-muted-foreground\">\n {context.entity.label} &middot;{\" \"}\n <span className=\"text-foreground\">{context.entity.title}</span>\n </p>\n ) : null}\n\n {/* The surface's own sentence wins when it has one. A feature that\n knows WHY (a legal veto, a confidentiality tier) says it better\n than the generic copy — and the generic denied copy would be an\n outright lie on an absolute door, since it offers to pass along\n a request that will never be offered. */}\n {body ? (\n <p className=\"mt-2 text-sm text-muted-foreground\">{body}</p>\n ) : null}\n </div>\n </div>\n\n {/* Who has it.\n THE DOOR LAW cuts both ways here: a link the viewer cannot open is a\n worse dead end than no link. A denied viewer is, by definition,\n usually outside the owning org — so each identity is a door only when\n we know it actually opens. */}\n {!absolute && (context.owner || showOrg) ? (\n <div className=\"mt-5 flex flex-wrap items-center gap-4 rounded-lg border border-border bg-muted/30 px-4 py-3\">\n {context.owner ? (\n <IdentityBlock\n label=\"Owner\"\n name={context.owner.displayName ?? \"Someone else\"}\n href={\n context.owner.creatorHandle\n ? `/c/${context.owner.creatorHandle}`\n : null\n }\n avatar={\n <Avatar className=\"h-7 w-7\">\n {context.owner.avatarUrl ? (\n <AvatarImage\n src={context.owner.avatarUrl}\n alt={context.owner.displayName ?? \"Owner\"}\n />\n ) : null}\n <AvatarFallback className=\"text-[11px]\">\n {getInitials(context.owner.displayName)}\n </AvatarFallback>\n </Avatar>\n }\n />\n ) : null}\n\n {showOrg && context.organization ? (\n <IdentityBlock\n label=\"Organization\"\n name={context.organization.name ?? \"An organization\"}\n href={\n context.organization.viewerIsMember\n ? `/organizations/${context.organization.id}`\n : null\n }\n avatar={\n <span className=\"flex h-7 w-7 items-center justify-center rounded-full bg-background\">\n <Building2\n className=\"h-3.5 w-3.5 text-muted-foreground\"\n aria-hidden\n />\n </span>\n }\n />\n ) : null}\n </div>\n ) : null}\n\n {/* 🚨 ABSOLUTE DOORS GET NO ASK. Some refusals are dead ends by law —\n an accused person may never request the case against them, because\n the ASK ITSELF confirms the case exists. `canRequest` cannot express\n this: it only knows whether somebody exists to receive a request. */}\n {context.status === \"denied\" && !absolute && !context.organizationArchived ? (\n <div className=\"mt-4\">\n <RequestAccessPanel\n context={context}\n resourceId={id}\n href={selfHref}\n onChanged={onChanged}\n />\n </div>\n ) : null}\n\n {/* THE ONE ASK ON THE NOT-FOUND PAGE (V24-TAILS). It files for a real object and files\n nothing for a missing id, and says the same sentence either way. An absolute door\n (requestability \"absolute\") offers no ask here either. */}\n {context.status === \"missing\" && requestability !== \"absolute\" ? (\n <div className=\"mt-4\">\n <BlindAccessAsk token={context.entity.token} id={id} href={selfHref} />\n </div>\n ) : null}\n\n {/* WHERE TO GO INSTEAD. The buttons below get you OUT; these get you\n somewhere useful. A screen that only says \"back\" makes the user\n re-navigate from scratch to do the thing they came to do. */}\n {suggestions.length > 0 ? (\n <div className=\"mt-5 grid gap-2 sm:grid-cols-2\">\n {suggestions.map((s) => {\n const Icon = s.icon;\n return (\n <Link\n key={s.href + s.title}\n href={s.href}\n data-tap-target\n className=\"group flex items-start gap-3 rounded-lg border border-border bg-card px-4 py-3 transition-colors hover:border-foreground/20 hover:bg-accent\"\n >\n {Icon ? (\n <span className=\"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground group-hover:text-foreground\">\n <Icon className=\"h-4 w-4\" />\n </span>\n ) : null}\n <span className=\"min-w-0\">\n <span className=\"block text-sm font-medium text-foreground\">\n {s.title}\n </span>\n {s.description ? (\n <span className=\"mt-0.5 block text-xs leading-snug text-muted-foreground\">\n {s.description}\n </span>\n ) : null}\n </span>\n </Link>\n );\n })}\n </div>\n ) : null}\n\n {footer ? <div className=\"mt-4\">{footer}</div> : null}\n\n {/* Always a real way forward. */}\n <div className=\"mt-5 flex flex-wrap items-center gap-2\">\n {context.status === \"anonymous\" ? (\n <Button asChild icon={<LogIn aria-hidden />} variant=\"primary\">\n <Link href={signInHref} data-tap-target>\n Sign in\n </Link>\n </Button>\n ) : null}\n\n {mayRestoreArchived(context) ? (\n <RestoreArchived\n token={context.entity.token}\n id={id}\n kind={context.entity.label.toLowerCase()}\n onRestored={() => {\n onChanged();\n if (onRetry) onRetry();\n else router.refresh();\n }}\n />\n ) : null}\n\n {(context.status === \"ok\" || context.status === \"error\") &&\n onRetry ? (\n <Button icon={<RefreshCw aria-hidden />} variant=\"primary\" onClick={onRetry}>\n Try again\n </Button>\n ) : null}\n\n {ancestor && ancestorHref ? (\n <Button asChild icon={<ArrowLeft aria-hidden />} variant=\"outline\">\n <Link href={ancestorHref} data-tap-target>\n Open {ancestor.title ?? ancestor.label.toLowerCase()}\n </Link>\n </Button>\n ) : fallbackHref ? (\n <Button asChild icon={<ArrowLeft aria-hidden />} variant=\"outline\">\n <Link href={fallbackHref} data-tap-target>\n {fallbackLabel ?? \"Back to what you can see\"}\n </Link>\n </Button>\n ) : (\n <Button icon={<ArrowLeft aria-hidden />} variant=\"outline\" onClick={() => router.back()}>\n Go back\n </Button>\n )}\n </div>\n </div>\n </div>\n );\n}\n\n/**\n * The loader. Resolves why the record couldn't be opened, then renders it.\n *\n * A feature that genuinely earns a bespoke screen composes `AccessDeniedView`\n * (exported above) at its own call site — it does NOT register a variant here.\n * A token→component registry consulted during render is a dynamic component\n * boundary (react-hooks/static-components) for an extension point that has\n * exactly zero users, which is the speculative abstraction docs/reuse-first\n * bans. Passing your own component down is simpler and has no such hazard.\n */\nexport function AccessDenied({\n token,\n id,\n readError,\n fallbackHref,\n fallbackLabel,\n onRetry,\n suggestions,\n requestability,\n reason,\n headline,\n footer,\n}: AccessDeniedProps) {\n const { context, isLoading, refresh } = useAccessGate(token, id, {\n readError,\n });\n\n if (isLoading || !context) {\n // Deliberately quiet: this renders in a failure path that usually resolves\n // in well under a second, and a spinner-with-copy here would flash.\n return (\n <div className=\"flex h-full min-h-64 items-center justify-center p-6\">\n <div className=\"h-8 w-8 animate-pulse rounded-full bg-muted\" />\n </div>\n );\n }\n\n return (\n <AccessDeniedView\n context={context}\n id={id}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n onRetry={onRetry}\n onChanged={refresh}\n suggestions={suggestions}\n requestability={requestability}\n reason={reason}\n headline={headline}\n footer={footer}\n />\n );\n}\n","\"use client\";\n\n/**\n * RequestAccessPanel — the ask, and everything that happens after it.\n *\n * Three states in one place, because they are the same conversation:\n * ask → level choice + an optional note + Send\n * pending → who it went to, and a way to take it back\n * answered → what they said\n *\n * Deliberately NOT a dialog. The user is already stuck on a wall; making them\n * open a modal to knock on the door adds a step to the worst moment in the app.\n */\n\nimport { useState } from \"react\";\nimport { Check, Loader2, Send, Undo2 } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { useAccessUi } from \"./env\";\nimport { getAccessEnv } from \"@ai-matrx/data/access\";\nimport {\n createAccessRequest,\n withdrawAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type {\n AccessDeniedContext,\n RequestedLevel,\n} from \"@ai-matrx/data/access\";\n\ninterface RequestAccessPanelProps {\n context: AccessDeniedContext;\n /**\n * The record's id. It is NOT on the context — the RPC never echoes back an id\n * the caller already had, so the surface that knows it passes it through.\n */\n resourceId: string;\n /** Where the record lives, passed to the recipient's DM chip. */\n href?: string | null;\n onChanged: () => void;\n}\n\n/** \"AI Matrx Admin\", or an honest generic when the owner has no profile name. */\nfunction ownerName(context: AccessDeniedContext): string {\n return context.owner?.displayName ?? \"the owner\";\n}\n\nexport function RequestAccessPanel({\n context,\n resourceId,\n href,\n onChanged,\n}: RequestAccessPanelProps) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const currentUserId = ui.useCurrentUser().id;\n const [level, setLevel] = useState<RequestedLevel>(\"viewer\");\n const [note, setNote] = useState(\"\");\n const [busy, setBusy] = useState(false);\n /** Null until we've sent one; 0 means the row saved but nobody was reached. */\n const [delivered, setDelivered] = useState<number | null>(null);\n /** The user chose to ask again after a decline. */\n const [reasking, setReasking] = useState(false);\n\n const request = context.request;\n const kind = context.entity.label.toLowerCase();\n const cmsToken = getAccessEnv().entityTokens?.isCmsAccessGateToken(context.entity.token)\n ? context.entity.token\n : null;\n // A review cycle is decided by the organization's HR, never by whoever created it: the ask names that group.\n const hrToken = context.entity.token === \"hr_review_cycle\";\n const requestRecipientName = cmsToken\n ? (context.organization?.name ?? \"the organization’s admins\")\n : hrToken\n ? \"HR\"\n : ownerName(context);\n\n async function send() {\n setBusy(true);\n try {\n const result = cmsToken\n ? await ui.createCmsAccessRequest({\n token: cmsToken,\n resourceId,\n message: note,\n currentUserId,\n })\n : await createAccessRequest({\n resourceType: context.entity.token,\n resourceId,\n level,\n message: note,\n currentUserId,\n href: href ?? null,\n });\n if (result.blindAnswer) {\n toast.success(result.blindAnswer);\n } else if (result.already) {\n toast.success(\"You've already asked — they haven't answered yet.\");\n } else if (result.delivered === 0) {\n // The request row landed, but nobody was actually reached. Saying\n // \"sent\" here would be the same unverified claim this whole feature\n // exists to stop.\n toast.warning(\n \"Your request is saved, but we couldn't message them just now.\",\n );\n } else {\n toast.success(\n `Request sent to ${\n (hrToken ? null : result.recipients[0]?.displayName) ?? requestRecipientName\n }.`,\n );\n }\n setDelivered(result.already ? null : (result.delivered ?? null));\n onChanged();\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't send that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function withdraw() {\n if (!request) return;\n setBusy(true);\n try {\n await withdrawAccessRequest(request.id);\n toast.success(\"Request withdrawn.\");\n onChanged();\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't withdraw that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n if (request?.status === \"pending\") {\n return (\n <div className=\"rounded-lg border border-border bg-muted/40 p-4\">\n <p className=\"text-sm text-foreground\">\n <Check className=\"mr-1.5 inline h-4 w-4 text-primary\" aria-hidden />\n Waiting on {requestRecipientName}.\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {cmsToken\n ? \"Your request is saved. Once an owner adds you to the organization, this site will open.\"\n : delivered === 0\n ? \"We couldn't reach them with a message, but your request is saved and they'll see it.\"\n : \"They’ve been messaged. You’ll get a message back the moment they answer, and this page will open.\"}\n {ui.renderErrorMenu({})}\n </p>\n <Button\n className=\"mt-3\"\n icon={busy ? <Loader2 className=\"animate-spin\" aria-hidden /> : <Undo2 aria-hidden />}\n variant=\"outline\"\n disabled={busy}\n onClick={() => void withdraw()}\n >\n Withdraw request\n </Button>\n </div>\n );\n }\n\n // A declined ask used to end in \"reach out to them directly\" with no way to\n // do it — a dead end inside the No Dead Ends primitive. The database happily\n // accepts a fresh request (declined is neither pending nor reported), so the\n // door is real; it just wasn't rendered.\n if (request?.status === \"declined\" && !reasking) {\n return (\n <div className=\"rounded-lg border border-border bg-muted/40 p-4\">\n <p className=\"text-sm text-foreground\">\n {requestRecipientName} declined this request.\n </p>\n {request.decisionNote ? (\n <p className=\"mt-1 text-xs text-muted-foreground\">\n &ldquo;{request.decisionNote}&rdquo;\n </p>\n ) : null}\n <Button\n className=\"mt-3\"\n icon={<Send aria-hidden />}\n variant=\"outline\"\n onClick={() => setReasking(true)}\n >\n Ask again\n </Button>\n </div>\n );\n }\n\n if (request?.status === \"reported\" || !context.canRequest) {\n return null;\n }\n\n return (\n <div className=\"rounded-lg border border-border bg-card p-4\">\n <p className=\"text-sm font-medium text-foreground\">\n Ask {requestRecipientName} for access\n </p>\n\n {!cmsToken ? (\n <div className=\"mt-3 flex flex-wrap gap-2\">\n <LevelChoice\n active={level === \"viewer\"}\n label=\"Just to view\"\n onClick={() => setLevel(\"viewer\")}\n />\n <LevelChoice\n active={level === \"editor\"}\n label=\"To view and make changes\"\n onClick={() => setLevel(\"editor\")}\n />\n </div>\n ) : null}\n\n <ProTextarea\n className=\"mt-3 min-h-16 text-base md:text-sm\"\n placeholder={`Why you need this ${kind} (optional)`}\n value={note}\n maxLength={500}\n onChange={(event) => setNote(event.target.value)}\n />\n\n <Button\n className=\"mt-3\"\n icon={busy ? <Loader2 className=\"animate-spin\" aria-hidden /> : <Send aria-hidden />}\n variant=\"primary\"\n disabled={busy}\n onClick={() => void send()}\n >\n Request access\n </Button>\n </div>\n );\n}\n\nfunction LevelChoice({\n active,\n label,\n onClick,\n}: {\n active: boolean;\n label: string;\n onClick: () => void;\n}) {\n return (\n <button\n type=\"button\"\n aria-pressed={active}\n onClick={onClick}\n className={[\n \"whitespace-nowrap rounded-full border px-3 py-1 text-xs font-medium transition-colors\",\n active\n ? \"border-primary bg-primary/10 text-primary-ink\"\n : \"border-border bg-background text-muted-foreground hover:bg-accent\",\n ].join(\" \")}\n >\n {label}\n </button>\n );\n}\n","\"use client\";\n\n/**\n * BlindAccessAsk — the one \"Ask for access\" on the not-found page (lane V24-TAILS, chair ruling\n * 2026-09-25).\n *\n * A stranger who opens an unshared object and a person who opens a random id see the SAME page:\n * \"We couldn't find this <kind>. If someone shared a link with you, you can ask for access.\" and\n * this one control. Pressing it calls `public.access_request_blind`, which files the ordinary\n * request (the owner's /user-settings/access-requests inbox and an in-app notice) for a real object and\n * nothing for a missing one. The asker is told the same sentence either way and never who owns it.\n */\n\nimport { useState } from \"react\";\nimport { KeyRound } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { askForAccessBlind, BLIND_ASK_ANSWER } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\n\nexport function BlindAccessAsk({\n token,\n id,\n href,\n}: {\n token: string;\n id: string;\n href?: string | null;\n}) {\n const ui = useAccessUi();\n const [state, setState] = useState<\n { kind: \"idle\" } | { kind: \"asking\" } | { kind: \"asked\"; says: string } | { kind: \"failed\"; why: string }\n >({ kind: \"idle\" });\n\n if (state.kind === \"asked\") {\n return (\n <p className=\"text-sm text-foreground\" role=\"status\" data-blind-ask=\"asked\">\n {state.says || BLIND_ASK_ANSWER}\n </p>\n );\n }\n\n return (\n <div className=\"flex flex-col items-start gap-2\" data-blind-ask={state.kind}>\n <Button\n icon={<KeyRound aria-hidden />}\n variant=\"primary\"\n disabled={state.kind === \"asking\"}\n aria-busy={state.kind === \"asking\"}\n onClick={() => {\n setState({ kind: \"asking\" });\n void askForAccessBlind({\n resourceType: token,\n resourceId: id,\n href: href ?? (typeof window !== \"undefined\" ? window.location.pathname : null),\n }).then(\n (says) => setState({ kind: \"asked\", says }),\n (e: unknown) =>\n setState({\n kind: \"failed\",\n why: e instanceof Error ? e.message : \"We could not send that just now.\",\n }),\n );\n }}\n data-tap-target\n >\n {state.kind === \"asking\" ? \"Asking…\" : \"Ask for access\"}\n </Button>\n {state.kind === \"failed\" ? (\n <p className=\"text-xs text-destructive\" role=\"alert\">\n {state.why} Try again.\n {ui.renderErrorMenu({ className: \"ml-auto\" })}\n </p>\n ) : null}\n </div>\n );\n}\n","\"use client\";\n\n/**\n * useAccessGate — one hook, one honest answer.\n *\n * A surface whose read came back empty calls this with the entity it was trying\n * to open, and gets back the ONE status it should branch on: `denied`,\n * `deleted`, `missing`, `anonymous`, `ok` (the read failed for some other\n * reason), or `error`. No surface has to know about RLS, PostgREST codes, or\n * the four different meanings of a null row.\n *\n * `ok` is the one people forget: it means the caller CAN open the record, so\n * whatever failed was transient. Rendering a denial there would be a fresh lie.\n */\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport { fetchAccessDeniedContext } from \"@ai-matrx/data/access\";\nimport { classifyDataError } from \"@ai-matrx/data/access\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\nimport type { RecordUnavailableResolution } from \"@ai-matrx/data/db\";\nimport { useAccessUi } from \"./env\";\n\nexport interface UseAccessGateResult {\n context: AccessDeniedContext | null;\n status: AccessDeniedContext[\"status\"] | \"loading\";\n isLoading: boolean;\n /** Re-resolve — used after a request is sent, granted, or withdrawn. */\n refresh: () => void;\n}\n\nexport function useAccessGate(\n token: string | null | undefined,\n id: string | null | undefined,\n options: { enabled?: boolean; readError?: unknown } = {},\n): UseAccessGateResult {\n const resolveRecordUnavailableCapture = useAccessUi().resolveRecordUnavailableCapture;\n const [nonce, setNonce] = useState(0);\n\n // ONE key identifies \"which question is currently being asked\". Both the\n // freshness check and the loading state derive from it, so the effect never\n // has to call setState synchronously to reset itself when the target changes\n // (that pattern cascades renders — react-hooks/set-state-in-effect).\n const enabled = options.enabled !== false && Boolean(token && id);\n const key = enabled ? `${token}:${id}:${nonce}` : null;\n\n const [resolved, setResolved] = useState<{\n key: string;\n context: AccessDeniedContext;\n } | null>(null);\n\n useEffect(() => {\n if (!key || !token || !id) return;\n\n // An answer must never be applied to a different record — the user can\n // navigate between two denied ids faster than the RPC returns.\n let active = true;\n // WHAT THE SURFACE'S OWN READ DID is half the answer, and only the surface\n // knows it. A genuine fault leaves room for \"you can open this, that was\n // transient\"; a read that returned nothing is itself an access answer and\n // must not be overruled by a level claim (V-XT-2/N2 — see `deriveStatus`).\n const read =\n classifyDataError(options.readError) === \"fault\"\n ? \"fault\"\n : \"access-question\";\n void fetchAccessDeniedContext(token, id, read).then((next) => {\n if (!active) return;\n\n // `recordUnavailable()` had to capture immediately while the read was\n // still ambiguous. Now the platform resolver knows the truth, reconcile\n // that SAME inspector row before rendering the handled state. A resolver\n // `error` deliberately does nothing: unknown access gaps stay loud.\n const resolution: RecordUnavailableResolution | null =\n next.status === \"anonymous\"\n ? \"signed-out\"\n : next.status === \"denied\" ||\n next.status === \"deleted\" ||\n next.status === \"missing\" ||\n next.status === \"ok\"\n ? next.status\n : null;\n if (resolution) {\n resolveRecordUnavailableCapture(options.readError, resolution);\n }\n setResolved({ key, context: next });\n });\n return () => {\n active = false;\n };\n }, [key, token, id, options.readError, resolveRecordUnavailableCapture]);\n\n // Stale answers are discarded by comparing keys, not by clearing state.\n const context = resolved && resolved.key === key ? resolved.context : null;\n const isLoading = key !== null && context === null;\n\n const refresh = useCallback(() => setNonce((n) => n + 1), []);\n\n return {\n context,\n status: isLoading ? \"loading\" : (context?.status ?? \"error\"),\n isLoading,\n refresh,\n };\n}\n","\"use client\";\n\n/**\n * AccessGate — the drop-in that replaces a hand-rolled \"couldn't load it\" branch.\n *\n * if (site.isError || !site.data) {\n * return <AccessGate token=\"web_site\" id={siteId} error={site.error}\n * onRetry={site.refetch} fallbackHref=\"/marketing/sites\" />;\n * }\n *\n * It decides between a REAL error (a timeout, a broken query — show the error,\n * offer retry) and an ACCESS state (denied, deleted, missing, signed out — show\n * the explanation and the way forward). Surfaces stop having to know the\n * difference, which is the whole reason they kept getting it wrong.\n *\n * 🚨 AND WHEN THE SERVER REFUSED IN WORDS, THOSE WORDS WIN. A door that\n * answered `{code, user_message}` has already said the true thing; the gate\n * prints it verbatim, discloses the code, and offers no retry — it never\n * replaces it with a sentence composed here about what it believes the\n * viewer's access to be. That substitution is V-XT-2/N2: a conversation the\n * server refused with `404 conversation_not_found` was rendered as \"You do\n * have access to it — something went wrong on our side. Try again.\"\n * (`service/serverRefusal.ts`).\n */\n\nimport {\n AccessDenied,\n type AccessDeniedSuggestion,\n} from \"./AccessDenied\";\nimport { classifyDataError } from \"@ai-matrx/data/access\";\nimport { readServerRefusal } from \"@ai-matrx/data/access\";\nimport { useAccessGate } from \"./useAccessGate\";\nimport type { AccessRequestability } from \"@ai-matrx/data/access\";\n\nexport interface AccessGateProps {\n /** Canonical entity token of the record the surface tried to open. */\n token: string;\n id: string;\n /**\n * The error the read produced, if any. A null-row read (no error at all) is\n * the common case and is exactly what this gate is for.\n */\n error?: unknown | undefined;\n onRetry?: (() => void) | undefined;\n fallbackHref?: string | undefined;\n fallbackLabel?: string | undefined;\n /**\n * Parallel failed reads hidden by this gate's early return. Each is resolved\n * independently for truthful diagnostics; none renders a second surface.\n */\n relatedReads?: ReadonlyArray<{\n token: string;\n id: string;\n error: unknown;\n }>;\n /**\n * Render this instead when the failure was a genuine fault rather than an\n * access state. Defaults to the access surface, which handles faults with an\n * honest \"something went wrong on our side\" + retry.\n */\n renderFault?: (error: unknown) => React.ReactNode;\n /**\n * Two or three concrete things to do instead, in THIS feature — \"your\n * websites\", \"create one\". Without them the gate is honest and still a dead\n * end: it says what went wrong and leaves the user to re-navigate.\n */\n suggestions?: AccessDeniedSuggestion[] | undefined;\n /**\n * `\"absolute\"` removes the request affordance entirely — for a door closed by\n * law, where the ask itself would leak. Defaults to `\"requestable\"`.\n */\n requestability?: AccessRequestability | undefined;\n /** The surface's own worded reason, in place of the generic explanation. */\n reason?: string | undefined;\n /** The surface's own headline, in place of the kind-naming generic one. */\n headline?: string | undefined;\n /** The surface's own trailing disclosure (a reference code, an audit id). */\n footer?: React.ReactNode | undefined;\n}\n\nexport function AccessGate({\n token,\n id,\n error,\n onRetry,\n fallbackHref,\n fallbackLabel,\n relatedReads = [],\n renderFault,\n suggestions,\n requestability,\n reason,\n headline,\n footer,\n}: AccessGateProps) {\n // A hard fault (network, timeout, malformed query) is not an access story.\n // Surfaces with a good error component keep using it; everyone else gets the\n // access surface, whose `ok`/`error` states already say the honest thing.\n if (error && classifyDataError(error) === \"fault\" && renderFault) {\n return <>{renderFault(error)}</>;\n }\n\n // The server's own refusal, when there was one. It outranks BOTH the generic\n // copy and a `reason` the surface composed: the door already said the true\n // thing, in words the person can report.\n const refusal = readServerRefusal(error);\n\n return (\n <>\n {relatedReads.map((read) => (\n <AccessGateCaptureResolver\n key={`${read.token}:${read.id}`}\n token={read.token}\n id={read.id}\n error={read.error}\n />\n ))}\n <AccessDenied\n token={token}\n id={id}\n readError={error}\n // A refused door is not a retry: offering one is the \"Try again\" that\n // can never succeed.\n onRetry={refusal ? undefined : onRetry}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n suggestions={suggestions}\n requestability={requestability}\n reason={refusal?.message ?? reason}\n headline={headline}\n footer={\n refusal?.code ? (\n <>\n {footer}\n <ServerRefusalCode code={refusal.code} issues={refusal.issues} />\n </>\n ) : (\n footer\n )\n }\n />\n </>\n );\n}\n\n/** Resolves diagnostics for a parallel read without rendering another gate. */\nfunction AccessGateCaptureResolver({\n token,\n id,\n error,\n}: {\n token: string;\n id: string;\n error: unknown;\n}) {\n // This hook owns both the authoritative resolver call and capture\n // reconciliation. Its visual context is deliberately consumed by the one\n // primary AccessDenied above, never by a second competing surface.\n useAccessGate(token, id, { readError: error });\n return null;\n}\n\n/**\n * The refusal's machine code, disclosed where machine tokens belong: a closed\n * `<details>` under the body, never in the sentence a person reads. It is the\n * thing that makes a refusal reportable — \"it said conversation_not_found\" is\n * actionable, \"it wouldn't open\" is not.\n */\nfunction ServerRefusalCode({\n code,\n issues,\n}: {\n code: string;\n issues: string[];\n}) {\n return (\n <details className=\"text-[11px] text-muted-foreground\">\n <summary className=\"cursor-pointer select-none\">\n What the server said\n </summary>\n <p className=\"mt-1 font-mono\">{code}</p>\n {issues.length > 0 ? (\n <ul className=\"mt-1 list-disc pl-4\">\n {issues.map((issue) => (\n <li key={issue}>{issue}</li>\n ))}\n </ul>\n ) : null}\n </details>\n );\n}\n","\"use client\";\n\n/**\n * SlugAccessGate — the canonical access gate for a SLUG-addressed page.\n *\n * `<AccessGate>` is keyed on the record's uuid, but pages like `/shapes/[kind]`,\n * `/education/learn/[...slug]`, `/podcast/[slug]` and `/applets/[slug]` address their\n * item by slug. When their read comes back empty they cannot know the uuid —\n * RLS hid the very row that would say it. `access_gate_resolve_slug` (signed-in\n * only, existence-level disclosure; see migrations/access_gate_slug_resolver.sql)\n * asks the platform, and a resolved slug gets the full gate.\n *\n * `tokens` is tried in order and the first that resolves wins — `/podcast/[slug]`\n * is an episode OR a show, resolved the same way the page does (episode first).\n *\n * PUBLIC, PUBLISH-FILTERED PAGES (`publishFiltered`). Those pages 404 a row the\n * viewer CAN read but that is not published — the owner opening their own draft,\n * or anyone on a public-visibility episode not yet released. Showing that person\n * a denial would be a lie, so the gate asks the platform whether the viewer can\n * read the row at all; if they can, the honest answer is \"not published\", said\n * plainly.\n *\n * A slug nothing resolves (or a signed-out visitor, to whom the resolver says\n * nothing) gets exactly the truth we hold — \"this address doesn't match a\n * <thing> you can open\" — never upgraded to \"doesn't exist\" or \"no permission\".\n * Same contract as OrganizationAccessGate, generalised.\n */\n\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport { useEffect, useState } from \"react\";\nimport { ArrowLeft, Link2Off } from \"lucide-react\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { AccessGate } from \"./AccessGate\";\nimport {\n fetchAccessDeniedContext,\n resolveAccessGateSlug,\n} from \"@ai-matrx/data/access\";\n\nexport interface SlugAccessGateProps {\n /** Entity tokens to try, in the page's own resolution order. */\n tokens: readonly string[];\n /** The raw route slug (already decoded by the App Router). */\n slug: string;\n /** What the thing is called in the \"didn't match\" sentence, e.g. \"shape\". */\n noun: string;\n fallbackHref: string;\n fallbackLabel: string;\n /**\n * The page also filters by publication state (not just RLS), so a miss can\n * be a row the viewer may read that simply is not published.\n */\n publishFiltered?: boolean;\n}\n\nexport function SlugAccessGate({\n tokens,\n slug,\n noun,\n fallbackHref,\n fallbackLabel,\n publishFiltered = false,\n}: SlugAccessGateProps) {\n const tokenKey = tokens.join(\"|\");\n const [resolved, setResolved] = useState<{\n key: string;\n token: string | null;\n id: string | null;\n /** The viewer can read the row: the page's miss was publication. */\n readable: boolean;\n } | null>(null);\n const key = `${tokenKey}::${slug}`;\n\n useEffect(() => {\n let active = true;\n const list = tokenKey ? tokenKey.split(\"|\") : [];\n void (async () => {\n for (const token of list) {\n const id = slug ? await resolveAccessGateSlug(token, slug) : null;\n if (!active) return;\n if (id) {\n // `fault` lets the resolver report the viewer's real level: `ok`\n // means they can read the row, so only publication hid it.\n const readable = publishFiltered\n ? (await fetchAccessDeniedContext(token, id, \"fault\")).status ===\n \"ok\"\n : false;\n if (active) setResolved({ key, token, id, readable });\n return;\n }\n }\n // An id-shaped address names the record directly: the full gate (with\n // its request-access door) answers it, never \"doesn't match\".\n if (active && list.length && isUuidShape(slug)) {\n setResolved({ key, token: list[0] ?? null, id: slug, readable: false });\n return;\n }\n if (active) setResolved({ key, token: null, id: null, readable: false });\n })();\n return () => {\n active = false;\n };\n }, [key, tokenKey, slug, publishFiltered]);\n\n // Still asking — render nothing rather than flash a \"didn't match\" claim\n // that may be about to become the full gate. Keyed so a navigation never\n // applies a stale answer to the wrong slug.\n if (!resolved || resolved.key !== key) return null;\n\n if (resolved.token && resolved.id && resolved.readable) {\n return (\n <Notice\n title={`This ${noun} isn't published`}\n body={`It exists and you can open it, but it has no public page until it's published.`}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n }\n\n if (resolved.token && resolved.id) {\n return (\n <AccessGate\n token={resolved.token}\n id={resolved.id}\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n }\n\n return (\n <Notice\n title={`This address doesn't match ${/^[aeiou]/i.test(noun) ? \"an\" : \"a\"} ${noun} you can open`}\n body=\"Check the link, or sign in with the account it was shared with.\"\n fallbackHref={fallbackHref}\n fallbackLabel={fallbackLabel}\n />\n );\n}\n\nfunction Notice({\n title,\n body,\n fallbackHref,\n fallbackLabel,\n}: {\n title: string;\n body: string;\n fallbackHref: string;\n fallbackLabel: string;\n}) {\n return (\n <div className=\"flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-lg\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-muted\">\n <Link2Off className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n </div>\n <div className=\"min-w-0 flex-1\">\n <h1 className=\"text-lg font-semibold text-foreground\">{title}</h1>\n <p className=\"mt-2 text-sm text-muted-foreground\">{body}</p>\n </div>\n </div>\n <div className=\"mt-5\">\n <Button asChild variant=\"outline\">\n <Link href={fallbackHref}>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n {fallbackLabel}\n </Link>\n </Button>\n </div>\n </div>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * SettingAccessGate — the settings variant of the existing access gate.\n * Admins see the control. Other org members see a gentle, pre-filled request\n * that lands in the same durable ledger and actionable DM system.\n */\n\nimport { useState } from \"react\";\nimport { Check, Loader2, Lock, Send } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { useAccessUi } from \"./env\";\nimport { createSettingAccessRequest } from \"@ai-matrx/data/access\";\nimport type { JsonObject } from \"@ai-matrx/kit/json-format\";\n\nexport function SettingAccessGate({\n canManage,\n organizationId,\n organizationSlugOrId,\n settingKey,\n settingLabel,\n actionKey,\n actionPayload,\n defaultMessage,\n requestReady = true,\n children,\n}: {\n canManage: boolean;\n organizationId: string;\n organizationSlugOrId: string;\n settingKey: string;\n settingLabel: string;\n actionKey: string;\n actionPayload: JsonObject;\n defaultMessage: string;\n requestReady?: boolean;\n children: React.ReactNode;\n}) {\n const ui = useAccessUi();\n const currentUserId = ui.useCurrentUser().id;\n const ProTextarea = ui.Textarea;\n const toast = ui.toast;\n const [customMessage, setCustomMessage] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [pending, setPending] = useState(false);\n const message = customMessage ?? defaultMessage;\n\n if (canManage) return <>{children}</>;\n\n async function send() {\n setBusy(true);\n try {\n const result = await createSettingAccessRequest({\n organizationId,\n settingKey,\n settingLabel,\n href: ui.settingDoorHref({\n scope: \"organization\",\n organizationSlugOrId,\n controlId: settingKey,\n }),\n actionKey,\n actionPayload,\n message,\n currentUserId,\n });\n setPending(true);\n if (result.already) {\n toast.success(\"Your request is already waiting for an admin.\");\n } else if (result.delivered === 0) {\n toast.warning(\n \"Your request is saved, but we couldn't message an admin just now.\",\n );\n } else {\n toast.success(\"Request sent to your organization admins.\");\n }\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't send that request.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <div className=\"rounded-lg border border-border bg-muted/30 p-4\">\n <div className=\"flex items-start gap-3\">\n <span className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-background\">\n {pending ? (\n <Check className=\"h-4 w-4 text-primary\" aria-hidden />\n ) : (\n <Lock className=\"h-4 w-4 text-muted-foreground\" aria-hidden />\n )}\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium text-foreground\">\n {pending\n ? \"Your request is waiting\"\n : \"An organization admin controls this setting\"}\n </p>\n <p className=\"mt-1 text-xs leading-5 text-muted-foreground\">\n {pending\n ? \"It is saved in Access requests, even if the direct message could not be delivered.\"\n : \"Tell them what you need. The request is filled with this setting and includes an action they can complete inside the message.\"}\n </p>\n </div>\n </div>\n\n {!pending ? (\n <div className=\"mt-3 space-y-2\">\n <ProTextarea\n value={message}\n onChange={(event) => setCustomMessage(event.target.value)}\n rows={3}\n maxLength={1000}\n aria-label=\"Message to organization admins\"\n />\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Send aria-hidden />\n )}\n variant=\"primary\"\n disabled={busy || !message.trim() || !requestReady}\n onClick={() => void send()}\n >\n Request this change\n </Button>\n </div>\n ) : null}\n </div>\n );\n}\n","/**\n * ForbiddenSurface — the SERVER-side face of the access gate.\n *\n * Rendered by every `forbidden.tsx` boundary, i.e. whenever a Server Component\n * calls Next's `forbidden()` (see `requireAccess(..., { forbid: true })`). It\n * says the one thing we can actually prove — you're signed in and this page\n * isn't yours to open, or you're signed out — and hands over real doors. It\n * never claims a deletion, an absence, or a wrong link.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY THIS DOESN'T NAME THE RECORD, AND WHY YOU SHOULDN'T TRY (2026-08-11)\n *\n * The obvious idea is to have `requireAccess` stash `{token, id}` somewhere\n * request-scoped right before it throws, and let this component read it back\n * and render the full `<AccessGate>` — kind, name, owner, \"Request access\".\n * It was built that way (a `React.cache()` holder) and it DOES NOT WORK, for a\n * structural reason rather than a fixable bug:\n *\n * Next renders the `forbidden.tsx` fallback EAGERLY, as part of building the\n * loader tree — BEFORE the page component runs and throws. Instrumented in\n * the browser, the order is literally GET → GET → SET. Whatever the page\n * sets, the fallback has already rendered without it.\n *\n * So no request-scoped channel of any kind (cache, ALS, module global) can\n * carry the target here; the write always loses the race, and a module global\n * would additionally risk naming one user's record to another. Do not\n * reintroduce it.\n *\n * THE PATTERN THAT WORKS: a route that wants the record-specific gate must not\n * call `forbidden()` at all — it renders `<AccessGate token id/>` itself and\n * returns it. `AccessGate` is a client component, so a Server Component can\n * return it directly; `app/(core)/pick-lists/[id]/page.tsx` is the live example.\n * ─────────────────────────────────────────────────────────────────────────────\n */\nimport { AccessLink as Link } from \"./env\";\nimport { ArrowLeft, Lock, LogIn, RotateCw } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\n\n/**\n * WHAT THE APP'S SERVER BOUNDARY READS AND HANDS DOWN. The package cannot call\n * `headers()` or the session verdict (no `next/*`, no app imports, and an async\n * Server Component cannot live in a client entry). The app's `forbidden.tsx`\n * keeps a ~10-line server wrapper: read the verdict + the stamped request path,\n * build `signInHref`, and render `<ForbiddenSurfaceView …/>`.\n */\nexport interface ForbiddenSurfaceViewProps {\n /** `unverified` = the session could not be confirmed (neither \"no access\" nor \"sign in\"). */\n state: \"authenticated\" | \"anonymous\" | \"unverified\";\n isAuthenticated: boolean;\n /** The path the person was trying to open (the app stamps it on the request). */\n pathname: string;\n search?: string;\n /** Sign-in URL that returns to `pathname`+`search`. */\n signInHref: string;\n /** Where \"Back to what you can see\" goes. Default `/dashboard`. */\n homeHref?: string;\n}\n\nexport function ForbiddenSurfaceView({\n state,\n isAuthenticated,\n pathname,\n search = \"\",\n signInHref,\n homeHref = \"/dashboard\",\n}: ForbiddenSurfaceViewProps) {\n // A boundary answers IN PLACE (a redirect would lose the page), so it reads\n // the three-state verdict. \"Could not verify\" is neither \"no access\" nor\n // \"sign in\": it gets its own sentence and a way back to the same page.\n const unverified = state === \"unverified\";\n\n return (\n <div className=\"flex h-full min-h-64 w-full items-center justify-center p-6\">\n <div className=\"w-full max-w-lg\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-muted\">\n <Lock className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n </div>\n <div className=\"min-w-0 flex-1\">\n <h1 className=\"text-lg font-semibold text-foreground\">\n {unverified\n ? \"We could not confirm who you are just now\"\n : isAuthenticated\n ? \"You don't have access to this page\"\n : \"Sign in to open this page\"}\n </h1>\n <p className=\"mt-2 text-sm text-muted-foreground\">\n {unverified\n ? \"You have not been signed out. This usually clears in a few seconds — open the page again.\"\n : isAuthenticated\n ? \"Your account can't open it. If someone shared it with you, ask them to share it with this account.\"\n : \"We can't tell you anything about it until we know who you are.\"}\n </p>\n </div>\n </div>\n\n <div className=\"mt-5 flex flex-wrap items-center gap-2\">\n {unverified ? (\n <Button variant=\"primary\" asChild>\n <Link href={`${pathname}${search}`}>\n <RotateCw className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Open it again\n </Link>\n </Button>\n ) : isAuthenticated ? null : (\n <Button variant=\"primary\" asChild>\n <Link href={signInHref}>\n <LogIn className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Sign in\n </Link>\n </Button>\n )}\n <Button asChild variant=\"outline\">\n <Link href={homeHref}>\n <ArrowLeft className=\"mr-1.5 h-4 w-4\" aria-hidden />\n Back to what you can see\n </Link>\n </Button>\n </div>\n </div>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * RequestAccess — the platform's answer to a control the viewer cannot use.\n *\n * Owner ruling (Arman, 2026-09-25): the control is ABSENT; where the person\n * would plausibly want it, render this instead. One line + \"Ask for access\"\n * (or a key icon where space is tight) → a compact dialog with a note box and\n * the context we already know → organization admins (access-request ledger +\n * DM) or the platform team (user feedback). See `features/access-gate/FEATURE.md`.\n */\n\nimport { useState } from \"react\";\nimport { Check, KeyRound, Loader2, Send } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { useRequestAccess } from \"./useRequestAccess\";\nimport {\n contextLines,\n type RequestAccessTarget,\n} from \"@ai-matrx/data/access\";\n\nexport type { RequestAccessTarget } from \"@ai-matrx/data/access\";\n\nexport function RequestAccess({\n target,\n variant = \"inline\",\n reason,\n className,\n}: {\n target: RequestAccessTarget;\n /** `inline` = one line + button; `icon` = key icon only (tight headers). */\n variant?: \"inline\" | \"icon\";\n /** Inline only: the one-line why. Defaults from the owner. */\n reason?: string;\n className?: string;\n}) {\n const [open, setOpen] = useState(false);\n const request = useRequestAccess(target);\n const label = `Ask for access to ${target.action.toLowerCase()}`;\n const why =\n reason ??\n (request.owner.kind === \"system\"\n ? \"Only the platform team can change this.\"\n : `Only ${request.destination} can change this.`);\n\n return (\n <>\n {variant === \"icon\" ? (\n <button\n type=\"button\"\n aria-label={label}\n title={label}\n onClick={() => setOpen(true)}\n className={cn(\n \"inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n className,\n )}\n >\n {request.sent ? (\n <Check className=\"size-3.5 text-primary\" aria-hidden=\"true\" />\n ) : (\n <KeyRound className=\"size-3.5\" aria-hidden=\"true\" />\n )}\n </button>\n ) : (\n <div\n className={cn(\n \"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground\",\n className,\n )}\n >\n <span>{request.sent ? \"Request sent.\" : why}</span>\n {request.sent ? null : (\n <Button\n icon={<KeyRound aria-hidden=\"true\" />}\n variant=\"outline\"\n onClick={() => setOpen(true)}\n >\n Ask for access\n </Button>\n )}\n </div>\n )}\n {open ? (\n <RequestAccessDialog\n target={target}\n request={request}\n onOpenChange={setOpen}\n />\n ) : null}\n </>\n );\n}\n\nfunction RequestAccessDialog({\n target,\n request,\n onOpenChange,\n}: {\n target: RequestAccessTarget;\n request: ReturnType<typeof useRequestAccess>;\n onOpenChange: (open: boolean) => void;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const [note, setNote] = useState(\"\");\n const lines = contextLines(target, request.context());\n\n async function send() {\n try {\n const result = await request.send(note);\n if (result.undelivered) toast.warning(result.message);\n else toast.success(result.message);\n onOpenChange(false);\n } catch (error: unknown) {\n // Declining the organization picker is an answer, not a failure.\n if (ui.presentOrganizationRefusal(error, { act: \"sent\", subject: \"Your request\" })) return;\n toast.error(\n error instanceof Error ? error.message : \"We couldn't send that request.\",\n );\n }\n }\n\n return (\n <Dialog open onOpenChange={onOpenChange}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>Ask for access</DialogTitle>\n <DialogDescription>Goes to {request.destination}.</DialogDescription>\n </DialogHeader>\n <dl className=\"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs\">\n {lines.map(([label, value]) => (\n <div key={label} className=\"contents\">\n <dt className=\"text-muted-foreground\">{label}</dt>\n <dd className=\"min-w-0 text-foreground [overflow-wrap:anywhere]\">\n {value}\n </dd>\n </div>\n ))}\n </dl>\n <ProTextarea\n className=\"min-h-20 text-base md:text-sm\"\n value={note}\n maxLength={1000}\n autoFocus\n placeholder=\"What do you need, and why? (optional)\"\n aria-label=\"Note\"\n onChange={(event) => setNote(event.target.value)}\n />\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n Cancel\n </Button>\n <Button icon={request.sending ? (\n <Loader2 className=\"animate-spin\" aria-hidden=\"true\" />\n ) : (\n <Send aria-hidden=\"true\" />\n )} variant=\"primary\" disabled={request.sending} onClick={() => void send()}>\n Send request\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n","\"use client\";\n\n/**\n * useRequestAccess — send a `RequestAccessTarget` ask through the system that\n * owns it (see `service/requestAccess.ts`). Organization → the access-request\n * ledger + DM to its admins; system → a user-feedback item. Nothing new stored.\n */\n\nimport { useState } from \"react\";\nimport { requireAccessEnvField } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\nimport { createSettingAccessRequest } from \"@ai-matrx/data/access\";\nimport {\n destinationLabel,\n feedbackMetadata,\n orgActionPayload,\n orgManageHref,\n orgSettingKey,\n requestBody,\n requestTitle,\n resolveRequestOwner,\n type RequestAccessTarget,\n type RequestContext,\n} from \"@ai-matrx/data/access\";\n\nexport interface RequestAccessResult {\n /** A pending ask already existed — nothing new was sent. */\n already: boolean;\n /** Sentence for the confirmation toast. */\n message: string;\n /** Warning, not success: the ask is saved but no admin was messaged. */\n undelivered: boolean;\n}\n\nexport function useRequestAccess(target: RequestAccessTarget) {\n const ui = useAccessUi();\n const { id: userId, displayName, email } = ui.useCurrentUser();\n const owner = resolveRequestOwner(target.owner);\n const [sending, setSending] = useState(false);\n const [sent, setSent] = useState(false);\n\n const context = (): RequestContext => ({\n pageUrl: typeof window === \"undefined\" ? \"\" : window.location.href,\n requesterName: displayName,\n requesterEmail: email,\n });\n\n async function send(note: string): Promise<RequestAccessResult> {\n setSending(true);\n try {\n const ctx = context();\n if (owner.kind === \"system\") {\n // The request is filed under an organization; with none selected yet, ASK and continue\n // (ensureOrganizationContext waits for boot and opens the picker) — never a refusal\n // spelled from a nullable id while boot is still resolving (check:org-three-states).\n const organizationId = await requireAccessEnvField(\"ensureOrgId\", \"useRequestAccess\")(null);\n const result = await ui.reportFeedback({\n // The feedback vocabulary's access-request type; `metadata` carries\n // the structured target (FEATURE.md, RequestAccess).\n feedback_type: \"request\",\n route: typeof window === \"undefined\" ? \"\" : window.location.pathname,\n organization_id: organizationId,\n description: `Access request: ${requestTitle(target)}\\n\\n${requestBody(target, ctx, note)}`,\n metadata: feedbackMetadata(target, ctx),\n });\n if (!result.success) {\n throw new Error(result.error ?? \"We couldn't send that request.\");\n }\n setSent(true);\n return {\n already: false,\n undelivered: false,\n message: `Request sent to ${destinationLabel(owner)}.`,\n };\n }\n\n const result = await createSettingAccessRequest({\n organizationId: owner.organizationId,\n settingKey: orgSettingKey(target),\n settingLabel: requestTitle(target),\n href: orgManageHref(target, owner),\n actionKey: ui.manualRequestActionKey,\n actionPayload: orgActionPayload(target, owner),\n message: requestBody(target, ctx, note),\n currentUserId: userId,\n });\n setSent(true);\n if (result.already) {\n return {\n already: true,\n undelivered: false,\n message: \"Your request is already waiting for an answer.\",\n };\n }\n if (result.delivered === 0) {\n return {\n already: false,\n undelivered: true,\n message:\n \"Your request is saved in Access requests, but we couldn't message an admin just now.\",\n };\n }\n return {\n already: false,\n undelivered: false,\n message: `Request sent to ${destinationLabel(owner)}.`,\n };\n } finally {\n setSending(false);\n }\n }\n\n return {\n owner,\n destination: destinationLabel(owner),\n context,\n send,\n sending,\n sent,\n };\n}\n","\"use client\";\n\n/**\n * UnresolvedEntityRef — the inline sibling of `EntityRef`.\n *\n * `EntityRef` is THE DOOR LAW for a record you CAN read: name → route, new tab,\n * peek. This is the same law for the record you cannot. A list that joins to\n * another table always has rows whose embed came back null, and every one of\n * them is ambiguous for the four reasons `features/access-gate` exists to\n * disambiguate. Printing \"(record unavailable)\" is the surface asserting a\n * cause it never checked, offering no door and no repair.\n *\n * This renders the RESOLVED state in the cell — \"No access · Steven Wax\" — and\n * puts the whole explanation plus the one-click fix one click away: the owner,\n * the organization, and the canonical `RequestAccessPanel` for a denial, the\n * destination-preserving sign-in link when the session lapsed, a real Try again\n * when the caller actually HAS access and the read merely failed.\n *\n * The caller resolves the state with `useAccessStates` (one hook for the whole\n * page) and passes it down, so the row's action menu can branch on exactly the\n * same answer instead of resolving it a second time.\n */\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Ban,\n HelpCircle,\n Loader2,\n LogIn,\n RefreshCw,\n Trash2,\n TriangleAlert,\n} from \"lucide-react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@ai-matrx/design-system\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { RequestAccessPanel } from \"./RequestAccessPanel\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\n\nexport interface UnresolvedEntityRefProps {\n /** The record's id — the resolver never echoes back an id the caller had. */\n id: string;\n /**\n * The resolved answer, or null while `useAccessStates` is still asking.\n * Never synthesize one: a guessed state is the defect this component fixes.\n */\n context: AccessDeniedContext | null;\n /** Re-resolve after the owner grants, so the row heals in place. */\n onChanged?: () => void;\n /**\n * The surface's own repair for a record it cannot resolve — \"Remove from\n * outreach list\", \"Detach\", \"Replace\". Rendered inside the popover under the\n * platform's own actions. THE DOOR LAW's third corollary: a problem you can\n * detect ships with its fix.\n */\n repairAction?: React.ReactNode;\n className?: string;\n}\n\n/** The one-line label the cell shows. Short enough for a dense table row. */\nfunction chipLabel(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n // The state has to be readable WITHOUT opening the popover — a bare name in\n // a roster reads as an ordinary row, which is the lie all over again.\n case \"denied\":\n return context.entity.title\n ? `${context.entity.title} — no access`\n : `A ${kind} you can't open`;\n case \"deleted\":\n return context.entity.title\n ? `${context.entity.title} — deleted`\n : `Deleted ${kind}`;\n case \"missing\":\n return `This ${kind} no longer exists`;\n case \"anonymous\":\n return \"Sign in to see this\";\n case \"ok\":\n return context.entity.title ?? `This ${kind} didn't load`;\n default:\n return \"Couldn't check this record\";\n }\n}\n\n/** The honest sentence, in the popover. */\nfunction explanation(context: AccessDeniedContext): string {\n const kind = context.entity.label.toLowerCase();\n switch (context.status) {\n case \"denied\":\n return `This ${kind} exists, but it isn't shared with you. You can ask for access — the row stays in the list either way.`;\n case \"deleted\":\n return `This ${kind} was moved to the trash. Whoever deleted it can restore it; until then there is nothing here to open.`;\n case \"missing\":\n return `There is no ${kind} with this id. The reference is stale.`;\n case \"anonymous\":\n return \"Your session ended, so we can't tell you anything about this record. Sign in and it will load.\";\n case \"ok\":\n return `You DO have access to this ${kind} — the read failed for some other reason. Trying again should work.`;\n default:\n return \"We couldn't work out why this didn't load. That's a fault on our side, not a permission problem.\";\n }\n}\n\nfunction StatusIcon({ status }: { status: AccessDeniedContext[\"status\"] }) {\n const className = \"h-3.5 w-3.5 shrink-0\";\n switch (status) {\n case \"denied\":\n return <Ban className={className} aria-hidden />;\n case \"deleted\":\n return <Trash2 className={className} aria-hidden />;\n case \"missing\":\n return <HelpCircle className={className} aria-hidden />;\n case \"anonymous\":\n return <LogIn className={className} aria-hidden />;\n case \"ok\":\n return <RefreshCw className={className} aria-hidden />;\n default:\n return <TriangleAlert className={className} aria-hidden />;\n }\n}\n\nexport function UnresolvedEntityRef({\n id,\n context,\n onChanged,\n repairAction,\n className,\n}: UnresolvedEntityRefProps) {\n const [open, setOpen] = useState(false);\n const signInHref = useAccessUi().useLoginHref();\n\n if (!context) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 text-sm text-muted-foreground\",\n className,\n )}\n >\n <Loader2 className=\"h-3.5 w-3.5 animate-spin\" aria-hidden />\n Checking…\n </span>\n );\n }\n\n const label = chipLabel(context);\n // A denial is expected authorization, not a fault — muted. A resolver failure\n // and a stale reference are real problems and read as warnings.\n const tone =\n context.status === \"error\" || context.status === \"missing\"\n ? \"text-amber-700 dark:text-amber-400\"\n : \"text-muted-foreground\";\n const showOrg = Boolean(context.organization);\n\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n // Inside a clickable row: this opens the explanation, not the record.\n onClick={(e) => e.stopPropagation()}\n className={cn(\n \"inline-flex min-w-0 items-center gap-1.5 rounded-md border border-dashed border-border px-1.5 py-0.5 text-sm italic transition-colors hover:bg-muted\",\n tone,\n className,\n )}\n title=\"Why can't I see this?\"\n >\n <StatusIcon status={context.status} />\n <span className=\"truncate\">{label}</span>\n </button>\n </PopoverTrigger>\n <PopoverContent\n sizing=\"content\"\n align=\"start\"\n className=\"p-3\"\n onClick={(e) => e.stopPropagation()}\n >\n <p className=\"text-sm font-medium text-foreground\">\n {context.entity.title ?? context.entity.label}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {explanation(context)}\n </p>\n\n {/* Who has it. Each identity is a door only when it actually opens —\n a denied viewer is usually outside the owning org, and a link into a\n second locked door is a worse dead end than plain text. */}\n {context.owner || showOrg ? (\n <dl className=\"mt-2 space-y-0.5 rounded-md bg-muted/50 px-2 py-1.5 text-xs\">\n {context.owner ? (\n <div className=\"flex gap-1.5\">\n <dt className=\"text-muted-foreground\">Owner</dt>\n <dd className=\"min-w-0 truncate text-foreground\">\n {context.owner.creatorHandle ? (\n <Link\n href={`/c/${context.owner.creatorHandle}`}\n className=\"underline underline-offset-2\"\n >\n {context.owner.displayName ?? \"Someone else\"}\n </Link>\n ) : (\n (context.owner.displayName ?? \"Someone else\")\n )}\n </dd>\n </div>\n ) : null}\n {showOrg && context.organization ? (\n <div className=\"flex gap-1.5\">\n <dt className=\"text-muted-foreground\">Organization</dt>\n <dd className=\"min-w-0 truncate text-foreground\">\n {context.organization.viewerIsMember ? (\n <Link\n href={`/organizations/${context.organization.id}`}\n className=\"underline underline-offset-2\"\n >\n {context.organization.name ?? \"An organization\"}\n </Link>\n ) : (\n (context.organization.name ?? \"An organization\")\n )}\n </dd>\n </div>\n ) : null}\n </dl>\n ) : null}\n\n {context.status === \"denied\" ? (\n <div className=\"mt-2\">\n <RequestAccessPanel\n context={context}\n resourceId={id}\n onChanged={() => onChanged?.()}\n />\n </div>\n ) : null}\n\n {context.status === \"anonymous\" ? (\n <Button variant=\"primary\" asChild className=\"mt-2 w-full\">\n <Link href={signInHref}>\n <LogIn className=\"mr-1.5 h-3.5 w-3.5\" aria-hidden />\n Sign in\n </Link>\n </Button>\n ) : null}\n\n {(context.status === \"ok\" || context.status === \"error\") && onChanged ? (\n <Button\n icon={<RefreshCw aria-hidden />}\n variant=\"primary\"\n className=\"mt-2 w-full\"\n onClick={() => onChanged()}\n >\n Try again\n </Button>\n ) : null}\n\n {repairAction ? <div className=\"mt-2\">{repairAction}</div> : null}\n </PopoverContent>\n </Popover>\n );\n}\n","\"use client\";\n\n/**\n * Wraps a record page's `<AccessGate>` after an EMPTY SSR read: the browser\n * re-reads the row with its own (refreshed) session first. Readable → the\n * server page re-renders once with the fresh cookie and the record opens.\n * Not readable → the gate renders and answers honestly.\n * Why: `service/serverReadRecheck.ts`.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { getClaimsUser } from \"@ai-matrx/auth/claims\";\nimport { getAccessEnv, type AccessSupabaseClient } from \"@ai-matrx/data/access\";\nimport { useAccessUi } from \"./env\";\nimport { decideServerReadRecheck } from \"@ai-matrx/data/access\";\n\ntype BrowserClient = AccessSupabaseClient;\n\n/** Row readers per canonical entity token. Add a token when a page adopts this. */\nconst ROW_READERS = {\n conversation: async (supabase: BrowserClient, id: string) => {\n const { data, error } = await supabase\n .schema(\"chat\")\n .from(\"conversation\")\n .select(\"id\")\n .eq(\"id\", id)\n .is(\"deleted_at\", null)\n .maybeSingle();\n return !error && Boolean(data);\n },\n} satisfies Record<string, (supabase: BrowserClient, id: string) => Promise<boolean>>;\n\nexport type ServerReadRecheckToken = keyof typeof ROW_READERS;\n\n/** Records this tab already re-rendered for — a second SSR miss shows the gate. */\nconst refreshedOnce = new Set<string>();\n\nexport function ServerReadRecheck({\n token,\n id,\n children,\n pending,\n}: {\n token: ServerReadRecheckToken;\n id: string;\n /** The access gate. */\n children: ReactNode;\n /** What shows while the browser re-reads. */\n pending?: ReactNode;\n}) {\n const router = useAccessUi().router;\n const key = `${token}:${id}`;\n const [showGate, setShowGate] = useState(false);\n\n useEffect(() => {\n let active = true;\n void (async () => {\n let signedIn = false;\n let rowReadable = false;\n try {\n const supabase = getAccessEnv().getClient();\n const { data } = await getClaimsUser(supabase as unknown as Parameters<typeof getClaimsUser>[0]);\n signedIn = Boolean(data.user);\n if (signedIn) rowReadable = await ROW_READERS[token](supabase, id);\n } catch (error) {\n console.error(`[ServerReadRecheck] ${key}: browser re-read failed`, error);\n }\n if (!active) return;\n const verdict = decideServerReadRecheck({\n signedIn,\n rowReadable,\n alreadyRefreshed: refreshedOnce.has(key),\n });\n if (verdict === \"refresh\") {\n console.warn(\n `[ServerReadRecheck] ${key}: the server read came back empty but this browser can read it — re-rendering with the refreshed session`,\n );\n refreshedOnce.add(key);\n router.refresh();\n return;\n }\n setShowGate(true);\n })();\n return () => {\n active = false;\n };\n }, [key, token, id, router]);\n\n return <>{showGate ? children : (pending ?? null)}</>;\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n Archive,\n Check,\n EyeOff,\n KeyRound,\n Loader2,\n Send,\n ShieldCheck,\n Trash2,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport { useAccessGate } from \"./useAccessGate\";\nimport {\n createAccessRequest,\n createDeleteRequest,\n} from \"@ai-matrx/data/access\";\nimport { useHideForMe } from \"./useHiddenByMe\";\n\n/**\n * THE screen for \"you can see this, but removing it is not yours to do\"\n * (platform primitive, 2026-10-14). Any record a person can view but may not\n * archive or delete opens this instead of a refusal: ask the owner/admins to\n * do it, ask for full access, or hide it for yourself (it leaves your lists and\n * waits in that list's Hidden view). Open it BEFORE trying the write when\n * `useRemovalRights` says `canRemove: false`, and after a governed refusal\n * (`isGovernedActionDenial`).\n */\ntype RequestChoice = \"delete\" | \"hide\" | \"full\";\n\nexport function GovernedActionDialog({\n open,\n onOpenChange,\n resourceType,\n resourceId,\n itemName,\n itemLabel = \"site\",\n href,\n action = \"delete\",\n onHidden,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n resourceType: string;\n resourceId: string;\n itemName: string;\n itemLabel?: string;\n href?: string | null;\n /** The word for the removal the person tried: \"archive\" or \"delete\". */\n action?: \"archive\" | \"delete\";\n /** Called after the person hid the item (re-read a list that narrows server-side). */\n onHidden?: () => void;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const ProTextarea = ui.Textarea;\n const currentUserId = ui.useCurrentUser().id;\n const { context, isLoading } = useAccessGate(resourceType, resourceId, {\n enabled: open,\n });\n const [choice, setChoice] = useState<RequestChoice>(\"delete\");\n const [note, setNote] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [sent, setSent] = useState<RequestChoice | null>(null);\n const { hide } = useHideForMe(resourceType);\n const verb = action === \"archive\" ? \"archive\" : \"delete\";\n const ActionIcon = action === \"archive\" ? Archive : Trash2;\n\n const ownerName =\n context?.owner?.displayName ??\n (context?.organization ? context.organization.name : null) ??\n \"the owner\";\n\n async function hideIt() {\n setBusy(true);\n try {\n await hide.mutateAsync({ id: resourceId, label: itemName });\n toast.success(`Hidden for you. Find ${itemName} under Hidden.`);\n onHidden?.();\n onOpenChange(false);\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't hide that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function sendRequest() {\n if (choice === \"hide\") return hideIt();\n setBusy(true);\n try {\n const result =\n choice === \"delete\"\n ? await createDeleteRequest({\n resourceType,\n resourceId,\n message: note,\n currentUserId,\n href: href ?? null,\n })\n : await createAccessRequest({\n resourceType,\n resourceId,\n level: \"admin\",\n message: note,\n currentUserId,\n href: href ?? null,\n });\n setSent(choice);\n if (result.blindAnswer) {\n toast.success(result.blindAnswer);\n } else if (result.already) {\n toast.success(\"Your request is already waiting for an answer.\");\n } else if (result.delivered === 0) {\n toast.warning(\n \"Your request is saved, but we couldn't message them just now.\",\n );\n } else {\n toast.success(\n `Request sent to ${result.recipients[0]?.displayName ?? ownerName}.`,\n );\n }\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't send that request.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-xl\">\n <DialogHeader>\n <div className=\"mb-2 flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10\">\n <ActionIcon className=\"h-5 w-5 text-destructive\" aria-hidden />\n </div>\n <DialogTitle>\n Ask {ownerName} to {verb} this {itemLabel}\n </DialogTitle>\n <DialogDescription>\n You can work on{\" \"}\n <span className=\"font-medium text-foreground\">{itemName}</span>, but\n removing it is up to them. Ask them, or hide it just for you.\n </DialogDescription>\n </DialogHeader>\n\n {isLoading ? (\n <div className=\"flex items-center gap-2 rounded-lg border border-border bg-muted/30 p-4 text-sm text-muted-foreground\">\n <Loader2 className=\"h-4 w-4 animate-spin\" aria-hidden />\n Finding the person who can help…\n </div>\n ) : context?.status === \"error\" || context?.status === \"anonymous\" ? (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive-ink\">\n We couldn't find the right person to contact. Try again after\n refreshing.\n {ui.renderErrorMenu({})}\n </div>\n ) : sent ? (\n <div className=\"rounded-lg border border-primary/30 bg-primary/5 p-4\">\n <p className=\"flex items-center gap-2 text-sm font-medium text-foreground\">\n <Check className=\"h-4 w-4 text-primary\" aria-hidden />\n {sent === \"delete\"\n ? action === \"archive\"\n ? \"Archive requested\"\n : \"Deletion requested\"\n : \"Full access requested\"}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n The request is saved in Access requests and sent to {ownerName} in\n Messages.\n </p>\n </div>\n ) : (\n <>\n <div className=\"grid gap-2 sm:grid-cols-3\">\n <RequestChoiceButton\n active={choice === \"delete\"}\n icon={<ActionIcon className=\"h-4 w-4\" aria-hidden />}\n title={`Ask them to ${verb} it`}\n detail=\"They approve it from your message.\"\n onClick={() => setChoice(\"delete\")}\n />\n <RequestChoiceButton\n active={choice === \"hide\"}\n icon={<EyeOff className=\"h-4 w-4\" aria-hidden />}\n title=\"Hide it for me\"\n detail=\"Only you stop seeing it; undo under Hidden.\"\n onClick={() => setChoice(\"hide\")}\n />\n <RequestChoiceButton\n active={choice === \"full\"}\n icon={<ShieldCheck className=\"h-4 w-4\" aria-hidden />}\n title=\"Request full access\"\n detail={`Then you can ${verb} it yourself.`}\n onClick={() => setChoice(\"full\")}\n />\n </div>\n {choice === \"hide\" ? null : (\n <ProTextarea\n className=\"min-h-20 text-base md:text-sm\"\n value={note}\n maxLength={500}\n placeholder=\"Add a note for the owner (optional)\"\n onChange={(event) => setNote(event.target.value)}\n />\n )}\n </>\n )}\n\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n {sent ? \"Done\" : \"Cancel\"}\n </Button>\n {!sent &&\n context?.status !== \"error\" &&\n context?.status !== \"anonymous\" ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : choice === \"hide\" ? (\n <EyeOff aria-hidden />\n ) : choice === \"delete\" ? (\n <Send aria-hidden />\n ) : (\n <KeyRound aria-hidden />\n )}\n variant=\"primary\"\n disabled={busy || isLoading}\n onClick={() => void sendRequest()}\n >\n {choice === \"hide\" ? \"Hide for me\" : \"Send request\"}\n </Button>\n ) : null}\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nfunction RequestChoiceButton({\n active,\n icon,\n title,\n detail,\n onClick,\n}: {\n active: boolean;\n icon: React.ReactNode;\n title: string;\n detail: string;\n onClick: () => void;\n}) {\n return (\n <button\n type=\"button\"\n aria-pressed={active}\n onClick={onClick}\n className={`rounded-lg border p-3 text-left transition-colors ${\n active\n ? \"border-primary bg-primary/5\"\n : \"border-border hover:bg-muted/40\"\n }`}\n >\n <span className=\"flex items-center gap-2 text-sm font-medium text-foreground\">\n {icon}\n {title}\n </span>\n <span className=\"mt-1 block text-xs text-muted-foreground\">{detail}</span>\n </button>\n );\n}\n","\"use client\";\n\n/**\n * Hooks over THE per-person hide (`features/access-gate/service/hiddenByMe.ts`).\n *\n * The hidden ids live in ONE small module store per token (no React Query): the\n * list shell (`lib/entity-list`) reads them, and it renders in hosts and tests\n * that have no query client. Hide/unhide refresh the store, so every list of\n * that kind re-renders at once.\n *\n * `useHiddenByMe(token)` — the person's hidden ids for one record type.\n * `useHiddenItems(token)` — the same, with the names they saw (for the panel).\n * `useHideForMe(token)` — hide / unhide; `onChanged` re-reads a list that\n * narrows server-side (Marketing › Brands).\n * `useRemovalRights(token, id)` — the pre-check run BEFORE an archive/delete\n * confirm (own small state — no query client needed).\n */\n\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport {\n fetchRemovalRights,\n hideForMe,\n listHiddenItems,\n unhideForMe,\n type HiddenItem,\n type RemovalRights,\n} from \"@ai-matrx/data/access\";\nimport { getAccessEnv } from \"@ai-matrx/data/access\";\n\ninterface Slot {\n items: HiddenItem[] | undefined;\n /** Stable ids array for `items` (lists memoise on it). */\n ids: string[] | undefined;\n loading: Promise<void> | null;\n /** The last read failed: the next mount retries instead of trusting []. */\n failed: boolean;\n}\n\nconst slots = new Map<string, Slot>();\nconst listeners = new Set<() => void>();\nlet version = 0;\nlet watchingAuth = false;\n\nfunction emit() {\n version += 1;\n listeners.forEach((listener) => listener());\n}\n\n/** A sign-in, sign-out or account switch empties the store: hides belong to one person. */\nfunction watchAuth() {\n if (watchingAuth || typeof window === \"undefined\") return;\n watchingAuth = true;\n try {\n getAccessEnv().getClient().auth.onAuthStateChange((event) => {\n if (event === \"SIGNED_IN\" || event === \"SIGNED_OUT\" || event === \"USER_UPDATED\") {\n slots.clear();\n emit();\n }\n });\n } catch {\n // No auth client in this host (tests): nothing to watch.\n }\n}\n\nfunction slotFor(token: string): Slot {\n let slot = slots.get(token);\n if (!slot) {\n slot = { items: undefined, ids: undefined, loading: null, failed: false };\n slots.set(token, slot);\n }\n return slot;\n}\n\nfunction settle(slot: Slot, items: HiddenItem[], failed: boolean) {\n slot.items = items;\n slot.ids = items.map((item) => item.id);\n slot.failed = failed;\n}\n\n/** (Re)read one token's hidden items into the store. Signed out → nothing is hidden. */\nexport function refreshHiddenByMe(token: string): Promise<void> {\n watchAuth();\n const slot = slotFor(token);\n const loading = (async () => {\n try {\n const { data } = await getAccessEnv().getClient().auth.getSession();\n if (!data.session) {\n settle(slot, [], true);\n return;\n }\n settle(slot, await listHiddenItems(token), false);\n } catch {\n // An unreadable answer hides nothing: the list stays whole, never wrongly short.\n settle(slot, slot.items ?? [], true);\n }\n })().finally(() => {\n slot.loading = null;\n emit();\n });\n slot.loading = loading;\n return loading;\n}\n\nfunction useHiddenSlot(token: string, enabled: boolean): Slot | undefined {\n useSyncExternalStore(\n (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n () => version,\n () => version,\n );\n const active = enabled && Boolean(token);\n const slot = active ? slotFor(token) : undefined;\n useEffect(() => {\n if (!active) return;\n const current = slotFor(token);\n if ((current.items === undefined || current.failed) && !current.loading) void refreshHiddenByMe(token);\n }, [active, token]);\n return slot;\n}\n\nexport function useHiddenByMe(token: string, enabled = true) {\n const slot = useHiddenSlot(token, enabled);\n return {\n data: slot?.ids,\n isPending: enabled && Boolean(token) && slot?.ids === undefined,\n };\n}\n\nexport function useHiddenItems(token: string, enabled = true) {\n const slot = useHiddenSlot(token, enabled);\n return { data: slot?.items, isPending: enabled && slot?.items === undefined };\n}\n\nexport function useRemovalRights(token: string, id: string | null) {\n const [nonce, setNonce] = useState(0);\n const key = id ? `${token}:${id}:${nonce}` : null;\n const [settled, setSettled] = useState<{\n key: string;\n data?: RemovalRights;\n error?: unknown;\n } | null>(null);\n\n // Always re-read on mount / target change (the old query had staleTime 0).\n useEffect(() => {\n if (!key || !id) return;\n let active = true;\n fetchRemovalRights(token, id).then(\n (data) => active && setSettled({ key, data }),\n (error: unknown) => active && setSettled({ key, error }),\n );\n return () => {\n active = false;\n };\n }, [key, token, id]);\n\n // Stale answers are discarded by comparing keys, never by clearing state.\n const current = key && settled?.key === key ? settled : null;\n const isLoading = key !== null && current === null;\n return {\n data: current?.data,\n error: current?.error,\n isLoading,\n isPending: isLoading,\n isError: current?.error !== undefined,\n refetch: () => setNonce((n) => n + 1),\n };\n}\n\ntype HideArgs = string | { id: string; label?: string | null };\n\n/** Hide / unhide for the person. `onChanged` runs after the store refreshed. */\nexport function useHideForMe(token: string, onChanged?: () => void | Promise<void>) {\n const [busy, setBusy] = useState(false);\n const run = async (work: () => Promise<void>) => {\n setBusy(true);\n try {\n await work();\n await refreshHiddenByMe(token);\n await onChanged?.();\n } finally {\n setBusy(false);\n }\n };\n return {\n hide: {\n isPending: busy,\n mutateAsync: (args: HideArgs) =>\n run(() =>\n typeof args === \"string\" ? hideForMe(token, args) : hideForMe(token, args.id, args.label),\n ),\n },\n unhide: {\n isPending: busy,\n mutateAsync: (id: string) => run(() => unhideForMe(token, id)),\n },\n };\n}\n","\"use client\";\n\n/**\n * HiddenByMeButton — the one-click \"Hidden by me\" place for ANY list\n * (2026-10-14, the archived-items law's sibling). The list shell renders it in\n * its toolbar with the list's entity token; it is absent until the person has\n * hidden something of that kind. It opens a panel naming each hidden record\n * (each one opens — no dead ends) with \"Show again\".\n *\n * Lists whose own query narrows hidden rows server-side (Marketing › Brands)\n * use `HiddenFilter` + `applyHiddenView` instead.\n */\n\nimport { useState } from \"react\";\nimport { Eye, EyeOff } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"@ai-matrx/design-system\";\nimport { useAccessUi } from \"./env\";\nimport {\n useHiddenByMe,\n useHiddenItems,\n useHideForMe,\n} from \"./useHiddenByMe\";\n\nexport function HiddenByMeButton({\n token,\n pluralLabel,\n}: {\n /** Platform entity token of the list (`note`, `transcript`, …). */\n token: string;\n /** \"notes\" — the list's own word for its records. */\n pluralLabel: string;\n}) {\n const ui = useAccessUi();\n const { toast } = ui;\n const [open, setOpen] = useState(false);\n const ids = useHiddenByMe(token);\n const items = useHiddenItems(token, open);\n const { unhide } = useHideForMe(token);\n const count = ids.data?.length ?? 0;\n if (count === 0 && !open) return null;\n\n const showAgain = async (id: string, name: string) => {\n try {\n await unhide.mutateAsync(id);\n toast.success(`${name} is back in your list`);\n if (count <= 1) setOpen(false);\n } catch (error) {\n toast.error(error instanceof Error ? error.message : \"We couldn't show that again.\");\n }\n };\n\n return (\n <>\n <Button\n type=\"button\"\n variant=\"quiet\"\n icon={<EyeOff />}\n title={`${pluralLabel} you hid`}\n onClick={() => setOpen(true)}\n >\n {`Hidden ${count}`}\n </Button>\n <Dialog open={open} onOpenChange={setOpen}>\n <DialogContent className=\"matrx-touch-targets sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>Hidden by me</DialogTitle>\n <DialogDescription>\n Only you stopped seeing these {pluralLabel}.\n </DialogDescription>\n </DialogHeader>\n <ul className=\"flex max-h-[60dvh] flex-col divide-y divide-border overflow-y-auto\">\n {(items.data ?? []).map((item) => {\n const name = item.label ?? \"Untitled\";\n return (\n <li key={item.id} className=\"flex items-center gap-2 py-2\">\n <div className=\"min-w-0 flex-1\">\n {ui.renderEntityRef({ token: item.token, id: item.id, name })}\n </div>\n <Button\n type=\"button\"\n variant=\"outline\"\n icon={<Eye />}\n disabled={unhide.isPending}\n onClick={() => void showAgain(item.id, name)}\n >\n Show again\n </Button>\n </li>\n );\n })}\n </ul>\n </DialogContent>\n </Dialog>\n </>\n );\n}\n","\"use client\";\n\n/**\n * HiddenFilter — the one-click way into a list's \"Hidden by me\" view (platform\n * primitive, 2026-10-14; sits beside `ArchiveFilter`). Absent until the person\n * has hidden something in this list, so it adds nothing to a clean list.\n */\n\nimport { EyeOff } from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport type { HiddenView } from \"@ai-matrx/data/access\";\n\nexport function HiddenFilter({\n count,\n value,\n onValueChange,\n}: {\n /** How many items of this list the person has hidden. */\n count: number;\n value: HiddenView;\n onValueChange: (value: HiddenView) => void;\n}) {\n if (count === 0 && value === \"visible\") return null;\n const showing = value === \"hidden\";\n return (\n <Button\n type=\"button\"\n variant={showing ? \"outline\" : \"quiet\"}\n icon={<EyeOff />}\n aria-pressed={showing}\n title={showing ? \"Back to the list\" : \"Items you hid\"}\n onClick={() => onValueChange(showing ? \"visible\" : \"hidden\")}\n >\n {`Hidden ${count}`}\n </Button>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Check,\n CircleSlash,\n ExternalLink,\n Flag,\n KeyRound,\n Loader2,\n Trash2,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n decideAccessRequest,\n getResourceActionRequestForDecision,\n reportAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type { AccessRequestStatus } from \"@ai-matrx/data/access\";\n\nexport function ResourceActionRequestButtons({\n requestId,\n actionKey,\n href,\n itemName,\n isOwn = false,\n compact = false,\n onDone,\n}: {\n requestId: string;\n actionKey: string;\n href?: string | null;\n itemName: string;\n isOwn?: boolean;\n compact?: boolean;\n onDone?: (status: AccessRequestStatus) => void;\n}) {\n const ui = useAccessUi();\n const { toast, confirm, getResourceActionRequestAction } = ui;\n const currentUserId = ui.useCurrentUser().id;\n const [busy, setBusy] = useState(false);\n const [done, setDone] = useState<AccessRequestStatus | null>(null);\n const action = getResourceActionRequestAction(actionKey);\n const safeHref =\n href?.startsWith(\"/\") && !href.startsWith(\"//\") ? href : null;\n const size = compact ? \"h-7 px-2 text-[11px]\" : \"h-11 sm:h-8\";\n\n if (isOwn) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-inherit\">\n <Trash2 className=\"h-3 w-3\" aria-hidden />\n Deletion requested\n </span>\n );\n }\n if (done) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-muted-foreground\">\n <Check className=\"h-3 w-3\" aria-hidden />\n {done === \"granted\"\n ? \"Completed\"\n : done === \"reported\"\n ? \"Reported\"\n : \"Declined\"}\n </span>\n );\n }\n\n async function completeAction() {\n if (!action) {\n toast.error(\"This request uses an action the app does not recognize.\");\n return;\n }\n const ok = await confirm({\n title: action.confirmTitle(itemName),\n description: action.confirmDescription,\n confirmLabel: action.label,\n variant: \"destructive\",\n });\n if (!ok) return;\n setBusy(true);\n try {\n const request = await getResourceActionRequestForDecision(requestId);\n const durableAction = getResourceActionRequestAction(\n request.resourceAction.actionKey,\n );\n if (!durableAction) {\n throw new Error(\n \"This request uses an action the app does not recognize.\",\n );\n }\n await durableAction.execute({\n resourceType: request.resourceType,\n resourceId: request.resourceId,\n });\n const result = await decideAccessRequest({\n requestId,\n decision: \"complete\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(durableAction.completedLabel);\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't complete that action.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function grantFullAccess() {\n setBusy(true);\n try {\n const result = await decideAccessRequest({\n requestId,\n decision: \"grant\",\n level: \"admin\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Full access granted.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't grant access.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function decline() {\n setBusy(true);\n try {\n const result = await decideAccessRequest({\n requestId,\n decision: \"decline\",\n currentUserId,\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Request declined.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't decline that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function report() {\n const ok = await confirm({\n title: \"Report this request?\",\n description:\n \"This ends the conversation for good. They won't be able to ask about this item again.\",\n confirmLabel: \"Report\",\n variant: \"destructive\",\n });\n if (!ok) return;\n setBusy(true);\n try {\n await reportAccessRequest(requestId);\n setDone(\"reported\");\n onDone?.(\"reported\");\n toast.success(\"Request reported.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't report that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n return (\n <div className=\"flex flex-wrap gap-2\">\n {action ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Trash2 aria-hidden />\n )}\n variant=\"primary\"\n className={size}\n disabled={busy}\n onClick={() => void completeAction()}\n >\n {action.label}\n </Button>\n ) : null}\n <Button\n icon={<KeyRound aria-hidden />}\n className={size}\n variant=\"outline\"\n disabled={busy}\n onClick={() => void grantFullAccess()}\n >\n Give full access\n </Button>\n {safeHref ? (\n <Button asChild className={size} variant=\"outline\">\n <Link href={safeHref} target=\"_blank\" rel=\"noopener noreferrer\">\n <ExternalLink className=\"h-3.5 w-3.5\" aria-hidden />\n Open item\n </Link>\n </Button>\n ) : null}\n <Button\n icon={<CircleSlash aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void decline()}\n >\n Decline\n </Button>\n <Button\n icon={<Flag aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void report()}\n >\n Report\n </Button>\n </div>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n Check,\n CircleSlash,\n ExternalLink,\n Loader2,\n Settings,\n} from \"lucide-react\";\nimport { Button } from \"@ai-matrx/design-system/controls\";\nimport {\n decideSettingAccessRequest,\n getSettingAccessRequestForDecision,\n} from \"@ai-matrx/data/access\";\nimport type { AccessRequestStatus } from \"@ai-matrx/data/access\";\n\nexport function SettingRequestActionButtons({\n requestId,\n href,\n actionKey,\n isOwn = false,\n compact = false,\n onDone,\n}: {\n requestId: string;\n href: string;\n actionKey: string;\n isOwn?: boolean;\n compact?: boolean;\n onDone?: (status: AccessRequestStatus) => void;\n}) {\n const ui = useAccessUi();\n const toast = ui.toast;\n const getSettingRequestAction = ui.getSettingRequestAction;\n const [busy, setBusy] = useState(false);\n const [done, setDone] = useState<AccessRequestStatus | null>(null);\n const action = getSettingRequestAction(actionKey);\n const safeHref = href.startsWith(\"/\") && !href.startsWith(\"//\") ? href : null;\n\n if (isOwn) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-inherit\">\n <Settings className=\"h-3 w-3\" aria-hidden />\n Setting change requested\n </span>\n );\n }\n\n if (done) {\n return (\n <span className=\"inline-flex items-center gap-1 px-2 py-0.5 text-[11px] text-muted-foreground\">\n <Check className=\"h-3 w-3\" aria-hidden />\n {done === \"granted\" ? \"Change completed\" : \"Declined\"}\n </span>\n );\n }\n\n async function apply() {\n if (!action) {\n toast.error(\"This request uses an action the app does not recognize.\");\n return;\n }\n setBusy(true);\n try {\n const request = await getSettingAccessRequestForDecision(requestId);\n const durableAction = getSettingRequestAction(\n request.settingRequest.actionKey,\n );\n if (!durableAction) {\n throw new Error(\n \"This request uses an action the app does not recognize.\",\n );\n }\n await durableAction.execute(request.settingRequest.actionPayload, {\n organizationId: request.resourceId,\n });\n const result = await decideSettingAccessRequest({\n requestId,\n decision: \"complete\",\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(durableAction.completedLabel);\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"We couldn't make that change.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n async function decline() {\n setBusy(true);\n try {\n const result = await decideSettingAccessRequest({\n requestId,\n decision: \"decline\",\n });\n setDone(result.status);\n onDone?.(result.status);\n toast.success(\"Request declined.\");\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"We couldn't decline that.\",\n );\n } finally {\n setBusy(false);\n }\n }\n\n const size = compact ? \"h-7 px-2 text-[11px]\" : \"h-11 sm:h-8\";\n return (\n <div className=\"flex flex-wrap gap-2\">\n {action ? (\n <Button\n icon={busy ? (\n <Loader2 className=\"animate-spin\" aria-hidden />\n ) : (\n <Check aria-hidden />\n )}\n variant=\"primary\"\n className={size}\n disabled={busy}\n onClick={() => void apply()}\n >\n {action.label}\n </Button>\n ) : null}\n {safeHref ? (\n <Button asChild className={size} variant=\"outline\">\n <Link href={safeHref} target=\"_blank\" rel=\"noopener noreferrer\">\n <ExternalLink className=\"h-3.5 w-3.5\" aria-hidden />\n Open setting\n </Link>\n </Button>\n ) : null}\n <Button\n icon={<CircleSlash aria-hidden />}\n className={size}\n variant=\"quiet\"\n disabled={busy}\n onClick={() => void decline()}\n >\n Decline\n </Button>\n </div>\n );\n}\n","\"use client\";\n\n/**\n * AccessRequestsSurface — the inbox for `iam.access_requests`, both directions.\n *\n * Why it exists: the request row is the durable fact and the DM is only how it\n * gets NOTICED. Until this page, the DM was the only place an ask was ever\n * visible — so a request whose delivery failed, or one filed while the sender\n * had no signed-in session to message from, became a row nobody on earth could\n * see or answer. This is the surface that makes the row reachable.\n *\n * It deliberately does NOT reimplement the decision: the same\n * `decideAccessRequest` / `reportAccessRequest` / `withdrawAccessRequest` the DM\n * chips call are called here, so grant-and-notify behaves identically in both\n * places and can never drift.\n *\n * Not built on `lib/entity-list`: that shell's contract is a server-side\n * scoped/sorted/filtered/faceted RPC over the five-scope vocabulary\n * (mine/orgs/shared/public). `access_request_list(p_box)` is a two-box,\n * unpaged, authorization-derived list — an inbox, not an entity list — and\n * satisfying the shell would mean inventing an `access_request_list_scoped`\n * family for a set that is small by construction.\n *\n * Where it lives (2026-10-01): a settings tab — `General › Access requests`,\n * `ACCESS_REQUESTS_HREF` — rendered by the ONE settings core, so the route,\n * the Preferences window and the phone drawer all show it. It therefore owns\n * no route chrome: the two boxes and Refresh sit in an inline bar, and the box\n * is local state (seeded once from `?box=sent`, which old DM links and the\n * `/settings/access-requests` redirect still carry), because pushing a URL\n * from inside the window would navigate the page out from under it. The old\n * standalone route is a config redirect in `next.config.js`.\n */\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport { AccessLink as Link, useAccessUi } from \"./env\";\nimport {\n CircleCheck,\n CircleSlash,\n Flag,\n Inbox,\n KeyRound,\n PenLine,\n Send,\n Undo2,\n} from \"lucide-react\";\nimport { Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { Button, SegmentedControl } from \"@ai-matrx/design-system/controls\";\nimport { SettingRequestActionButtons } from \"./SettingRequestActionButtons\";\nimport { ResourceActionRequestButtons } from \"./ResourceActionRequestButtons\";\nimport { RefreshCwTapButton } from \"@ai-matrx/design-system/tap-target/buttons\";\nimport { formatRelativeTime } from \"@ai-matrx/kit/format\";\nimport {\n decideAccessRequest,\n listAccessRequests,\n reportAccessRequest,\n withdrawAccessRequest,\n} from \"@ai-matrx/data/access\";\nimport type {\n AccessRequestRow,\n AccessRequestStatus,\n RequestedLevel,\n} from \"@ai-matrx/data/access\";\n\ntype Box = \"inbox\" | \"sent\";\n\n/** The one address of this inbox: the settings tab `accessRequests`. */\nexport const ACCESS_REQUESTS_HREF = \"/user-settings/access-requests\";\n\nconst STATUS_LABEL: Record<AccessRequestStatus, string> = {\n pending: \"Pending\",\n granted: \"Granted\",\n declined: \"Declined\",\n withdrawn: \"Withdrawn\",\n reported: \"Reported\",\n};\n\nconst STATUS_TONE: Record<AccessRequestStatus, string> = {\n pending: \"bg-muted text-muted-foreground\",\n granted: \"bg-primary/10 text-primary-ink\",\n declined: \"bg-muted text-muted-foreground\",\n withdrawn: \"bg-muted text-muted-foreground\",\n reported: \"bg-destructive/10 text-destructive-ink\",\n};\n\nfunction statusLabel(row: AccessRequestRow): string {\n return row.requestKind === \"resource_action\" && row.status === \"granted\"\n ? \"Completed\"\n : STATUS_LABEL[row.status];\n}\n\nfunction boxFromParam(value: string | null): Box {\n return value === \"sent\" ? \"sent\" : \"inbox\";\n}\n\n/**\n * BOTH boxes, every time. The tab the user is not standing on still has to\n * show an honest count — a badge that only becomes true once you click the tab\n * is exactly the kind of small lie this feature exists to stop.\n *\n * Module-level and state-free on purpose: the mount effect can then await it\n * and set state in the callback, instead of calling a setState-bearing helper\n * synchronously inside the effect body (React Compiler's\n * `react-hooks/set-state-in-effect`).\n */\nasync function fetchBoxes(): Promise<{\n rows: Record<Box, AccessRequestRow[]>;\n error: string | null;\n}> {\n try {\n const [inbox, sent] = await Promise.all([\n listAccessRequests(\"inbox\"),\n listAccessRequests(\"sent\"),\n ]);\n return { rows: { inbox, sent }, error: null };\n } catch (e) {\n return {\n rows: { inbox: [], sent: [] },\n error:\n e instanceof Error\n ? e.message\n : \"We couldn't load your access requests.\",\n };\n }\n}\n\n/** The record the ask is about. A door where one resolves, plain text where not. */\nfunction EntityCell({ row }: { row: AccessRequestRow }) {\n const ui = useAccessUi();\n const label = row.entityLabel ?? \"Item\";\n if (row.requestKind === \"setting\" && row.settingRequest) {\n return (\n <span className=\"flex min-w-0 items-center gap-1.5 text-sm\">\n <span className=\"shrink-0 text-xs uppercase tracking-wide text-muted-foreground\">\n Setting\n </span>\n <Link\n href={row.settingRequest.href}\n className=\"min-w-0 truncate font-medium text-primary hover:underline\"\n >\n {row.settingRequest.settingLabel}\n </Link>\n </span>\n );\n }\n if (!row.entityTitle) {\n // No title to show, and an 8-character uuid stem is not a name. Say the\n // kind and stop — never print an id the user cannot open.\n return (\n <span className=\"text-sm text-muted-foreground\">\n Untitled {label.toLowerCase()}\n </span>\n );\n }\n return (\n <span className=\"flex min-w-0 items-center gap-1.5 text-sm\">\n <span className=\"shrink-0 text-xs uppercase tracking-wide text-muted-foreground\">\n {label}\n </span>\n {/* Renders as plain text when no route resolves for this token — the\n component decides, so this surface can never invent a dead link. */}\n {ui.renderEntityRef({\n token: row.resourceType,\n id: row.resourceId,\n name: row.entityTitle,\n showIcon: false,\n className: \"min-w-0 font-medium\",\n })}\n </span>\n );\n}\n\nfunction RowShell({ children }: { children: React.ReactNode }) {\n return (\n <li className=\"rounded-lg border border-border bg-card p-3 sm:p-4\">\n {children}\n </li>\n );\n}\n\nfunction LoadingRows() {\n return (\n <ul className=\"space-y-2\">\n {[0, 1, 2].map((i) => (\n <RowShell key={i}>\n <div className=\"flex items-start gap-3\">\n <Skeleton className=\"h-8 w-8 shrink-0 rounded-full\" />\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Skeleton className=\"h-4 w-1/3\" />\n <Skeleton className=\"h-3 w-2/3\" />\n </div>\n </div>\n </RowShell>\n ))}\n </ul>\n );\n}\n\nfunction EmptyState({ box }: { box: Box }) {\n const Icon = box === \"inbox\" ? Inbox : Send;\n return (\n <div className=\"flex flex-col items-center gap-2 rounded-lg border border-dashed border-border px-6 py-12 text-center\">\n <Icon className=\"h-6 w-6 text-muted-foreground\" aria-hidden />\n <p className=\"text-sm font-medium text-foreground\">\n {box === \"inbox\"\n ? \"Nothing waiting on you\"\n : \"You haven't asked for anything\"}\n </p>\n <p className=\"max-w-sm text-xs text-muted-foreground\">\n {box === \"inbox\"\n ? \"When someone asks to open something you own, it lands here — and in your messages.\"\n : \"When you open something you don't have access to yet, you can ask the owner from there. Your request shows up here.\"}\n </p>\n </div>\n );\n}\n\nexport function AccessRequestsSurface() {\n const ui = useAccessUi();\n const { toast, confirm } = ui;\n const [box, setBox] = useState<Box>(() => boxFromParam(ui.searchParam(\"box\")));\n const currentUserId = ui.useCurrentUser().id;\n\n const [rows, setRows] = useState<Record<Box, AccessRequestRow[] | null>>({\n inbox: null,\n sent: null,\n });\n const [error, setError] = useState<string | null>(null);\n const [busyId, setBusyId] = useState<string | null>(null);\n const [refreshing, setRefreshing] = useState(false);\n\n const refresh = useCallback(async () => {\n setRefreshing(true);\n const result = await fetchBoxes();\n setRows(result.rows);\n setError(result.error);\n setRefreshing(false);\n }, []);\n\n useEffect(() => {\n let alive = true;\n void (async () => {\n const result = await fetchBoxes();\n if (!alive) return;\n setRows(result.rows);\n setError(result.error);\n })();\n return () => {\n alive = false;\n };\n }, []);\n\n const current = rows[box];\n // The inbox RPC returns ONLY pending asks I am entitled to answer, so its\n // length IS the count of things waiting on me.\n const inboxCount = rows.inbox?.length ?? 0;\n const sentPending =\n rows.sent?.filter((r) => r.status === \"pending\").length ?? 0;\n\n async function run(id: string, work: () => Promise<void>, done: string) {\n setBusyId(id);\n try {\n await work();\n toast.success(done);\n await refresh();\n } catch (e) {\n toast.error(e instanceof Error ? e.message : \"We couldn't do that.\");\n } finally {\n setBusyId(null);\n }\n }\n\n function decide(row: AccessRequestRow, level: RequestedLevel) {\n void run(\n row.id,\n async () => {\n await decideAccessRequest({\n requestId: row.id,\n decision: \"grant\",\n level,\n currentUserId,\n });\n },\n `Access granted${row.entityTitle ? ` to ${row.entityTitle}` : \"\"}.`,\n );\n }\n\n async function decline(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Decline this request?\",\n description:\n \"They'll be told you said no. They can ask again later if something changes.\",\n confirmLabel: \"Decline\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await decideAccessRequest({\n requestId: row.id,\n decision: \"decline\",\n currentUserId,\n });\n },\n \"Request declined.\",\n );\n }\n\n async function report(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Report this request?\",\n description:\n \"This ends the conversation for good — they won't be able to ask about this again.\",\n confirmLabel: \"Report\",\n variant: \"destructive\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await reportAccessRequest(row.id);\n },\n \"Reported. They can't ask about this again.\",\n );\n }\n\n async function withdraw(row: AccessRequestRow) {\n const ok = await confirm({\n title: \"Withdraw your request?\",\n description: \"The owner will no longer see it waiting for an answer.\",\n confirmLabel: \"Withdraw\",\n });\n if (!ok) return;\n void run(\n row.id,\n async () => {\n await withdrawAccessRequest(row.id);\n },\n \"Request withdrawn.\",\n );\n }\n\n const tabLabel = (target: Box, label: string) => (\n <span className=\"inline-flex items-center gap-1.5\">\n {target === \"inbox\" ? (\n <Inbox className=\"h-3.5 w-3.5\" aria-hidden />\n ) : (\n <Send className=\"h-3.5 w-3.5\" aria-hidden />\n )}\n {label}\n </span>\n );\n\n return (\n <div className=\"mx-auto w-full max-w-3xl\">\n <div className=\"mb-3 flex items-center justify-between gap-2\">\n {/* The host (settings breadcrumb, drawer header) already names the\n page on a phone; the title steps out there so the pill fits. */}\n <span className=\"hidden items-center gap-1.5 text-sm font-medium sm:inline-flex\">\n <KeyRound className=\"h-4 w-4\" aria-hidden />\n Access requests\n </span>\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n <SegmentedControl<Box>\n aria-label=\"Request box\"\n value={box}\n onValueChange={setBox}\n data={[\n { value: \"inbox\", label: tabLabel(\"inbox\", \"To me\"), count: inboxCount > 0 ? inboxCount : null },\n { value: \"sent\", label: tabLabel(\"sent\", \"I sent\"), count: sentPending > 0 ? sentPending : null },\n ]}\n />\n <RefreshCwTapButton\n ariaLabel=\"Refresh access requests\"\n disabled={refreshing}\n onClick={() => void refresh()}\n />\n </div>\n </div>\n\n <div>\n {error && (\n <div className=\"mb-3 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink\">\n {error}\n {ui.renderErrorMenu({ error })}\n </div>\n )}\n\n {/* An error is never dressed up as an empty inbox: \"nothing waiting\n on you\" when the read failed is the same class of lie this whole\n feature exists to kill. */}\n {error ? null : current === null ? (\n <LoadingRows />\n ) : current.length === 0 ? (\n <EmptyState box={box} />\n ) : (\n <ul className=\"space-y-2\">\n {current.map((row) => (\n <RowShell key={row.id}>\n <div className=\"flex min-w-0 flex-col gap-3\">\n <div className=\"flex min-w-0 flex-wrap items-start justify-between gap-2\">\n <div className=\"flex min-w-0 items-start gap-3\">\n {box === \"inbox\" && (\n ui.renderUserIdentity({\n user: {\n id: row.requester?.userId,\n displayName: row.requester?.displayName,\n avatarUrl: row.requester?.avatarUrl,\n },\n size: \"sm\",\n subtitle: false,\n avatarOnly: true,\n })\n )}\n <div className=\"min-w-0 space-y-1\">\n <p className=\"text-sm text-foreground\">\n {box === \"inbox\" ? (\n <span className=\"font-medium\">\n {row.requester?.displayName ?? \"Someone\"}\n </span>\n ) : (\n <span className=\"font-medium\">You</span>\n )}{\" \"}\n {row.requestKind === \"setting\"\n ? \"asked for a setting change\"\n : row.requestKind === \"resource_action\"\n ? \"asked you to delete\"\n : `asked to ${\n row.requestedLevel === \"admin\"\n ? \"give full access to\"\n : row.requestedLevel === \"editor\"\n ? \"edit\"\n : \"view\"\n }`}\n </p>\n <EntityCell row={row} />\n </div>\n </div>\n <div className=\"flex shrink-0 items-center gap-2\">\n {box === \"sent\" && (\n <span\n className={cn(\n \"rounded-full px-2 py-0.5 text-[11px] font-medium\",\n STATUS_TONE[row.status],\n )}\n >\n {statusLabel(row)}\n </span>\n )}\n {row.createdAt && (\n <span\n className=\"text-xs tabular-nums text-muted-foreground\"\n title={new Date(row.createdAt).toLocaleString()}\n >\n {formatRelativeTime(row.createdAt)}\n </span>\n )}\n </div>\n </div>\n\n {row.message && (\n <p className=\"whitespace-pre-line rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground [overflow-wrap:anywhere]\">\n {row.message}\n </p>\n )}\n\n {box === \"sent\" && row.decisionNote && (\n <p className=\"text-xs text-muted-foreground\">\n <span className=\"font-medium text-foreground\">\n Their note:\n </span>{\" \"}\n {row.decisionNote}\n </p>\n )}\n\n {box === \"inbox\" &&\n row.requestKind === \"resource_action\" &&\n row.resourceAction ? (\n <ResourceActionRequestButtons\n requestId={row.id}\n actionKey={row.resourceAction.actionKey}\n itemName={\n row.entityTitle ?? row.entityLabel ?? \"this item\"\n }\n onDone={() => void refresh()}\n />\n ) : box === \"inbox\" &&\n row.requestKind === \"setting\" &&\n row.settingRequest ? (\n <SettingRequestActionButtons\n requestId={row.id}\n href={row.settingRequest.href}\n actionKey={row.settingRequest.actionKey}\n onDone={() => void refresh()}\n />\n ) : box === \"inbox\" ? (\n <div className=\"flex flex-wrap gap-2\">\n <Button\n icon={<CircleCheck aria-hidden />}\n variant=\"primary\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"viewer\")}\n >\n Let them view\n </Button>\n <Button\n icon={<PenLine aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"editor\")}\n >\n Let them edit\n </Button>\n <Button\n icon={<KeyRound aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => decide(row, \"admin\")}\n >\n Give full access\n </Button>\n <Button\n icon={<CircleSlash aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => void decline(row)}\n >\n Decline\n </Button>\n <Button\n icon={<Flag aria-hidden />}\n variant=\"quiet\"\n disabled={busyId === row.id}\n onClick={() => void report(row)}\n >\n Report\n </Button>\n </div>\n ) : (\n row.status === \"pending\" && (\n <div className=\"flex flex-wrap gap-2\">\n <Button\n icon={<Undo2 aria-hidden />}\n variant=\"outline\"\n disabled={busyId === row.id}\n onClick={() => void withdraw(row)}\n >\n Withdraw\n </Button>\n </div>\n )\n )}\n </div>\n </RowShell>\n ))}\n </ul>\n )}\n </div>\n </div>\n );\n}\n\nexport default AccessRequestsSurface;\n","\"use client\";\n\n/**\n * useAccessStates — the LIST counterpart of `useAccessGate`.\n *\n * `useAccessGate` answers \"why can't I open THIS record\" for a whole page. A\n * table is the other shape of the same question: a roster joins to another\n * table, some of those embeds come back null, and every one of them is\n * ambiguous for the same four reasons (denied / deleted / missing / signed\n * out). Rendering \"(record unavailable)\" is the surface guessing — the exact\n * thing `features/access-gate` exists to stop.\n *\n * One hook resolves every unresolved id on the page at once and hands the\n * answers back as a map, so BOTH halves of the fix read the same truth:\n * - the cell renders the real state (`<UnresolvedEntityRef>`), and\n * - the row's action menu suppresses the actions that state cannot satisfy.\n *\n * Answers are cached module-wide by `token:id` because a denial does not change\n * while the user pages back and forth, and because the same party can appear in\n * several lists. `refresh()` clears the ids it owns — that is what makes the\n * \"Request access\" loop close in place once the owner grants.\n */\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { fetchAccessDeniedContext } from \"@ai-matrx/data/access\";\nimport type { AccessDeniedContext } from \"@ai-matrx/data/access\";\n\n/** Resolved answers, shared across surfaces. A denial is stable; re-asking is waste. */\nconst CACHE = new Map<string, AccessDeniedContext>();\n/** In-flight promises, so ten rows naming one party issue ONE rpc. */\nconst INFLIGHT = new Map<string, Promise<AccessDeniedContext>>();\n\nfunction cacheKey(token: string, id: string): string {\n return `${token}:${id}`;\n}\n\nfunction resolveOne(token: string, id: string): Promise<AccessDeniedContext> {\n const key = cacheKey(token, id);\n const cached = CACHE.get(key);\n if (cached) return Promise.resolve(cached);\n\n const existing = INFLIGHT.get(key);\n if (existing) return existing;\n\n // `fetchAccessDeniedContext` never throws — it degrades to `status: \"error\"`,\n // which the UI renders as a retry-able fault rather than as a denial.\n const promise = fetchAccessDeniedContext(token, id).then((context) => {\n INFLIGHT.delete(key);\n // A resolver fault is not an answer — caching it would freeze a transient\n // outage into a permanent \"we couldn't check\" for the rest of the session.\n if (context.status !== \"error\") CACHE.set(key, context);\n return context;\n });\n INFLIGHT.set(key, promise);\n return promise;\n}\n\nexport interface UseAccessStatesResult {\n /** Resolved answers by record id. An absent id is still resolving. */\n states: ReadonlyMap<string, AccessDeniedContext>;\n /** True while at least one id on this page has no answer yet. */\n isLoading: boolean;\n /** Drop the cached answers for these ids and ask again. */\n refresh: () => void;\n}\n\n/**\n * Resolve the true access state of every id in `ids` for one entity token.\n *\n * Pass ONLY the ids that actually failed to resolve. Asking about records the\n * caller can already read is a wasted round trip per row, and the resolver is\n * deliberately a per-record call.\n */\nexport function useAccessStates(\n token: string,\n ids: readonly string[],\n): UseAccessStatesResult {\n const [nonce, setNonce] = useState(0);\n const [resolved, setResolved] = useState<\n ReadonlyMap<string, AccessDeniedContext>\n >(() => new Map());\n\n // A stable identity for \"which ids are we asking about\", so the effect does\n // not re-run on every render just because the caller rebuilt the array.\n const idKey = useMemo(() => Array.from(new Set(ids)).sort().join(\",\"), [ids]);\n\n useEffect(() => {\n const wanted = idKey ? idKey.split(\",\") : [];\n if (wanted.length === 0) return;\n\n let active = true;\n void Promise.all(\n wanted.map((id) =>\n resolveOne(token, id).then(\n (context) => [id, context] as const,\n ),\n ),\n ).then((entries) => {\n if (active) setResolved(new Map(entries));\n });\n return () => {\n active = false;\n };\n // `nonce` is the refresh trigger: bumping it re-runs the same question.\n }, [token, idKey, nonce]);\n\n const refresh = useCallback(() => {\n for (const id of idKey ? idKey.split(\",\") : []) {\n CACHE.delete(cacheKey(token, id));\n }\n setNonce((n) => n + 1);\n }, [token, idKey]);\n\n // What we publish is DERIVED, never cleared by the effect: an answer for an id\n // the page no longer shows is stale, not wrong, and clearing it with a\n // synchronous setState inside the effect is exactly the cascading-render\n // pattern React Compiler lint rejects.\n const wanted = useMemo(() => (idKey ? idKey.split(\",\") : []), [idKey]);\n const states = useMemo(() => {\n const out = new Map<string, AccessDeniedContext>();\n for (const id of wanted) {\n const context = resolved.get(id);\n if (context) out.set(id, context);\n }\n return out;\n }, [wanted, resolved]);\n\n return {\n states,\n isLoading: states.size < wanted.length,\n refresh,\n };\n}\n","/**\n * THE imperative door to \"you can't remove this: ask the owner, or hide it for me\" (2026-10-14). Any code\n * that tried to archive or delete a record the person may not remove calls `offerOwnerChoices(...)`.\n * The screen is the summon overlay `CANT_REMOVE_DIALOG` (render: `./cantRemoveDialog.render`), opened\n * through the host's overlay doors (`configureAccessUi({ overlays })`) and answered through summon's\n * one-shot request (`requestOverlay`, `@ai-matrx/summon/request`, loaded on the first ask).\n */\n\nimport { getAccessUi } from \"./env\";\nimport { isGovernedActionDenial } from \"@ai-matrx/data/access\";\nimport { fetchRemovalRights } from \"@ai-matrx/data/access\";\n\nexport interface CantRemoveRequest {\n /** Platform entity token (`web_brand`, `note`, …). */\n token: string;\n id: string;\n /** The record as a person says it (\"Kiln log\"). */\n itemName: string;\n /** The kind as a person says it (\"note\"). */\n itemLabel: string;\n action: \"archive\" | \"delete\";\n href?: string | null;\n}\n\n/** \"hidden\" when the person hid it for themselves; \"closed\" otherwise. */\nexport type CantRemoveOutcome = \"hidden\" | \"closed\";\n\n/** The overlay id a host registers with `./cantRemoveDialog.render` as its render. */\nexport const CANT_REMOVE_DIALOG = \"cantRemoveDialog\";\n\n/**\n * Open the owner-choices screen and await it: \"hidden\" when the person hid the record for themselves,\n * \"closed\" otherwise (also when the host has no overlay doors). One screen per record at a time.\n */\nexport async function requestCantRemove(request: CantRemoveRequest): Promise<CantRemoveOutcome> {\n const { requestOverlay } = await import(\"@ai-matrx/summon/request\");\n const ui = getAccessUi();\n return requestOverlay<CantRemoveRequest, CantRemoveOutcome>(CANT_REMOVE_DIALOG, request, {\n cancel: \"closed\",\n dedupeKey: `${request.token}:${request.id}`,\n open: ({ instanceId, data }) => ui.openOverlay(CANT_REMOVE_DIALOG, instanceId, data),\n close: ({ instanceId }) => ui.closeOverlay(CANT_REMOVE_DIALOG, instanceId),\n });\n}\n\n/** Thrown by a removal path that checked first and found the record isn't the person's to remove. */\nexport class RemovalNotYoursError extends Error {\n readonly token: string;\n readonly id: string;\n constructor(token: string, id: string) {\n super(\"Removing this is up to its owner.\");\n this.name = \"RemovalNotYoursError\";\n this.token = token;\n this.id = id;\n }\n}\n\n/** True for a check-first refusal or the database's governed refusal. */\nexport function isRemovalNotYours(error: unknown): boolean {\n return error instanceof RemovalNotYoursError || isGovernedActionDenial(error);\n}\n\nfunction openOnce(request: CantRemoveRequest) {\n void requestCantRemove(request);\n}\n\n/**\n * When `error` means \"not yours to remove\", open the owner-choices screen and\n * answer true (the caller shows nothing else). Otherwise answer false.\n */\nexport function offerOwnerChoices(\n error: unknown,\n request: CantRemoveRequest,\n): boolean {\n if (!isRemovalNotYours(error)) return false;\n openOnce(request);\n return true;\n}\n\n/**\n * CHECK FIRST, before any archive/delete confirm: answers true when the person\n * may remove the record (show your confirm), or opens the owner-choices screen\n * and answers false. An unreadable answer is true — the write's own refusal\n * still lands on `offerOwnerChoices`.\n */\nexport async function ensureRemovable(request: CantRemoveRequest): Promise<boolean> {\n const rights = await fetchRemovalRights(request.token, request.id).catch(() => null);\n if (rights?.canView && !rights.canRemove) {\n openOnce(request);\n return false;\n }\n return true;\n}\n"],"mappings":";;;AAwCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AACP,SAAS,QAAQ,gBAAgB,aAAa,gBAAgB;AAC9D,SAAS,mBAAmB;AAC5B,SAAS,WAAW,kBAAuC;AAqMhD,cAsCL,YAtCK;AAdJ,IAAM,+BAA+B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B;AAkB5B,IAAM,qBAAqB;AAMlC,eAAsB,kBAAkB,SAAwD;AAC9F,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,0BAA0B;AAClE,QAAM,KAAK,YAAY;AACvB,SAAO,eAAqD,oBAAoB,SAAS;AAAA,IACvF,QAAQ;AAAA,IACR,WAAW,GAAG,QAAQ,KAAK,IAAI,QAAQ,EAAE;AAAA,IACzC,MAAM,CAAC,EAAE,YAAY,KAAK,MAAM,GAAG,YAAY,oBAAoB,YAAY,IAAI;AAAA,IACnF,OAAO,CAAC,EAAE,WAAW,MAAM,GAAG,aAAa,oBAAoB,UAAU;AAAA,EAC3E,CAAC;AACH;AAGO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EACA;AAAA,EACT,YAAY,OAAe,IAAY;AACrC,UAAM,mCAAmC;AACzC,SAAK,OAAO;AACZ,SAAK,QAAQ;AACb,SAAK,KAAK;AAAA,EACZ;AACF;AAGO,SAAS,kBAAkB,OAAyB;AACzD,SAAO,iBAAiB,wBAAwB,uBAAuB,KAAK;AAC9E;AAEA,SAAS,SAAS,SAA4B;AAC5C,OAAK,kBAAkB,OAAO;AAChC;AAMO,SAAS,kBACd,OACA,SACS;AACT,MAAI,CAAC,kBAAkB,KAAK,EAAG,QAAO;AACtC,WAAS,OAAO;AAChB,SAAO;AACT;AAQA,eAAsB,gBAAgB,SAA8C;AAClF,QAAM,SAAS,MAAMA,oBAAmB,QAAQ,OAAO,QAAQ,EAAE,EAAE,MAAM,MAAM,IAAI;AACnF,MAAI,QAAQ,WAAW,CAAC,OAAO,WAAW;AACxC,aAAS,OAAO;AAChB,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["DefaultLink","AccessLink","useState","Avatar","AvatarFallback","AvatarImage","Button","jsx","jsxs","useState","Button","jsx","jsxs","useState","Button","useState","useState","getInitials","jsx","jsxs","useState","Button","Avatar","AvatarImage","AvatarFallback","headline","classifyDataError","Fragment","jsx","jsxs","headline","classifyDataError","useEffect","useState","ArrowLeft","Button","fetchAccessDeniedContext","jsx","jsxs","useState","useEffect","Button","ArrowLeft","useState","Check","Loader2","Lock","Send","Button","Fragment","jsx","jsxs","useState","Check","Lock","Button","Loader2","Send","ArrowLeft","Lock","LogIn","Button","jsx","jsxs","useState","Check","KeyRound","Loader2","Send","Button","useState","createSettingAccessRequest","useState","result","Fragment","jsx","jsxs","useState","Check","KeyRound","Button","Loader2","Send","useState","Loader2","LogIn","RefreshCw","Trash2","TriangleAlert","Button","cn","jsx","jsxs","explanation","StatusIcon","Trash2","LogIn","RefreshCw","TriangleAlert","useState","cn","Loader2","Button","useEffect","useState","getAccessEnv","Fragment","jsx","useState","useEffect","getAccessEnv","useState","Check","KeyRound","Loader2","Send","Trash2","Button","Dialog","DialogContent","DialogDescription","DialogFooter","DialogHeader","DialogTitle","createAccessRequest","useEffect","useState","getAccessEnv","Fragment","jsx","jsxs","useState","Trash2","ownerName","createAccessRequest","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","Loader2","Check","DialogFooter","Button","Send","KeyRound","useState","EyeOff","Button","Dialog","DialogContent","DialogDescription","DialogHeader","DialogTitle","Fragment","jsx","jsxs","useState","Button","EyeOff","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","EyeOff","Button","jsx","useState","Check","KeyRound","Loader2","Trash2","Button","jsx","jsxs","useState","useState","Check","CircleSlash","ExternalLink","Loader2","Button","jsx","jsxs","useState","useCallback","useEffect","useState","CircleSlash","Flag","KeyRound","Send","Undo2","cn","Button","decideAccessRequest","reportAccessRequest","withdrawAccessRequest","jsx","jsxs","Send","useState","useCallback","useEffect","KeyRound","cn","Button","CircleSlash","Flag","Undo2","useCallback","useEffect","useMemo","useState","fetchAccessDeniedContext","wanted","fetchRemovalRights"]}