SLOPSHOPPER

nerv

Barra lateral estilo Evangelion: cuota, contexto, qué hace el agente, PRs, subagentes y alertas

panebandspinnerrowsguardcommand
★ 1v0.1.0no licenseupdated 2026-10-25gonzalonicolasr/claude-code-nerv
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · nerv
│ ┃ NERV ✕ › fix the failing auth test and add an audit log call │ ┃ ▣ │ ┃ NERV ネルフ ⟋ MAGI ◎ EN ESPERA ⏺ Read(src/auth.ts) │ ┃ メルキオール バルタザール カス ⎿ Read 6 lines │ ┃ 承認 承認 承 ◇ Edit src/auth.ts │ ┃ ⏺ Bash(bun test) │ ┃ 1: ◆ MAGI 2: GIT 3: ⎿ 3 pass, 1 fail │ ┃ 4: EN VIVO 5: FORGE 6: │ ┃ 7: CORTEX 8: YOUTUBE 9: MO Done. I made refresh reject expired claims and added an audit call. │ ┃ 0: EDD 📌 fijar │ ┃ ───────────────────────────────────────────… ◆ 完了 · 42 s │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ⬢ SINCRONIZACIÓN ▾ › /nerv │ ┃ │ CUENTA personal cambiar ▾ │ ┃ │ PILOT claude-opus-5-5 │ ┃ │ SYNC ━━━━━━━━━━━━━━━━━━┈┈┈┈·┈┈┈┈┈┈┈┈┈┈┈┈┈ │ ┃ │ 5H ━━━━━━━━━━━┈┈┈┈┈┈┈┈┈┈┈·┈┈┈┈┈┈┈┈┈┈┈┈┈ │ ┃ │ 7D ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈… │ ┃ │ COSTO US$ 0.42 │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ ▶ ACTIVIDAD ▾ │ │ ┃ │ ◎ esperando tu próxima orden │ │ ┃ │ ✔ cambios verificados │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ r: ↻ refrescar q: ◌ silenciar ✻ Sincronizando · SYNC 49.0%… ⣿ ⠂ ⠂ ⠂ ⬢ NERV SYNC 49% · 5H 31% · /nerv · personal ▾ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ⟨Claude Code's own drawing⟩ ネルフ ⟋ ◆ personal ANTHROPIC ⟋ OPUS 5.5 ⟋ SYNC ▰▰▰▱▱ 97K/200K 49% ⟋ ⎇ feat/auth-refresh ●2 ⟋ 5H 31% ⟋ $0.42

Draws

Band
⬢ NERV SYNC 49% · 5H 31% · /nerv · personal ▾ ⟨Claude Code's own drawing⟩
Pane · NERV
▣ NERV ネルフ ⟋ MAGI ◎ EN ESPERA メルキオール バルタザール カスパー 承認 承認 承認 1: ◆ MAGI 2: GIT 3: HW 4: EN VIVO 5: FORGE 6: NODD 7: CORTEX 8: YOUTUBE 9: MODELOS 0: EDD 📌 fijar ─────────────────────────────────────────────────────── ╭──────────────────────────────────────────────────────────╮ │ ⬢ SINCRONIZACIÓN ▾ │ │ CUENTA personal cambiar ▾ │ │ PILOT claude-opus-5-5 │ │ SYNC ━━━━━━━━━━━━━━━━━━┈┈┈┈·┈┈┈┈┈┈┈┈┈┈┈┈┈┈ 49% │ │ 5H ━━━━━━━━━━━┈┈┈┈┈┈┈┈┈┈┈·┈┈┈┈┈┈┈┈┈┈┈┈┈┈ 31% │ │ 7D ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ – │ │ COSTO US$ 0.42 │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ ▶ ACTIVIDAD ▾ │ │ ◎ esperando tu próxima orden │ │ ✔ cambios verificados │ ╰──────────────────────────────────────────────────────────╯ r: ↻ refrescar q: ◌ silenciar ◈ UNIDAD EVA-01 ─────────────────────────────────────────────────────── ◆ EFFORT sin dato ▱▱▱▱▱ 0/5 ▄▀▀▀▀▀▀▀▀▀▄▀▀▀▀▀▀▀▀▀▄▀▀▀▀▀▀▀▀▀▄▀▀▀▀▀▀▀▀▀▄▀▀▀▀▀▀▀▀▀ ▄▀▄▄▄▄▄▄▄▀▄▀▄▄▄▄▄▄▄▀▄▀▄▄▄▄▄▄▄▀▄▀▄▄▄▄▄▄▄▀▄▀▄▄▄▄▄▄▄▀ LOW MED HIGH XHIGH MAX
Spinner
✻ Sincronizando · SYNC 49.0%… ⣿ ⠂ ⠂ ⠂
Prompt hint
⟨Claude Code's own drawing⟩ ネルフ ⟋ ◆ personal ANTHROPIC ⟋ OPUS 5.5 ⟋ SYNC ▰▰▰▱▱ 97K/200K 49% ⟋ ⎇ feat/auth-refresh ●2 ⟋ 5H 31…
Turn line
◆ 完了 · 42 s
Claude's reply
Done. I made refresh reject expired claims and added an audit call.
Tool row
◇ Edit src/auth.ts
README

NERV — barra lateral estilo Evangelion para Claude Code

Un mod de Claude Code (v2.1.287 o más nuevo) que agrega una barra lateral con estética NERV: qué está haciendo el agente, cuánto contexto y cuota te queda, tus PRs, tu máquina, tus otras sesiones y un panel para manejar forge.

Pestañas MAGI y FORGE

Qué muestra

La cabecera queda siempre fija: dos cintas de neón animadas, la tríada MAGI (MELCHIOR, BALTHASAR y CASPER), el estado (en espera u operando) y las pestañas. Abajo, también fijo, está el medidor de effort del modelo. El contenido de cada pestaña scrollea por su cuenta, las tarjetas largas tienen su propio scroll, y cualquier tarjeta se pliega con un click en su ▾ (arrancan abiertas y lo que pliegues queda guardado).

  • 1 · MAGI
  • Sincronización: modelo, contexto (SYNC), cuota de 5 h y 7 días, y costo de la sesión. Con el contexto o la cuota arriba del 85 % pasa a BATERÍA INTERNA: se pone roja y estima cuánto tiempo te queda al ritmo actual. En CUENTA → cambiar ▾ pasás la conversación entre tu cuenta personal (directo a Anthropic) y priv8 (la cuenta del CPAM con prefijo priv8): abre una tab nueva de herdr que la reanuda en fork, con el mismo Claude si priv8 lo tiene. También /nerv cuenta <personal|priv8>.
  • Actividad: qué herramienta está corriendo y hace cuánto, archivos editados sin verificar y PATTERN BLUE cuando el mismo error se repite tres veces.
  • Tareas: comandos y subagentes en segundo plano, con su estado.
  • ÚLTIMA MISIÓN: si la sesión anterior en esa carpeta se cortó sin cerrarse, te muestra el último pedido.
  • 2 · GIT
  • Rama: upstream, commits adelante y atrás, y cambios sin commitear.
  • Commits: un mapa de calor como el de GitHub, de frío a caliente, con el total, la racha de días seguidos y los commits de hoy.
  • Últimos commits y las PRs abiertas del repo, con su estado de review y de checks, como links.
  • Fuera de un repo (por ejemplo, la sesión en tu home) junta todos tus proyectos: los más recientes con su rama y cambios, el mapa de calor sumando todos los repos (cada commit cuenta una vez aunque esté en varios clones, y en cada repo vale su propia identidad de git), los últimos commits y tus PRs abiertas en todas tus cuentas de gh. Escanea ~/projects, o las carpetas que pongas en ~/.config/nerv/projects.json como { "roots": ["~/projects", "~/otra"] }.
  • 3 · HW: GPU, VRAM, CPU y RAM con un gráfico animado, periféricos, monitores y máquinas secundarias.
  • 4 · EN VIVO: la StreamCam y el iPhone en miniatura con los botones para abrir los overlays, cambiar la banda y tapar la cámara; de Discord, sólo quiénes te miran mientras estás en Go Live y el chat del canal de voz.
  • 5 · FORGE: el panel de forge: fases, perfiles, modelo y effort por fase, modo, rondas y el botón para iniciar una corrida.
  • 0 · EDD: la historia activa de EDD leída del .edd/ del repo (o de la última historia si no estás en un branch edd/…): el pacto (propuesto/aprobado), los tests verdes/sellados/pendientes con su barra, el paso abierto, la última demo y el informe del Perito, y las decisiones que te frenan. Y se maneja desde ahí: sin .edd/ tenés ▶ edd init y ▶ /edd:backlog (que también arma una carpeta vacía); sin historia activa (o con la última cerrada) lista el BACKLOG.md con un ▶ N por historia que corre /edd:story N (↻ si quedó abierta, ✓ si ya se cerró); con una historia en curso, ↻ continuar, ■ parar (edd stop) y estado, ✓ aprobar pacto cuando el pacto está propuesto (manda ok al chat), y en cada decisión allow/deny, sugerido o tu respuesta escrita, que van al chat para que el orquestador las registre (con la variante cli, edd decide … --by cli, para cuando no hay skill esperando). Al cerrar la historia: git checkout main y ▶ siguiente. Si edd no está en el PATH, te lo dice.
  • 9 · MODELOS: los modelos del CPAM agrupados por cuenta (NaN, DeepSeek API oficial, Claude, Codex/GPT, Google ag…ag9, Wibond al final en rojo), con filtro. Al tocar un modelo, sus botones aparecen ahí mismo, debajo de su grupo, y el resultado también; tocarlo de nuevo lo suelta.
  • Sesión por el CPAM: "usar acá" cambia con /model, sin reabrir.
  • Sesión directa a Anthropic: "cambiar acá" cierra este Claude (/exit) y un ayudante suelto (setsid) espera a que el pane vuelva a la shell y retoma la misma conversación en el mismo pane con el modelo nuevo, los mismos flags y el contexto real del modelo. "↩ volver a Anthropic" hace lo mismo al revés. Si hay texto escrito en el prompt o el turno está corriendo, no cierra nada; si el /exit no llega en 10 s, queda todo como estaba.
  • "en tab nueva" abre un fork de la conversación en otra tab de herdr y deja esta abierta.

