{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "app-assistant-approval",
  "type": "registry:block",
  "title": "App, assistant approval",
  "description": "An action the assistant wants to take and needs a person to allow: title, why, scoped detail, a risk level and Approve / Deny buttons named after the action. Pending, approved and denied via the state prop.",
  "categories": [
    "app"
  ],
  "dependencies": [
    "lucide-react@^1.49.0",
    "zod@^4.6.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/block-kit.json",
    "https://ui.klarhimmel.com/r/button.json",
    "https://ui.klarhimmel.com/r/editing.json",
    "https://ui.klarhimmel.com/r/kit-invalid.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/blocks/app-assistant-approval/spec.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-assistant-approval/spec.ts",
      "content": "import { z } from 'zod';\nimport { defineSpec, t, req } from '../_shared/schema';\n\nconst schema = z.object({\n  state: z.enum(['pending', 'approved', 'denied']),\n  /** none: no risk pill (a member's 'send to the team' card, Klar Portal 10-25). */\n  risk: z.enum(['none', 'low', 'medium', 'high']),\n  title: req(80),\n  description: t(240),\n  scope: z.array(z.object({ label: t(30), value: t(300) })).min(1).max(4),\n  action: t(60),\n  approve: t(24),\n  deny: t(24),\n  resolvedNote: t(200).optional(),\n  labels: z.object({ approved: t(24), denied: t(24), low: t(24), medium: t(24), high: t(24) }),\n});\n\nexport const spec = defineSpec({\n  type: 'app-assistant-approval',\n  aliases: ['app/assistant-approval'],\n  name: 'App, assistant approval',\n  category: 'app',\n  strict: true,\n  role: 'body',\n  description: 'An action the assistant wants to take and needs a person to allow: title, why, scoped detail, a risk level and Approve / Deny buttons named after the action. Pending, approved and denied via the state prop.',\n  schema,\n  defaults: {\n    \"state\": \"pending\",\n    \"risk\": \"medium\",\n    \"title\": \"Say what the assistant wants to do\",\n    \"description\": \"Say why the assistant wants this and what it will do, in one or two sentences, with the key fact.\",\n    \"scope\": [\n      {\n        \"label\": \"Touches\",\n        \"value\": \"Name what it acts on, with its identifier\"\n      },\n      {\n        \"label\": \"Changes\",\n        \"value\": \"Say what changes and by how much\"\n      },\n      {\n        \"label\": \"Sends\",\n        \"value\": \"Say what is sent and to whom\"\n      },\n      {\n        \"label\": \"Undo\",\n        \"value\": \"Say how it can be undone and what cannot be\"\n      }\n    ],\n    \"action\": \"do this action\",\n    \"approve\": \"Approve\",\n    \"deny\": \"Deny\",\n    \"labels\": {\n      \"approved\": \"Approved\",\n      \"denied\": \"Denied\",\n      \"low\": \"Low risk\",\n      \"medium\": \"Medium risk\",\n      \"high\": \"High risk\"\n    }\n  },\n});\n"
    },
    {
      "path": "src/blocks/app-assistant-approval/index.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-assistant-approval/index.tsx",
      "content": "import { useEffect, useId, useRef, useState, type ReactNode } from 'react';\nimport { Check, CircleAlert, ShieldQuestion, X } from 'lucide-react';\nimport { Text, withHeadingLevel } from '../../editing';\nimport { cn } from '../../lib/utils';\nimport { Button } from '../../ui/button';\nimport { Container, Opt, Section, useEditing } from '../_shared/kit';\nimport { InvalidNotice } from '../_shared/invalid-kit';\nimport { spec } from './spec';\nimport type { BlockProps } from '../types';\nimport type { z } from 'zod';\n\nexport { spec };\nexport { ProposalProject, ProposalChanges, ProposalDiff, diffLines, nestByParent, type ProposedTask } from './previews';\ntype Props = z.infer<typeof spec.schema>;\n\nconst RISK_TONE = { none: '', low: 'border-kh-line text-kh-muted', medium: 'border-kh-line-strong text-kh-ink', high: 'border-kh-danger text-kh-ink' } as const;\n/** Long unbroken text (a URL, a path) wraps instead of being clipped: this is the text a person is consenting to. */\nconst WRAP = '[overflow-wrap:anywhere]';\n\n/** What a host adds around the content: the proposal itself, and where the written thing is once accepted. */\nexport interface ApprovalHost {\n  onApprove?: () => void;\n  onDeny?: () => void;\n  /** What would be written, under the description: ProposalProject, ProposalChanges or ProposalDiff (./previews). */\n  preview?: ReactNode;\n  /** Shown on the approved line as a link: the thing that now exists (\"Open the project\"). */\n  done?: { label: string; href: string };\n  /** The words of the card shown when the request itself is invalid, in the page's language (its own props cannot be trusted then). */\n  invalidLabels?: { title?: string; approve?: string; deny?: string };\n}\n\n/**\n * The approval card. The buttons resolve it in place (`onApprove` / `onDeny` let a host act too); a changed `state` prop wins.\n * When a person decides, the buttons disappear and focus moves to the outcome line, which is the card's one status region.\n */\nexport function Approval(p: { props: Props } & ApprovalHost) {\n  // A strict block: invalid content is never replaced by default text, and nothing can be approved.\n  if (!spec.schema.safeParse(p.props).success) return <InvalidApproval labels={p.invalidLabels} />;\n  return <ApprovalCard {...p} />;\n}\n\n/** What shows when the request's own text is invalid: said in words, Approve and Deny disabled. */\nexport function InvalidApproval({ labels }: { labels?: ApprovalHost['invalidLabels'] } = {}) {\n  return (\n    <InvalidNotice title={labels?.title || 'This request could not be shown'} wrap={false}>\n      <div className=\"mt-3 flex flex-wrap gap-2\">\n        <Button variant=\"primary\" disabled icon={<Check aria-hidden className=\"size-4\" />}>{labels?.approve || 'Approve'}</Button>\n        <Button variant=\"secondary\" disabled icon={<X aria-hidden className=\"size-4\" />}>{labels?.deny || 'Deny'}</Button>\n      </div>\n    </InvalidNotice>\n  );\n}\n\nfunction ApprovalCard({ props, onApprove, onDeny, preview, done }: { props: Props } & ApprovalHost) {\n  const id = useId();\n  const editing = useEditing();\n  const [state, setState] = useState(props.state);\n  useEffect(() => {\n    setState(props.state);\n    setByPerson(false);\n  }, [props.state]);\n  const status = useRef<HTMLParagraphElement>(null);\n  const decided = useRef(false);\n  const [byPerson, setByPerson] = useState(false);\n  useEffect(() => {\n    if (decided.current && state !== 'pending') {\n      status.current?.focus();\n      decided.current = false;\n    }\n  }, [state]);\n  const decide = (next: 'approved' | 'denied', cb?: () => void) => {\n    decided.current = true;\n    setByPerson(true);\n    setState(next);\n    cb?.();\n  };\n  const pending = state === 'pending';\n  const approved = state === 'approved';\n  return (\n    <section aria-labelledby={`${id}-t`} data-state={state} className=\"min-w-0 rounded-kh-lg border border-kh-line-strong bg-kh-canvas p-4 shadow-kh-1 @xl:p-5\">\n      <div className=\"flex flex-wrap items-start gap-x-3 gap-y-2\">\n        <ShieldQuestion aria-hidden className=\"mt-0.5 size-5 shrink-0 text-kh-accent-ink\" />\n        <h3 id={`${id}-t`} className={cn('min-w-0 flex-1 basis-56 text-kh-body font-semibold', WRAP)}>\n          <Text path={['title']} value={props.title} as=\"span\" />\n        </h3>\n        {props.risk !== 'none' && (\n        <span className={cn('inline-flex items-center gap-1 rounded-kh-pill border px-2.5 py-0.5 text-kh-caption font-medium', RISK_TONE[props.risk])}>\n          {props.risk === 'high' && <CircleAlert aria-hidden className=\"size-3.5 text-kh-danger\" />}\n          <Text path={['labels', props.risk as 'low']} value={props.labels[props.risk as 'low']} as=\"span\" />\n        </span>\n        )}\n      </div>\n      <Text path={['description']} value={props.description} as=\"p\" className={cn('mt-2 text-kh-small text-kh-muted', WRAP)} />\n      {preview}\n      {/* The action's name only when nothing else says what changes: under a preview it read as debug text (Felix 19:21, /ws). */}\n      {(!preview || editing) && (\n        <p className=\"mt-3 text-kh-caption text-kh-muted\">\n          <Text path={['action']} value={props.action} as=\"code\" className={cn('rounded-kh bg-kh-surface-2 px-1.5 py-0.5 font-kh-mono text-kh-ink', WRAP)} />\n        </p>\n      )}\n      <dl className=\"mt-4 grid gap-x-4 gap-y-2 rounded-kh border border-kh-line bg-kh-surface p-3 text-kh-small @md:grid-cols-[minmax(0,max-content)_minmax(0,1fr)]\">\n        {props.scope.map((s, i) => (\n          <div key={i} className=\"contents\">\n            <dt className={cn('min-w-0 font-medium text-kh-muted', WRAP)}>\n              <Text path={['scope', i, 'label']} value={s.label} as=\"span\" />\n            </dt>\n            <dd className={cn('m-0 min-w-0', WRAP)}>\n              <Text path={['scope', i, 'value']} value={s.value} as=\"span\" />\n            </dd>\n          </div>\n        ))}\n      </dl>\n      {(pending || editing) && (\n        <div className=\"mt-4 flex flex-wrap gap-2\">\n          <Button variant=\"primary\" icon={<Check aria-hidden className=\"size-4\" />} aria-label={`${props.approve}: ${props.action}`} onClick={() => decide('approved', onApprove)}>\n            <Text path={['approve']} value={props.approve} as=\"span\" />\n          </Button>\n          <Button variant=\"secondary\" icon={<X aria-hidden className=\"size-4\" />} aria-label={`${props.deny}: ${props.action}`} onClick={() => decide('denied', onDeny)}>\n            <Text path={['deny']} value={props.deny} as=\"span\" />\n          </Button>\n        </div>\n      )}\n      <p\n        ref={status}\n        role=\"status\"\n        // The person who decided hears the outcome once, from focus landing here; a decision that arrives from outside is announced by this region.\n        aria-live={byPerson ? 'off' : undefined}\n        tabIndex={-1}\n        className={cn('flex flex-wrap items-center gap-x-2 gap-y-1 rounded-kh text-kh-small outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)', (!pending || editing) && 'mt-4')}\n      >\n        {(!pending || editing) && (\n          <>\n            {approved ? <Check aria-hidden className=\"size-4 text-kh-accent-ink\" /> : <X aria-hidden className=\"size-4 text-kh-muted\" />}\n            <span className=\"font-medium\">\n              <Text path={['labels', approved ? 'approved' : 'denied']} value={props.labels[approved ? 'approved' : 'denied']} as=\"span\" />\n            </span>\n            <Opt path={['resolvedNote']} value={props.resolvedNote} as=\"span\" className={cn('text-kh-muted', WRAP)} placeholder=\"Note\" />\n            {approved && done && <a href={done.href} className=\"font-medium text-kh-ink underline decoration-kh-line-strong underline-offset-4 hover:decoration-current\">{done.label}</a>}\n          </>\n        )}\n      </p>\n      {editing && (\n        <p className=\"mt-2 flex flex-wrap gap-x-4 text-kh-caption text-kh-muted\">\n          {(['low', 'medium', 'high'] as const).filter((k) => k !== props.risk).map((k) => (\n            <Text key={k} path={['labels', k]} value={props.labels[k]} as=\"span\" />\n          ))}\n          <Text path={['labels', approved ? 'denied' : 'approved']} value={props.labels[approved ? 'denied' : 'approved']} as=\"span\" />\n        </p>\n      )}\n    </section>\n  );\n}\n\nfunction AppAssistantApproval({ props }: BlockProps<Props>) {\n  return (\n    <Section>\n      <Container width=\"narrow\">\n        <Approval props={props} />\n      </Container>\n    </Section>\n  );\n}\n\nexport default withHeadingLevel(AppAssistantApproval);\n"
    },
    {
      "path": "src/blocks/app-assistant-approval/previews.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-assistant-approval/previews.tsx",
      "content": "// What the assistant proposes to write, shown inside the approval card before anyone accepts (workspace slice 2, 22 Oct):\n// a new project (key, goal, deliverables, its task tree), a change to a task (each field before and after), and an edit to\n// a description (the changed lines). Pure presentation: the host passes the proposal; nothing here writes anything.\nimport { useId, useState, type ReactNode } from 'react';\nimport { ArrowRight, ChevronRight } from 'lucide-react';\nimport { cn } from '../../lib/utils';\n\nconst WRAP = '[overflow-wrap:anywhere]';\nconst BOX = 'mt-3 min-w-0 rounded-kh border border-kh-line bg-kh-surface p-3 text-kh-small';\n\nexport interface ProposedTask { title: string; children?: ProposedTask[] }\n\n/** A flat task list whose `parent` is the index of another entry (the workspace 'workplan' shape) as the nested tree\n *  ProposalProject draws. An entry whose parent is missing or points forward to itself stays at the top. */\nexport function nestByParent(list: { title: string; parent?: number }[]): ProposedTask[] {\n  const nodes = list.map((t) => ({ title: t.title, children: [] as ProposedTask[] }));\n  const roots: ProposedTask[] = [];\n  list.forEach((t, i) => {\n    const p = t.parent;\n    if (p != null && p >= 0 && p < list.length && p !== i) nodes[p]!.children.push(nodes[i]!);\n    else roots.push(nodes[i]!);\n  });\n  return roots;\n}\n\n/** A new project: its key and goal, the deliverables, and the task tree (three levels), folded after `visible` rows. */\nexport function ProposalProject({ projectKey, goal, deliverables = [], tasks, visible = 5, labels = {} }: {\n  projectKey: string; goal: string; deliverables?: string[]; tasks: ProposedTask[]; visible?: number;\n  labels?: { goal?: string; deliverables?: string; tasks?: string; more?: (n: number) => string; less?: string };\n}) {\n  const id = useId();\n  const [open, setOpen] = useState(false);\n  const rows: { title: string; depth: number }[] = [];\n  const walk = (ts: ProposedTask[], depth: number) => ts.forEach((t) => { rows.push({ title: t.title, depth }); if (depth < 2 && t.children) walk(t.children, depth + 1); });\n  walk(tasks, 0);\n  const shown = open ? rows : rows.slice(0, visible);\n  const hidden = rows.length - shown.length;\n  return (\n    <div className={BOX}>\n      <p className=\"flex flex-wrap items-baseline gap-x-2\"><span className=\"rounded-kh bg-kh-surface-2 px-1.5 py-0.5 font-kh-mono text-kh-caption text-kh-ink\">{projectKey}</span><span className=\"text-kh-muted\">{labels.goal ?? 'Goal'}</span><span className={cn('min-w-0 font-medium', WRAP)}>{goal}</span></p>\n      {deliverables.length > 0 && (\n        <div className=\"mt-2\"><p className=\"text-kh-caption font-medium text-kh-muted\">{labels.deliverables ?? 'Deliverables'}</p>\n          <ul className=\"mt-1 flex list-disc flex-col gap-0.5 pl-5\">{deliverables.map((d, i) => <li key={i} className={WRAP}>{d}</li>)}</ul></div>\n      )}\n      <p className=\"mt-2 text-kh-caption font-medium text-kh-muted\">{labels.tasks ?? 'Tasks'} · {rows.length}</p>\n      <ul id={`${id}-tree`} className=\"mt-1 flex flex-col\">\n        {shown.map((r, i) => (\n          <li key={i} className={cn('flex min-w-0 items-start gap-1.5 py-0.5', r.depth === 1 && 'pl-5', r.depth === 2 && 'pl-10')}>\n            <span aria-hidden className={cn('mt-[0.45em] size-1.5 shrink-0 rounded-kh-pill', r.depth === 0 ? 'bg-kh-ink-2' : 'border border-kh-line-strong')} />\n            <span className={cn('min-w-0', WRAP, r.depth === 0 && 'font-medium')}>{r.title}</span>\n          </li>\n        ))}\n      </ul>\n      {rows.length > visible && (\n        <button type=\"button\" aria-expanded={open} aria-controls={`${id}-tree`} onClick={() => setOpen((o) => !o)} className=\"mt-1 inline-flex min-h-9 items-center gap-1 rounded-kh px-1 text-kh-caption font-medium text-kh-ink-2 hover:text-kh-ink focus-visible:outline-2 focus-visible:outline-(--kh-focus)\">\n          <ChevronRight aria-hidden className={cn('size-3.5 transition-transform duration-(--kh-dur)', open && 'rotate-90')} />\n          {open ? (labels.less ?? 'Show fewer') : (labels.more?.(hidden) ?? `${hidden} more`)}\n        </button>\n      )}\n    </div>\n  );\n}\n\n/** A change to one thing: each field that changes, before and after. An empty side says so in words. The field column fits its\n *  words up to 14rem and wraps beyond, so a long label never crushes the change beside it (Felix 11-02 15:5x on Studio: 'Waiting →\n *  Approved' one letter a line under a long field). */\nexport function ProposalChanges({ rows, labels = {} }: { rows: { field: string; before: ReactNode; after: ReactNode }[]; labels?: { before?: string; after?: string; empty?: string } }) {\n  const empty = <span className=\"italic text-kh-muted\">{labels.empty ?? 'empty'}</span>;\n  return (\n    <dl className={cn(BOX, 'grid gap-x-3 gap-y-2 @md:grid-cols-[fit-content(14rem)_minmax(0,1fr)]')}>\n      {rows.map((r, i) => (\n        <div key={i} className=\"contents\">\n          <dt className={cn('font-medium text-kh-muted', WRAP)}>{r.field}</dt>\n          <dd className=\"m-0 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n            <span className={cn('text-kh-muted line-through decoration-kh-line-strong', WRAP)}><span className=\"sr-only\">{labels.before ?? 'Before'}: </span>{r.before === '' || r.before == null ? empty : r.before}</span>\n            <ArrowRight aria-hidden className=\"size-3.5 shrink-0 text-kh-muted\" />\n            <span className={cn('font-medium', WRAP)}><span className=\"sr-only\">{labels.after ?? 'After'}: </span>{r.after === '' || r.after == null ? empty : r.after}</span>\n          </dd>\n        </div>\n      ))}\n    </dl>\n  );\n}\n\ntype Line = { kind: 'same' | 'del' | 'add'; text: string };\n/** Line diff by longest common subsequence: enough for a description (frontmatter + body), not for whole files. */\nexport function diffLines(before: string, after: string): Line[] {\n  const a = before.split('\\n'), b = after.split('\\n');\n  const n = a.length, m = b.length;\n  const L: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));\n  for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i]![j] = a[i] === b[j] ? L[i + 1]![j + 1]! + 1 : Math.max(L[i + 1]![j]!, L[i]![j + 1]!);\n  const out: Line[] = [];\n  let i = 0, j = 0;\n  while (i < n && j < m) {\n    if (a[i] === b[j]) { out.push({ kind: 'same', text: a[i]! }); i++; j++; }\n    else if (L[i + 1]![j]! >= L[i]![j + 1]!) out.push({ kind: 'del', text: a[i++]! });\n    else out.push({ kind: 'add', text: b[j++]! });\n  }\n  while (i < n) out.push({ kind: 'del', text: a[i++]! });\n  while (j < m) out.push({ kind: 'add', text: b[j++]! });\n  return out;\n}\n\n/** An edit to a text: only the changed lines, with `context` unchanged lines around each change and a gap marker between. */\nexport function ProposalDiff({ before, after, context = 1, labels = {} }: { before: string; after: string; context?: number; labels?: { removed?: string; added?: string; unchanged?: (n: number) => string } }) {\n  const lines = diffLines(before, after);\n  const keep = lines.map((l, k) => l.kind !== 'same' || lines.slice(Math.max(0, k - context), k + context + 1).some((x) => x.kind !== 'same'));\n  const out: ReactNode[] = [];\n  let skipped = 0;\n  lines.forEach((l, k) => {\n    if (!keep[k]) { skipped++; return; }\n    if (skipped) { out.push(<li key={`g${k}`} className=\"px-2 py-0.5 text-kh-caption text-kh-muted\">{labels.unchanged?.(skipped) ?? `${skipped} unchanged`}</li>); skipped = 0; }\n    out.push(\n      <li key={k} className={cn('flex gap-2 px-2 py-0.5 font-kh-mono text-kh-caption', l.kind === 'add' && 'bg-kh-accent-soft', l.kind === 'del' && 'bg-[color-mix(in_oklab,var(--kh-danger)_8%,var(--kh-surface))]')}>\n        <span aria-hidden className=\"w-3 shrink-0 text-kh-muted\">{l.kind === 'add' ? '+' : l.kind === 'del' ? '−' : ''}</span>\n        {l.kind !== 'same' && <span className=\"sr-only\">{l.kind === 'add' ? (labels.added ?? 'Added') : (labels.removed ?? 'Removed')}: </span>}\n        <span className={cn('min-w-0 whitespace-pre-wrap', WRAP, l.kind === 'del' && 'text-kh-muted line-through')}>{l.text || ' '}</span>\n      </li>,\n    );\n  });\n  if (skipped) out.push(<li key=\"gend\" className=\"px-2 py-0.5 text-kh-caption text-kh-muted\">{labels.unchanged?.(skipped) ?? `${skipped} unchanged`}</li>);\n  return <ul className={cn(BOX, 'p-1')}>{out}</ul>;\n}\n"
    }
  ]
}
