{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-08",
  "title": "Agent memory",
  "description": "What an agent remembers, where a new memory folds into the list when the agent saves it, searchable by scope, with edits in place, pins that re-sort the list, forget with Undo, forget by source and why a memory was used.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/dropdown-menu.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/popover.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/textarea.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/toggle-group.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/agent/agent-08.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  useSession,\n  type SessionStep,\n} from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  emptyRun,\n  type RunEvent,\n  type RunSnapshot,\n  type ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport {\n  pressedQuietOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CheckIcon,\n  EraserIcon,\n  FileTextIcon,\n  HistoryIcon,\n  MessageCircleIcon,\n  PencilIcon,\n  PinIcon,\n  PinOffIcon,\n  RotateCcwIcon,\n  SearchIcon,\n  TrashIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf, springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { applyBatchAt, restingOf } from '@/registry/ndeko/lib/run-session';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf, nounOf } from '@/registry/ndeko/lib/words';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTitle,\n  PopoverTrigger,\n} from '@/registry/ndeko/ui/popover';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\nimport { ToggleGroup, ToggleGroupItem } from '@/registry/ndeko/ui/toggle-group';\n\nimport { focusLater } from './_parts/focus-later';\nimport { RelativeTime } from './_parts/relative-time';\n\nexport type MemoryScope = 'project' | 'everywhere';\n\nexport type MemorySource = {\n  id: string;\n  kind: 'conversation' | 'file';\n  title: string;\n};\n\nexport type AgentMemoryItem = {\n  id: string;\n  text: string;\n  scope: MemoryScope;\n  source: MemorySource;\n  isPinned: boolean;\n  lastUsedAt: number;\n  /** The recall of the turn that used it last, for \"Why was this used?\". */\n  usedBy?: ToolCall;\n};\n\nexport type MemoryVariant = 'full' | 'compact';\n\ntype PendingForget = {\n  key: string;\n  memoryIds: string[];\n  anchorId: string;\n  label: string;\n};\n\ntype ListEntry =\n  | { kind: 'heading'; key: string; label: string }\n  | { kind: 'memory'; key: string; memory: AgentMemoryItem }\n  | { kind: 'undo'; key: string; pending: PendingForget };\n\nconst UNDO_MS = 5000;\n\nconst RECENT_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst COMPACT_LIMIT = 5;\n\nconst SCOPE_LABEL: Record<MemoryScope, string> = {\n  project: 'This project',\n  everywhere: 'Everywhere',\n};\n\nconst SCOPES: MemoryScope[] = ['project', 'everywhere'];\n\nconst ALL_SCOPES: MemoryScope[] = ['project', 'everywhere'];\n\nconst SOURCE_GLYPH: Record<MemorySource['kind'], React.ReactNode> = {\n  conversation: <MessageCircleIcon />,\n  file: <FileTextIcon />,\n};\n\ntype TextPiece = { text: string; isMatch: boolean };\n\nfunction piecesOf(text: string, query: string): TextPiece[] {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return [{ text, isMatch: false }];\n  }\n  const haystack = text.toLowerCase();\n  const pieces: TextPiece[] = [];\n  let cursor = 0;\n  let found = haystack.indexOf(needle, cursor);\n  while (found >= 0) {\n    const before = text.slice(cursor, found);\n    const matchEnd = found + needle.length;\n    const match = text.slice(found, matchEnd);\n    if (before !== '') {\n      pieces.push({ text: before, isMatch: false });\n    }\n    pieces.push({ text: match, isMatch: true });\n    cursor = matchEnd;\n    found = haystack.indexOf(needle, cursor);\n  }\n  const rest = text.slice(cursor);\n  if (rest !== '') {\n    pieces.push({ text: rest, isMatch: false });\n  }\n  return pieces;\n}\n\nfunction Marked({ text, query }: { text: string; query: string }) {\n  const pieces = piecesOf(text, query);\n\n  return (\n    <>\n      {pieces.map((piece, index) => {\n        if (piece.isMatch) {\n          return (\n            <mark\n              key={index}\n              className='bg-warning/25 text-foreground rounded-[3px] px-px'\n            >\n              {piece.text}\n            </mark>\n          );\n        }\n        return <span key={index}>{piece.text}</span>;\n      })}\n    </>\n  );\n}\n\nfunction matchesQuery(memory: AgentMemoryItem, query: string) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return true;\n  }\n  const text = memory.text.toLowerCase();\n  const source = memory.source.title.toLowerCase();\n  const isInText = text.includes(needle);\n  const isInSource = source.includes(needle);\n  return isInText || isInSource;\n}\n\nfunction byPinThenUse(first: AgentMemoryItem, second: AgentMemoryItem) {\n  const pinOrder = Number(second.isPinned) - Number(first.isPinned);\n  if (pinOrder !== 0) {\n    return pinOrder;\n  }\n  return second.lastUsedAt - first.lastUsedAt;\n}\n\nfunction isRecent(memory: AgentMemoryItem, newest: number) {\n  const age = newest - memory.lastUsedAt;\n  return age < RECENT_MS;\n}\n\nfunction newestUseOf(memories: AgentMemoryItem[]) {\n  let newest = 0;\n  for (const memory of memories) {\n    newest = Math.max(newest, memory.lastUsedAt);\n  }\n  return newest;\n}\n\nfunction compactOf(sorted: AgentMemoryItem[]) {\n  const newest = newestUseOf(sorted);\n  const kept = sorted.filter((memory) => {\n    const isKept = memory.isPinned || isRecent(memory, newest);\n    return isKept;\n  });\n  return kept.slice(0, COMPACT_LIMIT);\n}\n\nfunction hiddenIdsOf(pending: PendingForget[]) {\n  const ids = new Set<string>();\n  for (const forget of pending) {\n    for (const memoryId of forget.memoryIds) {\n      ids.add(memoryId);\n    }\n  }\n  return ids;\n}\n\nfunction pendingAt(pending: PendingForget[], memoryId: string) {\n  return pending.filter((forget) => forget.anchorId === memoryId);\n}\n\ntype MemoryGroup = 'pinned' | 'other';\n\nfunction groupOf(memory: AgentMemoryItem): MemoryGroup {\n  if (memory.isPinned) {\n    return 'pinned';\n  }\n  return 'other';\n}\n\n/** Pinned first under its heading, then the rest; a forgotten row leaves its Undo line in its place. */\nfunction entriesOf(\n  ordered: AgentMemoryItem[],\n  pending: PendingForget[],\n  otherLabel: string\n) {\n  const hiddenIds = hiddenIdsOf(pending);\n  const entries: ListEntry[] = [];\n  let lastGroup: MemoryGroup | null = null;\n  for (const memory of ordered) {\n    const group = groupOf(memory);\n    const isNewGroup = group !== lastGroup;\n    if (isNewGroup) {\n      entries.push(headingOf(group, otherLabel));\n      lastGroup = group;\n    }\n    const undoLines = pendingAt(pending, memory.id);\n    for (const forget of undoLines) {\n      entries.push({ kind: 'undo', key: forget.key, pending: forget });\n    }\n    const isHidden = hiddenIds.has(memory.id);\n    if (!isHidden) {\n      entries.push({ kind: 'memory', key: memory.id, memory });\n    }\n  }\n  return entries;\n}\n\nfunction headingOf(group: MemoryGroup, otherLabel: string): ListEntry {\n  if (group === 'pinned') {\n    return { kind: 'heading', key: 'heading-pinned', label: 'Pinned' };\n  }\n  return { kind: 'heading', key: 'heading-other', label: otherLabel };\n}\n\nfunction otherLabelOf(isCompact: boolean) {\n  if (isCompact) {\n    return 'Recent';\n  }\n  return 'Everything else';\n}\n\nfunction pinLabelOf(isPinned: boolean) {\n  if (isPinned) {\n    return 'Unpin this memory';\n  }\n  return 'Pin this memory';\n}\n\nfunction queryOf(call: ToolCall | undefined) {\n  const query = call?.input?.query;\n  if (typeof query === 'string') {\n    return query;\n  }\n  return '';\n}\n\nfunction WhyUsed({ memory }: { memory: AgentMemoryItem }) {\n  const call = memory.usedBy;\n  if (!call) {\n    return null;\n  }\n  const query = queryOf(call);\n  const hasQuery = query !== '';\n\n  return (\n    <Popover>\n      <PopoverTrigger\n        render={\n          <Button\n            type='button'\n            variant='ghost'\n            size='icon-sm'\n            aria-label='Why was this used?'\n            className='text-muted-foreground'\n          />\n        }\n      >\n        <HistoryIcon />\n      </PopoverTrigger>\n      <PopoverContent align='end' className='flex w-72 flex-col gap-2 p-3'>\n        <PopoverTitle className='text-muted-foreground text-xs font-normal'>\n          Used while answering\n        </PopoverTitle>\n        <p className='text-[13px] leading-5 font-medium text-balance'>\n          {call.label}\n        </p>\n        {hasQuery && (\n          <p className='text-muted-foreground text-xs leading-5'>\n            Memory was searched for &ldquo;{query}&rdquo;,{' '}\n            <RelativeTime at={call.startedAt ?? 0} />\n          </p>\n        )}\n      </PopoverContent>\n    </Popover>\n  );\n}\n\nfunction usedKeyOf(memory: AgentMemoryItem) {\n  return memory.usedBy?.id ?? 'never';\n}\n\n/**\n * A memory lights for a moment when a turn uses it, then the tint leaves: one transition on its\n * colour, started by the row being keyed on the turn. Nothing lights when the list is first shown.\n */\nconst USED_FLASH =\n  'bg-primary/0 pointer-events-none absolute inset-x-0 inset-y-0.5 -z-10 rounded-lg transition-colors duration-[1600ms] ease-linear starting:bg-primary/[0.09]';\n\ntype MemoryRowProps = {\n  memory: AgentMemoryItem;\n  query: string;\n  sourceCount: number;\n  isEditing: boolean;\n  isConfirmingSource: boolean;\n  /** True once a turn used the memory after the list was shown: the row lights for that turn. */\n  showsUse: boolean;\n  isPinPressed: boolean;\n  onStartEdit: (memoryId: string) => void;\n  onEndEdit: (memoryId: string, text: string | null) => void;\n  onPin: (memoryId: string, isPinned: boolean) => void;\n  onForget: (memory: AgentMemoryItem) => void;\n  onAskForgetSource: (memoryId: string) => void;\n  onCancelForgetSource: (memoryId: string) => void;\n  onForgetSource: (memory: AgentMemoryItem) => void;\n};\n\nfunction MemoryRow({\n  memory,\n  query,\n  sourceCount,\n  isEditing,\n  isConfirmingSource,\n  showsUse,\n  isPinPressed,\n  onStartEdit,\n  onEndEdit,\n  onPin,\n  onForget,\n  onAskForgetSource,\n  onCancelForgetSource,\n  onForgetSource,\n}: MemoryRowProps) {\n  const [draft, setDraft] = useState(memory.text);\n  const confirmRef = useRef<HTMLButtonElement>(null);\n  const fieldId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const usedKey = usedKeyOf(memory);\n  const sourceWord = countOf(sourceCount, 'memory', 'memories');\n  const isBlank = draft.trim() === '';\n\n  function startEdit() {\n    setDraft(memory.text);\n    onStartEdit(memory.id);\n  }\n\n  function save() {\n    if (isBlank) {\n      return;\n    }\n    onEndEdit(memory.id, draft.trim());\n  }\n\n  function cancel() {\n    onEndEdit(memory.id, null);\n  }\n\n  function handleFieldKeys(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      cancel();\n      return;\n    }\n    const hasCommandKey = event.metaKey || event.ctrlKey;\n    const isSaveKey = event.key === 'Enter' && hasCommandKey;\n    if (isSaveKey) {\n      event.preventDefault();\n      save();\n    }\n  }\n\n  return (\n    <div data-memory={memory.id} className='relative isolate px-2 py-2.5'>\n      {showsUse && (\n        <span key={usedKey} aria-hidden='true' className={USED_FLASH} />\n      )}\n      {memory.isPinned && <span className='sr-only'>Pinned. </span>}\n      {isEditing && (\n        <div className='flex flex-col gap-2'>\n          <label htmlFor={fieldId} className='sr-only'>\n            Edit the memory\n          </label>\n          <Textarea\n            id={fieldId}\n            value={draft}\n            onChange={(event) => setDraft(event.target.value)}\n            onKeyDown={handleFieldKeys}\n            aria-invalid={isBlank}\n            autoFocus\n            className='min-h-14'\n          />\n          <div className='flex flex-wrap items-center gap-2'>\n            <Button\n              type='button'\n              size='sm'\n              onClick={save}\n              disabled={isBlank}\n              focusableWhenDisabled\n            >\n              <CheckIcon />\n              Save\n            </Button>\n            <Button type='button' variant='ghost' size='sm' onClick={cancel}>\n              Cancel\n            </Button>\n            <span className='text-muted-foreground ms-auto hidden items-center gap-1 text-xs @sm:flex'>\n              <Kbd>Ctrl</Kbd>\n              <Kbd>Enter</Kbd> saves\n            </span>\n          </div>\n        </div>\n      )}\n      {!isEditing && (\n        <p className='text-[13px] leading-5 text-pretty'>\n          <Marked text={memory.text} query={query} />\n        </p>\n      )}\n      <div className='mt-1 flex items-center gap-2'>\n        <DropdownMenu>\n          <DropdownMenuTrigger\n            render={\n              <button\n                type='button'\n                aria-label={`Source: ${memory.source.title}, more actions`}\n                data-action='source'\n                className='text-muted-foreground hover:text-foreground focus-visible:ring-ring/25 -ms-1 flex min-w-0 cursor-pointer items-center gap-1.5 rounded-md px-1 py-0.5 text-xs outline-none focus-visible:ring-[3px] [&_svg]:size-3.5 [&_svg]:shrink-0'\n              />\n            }\n          >\n            {SOURCE_GLYPH[memory.source.kind]}\n            <span className='truncate'>\n              <Marked text={memory.source.title} query={query} />\n            </span>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent\n            align='start'\n            finalFocus={() => confirmRef.current ?? true}\n          >\n            <DropdownMenuItem\n              variant='destructive'\n              onClick={() => onAskForgetSource(memory.id)}\n            >\n              <EraserIcon />\n              Forget everything from this source\n            </DropdownMenuItem>\n          </DropdownMenuContent>\n        </DropdownMenu>\n        <span className='text-muted-foreground shrink-0 text-xs'>\n          used <RelativeTime at={memory.lastUsedAt} />\n        </span>\n        {!isEditing && (\n          <span className='ms-auto flex shrink-0 items-center'>\n            <WhyUsed memory={memory} />\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label={pinLabelOf(memory.isPinned)}\n              onClick={() => onPin(memory.id, !memory.isPinned)}\n              data-action='pin'\n              className={cn(\n                'text-muted-foreground',\n                pressedQuietOf(isPinPressed)\n              )}\n            >\n              <Swap swapKey={String(memory.isPinned)}>\n                {memory.isPinned && <PinOffIcon />}\n                {!memory.isPinned && <PinIcon />}\n              </Swap>\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label='Edit this memory'\n              onClick={startEdit}\n              data-action='edit'\n              className='text-muted-foreground'\n            >\n              <PencilIcon />\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label='Forget this memory'\n              onClick={() => onForget(memory)}\n              data-action='forget'\n              className='text-muted-foreground hover:text-destructive-ink'\n            >\n              <TrashIcon />\n            </Button>\n          </span>\n        )}\n      </div>\n      <AnimatePresence initial={false}>\n        {isConfirmingSource && (\n          <motion.div\n            key='confirm'\n            className='overflow-hidden'\n            {...rowPresence}\n          >\n            <div className='bg-destructive/[0.06] mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg px-3 py-2'>\n              <p className='min-w-0 flex-1 text-xs leading-5'>\n                Forget all {sourceWord} from {memory.source.title}?\n              </p>\n              <div className='flex items-center gap-1.5'>\n                <Button\n                  ref={confirmRef}\n                  type='button'\n                  size='sm'\n                  variant='destructive'\n                  onClick={() => onForgetSource(memory)}\n                >\n                  Forget {sourceWord}\n                </Button>\n                <Button\n                  type='button'\n                  size='sm'\n                  variant='ghost'\n                  onClick={() => onCancelForgetSource(memory.id)}\n                >\n                  Cancel\n                </Button>\n              </div>\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction UndoLine({\n  pending,\n  onUndo,\n}: {\n  pending: PendingForget;\n  onUndo: (key: string) => void;\n}) {\n  return (\n    <div className='bg-foreground/[0.03] dark:bg-foreground/[0.05] my-1.5 flex items-center gap-3 rounded-lg py-1.5 ps-3 pe-1.5'>\n      <p className='text-muted-foreground min-w-0 flex-1 truncate text-xs'>\n        {pending.label}\n      </p>\n      <Button\n        type='button'\n        variant='ghost'\n        size='sm'\n        onClick={() => onUndo(pending.key)}\n        data-undo={pending.key}\n        className='relative shrink-0 overflow-hidden'\n      >\n        <RotateCcwIcon />\n        Undo\n        <span\n          aria-hidden='true'\n          className='bg-foreground/25 absolute inset-x-2 bottom-1 h-px origin-left scale-x-0 transition-transform duration-[5000ms] ease-linear starting:scale-x-100'\n        />\n      </Button>\n    </div>\n  );\n}\n\nfunction quoteOf(text: string) {\n  const isLong = text.length > 42;\n  if (isLong) {\n    const cut = text.slice(0, 40).trimEnd();\n    return `“${cut}…”`;\n  }\n  return `“${text}”`;\n}\n\nfunction changeScopes(\n  values: unknown[],\n  onChange: (scopes: MemoryScope[]) => void\n) {\n  const scopes = SCOPES.filter((scope) => values.includes(scope));\n  onChange(scopes);\n}\n\nfunction countInScope(memories: AgentMemoryItem[], scope: MemoryScope) {\n  const inScope = memories.filter((memory) => memory.scope === scope);\n  return inScope.length;\n}\n\nfunction emptyLineOf(query: string, hasScopes: boolean) {\n  if (!hasScopes) {\n    return 'Turn a scope back on to see memories';\n  }\n  const trimmed = query.trim();\n  if (trimmed !== '') {\n    return `No memory mentions “${trimmed}”`;\n  }\n  return 'Nothing remembered yet';\n}\n\nconst NO_PENDING: PendingForget[] = [];\n\nexport type AgentMemoryProps = {\n  memories: AgentMemoryItem[];\n  variant?: MemoryVariant;\n  agentName?: string;\n  onEdit?: (memoryId: string, text: string) => void;\n  onPinChange?: (memoryId: string, isPinned: boolean) => void;\n  /** Called once the Undo window has closed. */\n  onForget?: (memoryIds: string[]) => void;\n  /** The memory whose pin a demonstration holds down. */\n  pressedPinId?: string | null;\n  className?: string;\n};\n\nfunction usedKeysOf(memories: AgentMemoryItem[]) {\n  const keys = memories.map(usedKeyOf);\n  return new Set(keys);\n}\n\n/** The order of the rows: a row travels to a new place only when it changes. */\nfunction orderKeyOf(entries: ListEntry[]) {\n  const keys = entries.map((entry) => entry.key);\n  return keys.join(' ');\n}\n\nexport function AgentMemory({\n  memories,\n  variant = 'full',\n  agentName = 'The agent',\n  onEdit,\n  onPinChange,\n  onForget,\n  pressedPinId = null,\n  className,\n}: AgentMemoryProps) {\n  const [query, setQuery] = useState('');\n  const [scopes, setScopes] = useState<MemoryScope[]>(ALL_SCOPES);\n  const [editingId, setEditingId] = useState<string | null>(null);\n  const [confirmingId, setConfirmingId] = useState<string | null>(null);\n  const [pending, setPending] = useState<PendingForget[]>(NO_PENDING);\n  const [quietUseKeys] = useState(() => usedKeysOf(memories));\n  const rootRef = useRef<HTMLElement>(null);\n  const undoneKeys = useRef(new Set<string>());\n  const searchId = useId();\n  const { schedule } = useTimeouts();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const spring = springOf(shouldReduceMotion);\n  const rowTransition = { ...rowPresence.transition, layout: spring };\n  const isCompact = variant === 'compact';\n  const sorted = [...memories].sort(byPinThenUse);\n  const inScopes = sorted.filter((memory) => scopes.includes(memory.scope));\n  const matching = inScopes.filter((memory) => matchesQuery(memory, query));\n  const shown = compactOrAll(isCompact, sorted, matching);\n  const otherLabel = otherLabelOf(isCompact);\n  const entries = entriesOf(shown, pending, otherLabel);\n  const orderKey = orderKeyOf(entries);\n  const hiddenIds = hiddenIdsOf(pending);\n  const visibleMemories = shown.filter((memory) => !hiddenIds.has(memory.id));\n  const isEmpty = visibleMemories.length === 0;\n  const hasPending = pending.length > 0;\n  const showsEmpty = isEmpty && !hasPending;\n  const hasScopes = scopes.length > 0;\n  const hasQuery = query !== '';\n\n  function closeUndo(key: string) {\n    setPending((current) => current.filter((forget) => forget.key !== key));\n  }\n\n  function commit(forget: PendingForget) {\n    const wasUndone = undoneKeys.current.has(forget.key);\n    if (wasUndone) {\n      return;\n    }\n    closeUndo(forget.key);\n    onForget?.(forget.memoryIds);\n  }\n\n  function holdForget(forget: PendingForget) {\n    setPending((current) => [...current, forget]);\n    setConfirmingId(null);\n    focusLater(rootRef, `[data-undo=\"${forget.key}\"]`);\n    schedule(() => commit(forget), UNDO_MS);\n  }\n\n  function forgetOne(memory: AgentMemoryItem) {\n    holdForget({\n      key: `one-${memory.id}-${Date.now()}`,\n      memoryIds: [memory.id],\n      anchorId: memory.id,\n      label: `Forgot ${quoteOf(memory.text)}`,\n    });\n  }\n\n  function forgetSource(memory: AgentMemoryItem) {\n    const fromSource = memories.filter(\n      (candidate) => candidate.source.id === memory.source.id\n    );\n    const memoryIds = fromSource.map((candidate) => candidate.id);\n    const word = countOf(memoryIds.length, 'memory', 'memories');\n    holdForget({\n      key: `source-${memory.source.id}-${Date.now()}`,\n      memoryIds,\n      anchorId: memory.id,\n      label: `Forgot ${word} from ${memory.source.title}`,\n    });\n  }\n\n  function undo(key: string) {\n    const forget = pending.find((candidate) => candidate.key === key);\n    undoneKeys.current.add(key);\n    closeUndo(key);\n    if (forget) {\n      focusLater(\n        rootRef,\n        `[data-memory=\"${forget.anchorId}\"] [data-action=\"forget\"]`\n      );\n    }\n  }\n\n  function cancelForgetSource(memoryId: string) {\n    setConfirmingId(null);\n    focusLater(rootRef, `[data-memory=\"${memoryId}\"] [data-action=\"source\"]`);\n  }\n\n  function startEdit(memoryId: string) {\n    setEditingId(memoryId);\n    setConfirmingId(null);\n  }\n\n  function endEdit(memoryId: string, text: string | null) {\n    setEditingId(null);\n    if (text !== null) {\n      onEdit?.(memoryId, text);\n    }\n    focusLater(rootRef, `[data-memory=\"${memoryId}\"] [data-action=\"edit\"]`);\n  }\n\n  function pin(memoryId: string, isPinned: boolean) {\n    onPinChange?.(memoryId, isPinned);\n    focusLater(rootRef, `[data-memory=\"${memoryId}\"] [data-action=\"pin\"]`);\n  }\n\n  function clearSearch() {\n    setQuery('');\n    setScopes(ALL_SCOPES);\n  }\n\n  function sourceCountOf(memory: AgentMemoryItem) {\n    const fromSource = memories.filter(\n      (candidate) => candidate.source.id === memory.source.id\n    );\n    return fromSource.length;\n  }\n\n  return (\n    <section\n      ref={rootRef}\n      aria-label={`What ${agentName} remembers`}\n      className={cn(\n        'bg-card hairline-ring ring-border @container flex flex-col gap-3 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <header className='flex items-baseline justify-between gap-3'>\n        <h3 className='text-sm font-medium'>Memory</h3>\n        <p className='text-muted-foreground text-xs'>\n          <MotionNumber value={memories.length} />{' '}\n          {nounOf(memories.length, 'memory', 'memories')}\n        </p>\n      </header>\n      {!isCompact && (\n        <div className='flex flex-col gap-2'>\n          <div className='relative'>\n            <label htmlFor={searchId} className='sr-only'>\n              Search the memories\n            </label>\n            <SearchIcon className='text-muted-foreground pointer-events-none absolute start-2.5 top-1/2 size-4 -translate-y-1/2' />\n            <Input\n              id={searchId}\n              type='search'\n              value={query}\n              onChange={(event) => setQuery(event.target.value)}\n              placeholder='Search what it remembers'\n              className='ps-8 pe-8'\n            />\n            {hasQuery && (\n              <Button\n                type='button'\n                variant='ghost'\n                size='icon-sm'\n                aria-label='Clear the search'\n                onClick={() => setQuery('')}\n                className='text-muted-foreground absolute end-0.5 top-1/2 size-7 -translate-y-1/2'\n              >\n                <XIcon />\n              </Button>\n            )}\n          </div>\n          <ToggleGroup\n            multiple\n            aria-label='Scopes'\n            value={scopes}\n            onValueChange={(values) => changeScopes(values, setScopes)}\n            size='sm'\n            className='gap-1'\n          >\n            {SCOPES.map((scope) => (\n              <ToggleGroupItem\n                key={scope}\n                value={scope}\n                variant='outline'\n                className='rounded-full px-3 text-xs'\n              >\n                {SCOPE_LABEL[scope]}\n                <span className='text-muted-foreground tabular-nums'>\n                  <MotionNumber value={countInScope(memories, scope)} />\n                </span>\n              </ToggleGroupItem>\n            ))}\n          </ToggleGroup>\n        </div>\n      )}\n      <ul aria-label='Memories' className='-mx-2 flex flex-col'>\n        <AnimatePresence initial={false}>\n          {entries.map((entry) => (\n            <motion.li\n              key={entry.key}\n              layout='position'\n              layoutDependency={orderKey}\n              className='overflow-hidden'\n              {...rowPresence}\n              transition={rowTransition}\n            >\n              {entry.kind === 'heading' && (\n                <p\n                  aria-hidden='true'\n                  className='text-muted-foreground px-2 pt-2 pb-0.5 text-xs font-medium'\n                >\n                  {entry.label}\n                </p>\n              )}\n              {entry.kind === 'undo' && (\n                <UndoLine pending={entry.pending} onUndo={undo} />\n              )}\n              {entry.kind === 'memory' && (\n                <MemoryRow\n                  memory={entry.memory}\n                  query={query}\n                  sourceCount={sourceCountOf(entry.memory)}\n                  isEditing={editingId === entry.memory.id}\n                  isConfirmingSource={confirmingId === entry.memory.id}\n                  showsUse={!quietUseKeys.has(usedKeyOf(entry.memory))}\n                  isPinPressed={pressedPinId === entry.memory.id}\n                  onStartEdit={startEdit}\n                  onEndEdit={endEdit}\n                  onPin={pin}\n                  onForget={forgetOne}\n                  onAskForgetSource={setConfirmingId}\n                  onCancelForgetSource={cancelForgetSource}\n                  onForgetSource={forgetSource}\n                />\n              )}\n            </motion.li>\n          ))}\n        </AnimatePresence>\n      </ul>\n      <AnimatePresence initial={false}>\n        {showsEmpty && (\n          <motion.div key='empty' className='overflow-hidden' {...rowPresence}>\n            <div className='bg-foreground/[0.03] dark:bg-foreground/[0.05] flex flex-col items-center gap-3 rounded-lg px-4 py-6 text-center'>\n              <p className='text-muted-foreground text-[13px]'>\n                {emptyLineOf(query, hasScopes)}\n              </p>\n              {!isCompact && (\n                <Button\n                  type='button'\n                  variant='outline'\n                  size='sm'\n                  onClick={clearSearch}\n                >\n                  Show every memory\n                </Button>\n              )}\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </section>\n  );\n}\n\nfunction compactOrAll(\n  isCompact: boolean,\n  sorted: AgentMemoryItem[],\n  matching: AgentMemoryItem[]\n) {\n  if (isCompact) {\n    return compactOf(sorted);\n  }\n  return matching;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nconst HOUR_MS = 60 * 60 * 1000;\n\nconst LOADED_AT = Date.now();\n\nconst KICKOFF: MemorySource = {\n  id: 'kickoff',\n  kind: 'conversation',\n  title: 'Kickoff call, Oct 2',\n};\n\nconst CONTACTS: MemorySource = {\n  id: 'contacts',\n  kind: 'file',\n  title: 'vendor-contacts.csv',\n};\n\nconst STYLE_NOTES: MemorySource = {\n  id: 'style',\n  kind: 'conversation',\n  title: 'Style notes with Ines',\n};\n\nconst WRITING_GUIDE: MemorySource = {\n  id: 'guide',\n  kind: 'file',\n  title: 'writing-guide.md',\n};\n\nfunction earlierRecall(\n  id: string,\n  question: string,\n  query: string,\n  at: number\n): ToolCall {\n  return {\n    id,\n    tool: 'recall',\n    label: question,\n    status: 'done',\n    agentId: 'writer',\n    input: { query },\n    startedAt: at,\n    endedAt: at,\n  };\n}\n\nconst MEMORIES: AgentMemoryItem[] = [\n  {\n    id: 'terms',\n    text: 'Brightmoor bills at 45 days, not 30. Ask before assuming a late fee.',\n    scope: 'project',\n    source: KICKOFF,\n    isPinned: true,\n    lastUsedAt: LOADED_AT - 3 * DAY_MS,\n    usedBy: earlierRecall(\n      'earlier-terms',\n      'When is the Brightmoor invoice of October due?',\n      'Brightmoor payment terms',\n      LOADED_AT - 3 * DAY_MS\n    ),\n  },\n  {\n    id: 'contact',\n    text: 'Dana Ruiz handles credits at Brightmoor: accounts@brightmoor-supply.example',\n    scope: 'project',\n    source: CONTACTS,\n    isPinned: false,\n    lastUsedAt: LOADED_AT - 6 * DAY_MS,\n  },\n  {\n    id: 'money',\n    text: 'Write money with two decimals in every report: $1,840.20, never $1,840.',\n    scope: 'everywhere',\n    source: STYLE_NOTES,\n    isPinned: false,\n    lastUsedAt: LOADED_AT - 2 * HOUR_MS,\n    usedBy: earlierRecall(\n      'earlier-money',\n      'Write the Q3 spend summary for finance',\n      'how to write amounts in reports',\n      LOADED_AT - 2 * HOUR_MS\n    ),\n  },\n  {\n    id: 'ostrava',\n    text: 'We stopped ordering from Ostrava Supply in August.',\n    scope: 'project',\n    source: KICKOFF,\n    isPinned: false,\n    lastUsedAt: LOADED_AT - 12 * DAY_MS,\n  },\n  {\n    id: 'tone',\n    text: 'Keep vendor emails short and polite, under 150 words.',\n    scope: 'everywhere',\n    source: WRITING_GUIDE,\n    isPinned: false,\n    lastUsedAt: LOADED_AT - 20 * DAY_MS,\n  },\n  {\n    id: 'fiscal',\n    text: 'Our fiscal year starts on February 1.',\n    scope: 'everywhere',\n    source: STYLE_NOTES,\n    isPinned: false,\n    lastUsedAt: LOADED_AT - 41 * DAY_MS,\n  },\n];\n\nfunction recall(\n  id: string,\n  question: string,\n  query: string,\n  memoryIds: string[]\n): RunEvent {\n  return {\n    type: 'call.started',\n    call: {\n      id,\n      tool: 'recall',\n      label: question,\n      status: 'running',\n      agentId: 'writer',\n      input: { query, memoryIds },\n    },\n  };\n}\n\nfunction recalled(id: string): RunEvent {\n  return { type: 'call.updated', id, patch: { status: 'done' } };\n}\n\nconst CREDIT_THREAD: MemorySource = {\n  id: 'credit-thread',\n  kind: 'conversation',\n  title: 'Credit request, today',\n};\n\nconst SAVED_ID = 'credit-on-invoice';\n\nconst SAVED_TEXT =\n  'Brightmoor settles a credit on the next invoice, never as a refund.';\n\ntype MemoryState = {\n  run: RunSnapshot;\n  memories: AgentMemoryItem[];\n  /** What the agent last did with its memory, for the live region. */\n  note: string;\n};\n\ntype MemoryAction =\n  | { type: 'events'; events: RunEvent[] }\n  | { type: 'save' }\n  | { type: 'edit'; memoryId: string; text: string }\n  | { type: 'pin'; memoryId: string; isPinned: boolean }\n  | { type: 'forget'; memoryIds: string[] };\n\ntype MemoryStep = SessionStep<MemoryState, MemoryAction>;\n\nconst INITIAL_RUN = emptyRun({ id: 'memory' });\n\nconst INITIAL: MemoryState = { run: INITIAL_RUN, memories: MEMORIES, note: '' };\n\nfunction withChange(\n  state: MemoryState,\n  memoryId: string,\n  change: Partial<AgentMemoryItem>\n) {\n  const memories = state.memories.map((memory) => {\n    if (memory.id !== memoryId) {\n      return memory;\n    }\n    return { ...memory, ...change };\n  });\n  return { ...state, memories };\n}\n\n/** The agent keeps what it just learned: the memory joins the list, used a moment ago. */\nfunction withSaved(state: MemoryState, now: number) {\n  const isKnown = state.memories.some((memory) => memory.id === SAVED_ID);\n  if (isKnown) {\n    return state;\n  }\n  const saved: AgentMemoryItem = {\n    id: SAVED_ID,\n    text: SAVED_TEXT,\n    scope: 'project',\n    source: CREDIT_THREAD,\n    isPinned: false,\n    lastUsedAt: now,\n  };\n  const memories = [...state.memories, saved];\n  const note = `Writer saved a memory: ${SAVED_TEXT}`;\n  return { ...state, memories, note };\n}\n\nfunction applyAt(\n  state: MemoryState,\n  action: MemoryAction,\n  now: number\n): MemoryState {\n  if (action.type === 'save') {\n    return withSaved(state, now);\n  }\n  if (action.type === 'edit') {\n    return withChange(state, action.memoryId, { text: action.text });\n  }\n  if (action.type === 'pin') {\n    return withChange(state, action.memoryId, { isPinned: action.isPinned });\n  }\n  if (action.type === 'forget') {\n    const memories = state.memories.filter(\n      (memory) => !action.memoryIds.includes(memory.id)\n    );\n    return { ...state, memories };\n  }\n  const run = applyBatchAt(state.run, action, now);\n  const note = announcementOf(run.calls);\n  return { ...state, run, note };\n}\n\n/** Times are stamped when an action lands, as a backend would stream it. */\nfunction reducer(state: MemoryState, action: MemoryAction) {\n  return applyAt(state, action, Date.now());\n}\n\n/** The memories were used days ago, so the resting state is stamped on the same clock as they are. */\nfunction applyAfterLoading(\n  state: MemoryState,\n  action: MemoryAction,\n  sinceStart: number\n) {\n  return applyAt(state, action, LOADED_AT + sinceStart);\n}\n\nfunction landing(after: number, ...events: RunEvent[]): MemoryStep {\n  return { after, action: { type: 'events', events } };\n}\n\nconst SCRIPT: MemoryStep[] = [\n  landing(\n    1800,\n    recall(\n      'turn-1',\n      'Draft the credit request to Brightmoor',\n      'Brightmoor payment terms and contacts',\n      ['terms', 'contact']\n    )\n  ),\n  landing(500, recalled('turn-1')),\n  { after: 2600, action: { type: 'save' } },\n  {\n    after: 2400,\n    by: 'demo',\n    press: 'pin',\n    action: { type: 'pin', memoryId: SAVED_ID, isPinned: true },\n  },\n  landing(\n    2600,\n    recall(\n      'turn-2',\n      'Which vendors changed their prices in Q3?',\n      'vendors we still order from',\n      ['ostrava', 'money']\n    )\n  ),\n  landing(500, recalled('turn-2')),\n];\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: restingOf(INITIAL, SCRIPT, applyAfterLoading),\n  script: SCRIPT,\n  loopAfter: 3400,\n};\n\nfunction pressedPinOf(pressed: string | null) {\n  if (pressed === 'pin') {\n    return SAVED_ID;\n  }\n  return null;\n}\n\nfunction memoryIdsOf(call: ToolCall) {\n  const memoryIds = call.input?.memoryIds;\n  if (!Array.isArray(memoryIds)) {\n    return [];\n  }\n  return memoryIds.filter((value) => typeof value === 'string');\n}\n\nfunction lastRecallOf(calls: ToolCall[], memoryId: string) {\n  const recalls = calls.filter((call) => {\n    const memoryIds = memoryIdsOf(call);\n    return memoryIds.includes(memoryId);\n  });\n  return recalls.at(-1);\n}\n\nfunction withRecalls(memories: AgentMemoryItem[], calls: ToolCall[]) {\n  return memories.map((memory) => {\n    const recall = lastRecallOf(calls, memory.id);\n    const usedBy = recall ?? memory.usedBy;\n    const usedAt = usedBy?.startedAt ?? 0;\n    const lastUsedAt = Math.max(memory.lastUsedAt, usedAt);\n    return { ...memory, usedBy, lastUsedAt };\n  });\n}\n\nconst VARIANTS: Segment<MemoryVariant>[] = [\n  { value: 'full', label: 'Full' },\n  { value: 'compact', label: 'Compact' },\n];\n\nfunction announcementOf(calls: ToolCall[]) {\n  const latest = calls.at(-1);\n  if (!latest) {\n    return '';\n  }\n  const memoryIds = memoryIdsOf(latest);\n  const word = countOf(memoryIds.length, 'memory', 'memories');\n  return `Writer used ${word} to answer: ${latest.label}`;\n}\n\nexport default function Agent08() {\n  const [variant, setVariant] = useState<MemoryVariant>('full');\n  const [message, setMessage] = useState('');\n  const [round, setRound] = useState(0);\n  const { ref, isInView, isAutoplaying, state, act, pressed, restart } =\n    useSession(SESSION);\n  const shown = withRecalls(state.memories, state.run.calls);\n\n  function edit(memoryId: string, text: string) {\n    act({ type: 'edit', memoryId, text });\n    setMessage('Memory saved');\n  }\n\n  function changePin(memoryId: string, isPinned: boolean) {\n    act({ type: 'pin', memoryId, isPinned });\n    setMessage(pinMessageOf(isPinned));\n  }\n\n  function forget(memoryIds: string[]) {\n    act({ type: 'forget', memoryIds });\n    const word = countOf(memoryIds.length, 'memory', 'memories');\n    setMessage(`Forgot ${word} for good`);\n  }\n\n  function startOver() {\n    setMessage('Every memory is back');\n    setRound((current) => current + 1);\n    restart();\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[50.5rem] w-full max-w-[32rem] flex-col gap-3'\n    >\n      <Segments\n        value={variant}\n        segments={VARIANTS}\n        onValueChange={setVariant}\n        label='Variant'\n        className='w-40 self-end'\n      />\n      <ClockGate isActive={isInView}>\n        <AgentMemory\n          key={round}\n          memories={shown}\n          variant={variant}\n          agentName='Writer'\n          onEdit={edit}\n          onPinChange={changePin}\n          onForget={forget}\n          pressedPinId={pressedPinOf(pressed)}\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          onClick={startOver}\n          className='text-muted-foreground'\n        >\n          <RotateCcwIcon />\n          Start over\n        </Button>\n      </div>\n      <LiveRegion message={message} />\n      <LiveRegion message={spokenUnless(isAutoplaying, state.note)} />\n    </div>\n  );\n}\n\nfunction pinMessageOf(isPinned: boolean) {\n  if (isPinned) {\n    return 'Pinned. It moved to the Pinned group';\n  }\n  return 'Unpinned';\n}\n",
      "type": "registry:component",
      "target": "components/agent/agent-08.tsx"
    },
    {
      "path": "registry/ndeko/components/agent/_parts/focus-later.ts",
      "content": "/** Moves focus once React has committed the change that moved, replaced or removed the focused control. */\nexport function focusLater(\n  root: React.RefObject<HTMLElement | null>,\n  selector: string\n) {\n  requestAnimationFrame(() => {\n    const target = root.current?.querySelector<HTMLElement>(selector);\n    target?.focus();\n  });\n}\n",
      "type": "registry:component",
      "target": "components/agent/_parts/focus-later.ts"
    },
    {
      "path": "registry/ndeko/components/agent/_parts/relative-time.tsx",
      "content": "'use client';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { useLiveNow } from '@/registry/ndeko/ui/live-duration';\n\nconst MINUTE_MS = 60_000;\n\nconst HOUR_MS = 60 * MINUTE_MS;\n\nconst DAY_MS = 24 * HOUR_MS;\n\nexport function relativeTimeOf(at: number, now: number) {\n  const age = now - at;\n  const elapsed = Math.max(0, age);\n  if (elapsed < MINUTE_MS) {\n    return 'just now';\n  }\n  if (elapsed < HOUR_MS) {\n    const minutes = Math.floor(elapsed / MINUTE_MS);\n    return `${minutes} min ago`;\n  }\n  if (elapsed < DAY_MS) {\n    const hours = Math.floor(elapsed / HOUR_MS);\n    return `${hours} h ago`;\n  }\n  const days = Math.floor(elapsed / DAY_MS);\n  if (days === 1) {\n    return 'yesterday';\n  }\n  return `${days} days ago`;\n}\n\ntype RelativeTimeProps = {\n  at: number;\n  className?: string;\n};\n\nexport function RelativeTime({ at, className }: RelativeTimeProps) {\n  const now = useLiveNow(1000, true);\n  const label = relativeTimeOf(at, now);\n\n  return <span className={cn('tabular-nums', className)}>{label}</span>;\n}\n",
      "type": "registry:component",
      "target": "components/agent/_parts/relative-time.tsx"
    }
  ],
  "categories": [
    "components",
    "agent"
  ],
  "type": "registry:component"
}