Además, el spinner de "pensando" se reemplaza por un escáner animado con verbos EVA ("Sincronizando", "Consultando a MAGI"…) y el SYNC de contexto. Cuando un comando que fallaba pasa, sale un confeti. En los turnos de más de 3 minutos llega una notificación MISSION COMPLETE.

Debajo del prompt, bajo la línea de Claude Code (auto mode on, esc to interrupt), va una línea NERV fija: ネルフ ⟋ ◆ cuenta CPAM|ANTHROPIC ⟋ modelo ⟋ SYNC ▰▰▱▱▱ usado/total % ⟋ EFFORT ⟋ ⎇ rama ●cambios ⟋ 5H % ⟋ $costo. Por el CPAM la cuenta sale del prefijo del modelo (ag3/, nan/, priv8/…) y su email; directo, del CLAUDE_CONFIG_DIR (personal para ~/.claude). La cuenta de Wibond va en ámbar con ⚠. La ventana de contexto es CLAUDE_CODE_MAX_CONTEXT_TOKENS si está, si no la que reporta la sesión. En una terminal angosta se caen primero costo, 5H, rama y effort.

Requisitos

  • Claude Code 2.1.287 o más nuevo, con "tui": "fullscreen" en tus settings. Como barra lateral necesita al menos 110 columnas, y para abrirse sola al arrancar, 144. En una ventana más angosta se muestra arriba del prompt.
  • Una terminal con colores de 24 bits. Ghostty, kitty y WezTerm andan bien.
  • Opcionales: cada sección se apaga sola si falta lo suyo.
  • gh para las PRs y el CI.
  • camoverlay e iphonecam (mpv con socket IPC), socat, ImageMagick y wpctl para EN VIVO.
  • ~/.local/bin/jcode-rail --json para HARDWARE.
  • forge para la pestaña FORGE.

Instalación

git clone https://github.com/gonzalonicolasr/claude-code-nerv ~/claude-code-nerv
claude --plugin-dir ~/claude-code-nerv

Para cargarlo en todas tus sesiones, agregá a ~/.claude/settings.json:

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/ruta/a/claude-code-nerv" } }

Si tenés varios mods, separalos con :.

Comandos

ComandoQué hace
/nerv o /nerv onAbre la barra
/nerv quietLa esconde y apaga las animaciones (para grabar o compartir pantalla)
/nerv magi · git · hw · vivo · forgeVa a esa pestaña
`/nerv tema eva01\eva00\eva02\eva08\mark06`Cambia los colores de todo el panel
/nerv prsRefresca las PRs
/nerv debugMuestra el estado interno

Con la barra enfocada, las teclas 1 a 9 y 0 cambian de pestaña. Todo lo que se ve como botón se puede clickear.

Temas

TemaColores
eva01violeta y verde ácido (el de fábrica)
eva00azul, blanco y amarillo
eva02rojo, naranja y dorado
eva08rosa y verde
mark06azul marino y plata

El tema elegido se guarda y también se escribe en ~/.local/state/nerv/theme.json, para que otros mods puedan leerlo.

Desarrollo

claude plugin validate .
claude plugin test .

Mientras lo usás con --plugin-dir, Claude Code lo recarga solo cada vez que guardás hooks/register.ts.

Source 1 files
hooks/register.ts 4403 lines
1const PANE = 'nerv'
2const THEMES = {
3  eva01: { label: 'EVA-01', purple: '#8b5cf6', violet: '#7b3fb8', lime: '#a3e635', amber: '#f59e0b', orange: '#ff7a1a', red: '#ef4444', pink: '#ff4d6d', cyan: '#22d3ee', text: '#ece2fb', muted: '#8a73ad', dim: '#5b4a75', todo: '#f0c987', ink: '#140c22', deep: '#2e2340', chip: '#241a33', chipDim: '#1c1529', tabBg: '#3a2560', trail: '#1c1526', spark: '#4b2a7a' },
4  eva00: { label: 'EVA-00', purple: '#3b82f6', violet: '#60a5fa', lime: '#facc15', amber: '#f59e0b', orange: '#fb923c', red: '#ef4444', pink: '#ff4d6d', cyan: '#7dd3fc', text: '#e5e7eb', muted: '#8b9bb4', dim: '#475569', todo: '#fde68a', ink: '#0b1220', deep: '#1e2a44', chip: '#16213a', chipDim: '#111a2e', tabBg: '#1d3a70', trail: '#101828', spark: '#1e40af' },
5  eva02: { label: 'EVA-02', purple: '#ef4444', violet: '#dc2626', lime: '#fbbf24', amber: '#f59e0b', orange: '#f97316', red: '#ef4444', pink: '#ff4d6d', cyan: '#fdba74', text: '#fde8e1', muted: '#b0857a', dim: '#6b3b33', todo: '#fcd34d', ink: '#1a0a08', deep: '#3a1a14', chip: '#2c1410', chipDim: '#22100c', tabBg: '#5a1a14', trail: '#1f0d0a', spark: '#7f1d1d' },
6  eva08: { label: 'EVA-08', purple: '#ec4899', violet: '#f472b6', lime: '#22c55e', amber: '#f59e0b', orange: '#fb923c', red: '#ef4444', pink: '#ff4d6d', cyan: '#4ade80', text: '#fce7f3', muted: '#b47e9e', dim: '#6b3a5a', todo: '#f9a8d4', ink: '#1a0a14', deep: '#3a1430', chip: '#2c1224', chipDim: '#220e1c', tabBg: '#5c1846', trail: '#1f0b18', spark: '#86198f' },
7  mark06: { label: 'MK.06', purple: '#3b82f6', violet: '#1e3a8a', lime: '#cbd5e1', amber: '#f59e0b', orange: '#94a3b8', red: '#ef4444', pink: '#ff4d6d', cyan: '#93c5fd', text: '#e2e8f0', muted: '#94a3b8', dim: '#475569', todo: '#e2e8f0', ink: '#0a0f1e', deep: '#1e293b', chip: '#172036', chipDim: '#111827', tabBg: '#1e3a8a', trail: '#0f172a', spark: '#1e3a8a' },
8}
9type ThemeId = keyof typeof THEMES
10const THEME_IDS = Object.keys(THEMES) as ThemeId[]
11const int = (h: string) => parseInt(h.slice(1), 16)
12const rgbOf = (t: (typeof THEMES)[ThemeId]) => ({
13  purple: int(t.purple),
14  violet: int(t.violet),
15  lime: int(t.lime),
16  orange: int(t.orange),
17  red: int(t.red),
18  pink: int(t.pink),
19  amber: int(t.amber),
20  cyan: int(t.cyan),
21  deep: int(t.deep),
22  ink: int(t.ink),
23  trail: int(t.trail),
24  spark: int(t.spark),
25  none: 0x01000000,
26})
27let themeId: ThemeId = 'eva01'
28let C = { ...THEMES.eva01 }
29let RGB = rgbOf(THEMES.eva01)
30const applyTheme = (id: string) => {
31  if (!THEME_IDS.includes(id as ThemeId)) return false
32  themeId = id as ThemeId
33  C = { ...THEMES[themeId] }
34  RGB = rgbOf(THEMES[themeId])
35  return true
36}
37const EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
38const LONG_TURN_MS = 180000
39const BATTERY_AT = 85
40const TABS = [
41  { id: 'magi', label: 'MAGI', hotkey: '1' },
42  { id: 'git', label: 'GIT', hotkey: '2' },
43  { id: 'hw', label: 'HW', hotkey: '3' },
44  { id: 'live', label: 'EN VIVO', hotkey: '4' },
45  { id: 'forge', label: 'FORGE', hotkey: '5' },
46  { id: 'nodd', label: 'NODD', hotkey: '6' },
47  { id: 'cortex', label: 'CORTEX', hotkey: '7' },
48  { id: 'yt', label: 'YOUTUBE', hotkey: '8' },
49  { id: 'models', label: 'MODELOS', hotkey: '9' },
50  { id: 'edd', label: 'EDD', hotkey: '0' },
51]
52const PHASES = ['explore', 'plan', 'build', 'veredicto']
53const SPIN = ['◐', '◓', '◑', '◒']
54
55let quiet = false
56let placedOnce = false
57let paneOpen = false
58let away = false
59let fast: { cancel: () => void }[] = []
60let tab = 'magi'
61let pinned = ''
62let frame = 0
63let working = false
64let turnStart = 0
65let model = ''
66let project = ''
67let cwdNow = ''
68let gitRoot = ''
69let branch = ''
70let home = ''
71let paneId = ''
72let sessionId = ''
73let usage: any = undefined
74let account = ''
75let samples: { t: number; pct: number }[] = []
76let activity: { tool: string; label: string; start: number } | undefined
77let lastProgress = 0
78const unverified = new Set<string>()
79let lastErr = ''
80let errCount = 0
81let patternBlue: { tool: string; count: number; text: string } | undefined
82const failedCmds = new Set<string>()
83let confettiUntil = 0
84const tasks = new Map<string, { kind: string; desc: string; start: number; end?: number; status?: string }>()
85const agentToUse = new Map<string, string>()
86let prs: any[] | undefined
87let ws: { days: Record<string, number>; repos: any[]; recent: any[] } | undefined
88let wsAt = 0
89let wsBusy = false
90let prsWide = false
91let prError = ''
92let ghMe = ''
93let commitDays: Record<string, number> = {}
94let commitAuthor = ''
95let gitInfo: any = { ok: false, upstream: '', ahead: 0, behind: 0, dirty: 0, recent: [] }
96const folded = new Set<string>()
97let sessionTasks: { id: string; subject: string; status: string; blockedBy: string[] }[] = []
98let configDir = ''
99let acctMenu = false
100let acctNote = ''
101const emails: Record<string, string> = {}
102const ACCOUNTS = [
103  { id: 'personal', conf: '.claude.json', tag: 'PERSONAL' },
104  { id: 'priv8', conf: '', tag: 'CPAM' },
105]
106let health = { ok: true, when: '', text: '' }
107let recap: { prompt: string; at: number } | undefined
108let hw: any = undefined
109let hwBusy = false
110const cpuHist: number[] = []
111const gpuHist: number[] = []
112type LiveCam = { on: boolean; w: number; h: number; fps: number; cpu: number }
113type LiveDcMember = { name: string; self: boolean; speaking: boolean; mute: boolean; deaf: boolean; streaming: boolean }
114type LiveDc = { ch: string; g: string; n: number; m: LiveDcMember[]; live: boolean; vc: number; v: string[] }
115export type LiveChatMsg = { a: string; t: string; ts: number; self: boolean }
116let live: {
117  cam: LiveCam
118  ip: LiveCam & { mode: string; scene: string; blur: boolean; name: string; bat: number; charging: boolean; lens: string; reach: boolean }
119  text: string
120  discord: boolean
121  dc: LiveDc | null | undefined
122  chat: LiveChatMsg[] | undefined
123  busy: boolean
124  n: number
125} = {
126  cam: { on: false, w: 0, h: 0, fps: 0, cpu: 0 },
127  ip: { on: false, w: 0, h: 0, fps: 0, cpu: 0, mode: '', scene: '', blur: false, name: '', bat: -1, charging: false, lens: '', reach: false },
128  text: '',
129  discord: false,
130  dc: undefined,
131  chat: undefined,
132  busy: false,
133  n: 0,
134}
135let liveText: string | undefined
136let liveTextKey = 0
137let bodyOffset = 0
138let bodyMax = 0
139let bodyTab = ''
140let lastView = 0
141let openDrop = ''
142const forgeAccounts: Record<string, boolean> = {}
143const cardScroll: Record<string, number> = {}
144const cardMax: Record<string, number> = {}
145let cardHits: { key: string; top: number; bottom: number }[] = []
146let lastContent = 0
147let ramTotal = ''
148let effort: string | number | undefined
149let effortPick: string | undefined
150let settingsEffort = ''
151let effortFrom = 0
152let effortAt = 0
153let forge: any = undefined
154let nodd: any = undefined
155let edd: any = undefined
156const eddAnswers: Record<string, string> = {}
157let cortex: { stats?: any; recent?: any[]; err?: string; at?: number } = {}
158let blue = { ars: 1555, live: false, at: 0 }
159type YtItem = { id: string; title: string; ch: string; d: number }
160let yt: { results: YtItem[]; queue: YtItem[]; query: string; busy: boolean; err: string; now?: { pos?: number; dur?: number; pause?: boolean; idx: number; vol?: number; title?: string } } = { results: [], queue: [], query: '', busy: false, err: '' }
161let runDir = '/tmp'
162let ytDraft = ''
163let ytVolDraft: string | undefined
164let ytVolKey = 0
165const ytThumb: Record<string, string> = {}
166const ytThumbPath = (id: string) => `${home}/.cache/nerv/yt/${id}.png`
167let ytRecent: string[] = []
168const ytSock = () => `${runDir}/nerv-yt.sock`
169const YT_COOKIES = 'chrome+gnomekeyring:Default'
170const YT_FILL = [
171  'sock=$1; ck=$2; map=$3; shift 3',
172  'for id in "$@"; do',
173  '  u=$(yt-dlp --cookies-from-browser "$ck" -f bestaudio/best -g --no-warnings "https://youtu.be/$id" 2>/dev/null | head -1)',
174  '  [ -S "$sock" ] || exit 0',
175  '  case "$u" in http*) c="{\\"command\\":[\\"loadfile\\",\\"$u\\",\\"append\\"]}" ;; *) c="{\\"command\\":[\\"loadfile\\",\\"https://youtu.be/$id\\",\\"append\\",-1,\\"ytdl=yes\\"]}" ;; esac',
176  '  case "$u" in http*) printf "%s\\t%s\\n" "$u" "$id" >> "$map" ;; esac',
177  '  printf "%s\\n" "$c" | socat -t 1 - UNIX-CONNECT:"$sock" >/dev/null 2>&1 || exit 0',
178  'done',
179].join('\n')
180const ytState = () => `${runDir}/nerv-yt.json`
181const YT_KILL = 'for p in $(pgrep -x mpv) $(pgrep -x bash); do tr "\\0" "\\n" </proc/$p/cmdline 2>/dev/null | grep -qx -e "--input-ipc-server=$1" -e nerv-yt-fill && [ "$p" != $$ ] && kill "$p"; done; true'
182let ytStarting = 0
183const ytStartFile = () => `${runDir}/nerv-yt.starting`
184const ytPend = new Set<string>()
185const ytMapPath = () => `${runDir}/nerv-yt.map`
186let ytMap: Record<string, string> = {}
187let ytItems: Record<string, YtItem> = {}
188let ytFilesSize = -1
189let ytLegacy: YtItem[] = []
190let ytNote = ''
191const clockOf = (sec: number) => mmss((sec || 0) * 1000)
192let cortexKey = ''
193let cortexBusy = false
194const CORTEX_URL = 'https://cortexmem.com/api/cortex/mcp'
195const CORTEX_TYPES: Record<string, string> = { bug_fix: 'bugs', discovery: 'hallazgos', config: 'config', architecture: 'arquitectura', decision: 'decisiones', lesson: 'lecciones', pattern: 'patrones', preference: 'preferencias', session_summary: 'sesiones', context: 'contexto' }
196export type CxEvent = { ts: string; kind: string; ws: string; tool: string; ids: number[]; titles: string[]; types: string[]; projects: string[]; workspaces: string[]; session: string; project: string; prompt: string }
197export type CxHit = { id: number; type: string; title: string; project: string; workspace: string }
198const CX_VERBS: Record<string, string> = {
199  memoria_search: 'buscó',
200  memoria_recall: 'recordó',
201  memoria_get: 'abrió',
202  memoria_hint: 'pidió pistas',
203  memoria_context: 'cargó el contexto',
204  memoria_recent: 'miró lo reciente',
205  memoria_timeline: 'miró la línea de tiempo',
206  memoria_projects: 'listó proyectos',
207  memoria_stats: 'miró estadísticas',
208  memoria_session_find: 'buscó sesiones',
209  memoria_pending: 'miró pendientes',
210  memoria_pending_done: 'cerró un pendiente',
211  memoria_save: 'guardó',
212  memoria_update: 'actualizó',
213  memoria_session_start: 'abrió sesión',
214  memoria_session_end: 'cerró la sesión',
215  memoria_feedback: 'dio feedback',
216  memoria_project_describe: 'describió el proyecto',
217  memoria_save_prompt: 'guardó el pedido',
218}
219const CX_EMOJI: Record<string, string> = { '🐛': 'bug_fix', '💡': 'discovery', '⚙': 'config', '🏛': 'architecture', '🧭': 'decision', '🎓': 'lesson', '🧩': 'pattern', '⭐': 'preference', '📋': 'session_summary', '🗺': 'context' }
220const CX_ROWS = 5
221const CX_READS = new Set(['memoria_search', 'memoria_recall', 'memoria_get', 'memoria_hint', 'memoria_context', 'memoria_recent', 'memoria_timeline', 'memoria_session_find', 'memoria_pending', 'memoria_projects', 'memoria_stats'])
222const CX_SAVES = new Set(['memoria_save', 'memoria_update'])
223const CX_AWK = 'd=$(date +%F); echo "$d"; awk -v k="$1" -v f="$2" -v d="$d" \'NR>=k && (f==0 || index($0,d)) {print NR "\\t" $0} END {print NR}\' "$3"'
224let cxLog = { path: '', primed: false, line: 0, size: 0, mtime: 0, day: '', missing: false, busy: false, events: [] as CxEvent[] }
225let forgeMissing = false
226let forgeDraft = ''
227const forgeGroup: Record<string, string> = {}
228
229const now = () => Date.now()
230const base = (p: string) => (p || '').split('/').filter(Boolean).at(-1) || p
231const clip = (s: string, n: number) => {
232  s = String(s ?? '')
233  return s.length > n ? s.slice(0, Math.max(0, n - 1)) + '…' : s
234}
235const took = (ms: number) => {
236  const sec = Math.max(0, Math.round(ms / 1000))
237  if (sec < 60) return `${sec} s`
238  const min = Math.floor(sec / 60)
239  return min < 60 ? `${min} min ${sec % 60} s` : `${Math.floor(min / 60)} h ${min % 60} min`
240}
241
242const shortPath = (p: unknown) => {
243  const s = String(p || '')
244  if (cwdNow && s.startsWith(cwdNow + '/')) return s.slice(cwdNow.length + 1)
245  return home && s.startsWith(home + '/') ? '~' + s.slice(home.length) : s
246}
247
248const oneLine = (v: unknown) => String(v ?? '').replace(/\s+/g, ' ').trim()
249
250const toolHead = (tool: string, input: any) => {
251  const i = input && typeof input === 'object' ? input : {}
252  const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
253  if (mcp) return { name: `${mcp[1]} · ${mcp[2]}`, arg: oneLine(Object.values(i).find((v) => typeof v === 'string') || '') }
254  if (tool === 'Bash') return { name: oneLine(i.description) || 'Bash', arg: oneLine(i.command) }
255  if (['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(tool)) return { name: tool, arg: shortPath(i.file_path ?? i.notebook_path) }
256  if (tool === 'Grep' || tool === 'Glob') return { name: tool === 'Grep' ? 'Buscar' : 'Glob', arg: oneLine(i.pattern) + (i.path ? ` en ${shortPath(i.path)}` : '') }
257  if (tool === 'Agent' || tool === 'Task') return { name: `Agente${i.subagent_type ? ' ' + i.subagent_type : ''}`, arg: oneLine(i.description) }
258  if (tool === 'WebFetch' || tool === 'WebSearch') return { name: tool, arg: oneLine(i.url ?? i.query) }
259  const first = Object.values(i).find((v) => typeof v === 'string')
260  return { name: tool, arg: oneLine(first || '') }
261}
262
263const toolGlyph = (p: { isRunning?: boolean; isErrored?: boolean; isInterrupted?: boolean }) =>
264  p.isRunning ? { g: SPIN[frame % 4], c: C.lime } : p.isErrored ? { g: '✖', c: C.red } : p.isInterrupted ? { g: '◌', c: C.dim } : { g: '◇', c: C.purple }
265
266const GROUP_WORDS: Record<string, [string, string]> = {
267  Read: ['lectura', 'lecturas'],
268  Bash: ['comando', 'comandos'],
269  Grep: ['búsqueda', 'búsquedas'],
270  Glob: ['búsqueda', 'búsquedas'],
271  LS: ['listado', 'listados'],
272  WebFetch: ['página', 'páginas'],
273  WebSearch: ['búsqueda web', 'búsquedas web'],
274  ToolSearch: ['tool cargada', 'tools cargadas'],
275}
276
277const groupSummary = (calls: readonly any[]) => {
278  const counts = new Map<string, number>()
279  for (const c of calls) {
280    const w = GROUP_WORDS[c.tool]
281    const key = w ? w.join('|') : c.tool
282    counts.set(key, (counts.get(key) || 0) + 1)
283  }
284  return [...counts].map(([k, n]) => (k.includes('|') ? `${n} ${n === 1 ? k.split('|')[0] : k.split('|')[1]}` : `${n} ${k}`)).join(' · ')
285}
286
287const mmss = (ms: number) => {
288  const s = Math.max(0, Math.floor(ms / 1000))
289  const m = Math.floor(s / 60)
290  return m >= 60 ? `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}` : `${m}:${String(s % 60).padStart(2, '0')}`
291}
292const escHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
293export const missionNotify = (root: string, project: string, took: string, unverified: number, c: { orange: string; amber: string; lime: string }) => {
294  const check = unverified
295    ? `<font color="${c.amber}"><b>⚠ ${unverified} sin verificar</b></font>`
296    : `<font color="${c.lime}">✓ verificado</font>`
297  const body = `<b>${escHtml(project)}</b>  ·  <font color="${c.orange}">⏱ ${took}</font>  ·  ${check}`
298  return ['notify-send', '-a', 'NERV', '-i', `${root}/assets/mission-complete.png`, 'MISSION COMPLETE', body]
299}
300export const missionWindow = (project: string, took: string, unverified: number) => [
301  'omarchy-shell',
302  'shell',
303  'summon',
304  'gon.nerv-mission',
305  JSON.stringify({ project, took, unverified }),
306]
307const ago = (ms: number) => {
308  const m = Math.floor(ms / 60000)
309  return m < 60 ? `hace ${m} min` : m < 1440 ? `hace ${Math.floor(m / 60)} h` : `hace ${Math.floor(m / 1440)} d`
310}
311const heat = (p: number) => (p >= 90 ? C.red : p >= 70 ? C.amber : C.lime)
312const energyBar = (p: number, w: number, hue: string, t = now()) => {
313  const filled = Math.max(p > 0 ? 1 : 0, Math.min(w, Math.round((p / 100) * w)))
314  const base = int(hue)
315  const step = Math.floor(t / 70)
316  const glint = step % (filled + 4)
317  const cells: { ch: number; color: number }[] = []
318  for (let i = 0; i < w; i++) {
319    if (i < filled) {
320      let c = mix(int(C.ink), base, 0.45 + (0.55 * (i + 1)) / filled)
321      if (i === glint) c = mix(base, 0xffffff, 0.6)
322      else if (i === glint - 1 || i === glint + 1) c = mix(base, 0xffffff, 0.25)
323      if (i === filled - 1 && step % 3 === 0) c = mix(c, 0xffffff, 0.35)
324      if (p >= 90 && Math.floor(t / 250) % 2 === 0) c = mix(c, int(C.red), 0.4)
325      cells.push({ ch: 0x2501, color: c })
326    } else cells.push((step + i * 5) % 29 === 0 ? { ch: 0xb7, color: mix(int(C.dim), base, 0.45) } : { ch: 0x2508, color: int(C.dim) })
327  }
328  return cells
329}
330
331const gaugeCells = (p: number, w: number, hue: string) => {
332  const bar = energyBar(p, w, hue)
333  return glyphs(w, 1, (x) => [bar[x].ch, bar[x].color])
334}
335
336let gauges: { key: string; p: number; w: number; hue: string }[] = []
337
338const dots = (p: number, w: number) => {
339  const f = Math.max(0, Math.min(w, Math.round((p / 100) * w)))
340  return '●'.repeat(f) + '·'.repeat(w - f)
341}
342const blink = () => Math.floor(frame / 4) % 2 === 0
343const tag = (text: string, name: string) => (text.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`)) || [])[1]
344
345const label = (e: any) => {
346  if (e.tool === 'Bash') return e.description || e.command || 'Bash'
347  if (EDIT_TOOLS.includes(e.tool) || e.tool === 'Read') return base(e.file_path || e.notebook_path || '')
348  if (e.tool === 'Grep' || e.tool === 'Glob') return e.pattern || ''
349  if (e.tool === 'Agent' || e.tool === 'Task') return e.description || ''
350  if (e.tool === 'WebFetch') return (e.url || '').replace(/^https?:\/\//, '').split('/')[0]
351  if (e.tool === 'WebSearch') return e.query || ''
352  return ''
353}
354
355const pct = (k: string) => usage?.rateLimits?.find((l: any) => l.kind === k)?.percentUsed
356
357const take = (u: any) => {
358  if (!u) return
359  usage = u
360  const p = pct('five_hour')
361  if (typeof p === 'number') {
362    samples.push({ t: now(), pct: p })
363    samples = samples.filter((s) => now() - s.t < 3600000)
364  }
365}
366
367const remaining = () => {
368  const p = pct('five_hour')
369  if (typeof p !== 'number' || samples.length < 2) return undefined
370  const first = samples[0]
371  const rate = (p - first.pct) / ((now() - first.t) / 60000)
372  if (rate <= 0) return undefined
373  return ((100 - p) / rate) * 60000
374}
375
376const EFFORTS = [
377  { id: 'low', name: 'LOW', get hue() { return RGB.cyan } },
378  { id: 'medium', name: 'MEDIUM', get hue() { return RGB.lime } },
379  { id: 'high', name: 'HIGH', get hue() { return RGB.amber } },
380  { id: 'xhigh', name: 'XHIGH', get hue() { return RGB.orange } },
381  { id: 'max', name: 'MAX', get hue() { return RGB.red } },
382]
383
384const effortLevel = (v = effort) => {
385  if (typeof v === 'number') return Math.max(1, Math.min(5, Math.round(Math.log2(Math.max(1024, v) / 1024)) + 1))
386  return EFFORTS.findIndex((x) => x.id === v) + 1
387}
388
389const effortName = () => (typeof effort === 'number' ? `${Math.round(effort / 1000)}K` : EFFORTS[effortLevel() - 1]?.name || '–')
390
391const hex = (n: number) => '#' + n.toString(16).padStart(6, '0')
392
393const setEffort = (v: string | number | undefined) => {
394  if (v === undefined || v === effort) return
395  effortFrom = effortShown()
396  effortAt = now()
397  effort = v
398}
399
400const effortShown = () => {
401  const k = Math.min(1, (now() - effortAt) / 1100)
402  return effortFrom + (effortLevel() - effortFrom) * (1 - (1 - k) ** 3)
403}
404
405const battery = () => (usage?.context?.percent ?? 0) >= BATTERY_AT || (pct('five_hour') ?? 0) >= BATTERY_AT
406
407async function ghEnv($: any, cwd: string) {
408  const r = await $.process.run(['git', 'remote', 'get-url', 'origin'], { cwd, timeoutMs: 5000 }).catch(() => undefined)
409  const url = r?.stdout?.trim() || ''
410  if (!url) return undefined
411  if (!/github\.com[:/]gonzalonicolasr\//.test(url)) return {}
412  const t = await $.process.run(['gh', 'auth', 'token', '--user', 'gonzalonicolasr'], { timeoutMs: 5000 }).catch(() => undefined)
413  return t?.exitCode === 0 ? { GH_TOKEN: t.stdout.trim() } : {}
414}
415
416const WS_SCAN = [
417  'while IFS= read -r r; do',
418  '  [ -e "$r/.git" ] || continue',
419  '  e=$(git -C "$r" config user.email 2>/dev/null)',
420  '  [ -n "$e" ] || continue',
421  '  n=${r%/}; n=${n##*/}',
422  '  git -C "$r" log --all --since=26.weeks --format="D %H %ad" --date=short --author="$e" 2>/dev/null',
423  '  git -C "$r" log --all -3 --since=26.weeks --format="C%x1f$n%x1f%ct%x1f%h%x1f%s%x1f$r" --author="$e" 2>/dev/null',
424  "done | awk '/^D /{ if (!seen[$2]++) c[$3]++; next } { print } END { for (d in c) printf \"D\\x1f%d\\x1f%s\\n\", c[d], d }'",
425].join('\n')
426
427const WS_STATE = 'while IFS= read -r r; do printf "%s\\x1f%s\\x1f%s\\n" "$r" "$(git -C "$r" rev-parse --abbrev-ref HEAD 2>/dev/null)" "$(git -C "$r" status --porcelain 2>/dev/null | wc -l)"; done'
428
429async function refreshWorkspace($: any) {
430  if (wsBusy || !home) return
431  wsBusy = true
432  try {
433    let roots = [`${home}/projects`]
434    try {
435      const cfg = JSON.parse(String((await $.fs.read(`${home}/.config/nerv/projects.json`).catch(() => '')) || '{}'))
436      if (Array.isArray(cfg.roots) && cfg.roots.length) roots = cfg.roots.map((r: string) => String(r).replace(/^~(?=\/|$)/, home))
437    } catch {}
438    const dirs: string[] = []
439    for (const root of roots) for (const d of ((await $.fs.list(root).catch(() => [])) as any[])) if (d.kind === 'dir') dirs.push(`${root}/${d.name}`)
440    const r = await $.process.run(['bash', '-c', WS_SCAN], { stdin: dirs.join('\n') + '\n', timeoutMs: 60000 }).catch(() => undefined)
441    if (r?.exitCode !== 0) return
442    const days: Record<string, number> = {}
443    const commits: any[] = []
444    const seen = new Set<string>()
445    for (const line of String(r.stdout).split('\n')) {
446      const f = line.split('\x1f')
447      if (f[0] === 'D') days[f[2]] = (days[f[2]] || 0) + Number(f[1])
448      else if (f[0] === 'C' && !seen.has(f[3])) {
449        seen.add(f[3])
450        commits.push({ repo: f[1], ct: Number(f[2]), h: f[3], s: f[4], path: f[5] })
451      }
452    }
453    commits.sort((a, b) => b.ct - a.ct)
454    const last = new Map<string, any>()
455    for (const c of commits) if (!last.has(c.repo)) last.set(c.repo, c)
456    const top = [...last.values()].slice(0, 6)
457    const st = await $.process.run(['bash', '-c', WS_STATE], { stdin: top.map((c) => c.path).join('\n') + '\n', timeoutMs: 30000 }).catch(() => undefined)
458    const info = new Map<string, string[]>()
459    for (const line of String(st?.stdout || '').split('\n')) if (line) info.set(line.split('\x1f')[0], line.split('\x1f'))
460    ws = {
461      days,
462      repos: top.map((c) => ({ name: c.repo, ct: c.ct, branch: info.get(c.path)?.[1] || '?', dirty: Number(info.get(c.path)?.[2] || 0) })),
463      recent: commits.slice(0, 8),
464    }
465    wsAt = now()
466    if (!gitInfo.ok) commitDays = ws.days
467    $.ui.invalidate('ui.render')
468  } finally {
469    wsBusy = false
470  }
471}
472
473async function refreshWidePRs($: any) {
474  const who = await $.process.run(['bash', '-c', 'gh auth status 2>&1 | grep -o "account [^ ]*" | cut -d" " -f2 | sort -u'], { timeoutMs: 10000 }).catch(() => undefined)
475  const users = String(who?.stdout || '').split('\n').filter(Boolean)
476  const all: any[] = []
477  for (const u of users) {
478    const t = await $.process.run(['gh', 'auth', 'token', '--user', u], { timeoutMs: 5000 }).catch(() => undefined)
479    if (t?.exitCode !== 0) continue
480    const r = await $.process
481      .run(['gh', 'search', 'prs', '--author', '@me', '--state', 'open', '--limit', '15', '--json', 'repository,number,title,url,isDraft'], { env: { GH_TOKEN: t.stdout.trim() }, timeoutMs: 20000 })
482      .catch(() => undefined)
483    if (r?.exitCode !== 0) continue
484    try {
485      for (const p of JSON.parse(r.stdout)) all.push({ ...p, repo: p.repository?.name || '' })
486    } catch {}
487  }
488  prs = all
489  prsWide = true
490  prError = users.length ? '' : 'sin cuentas de gh'
491}
492
493async function refreshPRs($: any) {
494  const cwd = await $.session.cwd().catch(() => '')
495  if (!cwd) return
496  const env = await ghEnv($, cwd)
497  if (!env) return refreshWidePRs($)
498  prsWide = false
499  if (!ghMe) {
500    const me = await $.process.run(['gh', 'api', 'user', '-q', '.login'], { cwd, env, timeoutMs: 10000 }).catch(() => undefined)
501    ghMe = me?.exitCode === 0 ? me.stdout.trim() : ''
502  }
503  const r = await $.process
504    .run(['gh', 'pr', 'list', '--state', 'open', '--limit', '20', '--json', 'number,title,reviewDecision,isDraft,statusCheckRollup,url,author'], { cwd, env, timeoutMs: 20000 })
505    .catch((err: any) => ({ exitCode: 1, stdout: '', stderr: String(err) }))
506  if (r.exitCode !== 0) prError = clip((r.stderr || 'gh falló').split('\n')[0], 60)
507  else
508    try {
509      prs = JSON.parse(r.stdout)
510      prError = ''
511    } catch {
512      prError = 'respuesta de gh ilegible'
513    }
514}
515
516// Cuenta de la sesión: personal = ~/.claude directo a Anthropic; priv8 = la misma config pero por
517// el CPAM con un modelo priv8/…. Otro config dir (Wibond) u otro prefijo del CPAM: sin menú.
518export const acctFor = (o: { configDir: string; home: string; cpam: boolean; model: string }) =>
519  o.configDir && o.configDir !== `${o.home}/.claude` ? '' : !o.cpam ? 'personal' : /^priv8\//.test(o.model) ? 'priv8' : ''
520// El modelo priv8/ al que se pasa: el mismo Claude de ahora si priv8 lo tiene, si no el mismo
521// tipo (opus/sonnet/haiku) más nuevo, si no el opus más nuevo. '' = el CPAM no expone priv8/.
522export const priv8Pick = (ids: readonly string[], model: string) => {
523  const mine = ids.filter((x) => /^priv8\/claude-/.test(x)).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
524  const b = bare(model).replace(/\[.*\]$/, '')
525  const fam = /^(?:claude-)?(opus|sonnet|haiku|fable)\b/.exec(b)?.[1] || 'opus'
526  return mine.find((x) => x === 'priv8/' + b) || mine.find((x) => x.startsWith(`priv8/claude-${fam}-`)) || mine.find((x) => x.startsWith('priv8/claude-opus-')) || mine[0] || ''
527}
528const acctNow = () => acctFor({ configDir, home, cpam: mdlCpam, model })
529const acctName = (id: string) => (emails[id] || mdl.emails[id] || id).split('@')[0]
530const acctToggle = ($: any) => {
531  acctMenu = !acctMenu
532  acctNote = ''
533  if (acctMenu) void refreshModels($, true)
534  $.ui.invalidate('ui.render')
535}
536
537async function loadEmails($: any) {
538  for (const a of ACCOUNTS.filter((x) => x.conf)) {
539    try {
540      emails[a.id] = String(JSON.parse((await $.fs.read(`${home}/${a.conf}`).catch(() => '')) || '{}')?.oauthAccount?.emailAddress || '')
541    } catch {}
542  }
543}
544
545async function switchAccount($: any, id: string) {
546  // No reemplaza la sesión: abre una tab nueva de herdr que reanuda esta conversación (fork).
547  acctNote = working ? 'esperá a que termine el turno' : !paneId || !sessionId ? 'sólo se puede dentro de herdr' : ''
548  if (!acctNote && id === 'priv8' && !mdl.ids.length) await refreshModels($, true)
549  let target = id === 'priv8' ? priv8Pick(mdl.ids, model) : ''
550  if (!acctNote && id === 'priv8' && !target) {
551    await refreshModels($, true) // la lista cacheada puede ser de antes del prefix
552    target = priv8Pick(mdl.ids, model)
553  }
554  if (!acctNote && id === 'priv8' && !target) acctNote = mdl.ids.length ? 'el CPAM no expone priv8/ — falta el prefix' : mdl.err || 'el CPAM no respondió'
555  if (!acctNote) {
556    await relaunchWith($, target)
557    acctNote = mdlNote.startsWith('✓') ? `✓ ${acctName(id)} en tab nueva (fork de esta conversación)` : mdlNote
558  }
559  $.ui.invalidate('ui.render')
560}
561
562async function refreshTasks($: any) {
563  if (!home || !sessionId) return
564  const list = (await $.env.get('CLAUDE_CODE_TASK_LIST_ID').catch(() => '')) || sessionId
565  const dir = `${configDir || home + '/.claude'}/tasks/${list}`
566  const files = ((await $.fs.list(dir).catch(() => [])) as any[]).filter((f) => /^\d+\.json$/.test(f.name))
567  const out: typeof sessionTasks = []
568  for (const f of files) {
569    try {
570      const x = JSON.parse((await $.fs.read(`${dir}/${f.name}`).catch(() => '')) || '{}')
571      if (x?.subject && x.status !== 'deleted') out.push({ id: String(x.id ?? f.name.slice(0, -5)), subject: String(x.subject), status: String(x.status || 'pending'), blockedBy: (x.blockedBy || []).map(String) })
572    } catch {}
573  }
574  sessionTasks = out.sort((a, b) => Number(a.id) - Number(b.id))
575}
576
577async function refreshLocal($: any) {
578  await refreshTasks($)
579  const cwd = await $.session.cwd().catch(() => '')
580  cwdNow = cwd
581  project = base(cwd)
582  model = await $.session.model().catch(() => model)
583  const b = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd, timeoutMs: 5000 }).catch(() => undefined)
584  branch = b?.exitCode === 0 ? b.stdout.trim() : ''
585  const tl = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd, timeoutMs: 5000 }).catch(() => undefined)
586  gitRoot = tl?.exitCode === 0 ? tl.stdout.trim() : ''
587  const em = await $.process.run(['git', 'config', 'user.email'], { cwd, timeoutMs: 5000 }).catch(() => undefined)
588  const email = em?.exitCode === 0 ? em.stdout.trim() : ''
589  const lg = await $.process
590    .run(['git', 'log', '--all', '--since=26.weeks', '--format=%ad', '--date=short', ...(email ? ['--author=' + email] : [])], { cwd, timeoutMs: 10000 })
591    .catch(() => undefined)
592  const days: Record<string, number> = {}
593  if (lg?.exitCode === 0) for (const d of lg.stdout.split('\n')) if (d) days[d] = (days[d] || 0) + 1
594  commitDays = days
595  commitAuthor = email
596  const stb = await $.process.run(['git', 'status', '--porcelain=2', '--branch'], { cwd, timeoutMs: 8000 }).catch(() => undefined)
597  const sl = stb?.exitCode === 0 ? stb.stdout.split('\n') : []
598  const ab = (sl.find((l: string) => l.startsWith('# branch.ab')) || '').match(/\+(\d+) -(\d+)/)
599  const up = (sl.find((l: string) => l.startsWith('# branch.upstream')) || '').replace('# branch.upstream ', '')
600  const dirty = sl.filter((l: string) => l && !l.startsWith('#')).length
601  const rl = await $.process.run(['git', 'log', '-8', '--format=%h%x1f%s%x1f%ar%x1f%an'], { cwd, timeoutMs: 8000 }).catch(() => undefined)
602  gitInfo = {
603    ok: stb?.exitCode === 0,
604    upstream: up,
605    ahead: ab ? Number(ab[1]) : 0,
606    behind: ab ? Number(ab[2]) : 0,
607    dirty,
608    recent: rl?.exitCode === 0 ? rl.stdout.split('\n').filter(Boolean).map((l: string) => l.split('\x1f')) : [],
609  }
610  if (!gitInfo.ok) {
611    if (ws) commitDays = ws.days
612    if (now() - wsAt > 300000) void refreshWorkspace($)
613  }
614  const st: any = await $.settings.read().catch(() => undefined)
615  const se = String(st?.effortLevel || '')
616  if (se && se !== settingsEffort) {
617    settingsEffort = se
618    if (!effortPick) setEffort(se)
619  }
620  if (home) {
621    const log = await $.fs.read(`${home}/.local/state/claude-healthcheck.log`).catch(() => '')
622    const lines = (log || '').trim().split('\n')
623    const last = lines.filter((l: string) => /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d /.test(l)).at(-1) || ''
624    const when = last.slice(11, 16)
625    if (/ ok$/.test(last)) health = { ok: true, when, text: 'servicios ok' }
626    else if (last) {
627      const i = lines.lastIndexOf(last)
628      const falla = lines.slice(i + 1).find((l: string) => l.startsWith('- ')) || 'algo falló'
629      health = { ok: false, when, text: falla.replace(/^- /, '') }
630    }
631  }
632  // la línea bajo el prompt sólo se redibuja si alguien lo pide (rama, modelo, git)
633  $.ui.invalidate('ui.render')
634}
635
636async function refreshHw($: any) {
637  if (hwBusy || !home) return
638  hwBusy = true
639  try {
640    const env: Record<string, string> = ramTotal ? { JCODE_RAIL_RAM_TOTAL: ramTotal } : {}
641    const r = await $.process.run([`${home}/.local/bin/jcode-rail`, '--json'], { env, timeoutMs: 8000 }).catch(() => undefined)
642    if (r?.exitCode === 0) {
643      hw = JSON.parse(r.stdout)
644      if (typeof hw?.cpu?.pct === 'number') cpuHist.push(hw.cpu.pct)
645      if (typeof hw?.gpu?.util === 'number') gpuHist.push(hw.gpu.util)
646      while (cpuHist.length > 200) cpuHist.shift()
647      while (gpuHist.length > 200) gpuHist.shift()
648    }
649  } catch {
650  } finally {
651    hwBusy = false
652  }
653}
654
655const LIVE_SNAP = `deep=$1; rt=\${XDG_RUNTIME_DIR:-/run/user/$(id -u)}
656mpvpid() { for p in $(pgrep -x mpv); do tr '\\0' '\\n' </proc/$p/cmdline 2>/dev/null | grep -qx -- "--title=$1" && { echo $p; return; }; done; }
657q() { printf '{"command":["get_property","%s"]}\\n' "$2" | socat -t 0.3 - UNIX-CONNECT:"$rt/$1-mpv.sock" 2>/dev/null | jq -r '.data // empty' 2>/dev/null | head -1; }
658snap() {
659  p=$(mpvpid "$2")
660  if [ -z "$p" ]; then printf '%s\\toff\\n' "$1"; return; fi
661  printf '%s\\ton\\t%s\\t%s\\t%s\\t%s\\n' "$1" "$(q "$2" width)" "$(q "$2" height)" "$(q "$2" estimated-vf-fps)" "$(ps -o %cpu= -p "$p" | tr -d ' ')"
662}
663printf 'dc\t%s\n' "$(jq -c '{ch:.channel.name,g:.channel.guild,n:(.members|length),m:[.members[:9][]|{name,self,speaking,mute,deaf,streaming}],live:.live.on,vc:.live.count,v:[.live.viewers[:7][].name]}' "$rt/nerv-discord.json" 2>/dev/null)"
664snap cam camoverlay
665snap ip iphonecam
666st=\${XDG_STATE_HOME:-$HOME/.local/state}
667printf 'ipstate\\t%s\\t%s\\t%s\\n' "$(cat "$rt/iphonecam-mode" 2>/dev/null)" "$(cat "$st/iphonecam/scene" 2>/dev/null)" "$(cat "$rt/iphonecam-blur" 2>/dev/null)"
668printf 'text\\t%s\\n' "$(tr '\\n\\t' '  ' < "$st/camoverlay-text.txt" 2>/dev/null)"
669printf 'discord\\t%s\\n' "$(pgrep -ix discord >/dev/null && echo 1)"
670if [ "$deep" = 1 ]; then
671  ip=$(jq -r '.. | .cur_dev_ip? // empty' "$HOME/.config/droidcam-obs-client/basic/scenes/Untitled.json" 2>/dev/null | head -1)
672  if [ -n "$ip" ] && name=$(curl -fs -m 1.5 "http://$ip:4747/v1/phone/name"); then
673    printf 'ipapi\\t%s\\t%s\\t%s\\n' "$(echo "$name" | tr '\\n\\t' '  ')" "$(curl -fs -m 1.5 "http://$ip:4747/v1/phone/battery_info" | tr '\\n\\t' '  ')" "$(curl -fs -m 1.5 "http://$ip:4747/v1/camera/info" | tr '\\n\\t' '  ')"
674  else printf 'ipapi\\t\\n'; fi
675fi`
676
677const liveJson = (s: string): any => {
678  try {
679    return JSON.parse(s)
680  } catch {
681    return undefined
682  }
683}
684
685export const liveBattery = (raw: string): { bat: number; charging: boolean } => {
686  const j = liveJson(raw)
687  const lvl = Number(j?.level ?? j?.battery ?? j?.percent ?? (typeof j === 'number' ? j : NaN))
688  return { bat: Number.isFinite(lvl) ? Math.round(lvl <= 1 ? lvl * 100 : lvl) : -1, charging: !!(j?.charging ?? j?.isCharging ?? j?.plugged) }
689}
690
691export const liveDc = (raw: string): LiveDc | null | undefined => {
692  const j = liveJson(raw)
693  if (!j || typeof j !== 'object') return undefined
694  if (!j.ch) return null
695  const m = (Array.isArray(j.m) ? j.m : []).map((x: any) => ({ name: String(x?.name || '?'), self: !!x?.self, speaking: !!x?.speaking, mute: !!x?.mute, deaf: !!x?.deaf, streaming: !!x?.streaming }))
696  const v = (Array.isArray(j.v) ? j.v : []).map((x: any) => String(x || '?'))
697  return { ch: String(j.ch), g: String(j.g || ''), n: Math.max(Number(j.n) || 0, m.length), m, live: !!j.live, vc: Math.max(Number(j.vc) || 0, v.length), v }
698}
699
700// El chat del canal de voz viene en nerv-discord.json. Sin campo chat = el NervLive cargado
701// en Discord es el viejo (falta recargar); lista vacía = no hay mensajes.
702export const liveChat = (raw: string): LiveChatMsg[] | undefined => {
703  const c = liveJson(raw)?.chat
704  if (!c || typeof c !== 'object' || !Array.isArray(c.m)) return undefined
705  return c.m.slice(-8).map((x: any) => ({ a: String(x?.a || '?'), t: String(x?.t ?? '').replace(/\s+/g, ' ').trim(), ts: Number(x?.ts) || 0, self: !!x?.self }))
706}
707
708// Corta en palabras por ancho de celdas: la primera línea mide `first`, las siguientes `rest`.
709// Una palabra más larga que la línea se parte.
710export const wrapCells = (s: string, first: number, rest = first): string[] => {
711  const out: string[] = []
712  let line = ''
713  const room = () => Math.max(1, out.length ? rest : first)
714  for (const word of String(s).split(' ').filter(Boolean)) {
715    let wd = word
716    if (line && cellWidth(line) + 1 + cellWidth(wd) > room()) {
717      out.push(line)
718      line = ''
719    }
720    while (cellWidth((line ? line + ' ' : '') + wd) > room()) {
721      let cut = ''
722      for (const ch of wd) {
723        if (cellWidth((line ? line + ' ' : '') + cut + ch) > room()) break
724        cut += ch
725      }
726      if (!cut && line) {
727        out.push(line)
728        line = ''
729        continue
730      }
731      if (!cut) cut = [...wd][0]!
732      out.push((line ? line + ' ' : '') + cut)
733      line = ''
734      wd = wd.slice(cut.length)
735    }
736    line = line ? line + ' ' + wd : wd
737  }
738  if (line || !out.length) out.push(line)
739  return out
740}
741
742// Filas visibles de la tarjeta del chat en el dock; el resto se lee scrolleando adentro.
743export const CHAT_ROWS = 5
744let chatPrevMax = 0
745// Scroll del chat: si estaba abajo del todo (o nunca se tocó) sigue anclado al último mensaje;
746// si subiste a leer, se queda donde estabas.
747export const chatScroll = (off: number | undefined, prevMax: number, max: number) => (off === undefined || off >= prevMax ? max : Math.min(off, max))
748
749export type ChatLine = { author?: string; text: string; self: boolean; who: number }
750// Líneas del chat para `width` celdas, lo más nuevo abajo, en `max` líneas como mucho. Entran
751// mensajes enteros desde el último hacia atrás; si el último solo no entra, se recorta con "…".
752export const chatLines = (msgs: readonly LiveChatMsg[], width: number, max: number): ChatLine[] => {
753  const out: ChatLine[] = []
754  for (let i = msgs.length - 1; i >= 0 && max > 0; i--) {
755    const m = msgs[i]!
756    const author = clip(m.a, Math.max(4, Math.floor(width / 2)))
757    const body = wrapCells(m.t, width - cellWidth(author) - 2, width - 2)
758    const who = [...m.a].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) >>> 0, 7)
759    const lines: ChatLine[] = body.map((text, j) => (j ? { text: '  ' + text, self: m.self, who } : { author, text, self: m.self, who }))
760    if (out.length + lines.length > max) {
761      if (!out.length) {
762        const keep = lines.slice(0, max)
763        const last = keep[max - 1]!
764        const room = Math.max(1, width - (last.author ? cellWidth(last.author) + 2 : 0))
765        last.text = cellWidth(last.text) < room ? last.text + '…' : clip(last.text, room)
766        return keep
767      }
768      break
769    }
770    out.unshift(...lines)
771  }
772  return out
773}
774
775// En Go Live se listan sólo los que te miran; los que no entran quedan en "+N más".
776export const liveViewers = (dc: LiveDc) => ({ names: dc.v, more: Math.max(0, dc.vc - dc.v.length) })
777
778export const liveLens = (raw: string): string => {
779  const j = liveJson(raw)
780  if (!j) return ''
781  const list = j.cameras || j.lenses || j.list
782  const act = j.active ?? j.current ?? j.camera
783  if (Array.isArray(list) && act != null) {
784    const x = list[Number(act)] ?? list.find((c: any) => c?.id === act || c?.index === act)
785    const nm = typeof x === 'string' ? x : x?.name || x?.label || x?.type
786    if (nm) return String(nm)
787  }
788  return typeof act === 'string' ? act : act != null ? `lente ${act}` : ''
789}
790
791async function refreshLive($: any) {
792  if (live.busy || !home) return
793  live.busy = true
794  try {
795    const n = ++live.n
796    const r = await $.process.run(['bash', '-c', LIVE_SNAP, 'nerv-live', n % 10 === 1 ? '1' : '0'], { timeoutMs: 12000 }).catch(() => undefined)
797    for (const line of String(r?.stdout || '').split('\n')) {
798      const f = line.split('\t')
799      if (f[0] === 'cam' || f[0] === 'ip') {
800        const c = live[f[0] as 'cam' | 'ip']
801        c.on = f[1] === 'on'
802        if (c.on) {
803          c.w = Number(f[2]) || 0
804          c.h = Number(f[3]) || 0
805          c.fps = Math.round(Number(f[4]) || 0)
806          c.cpu = Math.round(Number(f[5]) || 0)
807        }
808      } else if (f[0] === 'ipstate') {
809        live.ip.mode = f[1] || ''
810        live.ip.scene = f[2] || ''
811        live.ip.blur = f[3] === '1'
812      } else if (f[0] === 'text') live.text = f[1] || ''
813      else if (f[0] === 'dc') live.dc = liveDc(f[1] || '')
814      else if (f[0] === 'discord') live.discord = f[1] === '1'
815      else if (f[0] === 'ipapi') {
816        live.ip.reach = !!f[1]
817        if (f[1]) {
818          live.ip.name = clip(liveJson(f[1])?.name || f[1].replace(/^"|"$/g, ''), 24)
819          Object.assign(live.ip, liveBattery(f[2] || ''))
820          live.ip.lens = liveLens(f[3] || '')
821        }
822      }
823    }
824    live.chat = live.discord && live.dc ? liveChat(String((await $.fs.read(`${runDir}/nerv-discord.json`).catch(() => '')) || '')) : undefined
825  } finally {
826    live.busy = false
827  }
828  $.ui.invalidate('ui.render')
829}
830
831async function liveRun($: any, args: string[]) {
832  await $.process.run(['setsid', '-f', ...args], { timeoutMs: 5000 }).catch(() => undefined)
833  await $.clock.sleep(1500).catch(() => undefined)
834  await refreshLive($)
835}
836
837async function herdrJson($: any, args: string[]) {
838  const r = await $.process.run(['herdr', ...args], { timeoutMs: 5000 }).catch(() => undefined)
839  if (r?.exitCode !== 0) return undefined
840  try {
841    return JSON.parse(r.stdout).result
842  } catch {
843    return undefined
844  }
845}
846
847async function checkFocus($: any) {
848  const r = await herdrJson($, ['pane', 'get', paneId])
849  if (!r?.pane) return
850  const was = away
851  away = r.pane.focused === false
852  if (!was && away) stopFast()
853  if (was && !away) {
854    startFast($)
855    refreshLocal($)
856    $.ui.invalidate('ui.render')
857  }
858}
859
860function stopFast() {
861  for (const t of fast) t.cancel()
862  fast = []
863}
864
865function startFast($: any) {
866  stopFast()
867  fast.push(
868    $.clock.every(125, () => {
869      frame++
870      if (!quiet && !placedOnce && frame % 24 === 0) void openPane($)
871      if (quiet || !paneOpen || away) return
872      if (tab === 'hw' && frame % 24 === 0) refreshHw($)
873      if (tab === 'live' && frame % 12 === 0) void refreshLive($)
874      if (tab === 'forge' && frame % 8 === 0) refreshForge($)
875      if (tab === 'nodd' && frame % 16 === 0) refreshNodd($)
876      if (tab === 'edd' && frame % 16 === 0) void refreshEdd($)
877      if (tab === 'cortex' && frame % 960 === 0) refreshCortex($)
878      if (tab === 'yt' && frame % 8 === 0) ytPoll($)
879      if (tab === 'models' && frame % 480 === 0) void refreshModels($)
880      if ((tab === 'models' || acctMenu) && frame % 24 === 0) void cpamWatch($)
881      if (working || battery() || patternBlue || now() < confettiUntil || tab !== 'magi' || frame % 2 === 0) $.ui.invalidate('ui.render')
882    }),
883    $.clock.every(50, () => {
884      if (quiet || !paneOpen || away || tab !== 'magi' || folded.has('sync') || !gauges.length) return
885      for (const g of gauges) $.ui.blit({ requestId: PANE, key: g.key, cells: gaugeCells(g.p, g.w, g.hue), columns: g.w, rows: 1 }).catch(() => undefined)
886    }),
887    $.clock.every(G0N_MS / 2, () => {
888      if (quiet || !paneOpen || away || g0nShown < 0 || g0nFrame() === g0nShown) return
889      $.ui.invalidate('ui.render')
890    }),
891  )
892}
893
894async function loadRecap($: any) {
895  const all = ((await $.store.get('sessions').catch(() => undefined)) || {}) as Record<string, any>
896  const cut = now() - 7 * 86400000
897  for (const k of Object.keys(all)) if (all[k].beat < cut) delete all[k]
898  const prev = Object.entries(all)
899    .filter(([id, s]: any) => id !== sessionId && s.cwd === cwdNow && now() - s.beat > 180000 && s.prompt)
900    .sort(([, a]: any, [, b]: any) => b.beat - a.beat)[0]
901  if (prev) {
902    recap = { prompt: (prev[1] as any).prompt, at: (prev[1] as any).beat }
903    delete all[prev[0]]
904  }
905  all[sessionId] = { cwd: cwdNow, beat: now(), prompt: '' }
906  await $.store.set('sessions', all).catch(() => undefined)
907}
908
909async function beat($: any, prompt?: string) {
910  if (!sessionId) return
911  const all = ((await $.store.get('sessions').catch(() => undefined)) || {}) as Record<string, any>
912  const mine = all[sessionId] || { cwd: cwdNow, prompt: '' }
913  all[sessionId] = { ...mine, beat: now(), ...(prompt ? { prompt: clip(prompt.replace(/\s+/g, ' '), 140) } : {}) }
914  await $.store.set('sessions', all).catch(() => undefined)
915}
916
917async function clean($: any) {
918  const all = ((await $.store.get('sessions').catch(() => undefined)) || {}) as Record<string, any>
919  delete all[sessionId]
920  await $.store.set('sessions', all).catch(() => undefined)
921}
922
923const cells = (cols: number, rows: number, paint: (x: number, y: number) => number) => {
924  const words = new Uint32Array(cols * rows * 3)
925  for (let r = 0; r < rows; r++)
926    for (let c = 0; c < cols; c++) {
927      const top = paint(c, r * 2)
928      const bot = paint(c, r * 2 + 1)
929      const i = (r * cols + c) * 3
930      if (top === RGB.none && bot === RGB.none) {
931        words[i] = 0x20
932        words[i + 1] = RGB.none
933        words[i + 2] = RGB.none
934      } else if (top === RGB.none) {
935        words[i] = 0x2584
936        words[i + 1] = bot
937        words[i + 2] = RGB.none
938      } else {
939        words[i] = 0x2580
940        words[i + 1] = top
941        words[i + 2] = bot
942      }
943    }
944  return (new Uint8Array(words.buffer) as any).toBase64()
945}
946
947const TRAIL = [0x28ff, 0x28f7, 0x28f6, 0x2876, 0x2836, 0x2816, 0x2806, 0x2804]
948
949const glyphs = (cols: number, rows: number, paint: (x: number, y: number) => [number, number] | undefined) => {
950  const words = new Uint32Array(cols * rows * 3)
951  for (let y = 0; y < rows; y++)
952    for (let x = 0; x < cols; x++) {
953      const i = (y * cols + x) * 3
954      const g = paint(x, y)
955      words[i] = g ? g[0] : 0x20
956      words[i + 1] = g ? g[1] : RGB.none
957      words[i + 2] = RGB.none
958    }
959  return (new Uint8Array(words.buffer) as any).toBase64()
960}
961
962const hash = (x: number, y: number, k: number) => {
963  const v = Math.sin(x * 127.1 + y * 311.7 + k * 74.7) * 43758.5453
964  return v - Math.floor(v)
965}
966
967const ramp = (stops: number[], v: number) => {
968  const p = Math.max(0, Math.min(0.9999, v)) * (stops.length - 1)
969  const i = Math.floor(p)
970  return mix(stops[i], stops[i + 1], p - i)
971}
972
973const G0N_FRAMES = 64
974const G0N_MS = 70
975let g0nShown = -1
976const g0nFrame = () => Math.floor(now() / G0N_MS) % G0N_FRAMES
977// En EN VIVO el cartel se oculta y sus filas quedan para las cámaras y el chat.
978export const g0nShownIn = (tabId: string) => tabId !== 'live'
979// El medidor de EFFORT de abajo también se oculta en EN VIVO: esas filas van a las cámaras.
980export const effortShownIn = (tabId: string) => tabId !== 'live'
981
982const dayKey = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
983
984const heatColor = (n: number) => (n <= 0 ? 0x3a2d52 : n === 1 ? RGB.violet : n <= 3 ? RGB.purple : n <= 6 ? RGB.lime : n <= 10 ? RGB.orange : RGB.red)
985
986const commitStats = (weeks: number) => {
987  const today = new Date()
988  let total = 0
989  for (let i = 0; i < weeks * 7; i++) total += commitDays[dayKey(new Date(today.getTime() - i * 86400000))] || 0
990  let streak = 0
991  for (let i = commitDays[dayKey(today)] ? 0 : 1; commitDays[dayKey(new Date(today.getTime() - i * 86400000))]; i++) streak++
992  return { total, streak, today: commitDays[dayKey(today)] || 0 }
993}
994
995const heatCells = (cols: number, weeks: number) => {
996  const today = new Date()
997  const dow = today.getDay()
998  const pulse = 0.5 + 0.5 * Math.sin(frame * 0.35)
999  return glyphs(cols, 7, (x, y) => {
1000    if (x % 2 === 1) return undefined
1001    const w = weeks - 1 - x / 2
1002    const back = w * 7 + (dow - y)
1003    if (w < 0 || back < 0) return undefined
1004    const n = commitDays[dayKey(new Date(today.getTime() - back * 86400000))] || 0
1005    const c = heatColor(n)
1006    return [0x25a0, back === 0 ? mix(n ? c : RGB.purple, 0xffffff, 0.25 + 0.45 * pulse) : c]
1007  })
1008}
1009
1010const sparkCells = (cols: number, rows: number) => {
1011  const h = rows * 2
1012  const level = (hist: number[], x: number) => {
1013    const v = hist[hist.length - cols + x]
1014    return typeof v === 'number' ? h - 1 - Math.round((v / 100) * (h - 1)) : undefined
1015  }
1016  return cells(cols, rows, (x, y) => {
1017    const g = level(gpuHist, x)
1018    const c = level(cpuHist, x)
1019    if (c !== undefined && y === c) return RGB.lime
1020    if (g !== undefined && y >= g) return y === g ? RGB.purple : RGB.deep
1021    return RGB.none
1022  })
1023}
1024
1025const SCAN_W = 18
1026const VERBS: Record<string, string[]> = {
1027  thinking: ['Sincronizando', 'Consultando a MAGI', 'Analizando patrón', 'Calculando'],
1028  requesting: ['Conectando cable umbilical', 'Enlazando con MAGI'],
1029  responding: ['Transmitiendo', 'Redactando informe'],
1030  'tool-input': ['Preparando despliegue', 'Armando la orden'],
1031  'tool-use': ['Desplegando', 'Ejecutando operación'],
1032}
1033const SCAN_COLOR: Record<string, number> = {
1034  get thinking() { return RGB.purple },
1035  get requesting() { return RGB.amber },
1036  get responding() { return RGB.cyan },
1037  get 'tool-input'() { return RGB.lime },
1038  get 'tool-use'() { return RGB.lime },
1039}
1040
1041const mix = (a: number, b: number, k: number) => {
1042  const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - k) + ((b >> s) & 255) * k)
1043  return (ch(16) << 16) | (ch(8) << 8) | ch(0)
1044}
1045
1046const scanCells = (mode: string) => {
1047  const span = SCAN_W - 1
1048  const pos = frame % (span * 2)
1049  const head = pos <= span ? pos : span * 2 - pos
1050  const dir = pos <= span ? 1 : -1
1051  const hue = SCAN_COLOR[mode] || RGB.purple
1052  return glyphs(SCAN_W, 1, (x) => {
1053    const behind = (head - x) * dir
1054    if (x === head) return [0x28ff, 0xffffff]
1055    if (behind > 0 && behind < TRAIL.length) return [TRAIL[behind], mix(hue, RGB.trail, behind / TRAIL.length)]
1056    if (hash(x, 0, Math.floor(frame / 2)) > 0.8) return [0x2802, RGB.spark]
1057    return undefined
1058  })
1059}
1060
1061const effortGeom = (cols: number) => {
1062  const segW = Math.max(3, Math.floor((cols - 4 - 4) / 5))
1063  return { segW, step: segW + 1 }
1064}
1065
1066const effortCells = (cols: number) => {
1067  const lvl = effortLevel()
1068  const shown = effortShown()
1069  const { segW, step } = effortGeom(cols)
1070  const charging = now() - effortAt < 1100
1071  return cells(cols, 2, (x, py) => {
1072    const sx = x - (3 - py)
1073    if (sx < 0) return RGB.none
1074    const seg = Math.floor(sx / step)
1075    const inner = sx % step
1076    if (seg > 4 || inner >= segW) return RGB.none
1077    const hue = EFFORTS[seg].hue
1078    const fillK = Math.max(0, Math.min(1, shown - seg))
1079    const lit = inner < fillK * segW
1080    const edge = py === 0 || py === 3 || inner === 0 || inner === segW - 1
1081    if (!lit) return edge ? mix(hue, RGB.ink, 0.72) : RGB.none
1082    if (lvl === 5 && seg === 4) return (sx + py + Math.floor(frame / 2)) % 4 < 2 ? RGB.red : 0x3a0a10
1083    let col = mix(mix(hue, RGB.ink, 0.25), hue, inner / Math.max(1, segW - 1))
1084    if (py === 0) col = mix(col, 0xffffff, 0.35)
1085    if (py === 3) col = mix(col, RGB.ink, 0.35)
1086    if (seg === lvl - 1) {
1087      const pulse = 0.5 + 0.5 * Math.sin(frame * (working ? 0.5 : 0.22))
1088      const sweep = (frame * (working ? 0.8 : 0.35)) % (segW + 6) - 3
1089      col = mix(col, 0xffffff, 0.15 * pulse + 0.55 * Math.exp(-(((inner - sweep) / 1.6) ** 2)))
1090    }
1091    if (charging && Math.abs(inner - fillK * segW) < 1.5) col = mix(col, 0xffffff, 0.7)
1092    return col
1093  })
1094}
1095
1096function draw($: any, e: any) {
1097  const { Box, Text, Raster, Button, Link, Input, Image } = $.ui.resolve(e)
1098  const dock = e.props.placement === 'dock' && (e.props.scroll?.bodyRows || 0) > 0
1099  for (const k of Object.keys(cardMax)) delete cardMax[k]
1100  const cols = Math.max(20, (e.props.bodyColumns || 40) - (dock ? 1 : 0))
1101  const compact = !dock
1102  const narrow = compact && cols < 56
1103  const w = cols - 4
1104  const t = (children: any[], color = C.text, extra: any = {}) => Text({ wrap: 'truncate', color, children, ...extra })
1105  const span = (s: string, color: string, extra: any = {}) => Text({ color, children: [s], ...extra })
1106  const foldBtn = (key: string) =>
1107    Button({
1108      key: 'fold-' + key,
1109      label: folded.has(key) ? '▸' : '▾',
1110      plain: true,
1111      dimColor: true,
1112      onPress: async () => {
1113        if (folded.has(key)) folded.delete(key)
1114        else folded.add(key)
1115        $.ui.invalidate('ui.render')
1116        await $.store.set('folded', [...folded]).catch(() => undefined)
1117        await savePrefs($, { folded: [...folded] })
1118      },
1119    })
1120  const titleRow = (key: string, parts: any[], color: string) =>
1121    Box({ key: 'title-' + key, flexDirection: 'row', justifyContent: 'space-between', children: [t(parts, color), foldBtn(key)] })
1122  const card = (key: string, title: string, color: string, rows: any[]) =>
1123    Box({ key, flexDirection: 'column', borderStyle: 'round', borderColor: color, paddingX: 1, children: [titleRow(key, [span(title, color, { bold: true })], color), ...(folded.has(key) ? [] : rows)] })
1124  const kv = (left: any[], right: any[]) => Box({ flexDirection: 'row', justifyContent: 'space-between', children: [t(left), t(right)] })
1125  const kvBtn = (left: any[], btn: any) => Box({ flexDirection: 'row', justifyContent: 'space-between', children: [t(left), btn] })
1126  const scard = (key: string, title: string, color: string, rows: any[], max: number) => {
1127    const content = measure(rows, w)
1128    if (!dock || content <= max || folded.has(key)) return card(key, title, color, rows)
1129    const cmax = content - max
1130    const off = Math.max(0, Math.min(cardScroll[key] || 0, cmax))
1131    cardScroll[key] = off
1132    cardMax[key] = cmax
1133    const thumb = Math.max(1, Math.round((max * max) / content))
1134    const at = Math.round(((max - thumb) * off) / cmax)
1135    const rail: any[] = []
1136    for (let i = 0; i < max; i++) rail.push(Text({ color: i >= at && i < at + thumb ? color : C.dim, children: [i >= at && i < at + thumb ? '┃' : '│'] }))
1137    return Box({
1138      key,
1139      flexDirection: 'column',
1140      borderStyle: 'round',
1141      borderColor: color,
1142      paddingLeft: 1,
1143      children: [
1144        Box({ key: 'title-' + key, flexDirection: 'row', justifyContent: 'space-between', paddingRight: 1, children: [t([span(title, color, { bold: true }), span(`  ↕ ${off + 1}-${off + max}/${content}`, C.dim)], color), foldBtn(key)] }),
1145        Box({
1146          key: key + '-win',
1147          flexDirection: 'row',
1148          height: max,
1149          overflow: 'hidden',
1150          children: [
1151            Box({ key: key + '-clip', flexDirection: 'column', flexGrow: 1, overflow: 'hidden', children: [Box({ key: key + '-in', flexDirection: 'column', flexShrink: 0, marginTop: -off, children: rows })] }),
1152            Box({ key: key + '-rail', flexDirection: 'column', width: 1, children: rail }),
1153          ],
1154        }),
1155      ],
1156    })
1157  }
1158  const chip = (key: string, label: string, active: boolean, bg: string, onPress: () => void) =>
1159    Box({ key: 'box-' + key, paddingX: 1, backgroundColor: active ? bg : C.chipDim, children: [Button({ key, label, plain: true, dimColor: !active, onPress })] })
1160
1161  const out: any[] = []
1162  const alert = battery()
1163  const ink = C.ink
1164  const magi = ['メルキオール', 'バルタザール', 'カスパー']
1165  const vote = (i: number) => {
1166    if (alert || (patternBlue && i === 2)) return { word: '否決', fg: blink() ? C.lime : C.purple, bg: C.chipDim, on: true }
1167    if (working && Math.floor(frame / 6) % 3 === i) return { word: '審議', fg: C.lime, bg: C.chipDim, on: true }
1168    if (working) return { word: '待機', fg: C.dim, bg: C.chipDim, on: false }
1169    return { word: '承認', fg: C.muted, bg: C.chipDim, on: false }
1170  }
1171  if (!g0nShownIn(tab)) g0nShown = -1
1172  else if (Image && e.surface === 'terminal') {
1173    const f = g0nFrame()
1174    g0nShown = f
1175    out.push(Box({ key: 'g0n', children: [Image({ key: 'g0n-img', source: { file: `${$.plugin.root}/assets/g0n/${themeId}/${String(f).padStart(2, '0')}.png`, format: 'png' }, columns: Math.max(1, cols - 2), rows: 6, alt: ' ' })] }))
1176  }
1177  out.push(
1178    Box({
1179      flexDirection: 'row',
1180      justifyContent: 'space-between',
1181      marginRight: 2,
1182      children: [
1183        t([
1184          span(' NERV ', ink, { bold: true, backgroundColor: alert && blink() ? C.lime : C.purple }),
1185          ...(narrow ? [span(' MAGI ', C.dim), ...[0, 1, 2].map((i) => span(vote(i).on ? '◆' : '◇', vote(i).fg, { bold: vote(i).on }))] : [span(' ネルフ', C.orange, { bold: true }), span(' ⟋ MAGI', C.dim)]),
1186        ]),
1187        t([
1188          ...(compact && !narrow ? [0, 1, 2].map((i) => span(` ${'メバカ'[i]}·${vote(i).word} `, vote(i).fg, { bold: vote(i).on })) : []),
1189          span(compact ? ' ' : ''),
1190          working
1191            ? span(` ${SPIN[frame % 4]} OPERANDO `, ink, { bold: true, backgroundColor: C.lime })
1192            : span(' ◎ EN ESPERA ', C.muted, { backgroundColor: C.chip }),
1193        ]),
1194      ],
1195    }),
1196  )
1197  if (!compact)
1198  out.push(
1199    Box({
1200      flexDirection: 'row',