Harness opinionado de Claude Code para construir aplicaciones serverless en Azure con Event Driven Architecture, Event Sourcing (Marten + Wolverine), Postgres…

<img src="docs/assets/mefisto-banner.svg" alt="Mefisto" width="100%">
<a href="https://github.com/augusto-romero-arango/mefisto/releases"><img alt="Última release" src="https://img.shields.io/github/v/release/augusto-romero-arango/mefisto"></a> <a href="LICENSE"><img alt="Licencia" src="https://img.shields.io/github/license/augusto-romero-arango/mefisto"></a> <a href="https://mefisto.io"><img alt="mefisto.io" src="https://img.shields.io/badge/sitio-mefisto.io-blueviolet"></a>
Mefisto es un harness opinionado para agentes de código que orquesta el desarrollo asistido de aplicaciones .NET 10 serverless en Azure con Event Driven Architecture y Event Sourcing.
Conoce más en mefisto.io.
Un guiño a Mefistófeles, el espíritu de Fausto de Goethe: quien invoca el harness encarna a Fausto, fija la intención y firma el pacto; el plugin, como Mefisto, la ejecuta bajo las reglas del marco (EDA, Event Sourcing, TDD). Fausto decide, Mefisto ejecuta (MEF-ADR-0055).
Los agentes de código improvisan arquitectura: cada sesión reinventa convenciones, tests y pipelines. Mefisto fija el marco una sola vez (ADRs, skills, agentes y pipelines) para equipos que construyen sistemas .NET sobre Azure con Event Sourcing y quieren que el agente trabaje dentro de esas reglas, de la idea al PR.
tmux y git worktree, con ejecución paralela y secuencial.MEF-ADR-) como fuente de verdad arquitectónica..NET 10 · Azure Functions (isolated worker) · PostgreSQL + Marten · Wolverine · Azure Service Bus · Terraform · GitHub Actions.
Claude Code y OpenCode, ambos con adaptador en el repo y sin privilegiar a uno (MEF-ADR-0049).
bash 3.2+, jq, gh autenticado, git 2.x con worktrees, dotnet 10.x, terraform 1.6+ y tmux (pipelines paralelos).
Claude Code (>= 2.1.287): Mefisto se instala una vez por usuario deshabilitado, y solo se activa en los repos que lo habilitan en su .claude/settings.json commiteado. Así no se carga en repos que no lo usan (MEF-ADR-0053, decisión 2). Registra el marketplace dentro de la sesión y, desde una terminal, instálalo y deshabilítalo a nivel usuario:
/plugin marketplace add augusto-romero-arango-harness
claude plugin install mefisto@augusto-romero-arango-harness --scope user
claude plugin disable mefisto@augusto-romero-arango-harness --scope user
En cada repo consumidor, commitea el .claude/settings.json con enabledPlugins (ver la guía del consumidor, paso 1). Los pipelines entregan a sus agentes la raíz de su propia versión, así que los worktrees no dependen de esta instalación.
OpenCode: desde Claude Code, /mefisto:upgrade instala la release OpenCode por usuario; cada repo consumidor la activa commiteando .opencode/plugins/mefisto.js, que /mefisto:onboard escribe. El procedimiento directo está en la guía del consumidor.
/mefisto:onboard para diagnosticar config, labels y CI del repo./mefisto:draft, refínala hasta estado:listo y córrela con /mefisto:implement <issue>: del issue al PR.El trabajo sobre el propio plugin nace como issue: /mefisto-plan captura y refina, el pipeline interno implementa en una rama propia (nunca contra main) y se entrega por Pull Request con Closes #<n>. Cada cambio notable se anota como fragmento en changelog.d/, sin editar CHANGELOG.md. Detalle en Desarrollo del plugin.
Apache-2.0. Ver LICENSE y NOTICE.
Se permite uso, modificación y uso comercial conservando los avisos de licencia y atribución.
Augusto Romero Arango · @augusto-romero-arango
hooks/index.tsx 12 lines1import type { Register } from 'claude-code'
2
3import { register as pact } from './fausto-blood-pact/register'
4import { register as board } from './register'
5
6// Claude Code carga un solo modulo por plugin (`claude plugin validate` rechaza una segunda entrada de `modules`):
7// este punto de entrada compone el tablero y la consola, que siguen siendo modulos independientes.
8export const register: Register = (on, options) => {
9 board(on, options)
10 pact(on, options)
11}
12hooks/fausto-blood-pact/register.tsx 1951 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { RASTER_ROWS, ROLES, face, sprite, toRasterCells, waitingFace } from '../sprites'
5import type { Role } from '../sprites'
6import { cropGrid, numberWidth, padEnd, reasonOf, usedColumns } from '../logic'
7import type { BoardList, Historian, PaneLine, PactMerge, PipelineResult, PipelineRun } from '../types'
8import type { IssueStats } from './logic'
9import type { BatchStatus, CurrentRow, LastEvent, LaunchKind, LaunchPlan, MascotPose, OpenPr, ParallelStatus } from './logic'
10import {
11 BAND_FETCH_ROWS,
12 BAND_LOG_ROWS,
13 PANE_MAX_LINES,
14 agentOf,
15 batchSeparator,
16 cleanLogLine,
17 durationText,
18 followTargetsOf,
19 isFailure,
20 mergePaneLines,
21 minutesSince,
22 paneHeaderOf,
23 parseEvent,
24 LAUNCH_POLL_WINDOW_MS,
25 LOG_TAIL_BYTES,
26 LOGS_DIR,
27 bandLinesOf,
28 eventLineOf,
29 isPipelineLaunch,
30 logTailLines,
31 runHeader,
32 stepsOf,
33 activeRunOf,
34 bandViewOf,
35 resultsFooterText,
36 eventsFileOf,
37 lastEventOf,
38 poseOfBatch,
39 poseOfResults,
40 poseOfRun,
41 DISMISSED_STORE_KEY,
42 HISTORY_FILE,
43 PAGE_ROWS,
44 PLANNER_AGENT,
45 agentFlagOf,
46 agentSettingOf,
47 NEXT_ORDER_ARGS,
48 ROW_KEYS,
49 answerText,
50 parseLaunchArg,
51 planIssue,
52 planLaunch,
53 clip,
54 footerRestOf,
55 launchCountOf,
56 isMefistoManifest,
57 nextOrderPath,
58 RUNS_POLL_MS,
59 dismissKey,
60 parseHistory,
61 parseStatus,
62 pruneDismissed,
63 reconcile,
64 repoRootOf,
65 resultLine,
66 runLine,
67 stateDirOf,
68 pageOf,
69 parseNextOrder,
70 rowParts,
71 transcriptPathOf,
72 PR_CHECK_MS,
73 mergeArgsOf,
74 mergeOptions,
75 mergeToast,
76 OPEN_PRS_ARGS,
77 openPrArgsOf,
78 openPrOptions,
79 parseOpenPrs,
80 parsePrArgs,
81 resultPrs,
82 viewOptions,
83 viewPrOf,
84 BATCH_KEEP_ANSWER,
85 BATCH_STOP_ANSWER,
86 batchCounts,
87 batchDismissKey,
88 batchCurrentOf,
89 batchHoldLine,
90 batchMark,
91 batchQueueMarks,
92 batchRunningHeader,
93 recentLines,
94 batchSummaryMarks,
95 batchEndLabel,
96 batchEndFromStats,
97 closeRowText,
98 closeTotalText,
99 nextCurrentRow,
100 runningRowText,
101 totalWithRunning,
102 elapsedText,
103 issueStatsFromHistory,
104 statsPending,
105 statsTotal,
106 stampToMs,
107 summaryTitleWidth,
108 batchPrOf,
109 batchRunOf,
110 batchStatusPath,
111 batchStopPath,
112 canStopBatch,
113 isBatchRunning,
114 newlyMerged,
115 parseBatchStatus,
116 stopQuestion,
117 PARALLEL_BAND_ROWS,
118 parallelClosedHeader,
119 parallelClosedTable,
120 parallelDismissKey,
121 parallelFailedIssue,
122 parallelMergeablePrs,
123 parallelSummaryMarks,
124 canStopParallel,
125 isParallelRunning,
126 issueFromAnswer,
127 lotViewOf,
128 paginateBands,
129 parallelHeader,
130 parallelPrLabel,
131 parallelPrs,
132 parallelQueueMarks,
133 parallelRunOf,
134 parallelRunning,
135 parallelStatusPath,
136 parallelStopQuestion,
137 parallelTable,
138 parseParallelStatus,
139 MERGE_POLL_MS,
140 finishMerge,
141 mergeRunArgsOf,
142 mergePrsOf,
143 mergeRibbonHeader,
144 mergeRibbonLine,
145 mergeRibbonRows,
146 mergeRibbonShown,
147 mergeSummaryText,
148 withMerged,
149 BITACORA_PR_ARGS,
150 FIELD_NOTES_DIR,
151 NOTES_POLL_MS,
152 PROCESSED_NOTES_DIR,
153 bitacoraCount,
154 bitacoraIntegrateLabel,
155 bitacoraPrOf,
156 bitacoraPrompt,
157 bitacoraQuestion,
158 fieldNoteNamesOf,
159 fieldNotesIn,
160 historianFrom,
161 historianHeader,
162 isAgentActive,
163 isHistorianType,
164 liveHistorian,
165 noteLine,
166 orderedNotes,
167 pendingNotes,
168 withProcessedNotes,
169 boardRowsOf,
170 inPrRowParts,
171 listosTextOf,
172} from './logic'
173import { shouldRearm, versionLabel } from '../logic'
174import type { ResultPr } from './logic'
175
176const POLL_MS = 60_000
177const STATE_DIR = '.mefisto/pipeline'
178const SCRIPT_TIMEOUT_MS = 180_000
179
180const activeAtom = atom({ plugin: 'mefisto', key: 'pactIsActive' } as const, false)
181const listAtom = atom({ plugin: 'mefisto', key: 'pactList' } as const, null)
182const pageAtom = atom({ plugin: 'mefisto', key: 'pactPage' } as const, 0)
183const runsAtom = atom({ plugin: 'mefisto', key: 'pactRuns' } as const, [] as PipelineRun[])
184const resultsAtom = atom({ plugin: 'mefisto', key: 'pactResults' } as const, [] as PipelineResult[])
185const lastEventAtom = atom({ plugin: 'mefisto', key: 'pactLastEvent' } as const, null as LastEvent | null)
186const openPrsAtom = atom({ plugin: 'mefisto', key: 'pactOpenPrs' } as const, [] as OpenPr[])
187const batchAtom = atom({ plugin: 'mefisto', key: 'pactBatch' } as const, null as BatchStatus | null)
188type BatchStats = { stats: Record<string, IssueStats>; endedMs: number | null }
189const batchStatsAtom = atom({ plugin: 'mefisto', key: 'pactBatchStats' } as const, { stats: {}, endedMs: null } as BatchStats)
190const batchCurrentAtom = atom({ plugin: 'mefisto', key: 'pactBatchCurrent' } as const, null as CurrentRow | null)
191type ParallelBand = { run: PipelineRun | null; lines: string[]; last: LastEvent | null }
192const parallelAtom = atom({ plugin: 'mefisto', key: 'pactParallel' } as const, null as ParallelStatus | null)
193const parallelStatsAtom = atom({ plugin: 'mefisto', key: 'pactParallelStats' } as const, {} as Record<string, IssueStats>)
194const parallelBandsAtom = atom({ plugin: 'mefisto', key: 'pactParallelBands' } as const, {} as Record<string, ParallelBand>)
195const parallelMergedAtom = atom({ plugin: 'mefisto', key: 'pactParallelMerged' } as const, [] as string[])
196const parallelPageAtom = atom({ plugin: 'mefisto', key: 'pactParallelPage' } as const, 0)
197const mergeAtom = atom({ plugin: 'mefisto', key: 'pactMerge' } as const, null as PactMerge | null)
198const fieldNotesAtom = atom({ plugin: 'mefisto', key: 'pactFieldNotes' } as const, null as number | null)
199const historianAtom = atom({ plugin: 'mefisto', key: 'pactHistorian' } as const, null as Historian | null)
200const bandLinesAtom = atom({ plugin: 'mefisto', key: 'pactBandLines' } as const, [] as string[])
201const logLinesAtom = atom({ plugin: 'mefisto', key: 'pactLogLines' } as const, [] as PaneLine[])
202const paneRunAtom = atom({ plugin: 'mefisto', key: 'pactPaneRun' } as const, null as PipelineRun | null)
203const tickAtom = atom({ plugin: 'mefisto', key: 'pactTick' } as const, 0)
204
205// Columnas comunes a todos los cuadros de la mascota: el recorte no cambia al alternar poses.
206const MASCOT_GRIDS = [
207 ...(Object.keys(ROLES) as Role[])
208 .filter(role => role !== 'planner')
209 .flatMap(role => Object.keys(ROLES[role]).flatMap(state => [sprite(role, state, 0), sprite(role, state, 1)])),
210 ...[null, 0, 1].map(tick => waitingFace(face('normal'), tick)),
211]
212const MASCOT_COLS = usedColumns(MASCOT_GRIDS)
213const MASCOT_WIDTH = MASCOT_COLS.to - MASCOT_COLS.from + 1
214
215const mascotGrid = (pose: MascotPose, frame: 0 | 1) => cropGrid(sprite(pose.role, pose.state, frame), MASCOT_COLS)
216let isAnimating = false
217// Tras ver el lanzamiento de un pipeline, el sondeo de corridas corre a 5 s hasta este instante aunque aun no haya status (#2320).
218let launchPollUntilMs = 0
219let lastNotesPollMs = 0
220let lastHistorianPollMs = 0
221let lastBitacoraPrCheckMs = 0
222let isPollingHistorian = false
223const HISTORIAN_POLL_MS = 2_000
224
225// La intencion on/off y la elegibilidad viven aqui: /clear no dispara session.start y reinicia los atoms.
226let isEligible = false
227let isWanted = true
228let isHealing = false
229let healTimer: { cancel: () => void } | null = null
230const HEAL_MS = 1_000
231let isRefreshing = false
232let timer: { cancel: () => void } | null = null
233let runsTimer: { cancel: () => void } | null = null
234let tickTimer: { cancel: () => void } | null = null
235let prTimer: { cancel: () => void } | null = null
236let isCheckingPrs = false
237let isRefreshingOpenPrs = false
238let isRefreshingRuns = false
239let mergeTimer: { cancel: () => void } | null = null
240let isPollingMerge = false
241// La llamada Bash a pr-sync.sh ya empezo; sin verla, el reloj cierra la cinta arrancada por teclas a los MERGE_STALE_MS.
242let isMergeScriptSeen = false
243let mergeStartedMs = 0
244const MERGE_STALE_MS = 60_000
245// Corridas que esta sesion vio activas y resultados `✓` ya derivados; viven aqui porque /clear reinicia los atoms.
246let seenRuns: Record<string, PipelineRun> = {}
247let carriedResults: PipelineResult[] = []
248let runsRepo = ''
249// Ultimo estado del lote leido: base para anunciar con un toast cada issue que pasa a `mergeado`.
250let lastBatchIssues: BatchStatus['issues'] | null = null
251// Estadisticas del lote (del historial: titulo, duracion y costo); se reinician al cambiar el `started` del lote.
252let batchStatsFor = ''
253// Primer instante en que se vio el lote ya terminado: cierra el reloj de la cabecera si el historial no lo da.
254let batchSeenEndedMs: number | null = null
255// Lote parallel (#2449): el `started` de las estadisticas en cache y, con el lote vivo, el sondeo rapido de corridas.
256let parallelStatsFor = ''
257let isParallelLive = false
258let lastParallelStatsReadMs = 0
259let parallelMergedFor = ''
260let isCheckingParallelPrs = false
261// Issue cuyo log sigue el pane cuando el lote es parallel (varias corridas a la vez).
262let paneIssue: number | null = null
263// El historial se relee para estadisticas faltantes a lo sumo cada BATCH_STATS_EVERY_MS (como `withStats` en la cinta interna).
264const BATCH_STATS_EVERY_MS = 5_000
265let lastBatchStatsReadMs = 0
266// Si al arrancar no se pudo saber el agente (sin linea de comando y sin transcript aun), se reintenta en cada refresh.
267let agentChecksLeft = 0
268const AGENT_CHECKS = 20
269
270async function pluginRoot($: EngineInterface): Promise<string | null> {
271 const own = $.plugin.root
272 if (own) return own
273 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel']).catch(() => ({ exitCode: 1, stdout: '' }))
274 const base = top.exitCode === 0 ? top.stdout.trim() : await $.session.cwd()
275 const root = await $.fs.read(`${base}/.mefisto/pipeline/.plugin-root`).catch(() => '')
276 return typeof root === 'string' && root.trim() !== '' ? root.trim() : null
277}
278
279const versionAtom = atom({ plugin: 'mefisto', key: 'pactVersion' } as const, null as string | null)
280
281async function loadVersion($: EngineInterface) {
282 const root = await pluginRoot($)
283 const base = root ? root.replace(/\/+$/, '') : null
284 const read1 = async (file: string) => (base ? await $.fs.read(`${base}/${file}`).catch(() => null) : null)
285 const label = versionLabel(await read1('mefisto-manifest.json'), await read1('.claude-plugin/plugin.json'))
286 await update($, versionAtom, () => label)
287}
288
289async function runNextOrder($: EngineInterface): Promise<BoardList> {
290 const root = await pluginRoot($)
291 if (!root) return parseNextOrder(2, '', 'raiz del plugin desconocida')
292 const { exitCode, stdout, stderr } = await $.process
293 .run([nextOrderPath(root), ...NEXT_ORDER_ARGS], { timeoutMs: SCRIPT_TIMEOUT_MS })
294 .catch(err => ({ exitCode: 2, stdout: '', stderr: String(err) }))
295 return parseNextOrder(exitCode, stdout, stderr)
296}
297
298async function readDismissed($: EngineInterface): Promise<string[]> {
299 const raw = await $.store.get(DISMISSED_STORE_KEY).catch(() => null)
300 return Array.isArray(raw) ? raw.filter((k): k is string => typeof k === 'string') : []
301}
302
303async function saveDismissed($: EngineInterface, keys: string[]) {
304 await $.store.set(DISMISSED_STORE_KEY, keys).catch(() => undefined)
305}
306
307// Lector puro: solo lee `.mefisto/pipeline/` del checkout principal; la ruta legada se ignora (MEF-ADR-0053).
308async function readRuns($: EngineInterface): Promise<PipelineRun[]> {
309 const cwd = await $.session.cwd()
310 const common = await $.process.run(['git', 'rev-parse', '--git-common-dir']).catch(() => ({ exitCode: 1, stdout: '' }))
311 const dir = stateDirOf(common.exitCode === 0 ? common.stdout.trim() : '.git', cwd)
312 runsRepo = repoRootOf(dir)
313 const ls = await $.process.run(['ls', dir]).catch(() => ({ exitCode: 1, stdout: '' }))
314 if (ls.exitCode !== 0) return []
315 const runs: PipelineRun[] = []
316 for (const name of ls.stdout.split('\n')) {
317 const file = name.trim()
318 if (!file.startsWith('pipeline-status-')) continue
319 const raw = await $.fs.read(`${dir}/${file}`).catch(() => '')
320 const run = typeof raw === 'string' ? parseStatus(file, raw) : null
321 if (run) runs.push(run)
322 }
323 return runs
324}
325
326// Cola del `events.jsonl` del ultimo intento del agente activo; lector puro de `<estado>/logs/*.events.jsonl`.
327async function readEventsTail($: EngineInterface, run: PipelineRun | null): Promise<string | null> {
328 if (!run) return null
329 const dir = `${runsRepo}/${STATE_DIR}/${LOGS_DIR}`
330 const ls = await $.process.run(['ls', dir]).catch(() => ({ exitCode: 1, stdout: '' }))
331 if (ls.exitCode !== 0) return null
332 const file = eventsFileOf(run, ls.stdout.split('\n'))
333 if (!file) return null
334 const tail = await $.process.run(['tail', '-c', '65536', `${dir}/${file}`]).catch(() => ({ exitCode: 1, stdout: '' }))
335 return tail.exitCode === 0 ? tail.stdout : null
336}
337
338// Ultimas lineas utiles: cola del log del pipeline (sin ANSI) y ultimo evento del agente; se calculan aqui, nunca al dibujar.
339async function readBandLines($: EngineInterface, run: PipelineRun | null, eventsTail: string | null): Promise<string[]> {
340 if (!run) return []
341 let logLines: string[] = []
342 if (run.log) {
343 const path = run.log.startsWith('/') ? run.log : `${runsRepo}/${run.log}`
344 const tail = await $.process.run(['tail', '-c', String(LOG_TAIL_BYTES), path]).catch(() => ({ exitCode: 1, stdout: '' }))
345 if (tail.exitCode === 0) logLines = logTailLines(tail.stdout, BAND_FETCH_ROWS)
346 }
347 return bandLinesOf(logLines, eventsTail ? eventLineOf(eventsTail) : null, BAND_FETCH_ROWS)
348}
349
350// Solo `.mefisto/pipeline/` (MEF-ADR-0053): la ruta legada ya no la escribe ningun pipeline.
351async function readHistory($: EngineInterface): Promise<string> {
352 const raw = await $.fs.read(`${runsRepo}/${STATE_DIR}/${HISTORY_FILE}`).catch(() => '')
353 return typeof raw === 'string' ? raw : ''
354}
355
356// Lector puro del status del lote (#2202); un lote terminado y cerrado (clave repo + `started` en el store) no se muestra.
357async function readBatch($: EngineInterface): Promise<BatchStatus | null> {
358 const raw = await $.fs.read(batchStatusPath(`${runsRepo}/${STATE_DIR}`)).catch(() => '')
359 return typeof raw === 'string' && raw !== '' ? parseBatchStatus(raw) : null
360}
361
362async function refreshBatch($: EngineInterface) {
363 const batch = await readBatch($)
364 if (!batch) {
365 lastBatchIssues = null
366 await update($, batchCurrentAtom, () => null)
367 await update($, batchAtom, () => null)
368 return
369 }
370 for (const i of newlyMerged(lastBatchIssues, batch.issues)) $.ui.toast(`#${i.issue} mergeado${i.pr ? ` · PR #${i.pr}` : ''}`)
371 lastBatchIssues = batch.issues
372 if (batchStatsFor !== batch.started) {
373 batchStatsFor = batch.started
374 batchSeenEndedMs = null
375 lastBatchStatsReadMs = 0
376 await update($, batchStatsAtom, () => ({ stats: {}, endedMs: null }))
377 }
378 const finished = (i: BatchStatus['issues'][number]) => i.status !== 'pendiente' && i.status !== 'en-curso'
379 const known = await read($, batchStatsAtom)
380 const missing = statsPending(batch.issues.filter(finished).map(i => String(i.issue)), known.stats)
381 let stats = known.stats
382 if (missing.length > 0 && Date.now() - lastBatchStatsReadMs >= BATCH_STATS_EVERY_MS) {
383 lastBatchStatsReadMs = Date.now()
384 stats = { ...stats, ...issueStatsFromHistory(await readHistory($), missing, stampToMs(batch.started)) }
385 }
386 if (isBatchRunning(batch)) batchSeenEndedMs = null
387 else batchSeenEndedMs ??= Date.now()
388 const endedMs = isBatchRunning(batch) ? null : (batchEndFromStats(stats) ?? batchSeenEndedMs)
389 if (stats !== known.stats || endedMs !== known.endedMs) await update($, batchStatsAtom, () => ({ stats, endedMs }))
390 const prevRow = await read($, batchCurrentAtom)
391 const nextRow = nextCurrentRow(batch, batchRunOf(batch, await read($, runsAtom)), prevRow, Date.now())
392 if (nextRow !== prevRow) await update($, batchCurrentAtom, () => nextRow)
393 const closed = !isBatchRunning(batch) && (await readDismissed($)).includes(batchDismissKey(runsRepo, batch))
394 await update($, batchAtom, () => (closed ? null : batch))
395}
396
397// Parada suave (MEF-ADR-0017): la misma senal vacia que /mefisto:batch-stop, en la raiz del checkout principal.
398async function requestStop($: EngineInterface): Promise<string> {
399 const batch = await read($, batchAtom)
400 if (!batch || !canStopBatch(batch)) return 'No hay un sequential en curso que detener.'
401 await $.fs.write(batchStopPath(runsRepo), '')
402 await update($, batchAtom, b => (b ? { ...b, stopRequested: true } : b))
403 $.ui.toast('parada pedida: termina el issue en curso y no arranca los siguientes')
404 return 'Parada pedida: termina el issue en curso y no arranca los siguientes.'
405}
406
407async function confirmStop($: EngineInterface): Promise<string> {
408 const batch = await read($, batchAtom)
409 if (batch && isBatchRunning(batch) && batch.stopRequested) return 'La parada ya esta pedida: termina el issue en curso.'
410 if (!batch || !canStopBatch(batch)) return 'No hay un sequential en curso que detener.'
411 const answer = await $.ui
412 .ask(stopQuestion(batch), { header: 'Detener', options: [BATCH_STOP_ANSWER, BATCH_KEEP_ANSWER] })
413 .catch(() => null)
414 return answer === BATCH_STOP_ANSWER ? requestStop($) : 'Sin cambios.'
415}
416
417async function viewBatchPr($: EngineInterface): Promise<string> {
418 const batch = await read($, batchAtom)
419 const pr = batch ? batchPrOf(batch) : null
420 if (!pr) return 'El lote no tiene PR que abrir.'
421 await $.process.run(['gh', 'pr', 'view', pr, '--web']).catch(() => undefined)
422 return `PR #${pr} abierto en GitHub.`
423}
424
425async function closeBatch($: EngineInterface) {
426 const batch = await read($, batchAtom)
427 if (!batch || isBatchRunning(batch)) return
428 const keys = new Set(await readDismissed($))
429 keys.add(batchDismissKey(runsRepo, batch))
430 await saveDismissed($, [...keys])
431 await update($, batchAtom, () => null)
432 await closeLogIfGone($)
433}
434
435// Lector puro del status del lote parallel (#2447): en curso o cerrado (#2450); un cerrado ya ocultado con `4: cerrar` no ocupa la banda.
436async function refreshParallel($: EngineInterface, runs: readonly PipelineRun[]) {
437 const raw = await $.fs.read(parallelStatusPath(`${runsRepo}/${STATE_DIR}`)).catch(() => '')
438 const parsed = typeof raw === 'string' && raw !== '' ? parseParallelStatus(raw) : null
439 const closed = parsed !== null && !isParallelRunning(parsed) && (await readDismissed($)).includes(parallelDismissKey(runsRepo, parsed))
440 const p = closed ? null : parsed
441 isParallelLive = isParallelRunning(p)
442 if (!p) {
443 await update($, parallelBandsAtom, () => ({}))
444 await update($, parallelAtom, () => null)
445 return
446 }
447 if (parallelStatsFor !== p.started) {
448 parallelStatsFor = p.started
449 lastParallelStatsReadMs = 0
450 await update($, parallelStatsAtom, () => ({}))
451 }
452 if (parallelMergedFor !== p.started) {
453 parallelMergedFor = p.started
454 await update($, parallelMergedAtom, () => [])
455 }
456 const known = await read($, parallelStatsAtom)
457 const finished = p.issues.filter(i => i.status === 'terminado' || i.status === 'fallido').map(i => String(i.issue))
458 const missing = statsPending(finished, known)
459 if (missing.length > 0 && Date.now() - lastParallelStatsReadMs >= BATCH_STATS_EVERY_MS) {
460 lastParallelStatsReadMs = Date.now()
461 const stats = { ...known, ...issueStatsFromHistory(await readHistory($), missing, stampToMs(p.started)) }
462 await update($, parallelStatsAtom, () => stats)
463 }
464 const bands: Record<string, ParallelBand> = {}
465 for (const i of parallelRunning(p)) {
466 const run = parallelRunOf(i, runs)
467 const eventsTail = await readEventsTail($, run)
468 bands[String(i.issue)] = { run, lines: await readBandLines($, run, eventsTail), last: eventsTail ? lastEventOf(eventsTail) : null }
469 }
470 await update($, parallelBandsAtom, () => bands)
471 await update($, parallelAtom, () => p)
472}
473
474// Parada suave (MEF-ADR-0017): la misma senal que /mefisto:batch-stop y el sequential; ningun proceso se mata.
475async function confirmStopParallel($: EngineInterface): Promise<string> {
476 const p = await read($, parallelAtom)
477 if (p && isParallelRunning(p) && p.stopRequested) return 'La parada ya esta pedida: no se lanzan mas issues.'
478 if (!p || !canStopParallel(p)) return 'No hay un parallel en curso con issues pendientes que detener.'
479 const answer = await $.ui
480 .ask(parallelStopQuestion(p), { header: 'Detener', options: [BATCH_STOP_ANSWER, BATCH_KEEP_ANSWER] })
481 .catch(() => null)
482 if (answer !== BATCH_STOP_ANSWER) return 'Sin cambios.'
483 await $.fs.write(batchStopPath(runsRepo), '')
484 await update($, parallelAtom, cur => (cur ? { ...cur, stopRequested: true } : cur))
485 $.ui.toast('parada pedida: los issues en curso terminan y no se lanzan mas')
486 return 'Parada pedida: los issues en curso terminan y no se lanzan mas.'
487}
488
489// Ocultado persistente del lote parallel terminado: clave repo + `started` en `$.store`; el archivo no se toca.
490async function closeParallel($: EngineInterface) {
491 const p = await read($, parallelAtom)
492 if (!p || p.state === 'running') return
493 const keys = new Set(await readDismissed($))
494 keys.add(parallelDismissKey(runsRepo, p))
495 await saveDismissed($, [...keys])
496 await update($, parallelAtom, () => null)
497 await closeLogIfGone($)
498}
499
500// Sondeo de 15 s (como el de corridas terminadas): un PR del lote ya `MERGED` deja de ofrecerse.
501async function probeParallelMerged($: EngineInterface) {
502 if (isCheckingParallelPrs || !isEligible || !isWanted) return
503 const p = await read($, parallelAtom)
504 if (!p || p.state === 'running') return
505 isCheckingParallelPrs = true
506 try {
507 const merged = await read($, parallelMergedAtom)
508 const found: string[] = []
509 for (const x of parallelMergeablePrs(p, new Set(merged))) {
510 const { exitCode, stdout } = await $.process
511 .run(['gh', 'pr', 'view', x.pr, '--json', 'state', '-q', '.state'])
512 .catch(() => ({ exitCode: 1, stdout: '' }))
513 if (exitCode === 0 && stdout.trim() === 'MERGED') found.push(x.pr)
514 }
515 if (found.length === 0) return
516 await update($, parallelMergedAtom, cur => [...new Set([...cur, ...found])])
517 void refreshOpenPrs($)
518 for (const pr of found) $.ui.toast(`PR #${pr} mergeado`)
519 } finally {
520 isCheckingParallelPrs = false
521 }
522}
523
524// `1: mergear` del lote terminado: solo los PRs del lote aun abiertos, con el mismo dialogo que las corridas terminadas.
525async function mergeParallel($: EngineInterface): Promise<string> {
526 const p = await read($, parallelAtom)
527 if (!p || p.state === 'running') return 'No hay un parallel terminado.'
528 const prs = parallelMergeablePrs(p, new Set(await read($, parallelMergedAtom)))
529 if (prs.length === 0) return 'El lote no tiene PRs abiertos que mergear.'
530 await refreshOpenPrs($)
531 return mergeListed($, prs, null)
532}
533
534async function viewParallelPr($: EngineInterface): Promise<string> {
535 const p = await read($, parallelAtom)
536 const prs = p ? parallelPrs(p) : []
537 if (prs.length === 0) return 'El lote no tiene PR que abrir.'
538 let pr = prs[0]!.pr
539 if (prs.length > 1) {
540 const answer = await $.ui.ask('¿Cuál PR ver?', { header: 'PR', options: prs.map(parallelPrLabel) }).catch(() => null)
541 const issue = issueFromAnswer(answer, prs.map(x => x.issue))
542 const chosen = prs.find(x => x.issue === issue)
543 if (!chosen) return 'Sin PR elegido.'
544 pr = chosen.pr
545 }
546 await $.process.run(['gh', 'pr', 'view', pr, '--web']).catch(() => undefined)
547 return `PR #${pr} abierto en GitHub.`
548}
549
550// ---- Pane de log (#2321): dos `tail -F` (eventos del agente y log del pipeline) mezclados en un mismo atom ----
551
552const PANE = 'fausto-blood-pact'
553const PANE_ROWS = 18
554const PANE_FIXED_ROWS = 7
555type Follow = { path: string; stream: AsyncGenerator<unknown, unknown> }
556type FollowKind = 'events' | 'log'
557
558let isLogOpen = false
559let isSyncingLog = false
560let eventsFollow: Follow | null = null
561let logFollow: Follow | null = null
562let separatedIssue: number | null = null
563
564const followOf = (kind: FollowKind) => (kind === 'events' ? eventsFollow : logFollow)
565
566async function stopFollow(kind: FollowKind) {
567 const current = followOf(kind)
568 if (kind === 'events') eventsFollow = null
569 else logFollow = null
570 if (current) await current.stream.return(undefined).catch(() => undefined)
571}
572
573async function stopFollows() {
574 await stopFollow('events')
575 await stopFollow('log')
576}
577
578async function consumeFollow($: EngineInterface, kind: FollowKind, follow: Follow) {
579 let pending = ''
580 try {
581 for await (const chunk of follow.stream) {
582 if (followOf(kind) !== follow) break
583 const { stream: channel, text } = chunk as { stream: string; text: string }
584 if (channel !== 'stdout') continue
585 pending += text
586 const rows = pending.split('\n')
587 pending = rows.pop() ?? ''
588 const added = rows
589 .map((row): PaneLine | null => {
590 if (kind === 'events') return parseEvent(row)
591 const clean = cleanLogLine(row)
592 return clean ? { kind: 'log', text: clean } : null
593 })
594 .filter((l): l is PaneLine => l !== null)
595 if (added.length > 0) await update($, logLinesAtom, list => mergePaneLines(list, added, PANE_MAX_LINES))
596 }
597 } catch (err) {
598 $.ui.log(`tail ${follow.path}: ${String(err)}`, { to: 'debug' })
599 }
600}
601
602async function startFollow($: EngineInterface, kind: FollowKind, path: string) {
603 await stopFollow(kind)
604 const stream = $.process.spawn({ argv: ['tail', '-n', '40', '-F', path], ...(runsRepo ? { cwd: runsRepo } : {}) })
605 const follow: Follow = { path, stream }
606 if (kind === 'events') eventsFollow = follow
607 else logFollow = follow
608 void consumeFollow($, kind, follow)
609}
610
611const isSameRun = (a: PipelineRun, b: PipelineRun) => a.issue === b.issue && a.pipeline === b.pipeline && a.variant === b.variant
612
613async function paneTarget($: EngineInterface): Promise<PipelineRun | null> {
614 const batch = await read($, batchAtom)
615 const runs = await read($, runsAtom)
616 const parallel = await read($, parallelAtom)
617 if (parallel && lotViewOf(batch, parallel) === 'parallel') {
618 const live = parallelRunning(parallel)
619 const chosen = live.find(i => i.issue === paneIssue) ?? live[0]
620 return chosen ? parallelRunOf(chosen, runs) : null
621 }
622 return batch ? batchRunOf(batch, runs) : activeRunOf(runs)
623}
624
625// Cada sondeo: elige los archivos a seguir (intento vigente del stage activo, log de la corrida o del lote) y pasa al nuevo si cambian.
626async function syncLog($: EngineInterface) {
627 if (!isLogOpen || isSyncingLog) return
628 isSyncingLog = true
629 try {
630 const batch = await read($, batchAtom)
631 const active = await paneTarget($)
632 let run = active ?? (await read($, paneRunAtom))
633 if (!active && run) {
634 const known = run
635 run = (await readRuns($)).find(r => isSameRun(r, known)) ?? run
636 }
637 if (run) await update($, paneRunAtom, () => run)
638 const ls = run ? await $.process.run(['ls', `${runsRepo}/${STATE_DIR}/${LOGS_DIR}`]).catch(() => ({ exitCode: 1, stdout: '' })) : null
639 const names = ls && ls.exitCode === 0 ? ls.stdout.split('\n') : []
640 const targets = followTargetsOf(run, batch, names, runsRepo)
641 if (batch && active && active.issue !== separatedIssue) {
642 separatedIssue = active.issue
643 await update($, logLinesAtom, list => mergePaneLines(list, [batchSeparator(active.issue)], PANE_MAX_LINES))
644 }
645 if (!isLogOpen) return
646 if (targets.events && targets.events !== eventsFollow?.path) await startFollow($, 'events', targets.events)
647 if (targets.log && targets.log !== logFollow?.path) await startFollow($, 'log', targets.log)
648 } finally {
649 isSyncingLog = false
650 }
651}
652
653async function closeLog($: EngineInterface) {
654 isLogOpen = false
655 await stopFollows()
656 separatedIssue = null
657 paneIssue = null
658 await update($, logLinesAtom, () => [])
659 await update($, paneRunAtom, () => null)
660 await $.ui.close({ id: PANE })
661}
662
663async function openLog($: EngineInterface, issue: number | null = null): Promise<boolean> {
664 if (issue !== null) paneIssue = issue
665 const run = await paneTarget($)
666 if (!run) return false
667 isLogOpen = true
668 separatedIssue = null
669 await update($, logLinesAtom, () => [])
670 await update($, paneRunAtom, () => run)
671 await $.ui.open({ id: PANE, title: 'mefisto', rows: PANE_ROWS, focus: true as const })
672 await syncLog($)
673 return true
674}
675
676// La tecla 3 abre el log o, si ya estaba abierto, lo cierra.
677async function toggleLog($: EngineInterface) {
678 if (isLogOpen) {
679 await closeLog($)
680 return
681 }
682 const parallel = await read($, parallelAtom)
683 const live = parallel && lotViewOf(await read($, batchAtom), parallel) === 'parallel' ? parallelRunning(parallel) : []
684 let issue: number | null = null
685 if (live.length > 1) {
686 const answer = await $.ui
687 .ask('¿Log de cuál corrida?', { header: 'Log', options: live.map(i => `#${i.issue}`) })
688 .catch(() => null)
689 issue = issueFromAnswer(answer, live.map(i => i.issue))
690 if (issue === null) return
691 }
692 if (!(await openLog($, issue))) $.ui.toast('No hay corrida que seguir')
693}
694
695// Cuando la vista se va (cerrar, ocultar o una corrida que cierra sola) el pane y sus `tail` se van con ella.
696async function closeLogIfGone($: EngineInterface) {
697 if (!isLogOpen) return
698 const batch = await read($, batchAtom)
699 const runs = await read($, runsAtom)
700 const results = await read($, resultsAtom)
701 if (!batch && !(await read($, parallelAtom)) && runs.length === 0 && results.length === 0) await closeLog($)
702}
703
704async function refreshRuns($: EngineInterface) {
705 if (isRefreshingRuns || !isEligible || !isWanted) return
706 isRefreshingRuns = true
707 try {
708 const statuses = await readRuns($)
709 const dismissed = await readDismissed($)
710 const wasSeen = seenRuns
711 const historyRaw = await readHistory($)
712 const view = reconcile(
713 runsRepo,
714 statuses,
715 wasSeen,
716 parseHistory(typeof historyRaw === 'string' ? historyRaw : ''),
717 new Set(dismissed),
718 carriedResults,
719 )
720 seenRuns = view.seen
721 carriedResults = view.results.filter(r => r.ok)
722 const live = new Set(statuses.map(s => dismissKey(runsRepo, s)))
723 const pruned = pruneDismissed(dismissed, runsRepo, live, Date.now())
724 if (pruned.length !== dismissed.length) await saveDismissed($, pruned)
725 const target = activeRunOf(view.runs)
726 const eventsTail = await readEventsTail($, target)
727 const last = eventsTail ? lastEventOf(eventsTail) : null
728 const lines = await readBandLines($, target, eventsTail)
729 await update($, lastEventAtom, () => last)
730 await update($, bandLinesAtom, () => lines)
731 await update($, runsAtom, () => view.runs)
732 await refreshBatch($)
733 await refreshParallel($, view.runs)
734 await update($, resultsAtom, () => view.results)
735 await syncLog($)
736 await closeLogIfGone($)
737 } finally {
738 isRefreshingRuns = false
739 }
740}
741
742async function dismissResults($: EngineInterface): Promise<number> {
743 const results = await read($, resultsAtom)
744 if (results.length === 0) return 0
745 const keys = new Set(await readDismissed($))
746 for (const r of results) keys.add(r.key)
747 await saveDismissed($, [...keys])
748 carriedResults = []
749 await update($, resultsAtom, () => [])
750 await update($, pageAtom, () => 0)
751 await closeLogIfGone($)
752 return results.length
753}
754
755// Un PR `MERGED` quita su linea sola: se guarda en `$.store` (nunca en archivos de estado) para que no reaparezca.
756async function closeMergedPrs($: EngineInterface) {
757 if (isCheckingPrs || !isEligible || !isWanted) return
758 isCheckingPrs = true
759 try {
760 const results = await read($, resultsAtom)
761 const merged: ResultPr[] = []
762 for (const p of resultPrs(results)) {
763 const { exitCode, stdout } = await $.process
764 .run(['gh', 'pr', 'view', p.pr, '--json', 'state', '-q', '.state'])
765 .catch(() => ({ exitCode: 1, stdout: '' }))
766 if (exitCode === 0 && stdout.trim() === 'MERGED') merged.push(p)
767 }
768 if (merged.length === 0) return
769 const keys = new Set(await readDismissed($))
770 for (const p of merged) keys.add(p.key)
771 await saveDismissed($, [...keys])
772 const gone = new Set(merged.map(p => p.key))
773 carriedResults = carriedResults.filter(r => !gone.has(r.key))
774 await update($, resultsAtom, rs => rs.filter(r => !gone.has(r.key)))
775 await update($, pageAtom, () => 0)
776 void refreshOpenPrs($)
777 for (const p of merged) {
778 $.ui.toast(`PR #${p.pr} mergeado${p.pipeline === 'infra' ? ' · el issue se cierra cuando termine el apply de CI' : ''}`)
779 }
780 } finally {
781 isCheckingPrs = false
782 }
783}
784
785// La cinta de merge: arranca con las teclas o al ver la llamada Bash a pr-sync.sh --merge; con --all la lista sale de los PRs abiertos de ese momento.
786async function startMerge($: EngineInterface, args: string) {
787 const current = await read($, mergeAtom)
788 if (current && current.finishedMs === null) return
789 let open = await read($, openPrsAtom)
790 if (/(^|\s)--all(\s|$)/.test(args)) {
791 const listed = await $.process.run(['gh', ...OPEN_PRS_ARGS]).catch(() => ({ exitCode: 1, stdout: '' }))
792 if (listed.exitCode === 0) open = parseOpenPrs(listed.stdout)
793 }
794 const prs = mergePrsOf(args, open)
795 if (prs.length === 0) return
796 isMergeScriptSeen = false
797 mergeStartedMs = Date.now()
798 await update($, mergeAtom, () => ({ prs, startedMs: mergeStartedMs, finishedMs: null }))
799}
800
801async function pollMerge($: EngineInterface) {
802 if (isPollingMerge) return
803 isPollingMerge = true
804 try {
805 const run = await read($, mergeAtom)
806 if (!run || run.finishedMs !== null) return
807 const pending = run.prs.filter(p => p.estado === 'pendiente').map(p => p.num)
808 const states = await Promise.all(
809 pending.map(n => $.process.run(['gh', 'pr', 'view', n, '--json', 'state', '-q', '.state']).catch(() => ({ exitCode: 1, stdout: '' }))),
810 )
811 const merged = pending.filter((_, i) => states[i]?.exitCode === 0 && states[i]?.stdout.trim() === 'MERGED')
812 if (merged.length > 0) await update($, mergeAtom, r => (r ? withMerged(r, merged) : r))
813 } finally {
814 isPollingMerge = false
815 }
816}
817
818async function endMerge($: EngineInterface) {
819 await pollMerge($)
820 const run = await read($, mergeAtom)
821 if (!run || run.finishedMs !== null) return
822 const done = finishMerge(run, Date.now())
823 await update($, mergeAtom, () => done)
824 $.ui.toast(mergeSummaryText(done))
825 void refreshOpenPrs($)
826}
827
828async function closeMerge($: EngineInterface) {
829 const run = await read($, mergeAtom)
830 if (run && run.finishedMs !== null) await update($, mergeAtom, () => null)
831}
832
833// Mergear: la confirmacion del dialogo es la unica; /mefisto:merge no pide otra. Nunca `--all`.
834async function mergePrs($: EngineInterface, preset: string[] | null = null): Promise<string> {
835 const prs = resultPrs(await read($, resultsAtom))
836 if (prs.length === 0) return 'No hay PRs de corridas terminadas.'
837 return mergeListed($, prs, preset)
838}
839
840async function mergeListed($: EngineInterface, prs: ResultPr[], preset: string[] | null): Promise<string> {
841 const scope = preset ? prs.filter(p => preset.includes(p.pr)) : prs
842 const options = mergeOptions(scope)
843 const answer = await $.ui
844 .ask(
845 scope.length === 1 ? `¿Mergear el PR #${scope[0]!.pr}?` : `¿Qué mergear? ${scope.length} PRs${scope.length > 3 ? ' (otros números: escríbelos en la opción de texto)' : ''}`,
846 scope.length === 1 ? options : { header: 'Merge', options, multiSelect: true as const },
847 )
848 .catch(() => null)
849 const args = mergeArgsOf(answer, options, scope)
850 if (!args) return 'Merge cancelado.'
851 $.ui.toast(mergeToast(args, prs))
852 await startMerge($, args)
853 await $.command.run({ command: 'mefisto:merge', args })
854 void refreshOpenPrs($)
855 return `/mefisto:merge ${args} en cola.`
856}
857
858async function refreshOpenPrs($: EngineInterface) {
859 if (isRefreshingOpenPrs || !isEligible || !isWanted) return
860 isRefreshingOpenPrs = true
861 try {
862 const { exitCode, stdout } = await $.process.run(['gh', ...OPEN_PRS_ARGS]).catch(() => ({ exitCode: 1, stdout: '' }))
863 if (exitCode === 0) await update($, openPrsAtom, () => parseOpenPrs(stdout))
864 } finally {
865 isRefreshingOpenPrs = false
866 }
867}
868
869// Reposo: la lista es de los PRs abiertos que no son borradores (field notes incluidos); "Todos" pasa `--all`.
870async function mergeOpenPrs($: EngineInterface): Promise<string> {
871 await refreshOpenPrs($)
872 const prs = await read($, openPrsAtom)
873 if (prs.length === 0) return 'No hay PRs abiertos.'
874 const options = openPrOptions(prs)
875 const answer = await $.ui
876 .ask(
877 prs.length === 1 ? `¿Mergear el PR #${prs[0]!.number}?` : `¿Qué mergear? ${prs.length} PRs${prs.length > 3 ? ' (otros números: escríbelos en la opción de texto)' : ''}`,
878 prs.length === 1 ? options : { header: 'Merge', options, multiSelect: true as const },
879 )
880 .catch(() => null)
881 const args = openPrArgsOf(typeof answer === 'string' ? answer : null, options, prs)
882 if (!args) return 'Merge cancelado.'
883 $.ui.toast(`/mefisto:merge ${args} en cola`)
884 await startMerge($, args)
885 await $.command.run({ command: 'mefisto:merge', args })
886 void refreshOpenPrs($)
887 return `/mefisto:merge ${args} en cola.`
888}
889
890async function viewPr($: EngineInterface, preset: string | null = null): Promise<string> {
891 const prs = resultPrs(await read($, resultsAtom))
892 if (prs.length === 0) return 'No hay PRs de corridas terminadas.'
893 let pr = preset
894 if (!pr) {
895 if (prs.length === 1) pr = prs[0]!.pr
896 else {
897 const options = viewOptions(prs)
898 const answer = await $.ui.ask('¿Cuál PR ver?', { header: 'PR', options }).catch(() => null)
899 pr = viewPrOf(answer, prs)
900 }
901 }
902 if (!pr) return 'Sin PR elegido.'
903 await $.process.run(['gh', 'pr', 'view', pr, '--web']).catch(() => undefined)
904 return `PR #${pr} abierto en GitHub.`
905}
906
907// La carpeta de las field notes es la del checkout principal, donde trabaja el historiador del consumidor.
908async function repoDir($: EngineInterface): Promise<string> {
909 return runsRepo || (await $.session.cwd())
910}
911
912async function refreshFieldNotes($: EngineInterface) {
913 const entries = await $.fs.list(`${await repoDir($)}/${FIELD_NOTES_DIR}`).catch(() => null)
914 await update($, fieldNotesAtom, () => (entries ? fieldNotesIn(entries.filter(n => n.kind === 'file').map(n => n.name)) : 0))
915}
916
917// Mientras el historiador corre (se sondea `$.agent.list()`: el tipo lleva el prefijo del plugin), la banda lo muestra
918// escribiendo con sus field notes: pendientes hasta que aparecen en `procesadas/`.
919async function pollHistorian($: EngineInterface) {
920 if (isPollingHistorian || !isEligible || !isWanted || Date.now() - lastHistorianPollMs < HISTORIAN_POLL_MS) return
921 isPollingHistorian = true
922 lastHistorianPollMs = Date.now()
923 try {
924 const agents = await $.agent.list().catch(() => [])
925 const active = agents.some(a => isHistorianType(a.type) && isAgentActive(a.status))
926 const prev = await read($, historianAtom)
927 const next = historianFrom(prev, active, Date.now())
928 if (next !== prev) {
929 await update($, historianAtom, () => next)
930 if (next && !next.finishedMs) {
931 await captureNotes($)
932 return
933 }
934 if (next?.finishedMs) {
935 lastNotesPollMs = 0
936 await pollNotes($)
937 await findBitacoraPr($)
938 void refreshOpenPrs($)
939 void refreshFieldNotes($)
940 }
941 return
942 }
943 if (next && !next.finishedMs) await pollNotes($)
944 if (next?.pr) await checkBitacoraPr($, next.pr.number)
945 if (next && next.finishedMs && !next.pr && !liveHistorian(next, Date.now())) await update($, historianAtom, () => null)
946 } finally {
947 isPollingHistorian = false
948 }
949}
950
951async function captureNotes($: EngineInterface) {
952 const local = await $.fs.list(`${await repoDir($)}/${FIELD_NOTES_DIR}`).catch(() => [])
953 const notePrs = (await read($, openPrsAtom)).filter(p => p.isFieldNote).map(p => p.number)
954 const files = await Promise.all(
955 notePrs.map(n => $.process.run(['gh', 'pr', 'view', n, '--json', 'files', '-q', '.files[].path']).catch(() => ({ exitCode: 1, stdout: '' }))),
956 )
957 const paths = files.flatMap(f => (f.exitCode === 0 ? f.stdout.split('\n').filter(Boolean) : []))
958 const names = fieldNoteNamesOf(local.filter(n => n.kind === 'file').map(n => n.name), paths)
959 await update($, historianAtom, h => (h && h.notes.length === 0 ? { ...h, notes: pendingNotes(names) } : h))
960 lastNotesPollMs = 0
961 await pollNotes($)
962}
963
964async function pollNotes($: EngineInterface) {
965 const h = await read($, historianAtom)
966 if (!h || !h.notes.some(n => n.estado === 'pendiente') || Date.now() - lastNotesPollMs < NOTES_POLL_MS) return
967 lastNotesPollMs = Date.now()
968 const listed = await $.fs.list(`${await repoDir($)}/${PROCESSED_NOTES_DIR}`).catch(() => [])
969 const processed = listed.filter(n => n.kind === 'file').map(n => n.name)
970 await update($, historianAtom, cur => (cur ? withProcessedNotes(cur, processed) : cur))
971}
972
973// Al terminar, un PR de bitacora abierto se ofrece para mergear, ver o cerrar; si no queda ninguno (el skill ya lo
974// mergeo), la cinta se va sola a los 8 s (el vencimiento tambien se calcula al dibujar).
975async function findBitacoraPr($: EngineInterface) {
976 const { exitCode, stdout } = await $.process.run(['gh', ...BITACORA_PR_ARGS]).catch(() => ({ exitCode: 1, stdout: '' }))
977 const pr = exitCode === 0 ? bitacoraPrOf(stdout) : null
978 if (!pr) return
979 lastBitacoraPrCheckMs = Date.now()
980 await update($, historianAtom, h => (h ? { ...h, pr } : h))
981}
982
983// Si el PR ofrecido se mergeo o cerro por fuera, la cinta se va en el siguiente chequeo.
984async function checkBitacoraPr($: EngineInterface, pr: number) {
985 if (Date.now() - lastBitacoraPrCheckMs < PR_CHECK_MS) return
986 lastBitacoraPrCheckMs = Date.now()
987 const { exitCode, stdout } = await $.process.run(['gh', 'pr', 'view', String(pr), '--json', 'state', '-q', '.state']).catch(() => ({ exitCode: 1, stdout: '' }))
988 if (exitCode === 0 && stdout.trim() !== 'OPEN') await dismissHistorian($)
989}
990
991async function dismissHistorian($: EngineInterface) {
992 await update($, historianAtom, () => null)
993 void refreshOpenPrs($)
994}
995
996async function mergeBitacoraPr($: EngineInterface) {
997 const pr = (await read($, historianAtom))?.pr
998 if (!pr) return
999 await dismissHistorian($)
1000 const args = String(pr.number)
1001 await startMerge($, args)
1002 await $.command.run({ command: 'mefisto:merge', args })
1003}
1004
1005async function openBitacoraPr($: EngineInterface) {
1006 const pr = (await read($, historianAtom))?.pr
1007 if (pr) await $.process.run(['gh', 'pr', 'view', String(pr.number), '--web']).catch(() => undefined)
1008}
1009
1010async function closeBitacoraPr($: EngineInterface) {
1011 const pr = (await read($, historianAtom))?.pr
1012 if (!pr) return
1013 const answer = await $.ui
1014 .ask(`¿Cerrar el PR #${pr.number} de la bitácora sin mergear y borrar su rama?`, { header: 'Cerrar PR', options: ['Cerrar PR', 'Cancelar'] })
1015 .catch(() => null)
1016 if (answer !== 'Cerrar PR') return
1017 const { exitCode, stderr } = await $.process
1018 .run(['gh', 'pr', 'close', String(pr.number), '--delete-branch'])
1019 .catch(err => ({ exitCode: 1, stderr: String(err) }))
1020 if (exitCode !== 0) {
1021 $.ui.toast(`no se pudo cerrar el PR #${pr.number}: ${clip(stderr ?? '', 80)}`)
1022 return
1023 }
1024 $.ui.toast(`PR #${pr.number} cerrado`)
1025 await dismissHistorian($)
1026}
1027
1028// Integrar la bitacora: elegir en el dialogo es la aprobacion; el prompt se envia como mensaje del usuario.
1029async function chooseBitacora($: EngineInterface) {
1030 const local = (await read($, fieldNotesAtom)) ?? 0
1031 const prs = (await read($, openPrsAtom)).filter(p => p.isFieldNote).map(p => p.number)
1032 if (local + prs.length === 0) return
1033 const integrate = bitacoraIntegrateLabel(prs.length)
1034 const answer = await $.ui.ask(bitacoraQuestion(local, prs.length), { header: 'Bitácora', options: [integrate, 'Cancelar'] }).catch(() => null)
1035 if (answer !== integrate) return
1036 await $.prompt.submit({ text: bitacoraPrompt(prs), asUser: true })
1037}
1038
1039async function refresh($: EngineInterface) {
1040 if (isRefreshing || !isEligible || !isWanted) return
1041 isRefreshing = true
1042 try {
1043 if (agentChecksLeft > 0) {
1044 agentChecksLeft -= 1
1045 const agent = await plannerSession($)
1046 if (agent !== null) agentChecksLeft = 0
1047 if (agent === true) {
1048 isEligible = false
1049 await deactivate($)
1050 isWanted = true
1051 return
1052 }
1053 }
1054 await refreshRuns($)
1055 await refreshOpenPrs($)
1056 await refreshFieldNotes($)
1057 const list = await runNextOrder($)
1058 await update($, listAtom, () => list)
1059 } finally {
1060 isRefreshing = false
1061 }
1062}
1063
1064// El comando queda escrito sin Enter: la persona lo revisa y lo envia (MEF-ADR-0055 decision 2).
1065async function applyPlan($: EngineInterface, plan: LaunchPlan): Promise<boolean> {
1066 if (plan.kind === 'none') {
1067 $.ui.toast(plan.message)
1068 return false
1069 }
1070 const text = plan.kind === 'fill'
1071 ? plan.text
1072 : answerText(plan.options, await $.ui.ask(plan.question, plan.options.map(o => o.label)).catch(() => null))
1073 if (text === null) return false
1074 await $.prompt.fill({ text, mode: 'replace' })
1075 return true
1076}
1077
1078async function launchKey($: EngineInterface, kind: LaunchKind) {
1079 const list = await read($, listAtom)
1080 if (list && !list.error) await applyPlan($, planLaunch(list, kind))
1081}
1082
1083async function launchRow($: EngineInterface, issue: number) {
1084 const item = (await read($, listAtom))?.items.find(i => i.number === issue)
1085 if (item) await applyPlan($, planIssue(item))
1086}
1087
1088async function activate($: EngineInterface) {
1089 isWanted = true
1090 await update($, activeAtom, () => true)
1091 timer?.cancel()
1092 timer = $.clock.every(POLL_MS, () => void refresh($))
1093 void loadVersion($)
1094 runsTimer?.cancel()
1095 // Ritmo rapido solo con corridas activas; sin ellas, `refresh` las relee al ritmo de los listos (CA-5).
1096 runsTimer = $.clock.every(RUNS_POLL_MS, () => {
1097 if (Object.keys(seenRuns).length > 0 || lastBatchIssues !== null || isParallelLive || Date.now() < launchPollUntilMs) void refreshRuns($)
1098 })
1099 prTimer?.cancel()
1100 prTimer = $.clock.every(PR_CHECK_MS, () => {
1101 void closeMergedPrs($)
1102 void probeParallelMerged($)
1103 })
1104 mergeTimer?.cancel()
1105 mergeTimer = $.clock.every(MERGE_POLL_MS, () => void pollMerge($))
1106 tickTimer?.cancel()
1107 // La mascota anima solo con corrida activa o con Claude trabajando; en reposo no hay re-render por segundo.
1108 tickTimer = $.clock.every(1000, () => {
1109 if (isAnimating) void update($, tickAtom, () => Math.floor(Date.now() / 1000))
1110 void closeStaleMerge($)
1111 void pollHistorian($)
1112 })
1113 void refresh($)
1114}
1115
1116async function deactivate($: EngineInterface) {
1117 isWanted = false
1118 if (isLogOpen) await closeLog($)
1119 timer?.cancel()
1120 timer = null
1121 runsTimer?.cancel()
1122 runsTimer = null
1123 tickTimer?.cancel()
1124 tickTimer = null
1125 mergeTimer?.cancel()
1126 mergeTimer = null
1127 prTimer?.cancel()
1128 prTimer = null
1129 await update($, activeAtom, () => false)
1130}
1131
1132async function isMefistoRepo($: EngineInterface): Promise<boolean> {
1133 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel']).catch(() => ({ exitCode: 1, stdout: '' }))
1134 if (top.exitCode !== 0) return false
1135 const raw = await $.fs.read(`${top.stdout.trim()}/.claude-plugin/plugin.json`).catch(() => '')
1136 return typeof raw === 'string' && isMefistoManifest(raw)
1137}
1138
1139// Agente principal de la sesion: primero la linea de comando de Claude Code, luego el transcript si ya existe.
1140async function plannerSession($: EngineInterface): Promise<boolean | null> {
1141 const ps = await $.process.run(['sh', '-c', 'ps -o args= -p "$PPID"']).catch(() => ({ exitCode: 1, stdout: '' }))
1142 const cmdline = ps.exitCode === 0 ? ps.stdout.trim() : ''
1143 if (/\bclaude\b/.test(cmdline)) return agentFlagOf(cmdline) === PLANNER_AGENT
1144 const home = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
1145 const path = transcriptPathOf(home, await $.session.cwd(), await $.session.id())
1146 const { stdout } = await $.process.run(['head', '-c', '200000', path]).catch(() => ({ stdout: '' }))
1147 const agent = agentSettingOf(stdout)
1148 return agent === null ? null : agent === PLANNER_AGENT
1149}
1150
1151// El engine no entrega classic.* a un plugin de tier user y session.start no se repite tras /clear, /resume ni /branch:
1152// cada segundo se compara la intencion del modulo con el atom y se rearma la banda. Corre desde el reloj, donde escribir esta permitido.
1153async function heal($: EngineInterface) {
1154 if (isHealing) return
1155 isHealing = true
1156 try {
1157 if (!shouldRearm({ isEligible, isWanted, isActive: await read($, activeAtom) })) return
1158 await activate($)
1159 await $.ui.invalidate('ui.render')
1160 } finally {
1161 isHealing = false
1162 }
1163}
1164
1165// Cinta vencida: una arrancada por teclas cuyo skill nunca invoco pr-sync.sh (p. ej. descarto todos los PRs).
1166async function closeStaleMerge($: EngineInterface) {
1167 if (!isEligible || !isWanted || isMergeScriptSeen) return
1168 const run = await read($, mergeAtom)
1169 if (run && run.finishedMs === null && Date.now() - run.startedMs > MERGE_STALE_MS) await endMerge($)
1170}
1171
1172export const register: Register = on => {
1173 // La senal del merge es la llamada Bash a pr-sync.sh: el plugin carga en tier user y el engine no le entrega classic.*.
1174 // Convive con el tool.call Bash del tablero (mismo matcher, #2302).
1175 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1176 if (isEligible && isWanted && isPipelineLaunch(e.command)) {
1177 launchPollUntilMs = Date.now() + LAUNCH_POLL_WINDOW_MS
1178 try {
1179 return await next(e)
1180 } finally {
1181 void refreshRuns($)
1182 }
1183 }
1184 const mergeArgs = isEligible && isWanted ? mergeRunArgsOf(e.command) : null
1185 if (mergeArgs === null) return next(e)
1186 await startMerge($, mergeArgs)
1187 isMergeScriptSeen = true
1188 try {
1189 return await next(e)
1190 } finally {
1191 await endMerge($)
1192 }
1193 }).catch(($, e, next) => next(e))
1194
1195 // Con matcher: el engine admite un solo session.start sin matcher por plugin (el del tablero), y asi `-p` ni lo dispara.
1196 on('session.start', { isInteractive: true }, async ($, e, next) => {
1197 isEligible = false
1198 const agent = (await isMefistoRepo($)) ? true : await plannerSession($)
1199 if (agent === true) {
1200 await deactivate($)hooks/register.tsx 649 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { BoardFocus, BoardList, BoardTab } from './types'
5import {
6 nextOrderPath,
7 typeBadge,
8 agentFlagOf,
9 isMefistoManifest,
10 agentSettingOf,
11 transcriptPathOf,
12 arrivals,
13 clip,
14 createdIssueOf,
15 showsDraftList,
16 createdText,
17 cropGrid,
18 isIssueChange,
19 issueClosed,
20 addPending,
21 applyPending,
22 dropIssue,
23 type Pending,
24 isIssueCreate,
25 usedColumns,
26 mascotPose,
27 isPlannerClosing,
28 issueMarkedListo,
29 numberWidth,
30 padEnd,
31 pageOf,
32 pageSizeOf,
33 parseNextOrder,
34 parseOpenIssues,
35 reasonOf,
36 refineTargetOf,
37 signatureOf,
38 topicOf,
39 versionLabel,
40 shouldRearm,
41} from './logic'
42import { DEFAULT_COLOR, HEIGHT, PALETTE, RASTER_ROWS, sprite } from './sprites'
43
44const PLANNER_AGENT = 'mefisto:planner'
45const POLL_MS = 60_000
46const SCRIPT_TIMEOUT_MS = 180_000
47const FLASH_MS = 8_000
48// GitHub tarda en reflejar un cambio en todas sus consultas: un refresco inmediato puede guardar la firma nueva
49// con listas viejas de next-order y el poll ya no vuelve a refrescar. Se repite forzado tras este margen.
50const SETTLE_MS = 15_000
51
52const activeAtom = atom({ plugin: 'mefisto', key: 'isActive' } as const, false)
53const plannerAtom = atom({ plugin: 'mefisto', key: 'isPlannerSession' } as const, false)
54const expandedAtom = atom({ plugin: 'mefisto', key: 'isExpanded' } as const, false)
55const pageAtom = atom({ plugin: 'mefisto', key: 'page' } as const, 0)
56const tabAtom = atom({ plugin: 'mefisto', key: 'tab' } as const, 'borrador')
57const focusAtom = atom({ plugin: 'mefisto', key: 'focus' } as const, null)
58const confirmAtom = atom({ plugin: 'mefisto', key: 'isConfirmingClose' } as const, false)
59const flashAtom = atom({ plugin: 'mefisto', key: 'flash' } as const, null)
60const refineAtom = atom({ plugin: 'mefisto', key: 'refine' } as const, null)
61const developAtom = atom({ plugin: 'mefisto', key: 'develop' } as const, null)
62const updatedAtom = atom({ plugin: 'mefisto', key: 'updatedMs' } as const, 0)
63const signatureAtom = atom({ plugin: 'mefisto', key: 'signature' } as const, '')
64const frameAtom = atom({ plugin: 'mefisto', key: 'frame' } as const, 0)
65const stepsAtom = atom({ plugin: 'mefisto', key: 'stepsInTurn' } as const, 0)
66const workingAtom = atom({ plugin: 'mefisto', key: 'isWorking' } as const, false)
67const knownAtom = atom({ plugin: 'mefisto', key: 'known' } as const, [])
68const pendingAtom = atom({ plugin: 'mefisto', key: 'pendingCount' } as const, 0)
69
70let isInteractive = false
71// La intencion vive aqui: /clear no dispara session.start y reinicia los atoms.
72let isBoardOn = false
73let isTurnedOff = false
74let isHealing = false
75let healTimer: { cancel: () => void } | null = null
76const HEAL_MS = 1_000
77let pending: Pending = new Map()
78let isRefreshing = false
79let settle: { cancel: () => void } | null = null
80let timer: { cancel: () => void } | null = null
81let animation: { cancel: () => void } | null = null
82const ANIMATION_MS = 600
83
84// Raiz del plugin: la que el engine expone como $.plugin.root; si faltara, el archivo que escribe el SessionStart del plugin.
85async function pluginRoot($: EngineInterface): Promise<string | null> {
86 const own = $.plugin.root
87 if (own) return own
88 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel']).catch(() => ({ exitCode: 1, stdout: '' }))
89 const base = top.exitCode === 0 ? top.stdout.trim() : await $.session.cwd()
90 const root = await $.fs.read(`${base}/.mefisto/pipeline/.plugin-root`).catch(() => '')
91 return typeof root === 'string' && root.trim() !== '' ? root.trim() : null
92}
93
94const versionAtom = atom({ plugin: 'mefisto', key: 'version' } as const, null as string | null)
95
96async function loadVersion($: EngineInterface) {
97 const root = await pluginRoot($)
98 const base = root ? root.replace(/\/+$/, '') : null
99 const read1 = async (file: string) => (base ? await $.fs.read(`${base}/${file}`).catch(() => null) : null)
100 const label = versionLabel(await read1('mefisto-manifest.json'), await read1('.claude-plugin/plugin.json'))
101 await update($, versionAtom, () => label)
102}
103
104async function runNextOrder($: EngineInterface, args: string[]): Promise<BoardList> {
105 const root = await pluginRoot($)
106 if (!root) return parseNextOrder(2, '', 'raiz del plugin desconocida')
107 const { exitCode, stdout, stderr } = await $.process
108 .run([nextOrderPath(root), ...args], { timeoutMs: SCRIPT_TIMEOUT_MS })
109 .catch(err => ({ exitCode: 2, stdout: '', stderr: String(err) }))
110 return parseNextOrder(exitCode, stdout, stderr)
111}
112
113async function refresh($: EngineInterface, isForced: boolean) {
114 if (isRefreshing || !(await read($, activeAtom))) return
115 isRefreshing = true
116 try {
117 const { exitCode, stdout } = await $.process
118 .run(['gh', 'issue', 'list', '--state', 'open', '--limit', '300', '--json', 'number,title,labels,updatedAt'])
119 .catch(() => ({ exitCode: 1, stdout: '' }))
120 const issues = exitCode === 0 ? parseOpenIssues(stdout) : null
121 if (!issues) return
122
123 const signature = signatureOf(issues)
124 if (!isForced && pending.size === 0 && signature === (await read($, signatureAtom))) return
125
126 const focus = await read($, focusAtom)
127 for (const a of arrivals(issues, await read($, knownAtom))) {
128 if (!focus?.created.includes(a.number)) $.ui.toast(`Nuevo ${a.kind} #${a.number}: ${clip(a.title, 60)}`)
129 }
130 const [refine, develop] = await Promise.all([runNextOrder($, ['--refinement', '--json']), runNextOrder($, ['--json'])])
131 const applied = applyPending(refine, pending, Date.now())
132 pending = applied.pending
133 await update($, refineAtom, () => applied.list)
134 await update($, pendingAtom, () => pending.size)
135 await update($, developAtom, () => develop)
136 await update($, signatureAtom, () => signature)
137 await update($, knownAtom, () => issues.map(i => i.number))
138 await update($, updatedAtom, () => Date.now())
139 } finally {
140 isRefreshing = false
141 }
142}
143
144async function activate($: EngineInterface) {
145 isBoardOn = true
146 isTurnedOff = false
147 await update($, activeAtom, () => true)
148 timer?.cancel()
149 timer = $.clock.every(POLL_MS, () => void refresh($, false))
150 void loadVersion($)
151 void refresh($, true)
152}
153
154async function deactivate($: EngineInterface) {
155 isTurnedOff = true
156 pending = new Map()
157 await update($, pendingAtom, () => 0)
158 timer?.cancel()
159 timer = null
160 await update($, activeAtom, () => false)
161}
162
163// El engine no entrega classic.* a un plugin de tier user y session.start no se repite tras /clear, /resume ni /branch:
164// cada segundo se compara la intencion del modulo con el atom y se rearma el tablero. Corre desde el reloj, donde escribir esta permitido.
165async function heal($: EngineInterface) {
166 if (isHealing) return
167 isHealing = true
168 try {
169 if (!shouldRearm({ isEligible: isBoardOn, isWanted: !isTurnedOff, isActive: await read($, activeAtom) })) return
170 await activate($)
171 await $.ui.invalidate('ui.render')
172 } finally {
173 isHealing = false
174 }
175}
176
177const DETECT_TRIES = 20
178const DETECT_EVERY_MS = 3_000
179
180// El agente principal de la sesion. Los eventos clasicos no llegan a un modulo cargado con --plugin-dir,
181// asi que se lee primero la linea de comando del proceso de Claude Code (padre del `sh` que corre aqui) y,
182// si no se puede, el inicio del transcript, que solo existe tras el primer mensaje: por eso se reintenta.
183async function detectPlanner($: EngineInterface, triesLeft: number) {
184 if (!isInteractive || isTurnedOff || (await read($, activeAtom))) return
185 const ps = await $.process.run(['sh', '-c', 'ps -o args= -p "$PPID"']).catch(() => ({ exitCode: 1, stdout: '' }))
186 const cmdline = ps.exitCode === 0 ? ps.stdout.trim() : ''
187 if (/\bclaude\b/.test(cmdline)) {
188 if (agentFlagOf(cmdline) === PLANNER_AGENT) await claimPlanner($)
189 return
190 }
191 const home = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
192 const path = transcriptPathOf(home, await $.session.cwd(), await $.session.id())
193 const { stdout } = await $.process.run(['head', '-c', '200000', path]).catch(() => ({ stdout: '' }))
194 const agent = agentSettingOf(stdout)
195 if (agent === PLANNER_AGENT) {
196 await claimPlanner($)
197 return
198 }
199 if (agent === null && triesLeft > 0) $.clock.after(DETECT_EVERY_MS, () => void detectPlanner($, triesLeft - 1))
200}
201
202// Marca la sesion como del planner y la activa si ya se sabe que es interactiva. Devuelve si la activo ahora.
203async function claimPlanner($: EngineInterface): Promise<boolean> {
204 await update($, plannerAtom, () => true)
205 if (!isInteractive || (await read($, activeAtom))) return false
206 await activate($)
207 return true
208}
209
210// Cada instruccion del agente (una herramienta, o tu mensaje que abre el turno) alterna el cuadro A/B.
211async function step($: EngineInterface, isNewTurn: boolean) {
212 await update($, frameAtom, f => (f === 1 ? 0 : 1))
213 await update($, stepsAtom, n => (isNewTurn ? 0 : (n ?? 0) + 1))
214}
215
216// Recorte comun a todos los cuadros del planner, calculado una vez: sin margen y sin saltos al alternar.
217const MASCOT_STATES = ['planeando', 'pensando', 'listo'] as const
218const MASCOT_COLS = usedColumns(MASCOT_STATES.flatMap(state => [sprite('planner', state, 0), sprite('planner', state, 1)]))
219const MASCOT_WIDTH = MASCOT_COLS.to - MASCOT_COLS.from + 1
220
221/** Celdas del Raster (dos pixeles por celda con ▀/▄), como toRasterCells de sprites.ts pero con el ancho recortado. */
222function mascotCells(grid: readonly string[]): string {
223 const color = (ch: string | undefined) => (!ch || ch === '.' || ch === ' ' ? null : (PALETTE[ch] ?? null))
224 const words: number[] = []
225 for (let y = 0; y < HEIGHT; y += 2) {
226 for (let x = 0; x < MASCOT_WIDTH; x++) {
227 const top = color(grid[y]?.[x])
228 const bottom = color(grid[y + 1]?.[x])
229 if (top !== null) words.push(0x2580, top, bottom ?? DEFAULT_COLOR)
230 else if (bottom !== null) words.push(0x2584, bottom, DEFAULT_COLOR)
231 else words.push(0x20, DEFAULT_COLOR, DEFAULT_COLOR)
232 }
233 }
234 let bin = ''
235 for (const b of new Uint8Array(Uint32Array.from(words).buffer)) bin += String.fromCharCode(b)
236 return btoa(bin)
237}
238
239// Mientras Claude trabaja (pensando o con herramientas) la mascota alterna sola; en reposo queda quieta.
240async function setWorking($: EngineInterface, isWorking: boolean) {
241 await update($, workingAtom, () => isWorking)
242 animation?.cancel()
243 animation = isWorking ? $.clock.every(ANIMATION_MS, () => void update($, frameAtom, f => (f === 1 ? 0 : 1))) : null
244}
245
246async function startFocus($: EngineInterface, focus: BoardFocus) {
247 await update($, confirmAtom, () => false)
248 await update($, flashAtom, () => null)
249 await update($, focusAtom, () => focus)
250}
251
252async function closeFocus($: EngineInterface, summary: string) {
253 await update($, confirmAtom, () => false)
254 await update($, focusAtom, () => null)
255 await update($, flashAtom, () => ({ text: summary, untilMs: Date.now() + FLASH_MS }))
256 $.clock.after(FLASH_MS, () => void update($, flashAtom, () => null))
257 void refresh($, true)
258}
259
260function summaryOf(focus: BoardFocus, isListo: boolean): string {
261 const created = createdText(focus.created)
262 const head =
263 focus.kind === 'refinar'
264 ? `✓ #${focus.issue}${isListo ? ' → listo' : ' · refinamiento cerrado'}`
265 : `✓ exploración «${clip(focus.topic, 40)}»`
266 return [head, created].filter(Boolean).join(' · ')
267}
268
269async function onPrompt($: EngineInterface, text: string) {
270 const focus = await read($, focusAtom)
271 const target = refineTargetOf(text)
272 if (target !== null && !(focus?.kind === 'refinar' && focus.issue === target)) {
273 const known = (await read($, refineAtom))?.items.find(i => i.number === target)
274 await startFocus($, { kind: 'refinar', issue: target, topic: known?.title ?? '', created: [], startedMs: Date.now() })
275 return
276 }
277 if (!focus && target === null && text.trim() !== '' && !text.trim().startsWith('/')) {
278 await startFocus($, { kind: 'explorar', issue: null, topic: topicOf(text), created: [], startedMs: Date.now() })
279 }
280}
281
282function refreshAfterSettle($: EngineInterface) {
283 settle?.cancel()
284 settle = $.clock.after(SETTLE_MS, () => void refresh($, true))
285}
286
287// Quita #N de la lista de borradores en el acto y lo oculta en los refrescos siguientes hasta que se confirme.
288async function hideFromDrafts($: EngineInterface, issue: number) {
289 pending = addPending(pending, issue, Date.now())
290 await update($, refineAtom, list => dropIssue(list, issue))
291 await update($, pendingAtom, () => pending.size)
292}
293
294async function onBash($: EngineInterface, command: string, output: string) {
295 const transitioned = issueMarkedListo(command) ?? issueClosed(command)
296 if (transitioned !== null) await hideFromDrafts($, transitioned)
297 if (isIssueChange(command)) refreshAfterSettle($)
298 const focus = await read($, focusAtom)
299 if (!focus) return
300 // Un mismo comando puede crear un borrador y pasar el foco a listo: se revisan las dos cosas.
301 if (isIssueCreate(command)) {
302 const created = createdIssueOf(output)
303 if (created !== null && !focus.created.includes(created)) {
304 if (focus.kind === 'explorar' && focus.created.length === 0) await update($, pageAtom, () => 0)
305 await update($, focusAtom, f => (f ? { ...f, created: [...f.created, created] } : f))
306 void refresh($, true)
307 }
308 }
309 const listo = issueMarkedListo(command)
310 const updated = (await read($, focusAtom)) ?? focus
311 if (focus.kind === 'refinar' && listo !== null && listo === focus.issue) {
312 await closeFocus($, summaryOf(updated, true))
313 return
314 }
315 if (isPlannerClosing(command)) await closeFocus($, summaryOf(updated, false))
316}
317
318// Cierre de la exploracion en dos teclas dentro de la banda: el planner corre sin AskUserQuestion, asi
319// que $.ui.ask se rechaza. Al confirmar le pide su rutina de cierre (resumen + field note); el foco se
320// cierra solo cuando el planner corre field-note.sh.
321async function closeSession($: EngineInterface, isConfirmed: boolean) {
322 if (!isConfirmed) {
323 await update($, confirmAtom, () => true)
324 return
325 }
326 await update($, confirmAtom, () => false)
327 await $.prompt.submit({ text: 'Cerremos la sesión.', asUser: true })
328}
329
330// La misma tecla abre su lista o, si ya estaba abierta, la cierra.
331async function toggleList($: EngineInterface, tab: BoardTab) {
332 if (await read($, focusAtom)) return
333 const isOpen = (await read($, expandedAtom)) && (await read($, tabAtom)) === tab
334 await update($, tabAtom, () => tab)
335 await update($, pageAtom, () => 0)
336 await update($, expandedAtom, () => !isOpen)
337}
338
339// Avanza de pagina y da la vuelta al final.
340async function nextPage($: EngineInterface) {
341 const tab = showsDraftList(await read($, focusAtom)) ? 'borrador' : await read($, tabAtom)
342 const list = tab === 'borrador' ? await read($, refineAtom) : await read($, developAtom)
343 const { page, pages } = pageOf(await read($, pageAtom), list?.items.length ?? 0, pageSizeOf(tab))
344 await update($, pageAtom, () => (page + 1) % pages)
345}
346
347async function fill($: EngineInterface, text: string) {
348 await $.prompt.fill({ text, mode: 'replace' })
349}
350
351// En el repo del propio Mefisto el tablero es el mod interno (/mefisto-planner-board): el publicado no se registra
352// ni se activa, porque su next-order.sh alli se niega a correr y la banda solo mostraria el fallo.
353async function isMefistoRepo($: EngineInterface): Promise<boolean> {
354 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel']).catch(() => ({ exitCode: 1, stdout: '' }))
355 if (top.exitCode !== 0) return false
356 const raw = await $.fs.read(`${top.stdout.trim()}/.claude-plugin/plugin.json`).catch(() => '')
357 return typeof raw === 'string' && isMefistoManifest(raw)
358}
359
360export const register: Register = on => {
361 on('session.start', async ($, e, next) => {
362 isInteractive = e.isInteractive
363 if (await isMefistoRepo($)) {
364 await deactivate($)
365 return next(e)
366 }
367 await $.command.register({
368 name: 'fausto-board',
369 description: 'Tablero de Fausto (planner): refresh | borradores | listos | cerrar | on | off',
370 argumentHint: '[refresh|borradores|listos|cerrar|on|off]',
371 immediate: true,
372 })
373 const isWanted = (await read($, activeAtom)) || (await read($, plannerAtom))
374 if (isInteractive && isWanted) await activate($)
375 if (isInteractive && (await read($, workingAtom))) await setWorking($, true)
376 else if (isInteractive) void detectPlanner($, DETECT_TRIES)
377 if (isInteractive) healTimer ??= $.clock.every(HEAL_MS, () => void heal($))
378 return next(e)
379 })
380
381 on('prompt.submit', async ($, e, next) => {
382 if (e.origin.kind === 'composer' && !(await read($, activeAtom))) await detectPlanner($, 0)
383 if (await read($, activeAtom)) {
384 await step($, true)
385 await setWorking($, true)
386 }
387 if (e.origin.kind === 'composer' && (await read($, activeAtom))) await onPrompt($, e.text)
388 return next(e)
389 }).catch(($, e, next) => next(e))
390
391 on('tool.call', async ($, e, next) => {
392 if (await read($, activeAtom)) await step($, false)
393 return next(e)
394 })
395
396 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
397 const ran = await next(e)
398 if (await read($, activeAtom)) {
399 const output = ran.text ?? JSON.stringify(ran.result ?? '')
400 await onBash($, e.command, output).catch(() => undefined)
401 }
402 return ran
403 })
404
405 on('turn.complete', async ($, e, next) => {
406 const done = await next(e)
407 if (await read($, activeAtom)) await setWorking($, false)
408 return done
409 })
410
411 on('command.run', { command: 'fausto-board' }, async ($, e) => {
412 const arg = e.args.trim()
413 if (arg === 'off') {
414 await deactivate($)
415 return { text: 'Tablero del planner apagado en esta sesión.' }
416 }
417 if (arg === 'on' || !(await read($, activeAtom))) {
418 await activate($)
419 return { text: 'Tablero del planner activo en esta sesión.' }
420 }
421 if (arg === 'borradores' || arg === 'listos') {
422 await toggleList($, arg === 'borradores' ? 'borrador' : 'listo')
423 return { text: `Lista de ${arg} alternada.` }
424 }
425 if (arg === 'cerrar') {
426 const focus = await read($, focusAtom)
427 if (focus) await closeFocus($, summaryOf(focus, false))
428 return { text: focus ? 'Foco cerrado.' : 'No había foco abierto.' }
429 }
430 await loadVersion($)
431 await refresh($, true)
432 return { text: 'Tablero actualizado.' }
433 })
434
435 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
436 if (!(await read($, activeAtom)) || e.props.hasSurvey) return next(e)
437 const { Box, Text, Button } = $.ui.resolve(e)
438 const focus = await read($, focusAtom)
439 const isConfirmingClose = await read($, confirmAtom)
440 const flash = await read($, flashAtom)
441 const showList = showsDraftList(focus)
442 const isExpanded = (await read($, expandedAtom)) || showList
443 const refine = await read($, refineAtom)
444 const develop = await read($, developAtom)
445 const inner = Math.max(40, (e.props.bodyColumns ?? 80) - 4)
446 const count = (l: BoardList | null) => (l ? String(l.items.length) : '…')
447 const isUpdating = (await read($, pendingAtom)) > 0
448 const tab = showList ? 'borrador' : await read($, tabAtom)
449 const suggested = refine?.items[0]?.number ?? null
450 const listButtons = (
451 <Box gap={2}>
452 <Button key="list-borrador" hotkey="3" plain variant={isExpanded && tab === 'borrador' ? 'primary' : undefined}
453 dimColor={!(isExpanded && tab === 'borrador')} label={`borradores ${count(refine)}`}
454 onPress={() => void toggleList($, 'borrador')} />
455 {isUpdating && <Text dimColor>actualizando…</Text>}
456 <Button key="list-listo" hotkey="4" plain variant={isExpanded && tab === 'listo' ? 'primary' : undefined}
457 dimColor={!(isExpanded && tab === 'listo')} label={`listos ${count(develop)}`}
458 onPress={() => void toggleList($, 'listo')} />
459 </Box>
460 )
461
462 let head
463 if (focus) {
464 const label =
465 focus.kind === 'refinar'
466 ? `refinar #${focus.issue}${focus.topic ? ` · ${focus.topic}` : ''}`
467 : `explorar · ${focus.topic}`
468 const created = createdText(focus.created)
469 head = (
470 <Box justifyContent="space-between">
471 <Box gap={2}>
472 <Text color="claude">●</Text>
473 <Text bold wrap="truncate-end">{clip(label, Math.max(20, inner - created.length - 46))}</Text>
474 {created !== '' && <Text color="success">{created}</Text>}
475 </Box>
476 {focus.kind === 'explorar' && !isConfirmingClose && (
477 <Button key="close-session" hotkey="1" plain label="cerrar sesión" onPress={() => void closeSession($, false)} />
478 )}
479 {focus.kind === 'explorar' && isConfirmingClose && (
480 <Box gap={2}>
481 <Text color="warning">¿cerrar? hará el resumen y la field note</Text>
482 <Button key="close-confirm" hotkey="1" plain label="sí, cerrar" onPress={() => void closeSession($, true)} />
483 <Button key="close-cancel" hotkey="2" plain label="seguir"
484 onPress={() => void update($, confirmAtom, () => false)} />
485 </Box>
486 )}
487 </Box>
488 )
489 } else if (flash && flash.untilMs > Date.now()) {
490 head = (
491 <Box justifyContent="space-between">
492 <Text color="success">{clip(flash.text, inner - 34)}</Text>
493 {listButtons}
494 </Box>
495 )
496 } else {
497 head = (
498 <Box justifyContent="space-between">
499 <Box gap={3}>
500 <Button key="mode-explorar" hotkey="1" plain label="explorar" onPress={() => void fill($, 'Quiero explorar: ')} />
501 {suggested !== null && (
502 <Button key="mode-refinar" hotkey="2" plain label={`refinar #${suggested}`}
503 onPress={() => void fill($, `Refina el borrador #${suggested}`)} />
504 )}
505 </Box>
506 {listButtons}
507 </Box>
508 )
509 }
510
511 const body = Math.max(30, inner - MASCOT_WIDTH - 2)
512 const frame = await read($, frameAtom)
513 const isWorking = e.props.isWorking || (await read($, workingAtom))
514 const state = mascotPose(isWorking, await read($, stepsAtom), !!flash && flash.untilMs > Date.now())
515 const grid = cropGrid(sprite('planner', state, frame), MASCOT_COLS)
516 const elements = $.ui.resolve(e)
517 const version = await read($, versionAtom)
518 const raster =
519 'Raster' in elements ? (
520 <elements.Raster key="mefisto-mascota" columns={MASCOT_WIDTH} rows={RASTER_ROWS} cells={mascotCells(grid)} />
521 ) : (
522 <Box width={MASCOT_WIDTH} />
523 )
524 const mascot = version ? (
525 <Box key="mefisto-mascota-version" flexDirection="column" width={MASCOT_WIDTH}>
526 {raster}
527 <Box width={MASCOT_WIDTH} justifyContent="center">
528 <Text dimColor wrap="truncate-end">{version}</Text>
529 </Box>
530 </Box>
531 ) : (
532 raster
533 )
534
535 const updatedMs = await read($, updatedAtom)
536 let content
537 if (focus && !showList) {
538 const minutes = Math.max(0, Math.floor((Date.now() - (focus.startedMs ?? Date.now())) / 60_000))
539 const what = focus.kind === 'refinar' ? `Refinando #${focus.issue}` : 'Explorando'
540 const ends =
541 focus.kind === 'refinar'
542 ? `termina al pasar #${focus.issue} a estado:listo o con el cierre`
543 : 'termina con el cierre del planner'
544 content = (
545 <Box flexDirection="column" width={body}>
546 <Text bold color="claude">{what}{minutes > 0 ? ` · ${minutes} min` : ''}</Text>
547 <Text wrap="wrap">{clip(focus.topic || ' ', body * 2 - 2)}</Text>
548 <Text color={focus.created.length > 0 ? 'success' : undefined} dimColor={focus.created.length === 0}>
549 {focus.created.length > 0 ? createdText(focus.created) : 'sin borradores nuevos'}
550 </Text>
551 <Text dimColor wrap="truncate-end">{ends}</Text>
552 <Text dimColor>{focus.kind === 'explorar' ? '1 cierra la sesión (pide confirmar)' : '/fausto-board cerrar lo cierra a mano'}</Text>
553 </Box>
554 )
555 } else if (!isExpanded) {
556 const nextRefine = refine?.items.slice(0, 2) ?? []
557 const nextDevelop = develop?.items[0]
558 content = (
559 <Box flexDirection="column" width={body}>
560 <Text dimColor>siguiente a refinar</Text>
561 {[0, 1].map(i => (
562 <Text key={`r-${i}`} dimColor={i > 0} wrap="truncate-end">
563 {nextRefine[i] ? `#${nextRefine[i].number} ${clip(nextRefine[i].title, body - 8)}` : ' '}
564 </Text>
565 ))}
566 <Text dimColor>siguiente a desarrollar</Text>
567 <Text wrap="truncate-end">{nextDevelop ? `#${nextDevelop.number} ${clip(nextDevelop.title, body - 8)}` : ' '}</Text>
568 <Text dimColor>{updatedMs ? ' ' : 'cargando…'}</Text>
569 </Box>
570 )
571 } else {
572 const list = tab === 'borrador' ? refine : develop
573 const size = pageSizeOf(tab)
574 const { page, pages } = pageOf(await read($, pageAtom), list?.items.length ?? 0, size)
575 const visible = list?.items.slice(page * size, (page + 1) * size) ?? []
576 const blankRows = Math.max(0, size - Math.max(visible.length, 1))
577 const numWidth = numberWidth(visible)
578 // Solo 'tras #N' ocupa columna: sin dependencias no se marca.
579 const afterWidth = Math.min(16, Math.max(0, ...visible.map(i => reasonOf(i).length)))
580 // Ancho exacto de la fila: el prefijo '5: ' de la tecla (solo en borradores), el numero, un espacio
581 // y, si alguno depende de otro, la columna 'tras #N'. El titulo ocupa el resto hasta el marco.
582 const keyPrefix = tab === 'borrador' ? 3 : 0
583 const badgeWidth = 2
584 const titleWidth = Math.max(12, body - keyPrefix - badgeWidth - numWidth - 1 - (afterWidth > 0 ? afterWidth + 2 : 0))
585 const more = list
586 ? [
587 list.blockedCount > 0 ? `${list.blockedCount} bloqueados` : '',
588 list.cycleCount > 0 ? `${list.cycleCount} en ciclo` : '',
589 ].filter(Boolean).join(' · ')
590 : ''
591 const hint = tab === 'borrador' ? '5-9 al prompt' : ''
592 content = (
593 <Box flexDirection="column" width={body}>
594 {list?.error && <Text color="error">next-order falló: {clip(list.error, body - 20)}</Text>}
595 {list && !list.error && visible.length === 0 && (
596 <Text dimColor>{tab === 'borrador' ? 'Sin borradores refinables.' : 'Sin issues lanzables.'}</Text>
597 )}
598 {visible.map((item, i) => {
599 const reason = reasonOf(item)
600 const badge = typeBadge(item.tipo)
601 return (
602 <Box>
603 <Text color={badge.color}>{`${badge.letter} `}</Text>
604 {tab === 'borrador' ? (
605 <Button
606 key={`item-${item.number}`}
607 hotkey={String(i + 5)}
608 plain
609 dimColor={page > 0 || i > 0}
610 label={`${padEnd(`#${item.number}`, numWidth)} ${padEnd(clip(item.title, titleWidth), titleWidth)}`}
611 onPress={() => void fill($, `Refina el borrador #${item.number}`)}
612 />
613 ) : (
614 <Text dimColor={page > 0 || i > 0}>
615 {`${padEnd(`#${item.number}`, numWidth)} ${padEnd(clip(item.title, titleWidth), titleWidth)}`}
616 </Text>
617 )}
618 <Text dimColor>{reason ? ` ${clip(reason, afterWidth)}` : ''}</Text>
619 </Box>
620 )
621 })}
622 {Array.from({ length: blankRows }, (_, i) => (
623 <Text key={`blank-${i}`}> </Text>
624 ))}
625 <Box justifyContent="space-between">
626 <Text dimColor>{hint}</Text>
627 <Box gap={2}>
628 {more !== '' && <Text dimColor>{more}</Text>}
629 {pages > 1 && (
630 <Button key="next-page" hotkey="0" plain dimColor label={`página ${page + 1}/${pages} ▸`} onPress={() => void nextPage($)} />
631 )}
632 </Box>
633 </Box>
634 </Box>
635 )
636 }
637
638 return (
639 <Box flexDirection="column" borderStyle="round" borderColor="claude" borderDimColor paddingX={1}>
640 {head}
641 <Box gap={2} height={RASTER_ROWS + 1} alignItems="flex-start">
642 {mascot}
643 <Box marginTop={1}>{content}</Box>
644 </Box>
645 </Box>
646 )
647 })
648}
649hooks/sprites.ts 830 lines1/**
2 * mefisto-sprites.ts
3 * Mascota Mefisto para mods de Claude Code. El planner no es un Mefisto: es Fausto, el que decide
4 * (birrete de doctor, barba y tunica del mismo color que el Mefisto de su lado).
5 *
6 * Cada sprite es una cuadrícula de 18×12 píxeles escrita como texto:
7 * cada carácter es un píxel y apunta a un color de PALETTE.
8 * '.' píxel transparente (en EMOTIONS)
9 * ' ' "no tocar" (en las capas de ROLES: deja ver lo de abajo)
10 *
11 * Un sprite se arma así: emoción (cara) + capa del rol (objeto y detalles)
12 * Cada estado tiene dos cuadros, A (0) y B (1), que se alternan con cada instrucción.
13 *
14 * Salidas:
15 * toRasterCells(grid) -> celdas empacadas para el elemento Raster (terminal), 18 columnas × 6 filas
16 * toSvg(grid) -> documento SVG para el elemento Svg (app de escritorio)
17 * ONE_LINERS -> versión de una línea para la status line (elemento Text)
18 */
19
20export type Grid = readonly string[]
21export type Frame = 0 | 1
22
23export const WIDTH = 18
24export const HEIGHT = 12
25/** Filas que ocupa el sprite en la terminal (dos píxeles por fila con ▀ / ▄). */
26export const RASTER_ROWS = HEIGHT / 2
27
28/** Color por defecto de la terminal (transparente), según la documentación de Raster. */
29export const DEFAULT_COLOR = 0x01000000
30
31/** Paleta: letra -> color 0xRRGGBB. */
32export const PALETTE: Record<string, number> = {
33 "h": 0xA32D2D, // cuernos
34 "r": 0xC4504D, // cuerpo (un poco mas opaco que el original 0xE24B4A)
35 "t": 0xA32D2D, // cola
36 "E": 0x2C2C2A, // ojos / pupilas
37 "M": 0x501313, // boca y cejas
38 "W": 0xF1EFE8, // colmillos
39 "p": 0xD4537E, // corazones y lengua
40 "s": 0xB4B2A9, // humo (enojado)
41 "B": 0x85B7EB, // Z y gota de sudor
42 "Y": 0xEF9F27, // bombillo, casco, flecha
43 "y": 0xFAC775, // destellos
44 "w": 0xFFF6D9, // brillo del bombillo
45 "G": 0x888780, // casquillo del bombillo
46 "o": 0xB4B2A9, // bombillo apagado
47 "D": 0x5F5E5A, // marco del portátil
48 "U": 0x378ADD, // pantalla
49 "u": 0xB5D4F4, // líneas de código
50 "q": 0xB4B2A9, // teclado / renglones
51 "Q": 0xFFFFFF, // blanco (pantalla, hoja)
52 "R": 0xE24B4A, // error / marcas rojas
53 "V": 0x639922, // verde de éxito
54 "g": 0x888780, // vidrio del matraz
55 "L": 0x97C459, // líquido del matraz
56 "l": 0xEAF3DE, // reflejo del líquido
57 "b": 0xC0DD97, // burbujas
58 "P": 0x7F77DD, // marco de la lupa
59 "e": 0xEEEDFE, // brillo de la lupa
60 "n": 0x854F0B, // mango de la lupa
61 "c": 0xB5D4F4, // nube
62 "C": 0x888780, // nube caída
63 "k": 0xF1C9A5, // piel de Fausto
64 "f": 0xD9A07F, // nariz de Fausto
65 "i": 0x8A6F5A, // bigote de Fausto
66 "K": 0x2C2C2A, // birrete de Fausto (negro)
67 "z": 0xC4504D, // borla del birrete
68 "a": 0x9C978C, // barba y pelo de Fausto
69 "T": 0xA32D2D, // tunica de Fausto (roja)
70 "d": 0x501313, // ribete de la tunica
71}
72
73export type Emotion =
74 | 'normal'
75 | 'feliz'
76 | 'sonriente'
77 | 'enojado'
78 | 'dormido'
79 | 'asustado'
80 | 'pensando'
81 | 'preocupado'
82 | 'concentrado'
83
84/** Caras base: [cuadro A, cuadro B]. Solo 'pensando' cambia entre cuadros (bombillo encendido / apagado). */
85export const EMOTIONS: Record<Emotion, readonly [Grid, Grid]> = (() => {
86 const normalA: Grid = [
87 '..................',
88 '..................',
89 '....h..........h..',
90 '....hh........hh..',
91 '.....hrrrrrrrrh...',
92 '.....rrrrrrrrrr..t',
93 '.....rrEErrEErr.tt',
94 '.....rrEErrEErr..t',
95 '.....rrrrrrrrrr..t',
96 '......rrMMMMrr..t.',
97 '.......rrrrrrtt...',
98 '.......rr..rr.....',
99 ]
100 const felizA: Grid = [
101 '......p.p..p.p....',
102 '......ppp..ppp....',
103 '....h..p....p..h..',
104 '....hh........hh..',
105 '.....hrrrrrrrrh...',
106 '.....rrrrrrrrrr..t',
107 '.....rrEErrEErr.tt',
108 '.....rrrrrrrrrr..t',
109 '.....rMrrrrrrMr..t',
110 '......rMMWWMMr..t.',
111 '.......rrrrrrtt...',
112 '.......rr..rr.....',
113 ]
114 const sonrienteA: Grid = [
115 '..................',
116 '..................',
117 '....h..........h..',
118 '....hh........hh..',
119 '.....hrrrrrrrrh...',
120 '.....rrrrrrrrrr..t',
121 '.....rrEErrEErr.tt',
122 '.....rrrrrrrrrr..t',
123 '.....rMrrrrrrMr..t',
124 '......rMMWWMMr..t.',
125 '.......rrrrrrtt...',
126 '.......rr..rr.....',
127 ]
128 const enojadoA: Grid = [
129 '.....s.s......s.s.',
130 '......s........s..',
131 '....h..........h..',
132 '....hh........hh..',
133 '.....hrrrrrrrrh...',
134 '.....rMrrrrrrMr..t',
135 '.....rrMMrrMMrr.tt',
136 '.....rrEErrEErr..t',
137 '.....rrrrrrrrrr..t',
138 '......rrMMMMrr..t.',
139 '.......rMrrMrtt...',
140 '.......rr..rr.....',
141 ]
142 const dormidoA: Grid = [
143 '...........BBB....',
144 '............B.....',
145 '....h......BBB.h..',
146 '....hh........hh..',
147 '.....hrrrrrrrrh...',
148 '.....rrrrrrrrrr..t',
149 '.....rrrrrrrrrr.tt',
150 '.....rEErrrrEEr..t',
151 '.....rrrrrrrrrr..t',
152 '......rrrMMrrr..t.',
153 '.......rrrrrrtt...',
154 '.......rr..rr.....',
155 ]
156 const asustadoA: Grid = [
157 '.......y......y...',
158 '........y....y....',
159 '....h..........h..',
160 '....hh........hh..',
161 '.....hrMMrrMMrhB..',
162 '.....rrrrrrrrrrB.t',
163 '.....rrWWrrWWrr.tt',
164 '.....rrWErrWErr..t',
165 '.....rrrrMMrrrr..t',
166 '......rrrMMrrr..t.',
167 '.......rrrrrrtt...',
168 '.......rr..rr.....',
169 ]
170 const pensandoA: Grid = [
171 '......y..YY..y....',
172 '........YwYY......',
173 '....h...YYYY...h..',
174 '....hh...GG...hh..',
175 '.....hrrrrrrrrh...',
176 '.....rrrrrrrrrr..t',
177 '.....rrrEErrEEr.tt',
178 '.....rrrrrrrrrr..t',
179 '.....rrrrrrrrrr..t',
180 '......rrrMMrrr..t.',
181 '.......rrrrrrtt...',
182 '.......rr..rr.....',
183 ]
184 const pensandoB: Grid = [
185 '.........oo.......',
186 '........oooo......',
187 '....h...oooo...h..',
188 '....hh...GG...hh..',
189 '.....hrrrrrrrrh...',
190 '.....rrrrrrrrrr..t',
191 '.....rrrEErrEEr.tt',
192 '.....rrrrrrrrrr..t',
193 '.....rrrrrrrrrr..t',
194 '......rrrMMrrr..t.',
195 '.......rrrrrrtt...',
196 '.......rr..rr.....',
197 ]
198 const preocupadoA: Grid = [
199 '.................R',
200 '.................R',
201 '....h..........h..',
202 '....hh........hh.R',
203 '.....hrrrrrrrrh...',
204 '....BrrrMrrMrrr..t',
205 '....BrrMrrrrMrr.tt',
206 '.....rrEErrEErr..t',
207 '.....rrrrrrrrrr..t',
208 '......rrrMrMrr..t.',
209 '.......rMrMrrtt...',
210 '.......rr..rr.....',
211 ]
212 const concentradoA: Grid = [
213 '..................',
214 '..................',
215 '....h..........h..',
216 '....hh........hh..',
217 '.....hrrrrrrrrh...',
218 '.....rrrrrrrrrr..t',
219 '.....rrEErrMMrr.tt',
220 '.....rrEErrEErr..t',
221 '.....rrrrrrrrrr..t',
222 '......rrrMMrrr..t.',
223 '.......rrrprrtt...',
224 '.......rr..rr.....',
225 ]
226 return {
227 normal: [normalA, normalA],
228 feliz: [felizA, felizA],
229 sonriente: [sonrienteA, sonrienteA],
230 enojado: [enojadoA, enojadoA],
231 dormido: [dormidoA, dormidoA],
232 asustado: [asustadoA, asustadoA],
233 pensando: [pensandoA, pensandoB],
234 preocupado: [preocupadoA, preocupadoA],
235 concentrado: [concentradoA, concentradoA],
236 }
237})()
238
239export type Role = 'desarrollador' | 'tester' | 'revisor' | 'planner' | 'infraestructura' | 'historiador' | 'merge'
240
241export interface RoleState {
242 /** Cara que usa este estado. */
243 emotion: Emotion
244 /** Capas del rol para el cuadro A y el B. ' ' deja ver la cara. */
245 layers: readonly [Grid, Grid]
246 /** Cara propia del rol en lugar de la de Mefisto (Fausto, el planner). */
247 face?: readonly [Grid, Grid]
248}
249
250/** Objetos y detalles de cada rol, por estado de trabajo. */
251export const ROLES: Record<Role, Record<string, RoleState>> = (() => {
252 // Desarrollador · portátil, azul
253 const desarrollador_trabajando_A: Grid = [
254 ' ',
255 ' ',
256 ' ',
257 ' ',
258 ' ',
259 ' ',
260 ' ',
261 'DDDDD ',
262 'DUuUD ',
263 'DuUUD ',
264 'DDDDD ',
265 'qqqqqqq ',
266 ]
267 const desarrollador_trabajando_B: Grid = [
268 ' ',
269 ' ',
270 ' ',
271 ' ',
272 ' ',
273 ' ',
274 ' ',
275 'DDDDD ',
276 'DuUUD ',
277 'DUUuD ',
278 'DDDDD ',
279 'qqqqqqq ',
280 ]
281 const desarrollador_pensando_A: Grid = [
282 ' ',
283 ' ',
284 ' ',
285 ' ',
286 ' ',
287 ' ',
288 ' ',
289 'DDDDD ',
290 'DUuUD ',
291 'DuUUD ',
292 'DDDDD ',
293 'qqqqqqq ',
294 ]
295 const desarrollador_error_A: Grid = [
296 ' ',
297 ' ',
298 ' ',
299 ' ',
300 ' ',
301 ' ',
302 ' ',
303 'DDDDD ',
304 'DQRQD ',
305 'DRQRD ',
306 'DDDDD ',
307 'qqqqqqq ',
308 ]
309 const desarrollador_error_B: Grid = [
310 ' ',
311 ' ',
312 ' ',
313 ' ',
314 ' ',
315 ' ',
316 ' ',
317 'DDDDD ',
318 'DRQRD ',
319 'DQRQD ',
320 'DDDDD ',
321 'qqqqqqq ',
322 ]
323 const desarrollador_resuelto_A: Grid = [
324 ' ',
325 ' ',
326 ' ',
327 ' ',
328 ' ',
329 ' ',
330 ' ',
331 'DDDDD ',
332 'DVVQD ',
333 'DQQVD ',
334 'DDDDD ',
335 'qqqqqqq ',
336 ]
337 // Tester · matraz, verde
338 const tester_trabajando_A: Grid = [
339 ' ',
340 ' ',
341 ' ',
342 ' ',
343 ' ',
344 ' b ',
345 ' b ',
346 ' ggg ',
347 ' g ',
348 ' LLL ',
349 'LlLLL ',
350 'LLLLL ',
351 ]
352 const tester_trabajando_B: Grid = [
353 ' ',
354 ' ',
355 ' ',
356 ' ',
357 ' ',
358 ' b ',
359 ' b ',
360 ' ggg ',
361 ' g ',
362 ' LLL ',
363 'LlLLL ',
364 'LLLLL ',
365 ]
366 const tester_pensando_A: Grid = [
367 ' ',
368 ' ',
369 ' ',
370 ' ',
371 ' ',
372 ' b ',
373 ' b ',
374 ' ggg ',
375 ' g ',
376 ' LLL ',
377 'LlLLL ',
378 'LLLLL ',
379 ]
380 const tester_feliz_A: Grid = [
381 ' ',
382 ' ',
383 ' ',
384 ' ',
385 ' ',
386 ' b ',
387 ' b ',
388 ' ggg ',
389 ' g ',
390 ' LLL ',
391 'LlLLL ',
392 'LLLLL ',
393 ]
394 const tester_feliz_B: Grid = [
395 ' ',
396 ' ',
397 ' ',
398 ' ',
399 ' ',
400 ' b ',
401 ' b ',
402 ' ggg ',
403 ' g ',
404 ' LLL ',
405 'LlLLL ',
406 'LLLLL ',
407 ]
408 // Revisor · lupa, morado
409 const revisor_trabajando_A: Grid = [
410 ' ',
411 ' ',
412 ' ',
413 ' ',
414 ' ',
415 ' PP ',
416 ' PeEP ',
417 ' PEEP ',
418 ' PP ',
419 ' n ',
420 ' n ',
421 ' n ',
422 ]
423 const revisor_trabajando_B: Grid = [
424 ' ',
425 ' ',
426 ' ',
427 ' ',
428 ' ',
429 ' PP ',
430 ' PEEP ',
431 ' PEeP ',
432 ' PP ',
433 ' n ',
434 ' n ',
435 ' n ',
436 ]
437 const revisor_pensando_A: Grid = [
438 ' ',
439 ' ',
440 ' ',
441 ' ',
442 ' ',
443 ' PP ',
444 ' PeEP ',
445 ' PEEP ',
446 ' PP ',
447 ' n ',
448 ' n ',
449 ' n ',
450 ]
451 const revisor_corrigiendo_A: Grid = [
452 ' ',
453 ' ',
454 ' ',
455 ' ',
456 ' ',
457 ' PP ',
458 ' PeEP ',
459 'QQQ PEEP ',
460 'qqR PP ',
461 'QQQ n ',
462 'qRq n ',
463 'QQQn ',
464 ]
465 const revisor_corrigiendo_B: Grid = [
466 ' ',
467 ' ',
468 ' ',
469 ' ',
470 ' ',
471 ' PP ',
472 ' PEEP ',
473 'QQQ PEeP ',
474 'qqR PP ',
475 'QQQ n ',
476 'qRq n ',
477 'QQQn ',
478 ]
479 const revisor_aprobado_A: Grid = [
480 ' ',
481 ' ',
482 ' ',
483 ' ',
484 ' ',
485 ' PP ',
486 ' PeEP ',
487 'QQQ PEEP ',
488 'QQV PP ',
489 'VQV n ',
490 'QVQ n ',
491 'QQQn ',
492 ]
493 // Planner · Fausto: mira a un lado y a otro mientras planea
494 const fausto_planeando_A: Grid = [
495 '..................',
496 '.....KKKKKKKKKK...',
497 '......KKKKKKKK.z..',
498 '.......KKKKKK..z..',
499 '......akkkkkka....',
500 '......akEkkEka....',
501 '......akkkkkka....',
502 '......akkffkka....',
503 '......aaiiiiaa....',
504 '.....TdaaaaaadT...',
505 '....TTTdaaaadTTT..',
506 '....TTTTdaadTTTT..',
507 ]
508 const fausto_planeando_B: Grid = fausto_planeando_A.map((row, y) => (y === 5 ? '......aEkkEkka....' : row))
509 const fausto_pensando_A: Grid = [
510 '.yYy..............',
511 '.YwY.KKKKKKKKKK...',
512 '..G...KKKKKKKK.z..',
513 ...fausto_planeando_B.slice(3),
514 ]
515 const fausto_pensando_B: Grid = ['.ooo..............', '.ooo.KKKKKKKKKK...', ...fausto_pensando_A.slice(2)]
516 const fausto_listo_A: Grid = fausto_planeando_A.map((row, y) =>
517 y === 8 ? '......aaiaaiaa....' : y === 9 ? '.....TdaaiiaadT...' : row,
518 )
519 const sin_capa: Grid = Array(HEIGHT).fill(' '.repeat(WIDTH))
520 // Infraestructura · nube y casco, amarillo
521 const infraestructura_desplegando_A: Grid = [
522 ' ',
523 ' ',
524 ' YyYY ',
525 ' YyYYYY ',
526 ' YYYYYYYY ',
527 ' cc ',
528 'cccc ',
529 'ccccc ',
530 'ccccc ',
531 ' Y ',
532 ' YYY ',
533 ' Y ',
534 ]
535 const infraestructura_desplegando_B: Grid = [
536 ' ',
537 ' ',
538 ' YyYY ',
539 ' YyYYYY ',
540 ' YYYYYYYY ',
541 ' cc ',
542 'cccc ',
543 'ccccc ',
544 'ccYcc ',
545 ' YYY ',
546 ' Y ',
547 ' ',
548 ]
549 const infraestructura_caido_A: Grid = [
550 ' ',
551 ' ',
552 ' YyYY ',
553 ' YyYYYY ',
554 ' YYYYYYYY ',
555 ' CC ',
556 'CCCC ',
557 'CCCCC ',
558 'CCCCC ',
559 ' RR ',
560 ' R ',
561 ' R ',
562 ]
563 const infraestructura_arriba_A: Grid = [
564 ' ',
565 ' ',
566 ' YyYY ',
567 ' YyYYYY ',
568 ' YYYYYYYY ',
569 ' cc ',
570 'cccc ',
571 'ccccc ',
572 'ccccc ',
573 ' V ',
574 ' V V ',
575 ' V ',
576 ]
577 // Merge · cremallera: el hilo de la rama (azul) y el de main (verde) bajan y se cierran diente a diente; los
578 // dientes corren hacia abajo mientras /mefisto:merge trabaja y en listo queda cerrada de punta a punta
579 const merge_cosiendo_A: Grid = [
580 'U V ',
581 'U V ',
582 ' U V ',
583 ' U V ',
584 ' UV ',
585 ' VU ',
586 ' UV ',
587 ' VU ',
588 ' UV ',
589 ' VU ',
590 ' UV ',
591 ' ',
592 ]
593 const merge_cosiendo_B: Grid = [
594 'U V ',
595 ' U V ',
596 ' U V ',
597 ' UV ',
598 ' VU ',
599 ' UV ',
600 ' VU ',
601 ' UV ',
602 ' VU ',
603 ' UV ',
604 ' VU ',
605 ' ',
606 ]
607 const merge_listo_A: Grid = [
608 'y y ',
609 ' UV ',
610 ' VU ',
611 ' UV ',
612 ' VU ',
613 'yUVy ',
614 ' VU ',
615 ' UV ',
616 ' VU ',
617 ' UV ',
618 ' VU ',
619 ' ',
620 ]
621 // Historiador · pluma y tintero: la pluma sube y baja a mojarse en la tinta (/mefisto:bitacora)
622 const historiador_escribiendo_A: Grid = [
623 ' ',
624 ' ',
625 ' B ',
626 ' BU ',
627 ' BU ',
628 ' BU ',
629 ' U ',
630 ' U ',
631 ' E ',
632 ' GGG ',
633 'DDDDD ',
634 'DDDDD ',
635 ]
636 const historiador_escribiendo_B: Grid = [
637 ' ',
638 ' ',
639 ' ',
640 ' B ',
641 ' BU ',
642 ' BU ',
643 ' BU ',
644 ' U ',
645 ' U ',
646 ' GUG ',
647 'DDDDD ',
648 'DDDDD ',
649 ]
650 const historiador_listo_A: Grid = [
651 ' ',
652 ' ',
653 ' B ',
654 ' BU ',
655 ' BU ',
656 ' BU ',
657 ' U ',
658 ' U ',
659 ' E ',
660 ' GGG ',
661 'DDDDD ',
662 'DDDDD ',
663 ]
664
665 return {
666 desarrollador: {
667 trabajando: { emotion: 'normal', layers: [desarrollador_trabajando_A, desarrollador_trabajando_B] },
668 pensando: { emotion: 'pensando', layers: [desarrollador_pensando_A, desarrollador_pensando_A] },
669 error: { emotion: 'preocupado', layers: [desarrollador_error_A, desarrollador_error_B] },
670 resuelto: { emotion: 'sonriente', layers: [desarrollador_resuelto_A, desarrollador_resuelto_A] },
671 },
672 tester: {
673 trabajando: { emotion: 'normal', layers: [tester_trabajando_A, tester_trabajando_B] },
674 pensando: { emotion: 'pensando', layers: [tester_pensando_A, tester_pensando_A] },
675 feliz: { emotion: 'feliz', layers: [tester_feliz_A, tester_feliz_B] },
676 },
677 revisor: {
678 trabajando: { emotion: 'normal', layers: [revisor_trabajando_A, revisor_trabajando_B] },
679 pensando: { emotion: 'pensando', layers: [revisor_pensando_A, revisor_pensando_A] },
680 corrigiendo: { emotion: 'concentrado', layers: [revisor_corrigiendo_A, revisor_corrigiendo_B] },
681 aprobado: { emotion: 'sonriente', layers: [revisor_aprobado_A, revisor_aprobado_A] },
682 },
683 planner: {
684 planeando: { emotion: 'normal', layers: [sin_capa, sin_capa], face: [fausto_planeando_A, fausto_planeando_B] },
685 pensando: { emotion: 'pensando', layers: [sin_capa, sin_capa], face: [fausto_pensando_A, fausto_pensando_B] },
686 listo: { emotion: 'sonriente', layers: [sin_capa, sin_capa], face: [fausto_listo_A, fausto_listo_A] },
687 },
688 infraestructura: {
689 desplegando: { emotion: 'normal', layers: [infraestructura_desplegando_A, infraestructura_desplegando_B] },
690 caido: { emotion: 'asustado', layers: [infraestructura_caido_A, infraestructura_caido_A] },
691 arriba: { emotion: 'sonriente', layers: [infraestructura_arriba_A, infraestructura_arriba_A] },
692 },
693 historiador: {
694 escribiendo: { emotion: 'normal', layers: [historiador_escribiendo_A, historiador_escribiendo_B] },
695 listo: { emotion: 'sonriente', layers: [historiador_listo_A, historiador_listo_A] },
696 },
697 merge: {
698 cosiendo: { emotion: 'concentrado', layers: [merge_cosiendo_A, merge_cosiendo_B] },
699 listo: { emotion: 'sonriente', layers: [merge_listo_A, merge_listo_A] },
700 },
701 }
702})()
703
704/** Versión de una línea por emoción, para la status line. */
705export const ONE_LINERS: Record<Emotion, string> = {
706 normal: "ψ(•‿•)",
707 feliz: "ψ(^▽^)♥",
708 sonriente: "ψ(^▽^)",
709 enojado: "ψ(ಠ益ಠ)",
710 dormido: "ψ(-.-)zz",
711 asustado: "ψ(°o°)!",
712 pensando: "ψ(•_•)💡",
713 preocupado: "ψ(°~°);",
714 concentrado: "ψ(•ᴗ<)",
715}
716
717/** Pone una capa encima de una cuadrícula. En la capa, ' ' significa "no tocar". */
718export function overlay(base: Grid, layer: Grid): Grid {
719 return base.map((row, y) => {
720 const top = layer[y] ?? ''
721 let out = ''
722 for (let x = 0; x < WIDTH; x++) {
723 const c = top[x]
724 out += c && c !== ' ' ? c : row[x] ?? '.'
725 }
726 return out
727 })
728}
729
730/** Arma el sprite de un rol en un estado y un cuadro. */
731export function sprite(role: Role, state: string, frame: Frame = 0): Grid {
732 const def = ROLES[role]?.[state]
733 if (!def) throw new Error(`Estado desconocido: ${role}.${state}`)
734 return overlay((def.face ?? EMOTIONS[def.emotion])[frame], def.layers[frame])
735}
736
737/** Sprite solo con la cara, sin objeto de rol. */
738export function face(emotion: Emotion, frame: Frame = 0): Grid {
739 return EMOTIONS[emotion][frame]
740}
741
742function colorOf(ch: string | undefined): number | null {
743 if (!ch || ch === '.' || ch === ' ') return null
744 const c = PALETTE[ch]
745 if (c === undefined) throw new Error(`Letra sin color en PALETTE: '${ch}'`)
746 return c
747}
748
749const UPPER = '▀'.codePointAt(0)!
750const LOWER = '▄'.codePointAt(0)!
751const SPACE = ' '.codePointAt(0)!
752
753/**
754 * Convierte una cuadrícula en las celdas empacadas que recibe el elemento Raster.
755 * Cada celda junta dos píxeles verticales: ▀ con el de arriba como color y el de abajo como fondo.
756 * Resultado: columns = `width` (WIDTH, 18, o el ancho ya recortado por `cropGrid`), rows = RASTER_ROWS (6).
757 */
758export function toRasterCells(grid: Grid, width: number = WIDTH): string {
759 const numbers: number[] = []
760 for (let y = 0; y < HEIGHT; y += 2) {
761 for (let x = 0; x < width; x++) {
762 const top = colorOf(grid[y]?.[x])
763 const bottom = colorOf(grid[y + 1]?.[x])
764 if (top !== null && bottom !== null) numbers.push(UPPER, top, bottom)
765 else if (top !== null) numbers.push(UPPER, top, DEFAULT_COLOR)
766 else if (bottom !== null) numbers.push(LOWER, bottom, DEFAULT_COLOR)
767 else numbers.push(SPACE, DEFAULT_COLOR, DEFAULT_COLOR)
768 }
769 }
770 const bytes = new Uint8Array(Uint32Array.from(numbers).buffer)
771 const anyBytes = bytes as Uint8Array & { toBase64?: () => string }
772 if (typeof anyBytes.toBase64 === 'function') return anyBytes.toBase64()
773 let bin = ''
774 for (const b of bytes) bin += String.fromCharCode(b)
775 return btoa(bin)
776}
777
778/** Props listas para Raster({ ...rasterProps(grid, 'mefisto') }). */
779export function rasterProps(grid: Grid, key: string) {
780 return { key, columns: WIDTH, rows: RASTER_ROWS, cells: toRasterCells(grid) }
781}
782
783/** Convierte una cuadrícula en un documento SVG (para la app de escritorio). */
784export function toSvg(grid: Grid, scale = 6): string {
785 const rects: string[] = []
786 grid.forEach((row, y) => {
787 let x = 0
788 while (x < WIDTH) {
789 const ch = row[x]
790 const c = colorOf(ch)
791 if (c === null) { x++; continue }
792 let end = x
793 while (end < WIDTH && row[end] === ch) end++
794 const hex = '#' + c.toString(16).padStart(6, '0')
795 rects.push(`<rect x="${x * scale}" y="${y * scale}" width="${(end - x) * scale}" height="${scale}" fill="${hex}"/>`)
796 x = end
797 }
798 })
799 const w = WIDTH * scale
800 const h = HEIGHT * scale
801 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" shape-rendering="crispEdges">${rects.join('')}</svg>`
802}
803
804/** Reloj de arena de la espera: dos cuadros (arena arriba / abajo), 4 columnas por 6 pixeles. */
805const HOURGLASS = [
806 ['YYYY', 'gyyg', '.yg.', 'g..g', 'g..g', 'YYYY'],
807 ['YYYY', 'g..g', '.gg.', 'g..g', 'gyyg', 'YYYY'],
808] as const
809
810/**
811 * Mefisto en espera, sobre la cara 'normal': boca plana corrida y un reloj de arena a la izquierda.
812 * Con `tick` (Claude trabaja) los ojos miran de lado a lado y la arena se voltea en cada tick;
813 * con `tick` null (reposo) mira de frente, quieto, con la arena arriba.
814 */
815export function waitingFace(base: Grid, tick: number | null): Grid {
816 const eyes =
817 tick === null ? ['.....rrEErrEErr.tt', '.....rrEErrEErr..t']
818 : tick % 2 === 0 ? ['.....rEErrEErrr.tt', '.....rEErrEErrr..t']
819 : ['.....rrrEErrEEr.tt', '.....rrrEErrEEr..t']
820 const glass = HOURGLASS[tick !== null && tick % 2 === 1 ? 1 : 0]
821 return base.map((row, y) => {
822 let out = row
823 if (y === 6 || y === 7) out = eyes[y - 6] ?? out
824 if (y === 9) out = '......rrrrMMMr..t.'
825 const g = y >= 6 ? glass[y - 6] : undefined
826 if (g) out = [...out].map((c, x) => (x < g.length && g[x] !== '.' ? g[x] : c)).join('')
827 return out
828 })
829}
830hooks/logic.ts 329 lines1import type { BoardItem, BoardList } from './types'
2
3export const NEXT_ORDER_FILE = 'scripts/next-order.sh'
4
5/** Ruta de next-order.sh bajo la raiz del plugin (`root` sin barra final). */
6export function nextOrderPath(root: string): string {
7 return `${root.replace(/\/+$/, '')}/${NEXT_ORDER_FILE}`
8}
9
10const TYPE_LETTERS: Record<string, { letter: string; color: string }> = {
11 feature: { letter: 'F', color: 'success' },
12 refactor: { letter: 'R', color: 'warning' },
13 projection: { letter: 'P', color: 'cyan' },
14 tooling: { letter: 'T', color: 'magenta' },
15 infra: { letter: 'I', color: 'blue' },
16}
17
18/** Letra y color del tipo (`tipo` de next-order --json); `?` gris si falta o es desconocido. */
19export function typeBadge(tipo: string | null | undefined): { letter: string; color: string } {
20 return (tipo ? TYPE_LETTERS[tipo] : undefined) ?? { letter: '?', color: 'gray' }
21}
22/** Filas fijas de la lista: la banda no cambia de alto con la cantidad de issues. */
23export const LIST_ROWS = 5
24
25type NextOrderJson = {
26 items?: { number: number; title: string; tipo?: string | null; after?: number[]; hasDepsSection?: boolean }[]
27 blocked?: unknown[]
28 cycles?: unknown[]
29 launch?: string | null
30}
31
32/** Exit 0 (hay orden) y 1 (vacio) traen JSON valido; 2 es un fallo de gh o de argumentos. */
33export function parseNextOrder(exitCode: number, stdout: string, stderr: string): BoardList {
34 if (exitCode !== 0 && exitCode !== 1) {
35 return { items: [], blockedCount: 0, cycleCount: 0, launch: null, error: firstLine(stderr) || `exit ${exitCode}` }
36 }
37 let json: NextOrderJson
38 try {
39 json = JSON.parse(stdout)
40 } catch {
41 return { items: [], blockedCount: 0, cycleCount: 0, launch: null, error: 'salida de next-order no es JSON' }
42 }
43 const items: BoardItem[] = (json.items ?? []).map(i => ({
44 number: i.number,
45 title: i.title,
46 tipo: i.tipo ?? null,
47 after: i.after ?? [],
48 hasDepsSection: i.hasDepsSection !== false,
49 }))
50 return {
51 items,
52 blockedCount: (json.blocked ?? []).length,
53 cycleCount: (json.cycles ?? []).length,
54 launch: json.launch ?? null,
55 error: null,
56 }
57}
58
59type OpenIssue = { number: number; title?: string; updatedAt?: string; labels?: { name: string }[] }
60
61export function parseOpenIssues(stdout: string): OpenIssue[] | null {
62 try {
63 const list = JSON.parse(stdout)
64 return Array.isArray(list) ? list : null
65 } catch {
66 return null
67 }
68}
69
70/** Cambia cuando entra, sale o se edita un issue abierto (labels o body actualizan updatedAt). */
71export function signatureOf(issues: OpenIssue[]): string {
72 return issues
73 .map(i => `${i.number}:${i.updatedAt ?? ''}:${(i.labels ?? []).map(l => l.name).sort().join(',')}`)
74 .sort()
75 .join('|')
76}
77
78export type Arrival = { number: number; title: string; kind: 'borrador' | 'listo' }
79
80/** Issues abiertos nuevos con estado borrador o listo. Sin conocidos previos (primer refresco) no hay avisos. */
81export function arrivals(issues: OpenIssue[], known: number[]): Arrival[] {
82 if (known.length === 0) return []
83 const seen = new Set(known)
84 const out: Arrival[] = []
85 for (const i of issues) {
86 if (seen.has(i.number)) continue
87 const names = (i.labels ?? []).map(l => l.name)
88 const kind = names.includes('estado:borrador') ? 'borrador' : names.includes('estado:listo') ? 'listo' : null
89 if (kind) out.push({ number: i.number, title: i.title ?? '', kind })
90 }
91 return out
92}
93
94/** De que depende el issue (`tras #A #B`), o vacio si no depende de nada abierto. */
95export function reasonOf(item: BoardItem): string {
96 return item.after.length > 0 ? `tras ${item.after.map(n => `#${n}`).join(' ')}` : ''
97}
98
99/** Ancho comun de la columna de numeros (#801 y #1981 alineados). */
100export function numberWidth(items: { number: number }[]): number {
101 return Math.max(4, ...items.map(i => String(i.number).length + 1))
102}
103
104export function padEnd(text: string, width: number): string {
105 return text.length >= width ? text : text + ' '.repeat(width - text.length)
106}
107
108export function clip(text: string, max: number): string {
109 const one = text.replace(/\s+/g, ' ').trim()
110 return one.length > max ? `${one.slice(0, Math.max(1, max - 1))}…` : one
111}
112
113export function clockOf(ms: number): string {
114 if (ms === 0) return ''
115 const d = new Date(ms)
116 const p = (n: number) => String(n).padStart(2, '0')
117 return `${p(d.getHours())}:${p(d.getMinutes())}`
118}
119
120function firstLine(text: string): string {
121 return text.split('\n').find(l => l.trim() !== '')?.trim() ?? ''
122}
123
124const REFINE = /\brefin\w*\s+(?:el\s+)?(?:borrador\s+)?#(\d+)/i
125
126/** `refina #801`, `Refina el borrador #801`, `refinemos #801`: el issue a refinar, o null. */
127export function refineTargetOf(prompt: string): number | null {
128 const m = REFINE.exec(prompt)
129 return m ? Number(m[1]) : null
130}
131
132/** El tema de una exploracion: la primera linea con contenido del mensaje, recortada. */
133export function topicOf(prompt: string): string {
134 const line = prompt.split('\n').map(l => l.trim()).find(l => l !== '') ?? ''
135 return clip(line.replace(/^quiero explorar:\s*/i, ''), 70)
136}
137
138// Un comando cuenta solo donde se ejecuta: al inicio (tras ; && || | ( then do o un salto de linea), con
139// asignaciones de entorno delante, y fuera de heredocs. Un texto que lo nombra (git show, grep, echo) no cuenta.
140const AT_COMMAND = String.raw`(?:^|[;&|(\n]|\bthen\b|\bdo\b)\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*`
141
142function withoutHeredocs(command: string): string {
143 return command.replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2[ \t]*(?=\n|$)/g, '<<heredoc')
144}
145
146const runs = (command: string, pattern: string) => new RegExp(`${AT_COMMAND}${pattern}`).exec(withoutHeredocs(command))
147
148/** Un cambio de issues hecho por el planner (crear, editar, cerrar, reabrir): sus listas pueden haber cambiado. */
149export function isIssueChange(command: string): boolean {
150 return runs(command, String.raw`gh\s+issue\s+(create|edit|close|reopen)\b`) !== null
151}
152
153export function isIssueCreate(command: string): boolean {
154 return runs(command, String.raw`gh\s+issue\s+create\b`) !== null
155}
156
157/** `gh issue edit 801 ... --add-label estado:listo`: el issue que pasa a listo, o null. */
158export function issueMarkedListo(command: string): number | null {
159 const m = runs(command, String.raw`gh\s+issue\s+edit\s+#?(\d+)\b[^\n;&|]*--add-label[=\s]+["']?[^"'\s]*estado:listo`)
160 return m ? Number(m[1]) : null
161}
162
163/** `gh issue close 801 ...`: el issue que se cierra, o null. */
164export function issueClosed(command: string): number | null {
165 const m = runs(command, String.raw`gh\s+issue\s+close\s+#?(\d+)\b`)
166 return m ? Number(m[1]) : null
167}
168
169/** Cuanto tiempo se oculta un issue en transicion si ningun refresco confirma el cambio. */
170export const PENDING_TTL_MS = 60_000
171
172/** Transiciones pendientes: numero de issue -> instante (ms) en que se registro. */
173export type Pending = ReadonlyMap<number, number>
174
175export function addPending(pending: Pending, issue: number, nowMs: number): Pending {
176 return new Map(pending).set(issue, nowMs)
177}
178
179/** Quita un issue de la lista de borradores sin reordenar ni tocar el resto. */
180export function dropIssue(list: BoardList | null, issue: number): BoardList | null {
181 if (!list || !list.items.some(i => i.number === issue)) return list
182 return { ...list, items: list.items.filter(i => i.number !== issue) }
183}
184
185/**
186 * Aplica las transiciones pendientes a una lista recien refrescada: filtra los pendientes vigentes y devuelve
187 * las que siguen pendientes (salen si el refresco ya no los trae como borrador, o al pasar PENDING_TTL_MS).
188 * Una lista con error de next-order no confirma nada: sus pendientes solo vencen por plazo.
189 */
190export function applyPending(list: BoardList, pending: Pending, nowMs: number): { list: BoardList; pending: Pending } {
191 const present = new Set(list.items.map(i => i.number))
192 const kept = new Map<number, number>()
193 for (const [n, since] of pending) {
194 if (nowMs - since < PENDING_TTL_MS && (list.error !== null || present.has(n))) kept.set(n, since)
195 }
196 const items = kept.size > 0 ? list.items.filter(i => !kept.has(i.number)) : list.items
197 return { list: items === list.items ? list : { ...list, items }, pending: kept }
198}
199
200/** El cierre del planner: ejecuta field-note.sh, con ruta sin comillas o entre comillas (puede tener espacios). */
201export function isPlannerClosing(command: string): boolean {
202 return runs(command, String.raw`(?:\S*/|"(?:[^"]*/)?|'(?:[^']*/)?)?field-note\.sh\b`) !== null
203}
204
205/** Numero del issue que `gh issue create` imprime como URL. */
206export function createdIssueOf(output: string): number | null {
207 const m = /\/issues\/(\d+)/.exec(output)
208 return m ? Number(m[1]) : null
209}
210
211export function createdText(created: number[]): string {
212 return created.length > 0 ? `creó ${created.map(n => `#${n}`).join(' ')}` : ''
213}
214
215/** Issues por pagina, igual en las dos listas. */
216export function pageSizeOf(_tab: 'borrador' | 'listo'): number {
217 return LIST_ROWS
218}
219
220/** Pagina valida (0-based) para una lista de `total` items; vuelve a 0 si la lista se achico. */
221export function pageOf(page: number, total: number, size: number): { page: number; pages: number } {
222 const pages = Math.max(1, Math.ceil(total / size))
223 return { page: page >= 0 && page < pages ? page : 0, pages }
224}
225
226/** Ruta del transcript de una sesion: ~/.claude/projects/<cwd con lo no alfanumerico como '-'>/<id>.jsonl. */
227export function transcriptPathOf(configDir: string, cwd: string, sessionId: string): string {
228 return `${configDir}/projects/${cwd.replace(/[^A-Za-z0-9]/g, '-')}/${sessionId}.jsonl`
229}
230
231/**
232 * `claude --agent mefisto:planner` deja en el transcript de la sesion filas
233 * `{"type":"agent-setting","agentSetting":"mefisto:planner"}`; manda la ultima. Un planner lanzado como
234 * subagente escribe en el transcript del subagente, nunca en el de la sesion que lo lanzo.
235 */
236export function agentSettingOf(transcript: string): string | null {
237 let found: string | null = null
238 for (const line of transcript.split('\n')) {
239 if (!line.includes('"agent-setting"')) continue
240 try {
241 const row = JSON.parse(line)
242 if (row.type === 'agent-setting' && typeof row.agentSetting === 'string') found = row.agentSetting
243 } catch {
244 continue
245 }
246 }
247 return found
248}
249
250/** El `--agent` de una linea de comando de Claude Code (`--agent x` o `--agent=x`), o null. */
251export function agentFlagOf(cmdline: string): string | null {
252 const m = /(?:^|\s)--agent(?:=|\s+)(\S+)/.exec(cmdline)
253 return m ? (m[1] ?? null) : null
254}
255
256export type MascotState = 'planeando' | 'pensando' | 'listo'
257
258/** Siempre la mascota del planner: trabajando con herramientas planea, sin ellas piensa y al cerrar un foco queda lista. */
259export function mascotPose(isWorking: boolean, stepsInTurn: number, hasFlash: boolean): MascotState {
260 if (isWorking) return stepsInTurn > 0 ? 'planeando' : 'pensando'
261 if (hasFlash) return 'listo'
262 return 'planeando'
263}
264
265type Grid = readonly string[]
266
267/** Columnas con algun pixel visible en cualquiera de los cuadros: recorta el margen sin que la mascota salte. */
268export function usedColumns(grids: readonly Grid[]): { from: number; to: number } {
269 let from = Infinity
270 let to = -1
271 for (const g of grids) {
272 for (const row of g) {
273 for (let x = 0; x < row.length; x++) {
274 const c = row[x]
275 if (c !== '.' && c !== ' ') {
276 from = Math.min(from, x)
277 to = Math.max(to, x)
278 }
279 }
280 }
281 }
282 return to < 0 ? { from: 0, to: 0 } : { from, to }
283}
284
285export function cropGrid(grid: Grid, cols: { from: number; to: number }): Grid {
286 return grid.map(row => row.slice(cols.from, cols.to + 1).padEnd(cols.to - cols.from + 1, '.'))
287}
288
289/**
290 * El manifiesto `.claude-plugin/plugin.json` en la raiz del repo es el del propio plugin Mefisto: ahi el tablero
291 * es el mod interno (`.claude/mods/mefisto-planner-board`) y el publicado no aplica (su next-order.sh es solo del
292 * consumidor).
293 */
294export function isMefistoManifest(raw: string): boolean {
295 try {
296 return (JSON.parse(raw) as { name?: unknown }).name === 'mefisto'
297 } catch {
298 return false
299 }
300}
301
302// Una exploracion que ya creo borradores muestra la lista de borradores como cuerpo de la banda.
303export function showsDraftList(focus: { kind: 'explorar' | 'refinar'; created: number[] } | null | undefined): boolean {
304 return focus?.kind === 'explorar' && focus.created.length > 0
305}
306
307const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
308
309function semverOf(raw: string | null | undefined): string | null {
310 if (typeof raw !== 'string') return null
311 try {
312 const version = (JSON.parse(raw) as { version?: unknown }).version
313 return typeof version === 'string' && SEMVER.test(version) ? version : null
314 } catch {
315 return null
316 }
317}
318
319/** `v<version>` del release cargado: la de `mefisto-manifest.json` si es SemVer valida, si no la de `plugin.json`, si no `null`. */
320export function versionLabel(manifestRaw: string | null | undefined, pluginRaw: string | null | undefined): string | null {
321 const version = semverOf(manifestRaw) ?? semverOf(pluginRaw)
322 return version === null ? null : `v${version}`
323}
324
325/** Rearme tras /clear, /resume o /branch: el modulo quiere el mod activo (elegible y no apagado) pero el atom quedo en blanco. */
326export function shouldRearm(s: { isEligible: boolean; isWanted: boolean; isActive: boolean }): boolean {
327 return s.isEligible && s.isWanted && !s.isActive
328}
329hooks/fausto-blood-pact/logic.ts 1651 lines1import type { Role } from '../sprites'
2import { padEnd, reasonOf, typeBadge } from '../logic'
3import type { BitacoraNote, BitacoraPr, BoardItem, BoardList, InPrItem, Historian, PactMerge, PactMergePr, PipelineKind, PaneLine, PipelineResult, PipelineRun, RunStep } from '../types'
4
5export const NEXT_ORDER_FILE = 'scripts/next-order.sh'
6export const PLANNER_AGENT = 'mefisto:planner'
7export const PAGE_ROWS = 5
8
9export function nextOrderPath(root: string): string {
10 return `${root.replace(/\/+$/, '')}/${NEXT_ORDER_FILE}`
11}
12
13type NextOrderJson = {
14 items?: { number: number; title: string; tipo?: string | null; after?: number[]; hasDepsSection?: boolean }[]
15 blocked?: unknown[]
16 inPr?: { number: number; title: string; tipo?: string | null; pr: number }[]
17 cycles?: unknown[]
18 launch?: string | null
19 infra?: number[]
20 parallel?: { issues?: number[]; launch?: string | null } | null
21}
22
23function firstLine(text: string): string {
24 return text.split('\n').find(l => l.trim() !== '')?.trim() ?? ''
25}
26
27/** Exit 0 (hay orden) y 1 (vacio) traen JSON valido; 2 u otro es un fallo. */
28export function parseNextOrder(exitCode: number, stdout: string, stderr: string): BoardList {
29 const failed = (error: string): BoardList => ({ items: [], blockedCount: 0, cycleCount: 0, launch: null, infra: [], parallel: null, error })
30 if (exitCode !== 0 && exitCode !== 1) return failed(firstLine(stderr) || `exit ${exitCode}`)
31 let json: NextOrderJson
32 try {
33 json = JSON.parse(stdout)
34 } catch {
35 return failed('salida de next-order no es JSON')
36 }
37 const items: BoardItem[] = (json.items ?? []).map(i => ({
38 number: i.number,
39 title: i.title,
40 tipo: i.tipo ?? null,
41 after: i.after ?? [],
42 hasDepsSection: i.hasDepsSection !== false,
43 }))
44 const inPr: InPrItem[] = (Array.isArray(json.inPr) ? json.inPr : []).map(i => ({
45 number: i.number,
46 title: i.title,
47 tipo: i.tipo ?? null,
48 pr: i.pr,
49 }))
50 return {
51 items,
52 inPr,
53 blockedCount: (json.blocked ?? []).length,
54 cycleCount: (json.cycles ?? []).length,
55 launch: json.launch ?? null,
56 infra: json.infra ?? [],
57 parallel: json.parallel ? { issues: json.parallel.issues ?? [], launch: json.parallel.launch ?? null } : null,
58 error: null,
59 }
60}
61
62export function clip(text: string, max: number): string {
63 const one = text.replace(/\s+/g, ' ').trim()
64 return one.length > max ? `${one.slice(0, Math.max(1, max - 1))}…` : one
65}
66
67/** Pagina vigente (acotada) y total de paginas; siempre al menos una. */
68export function pageOf(page: number, total: number, size: number): { page: number; pages: number } {
69 const pages = Math.max(1, Math.ceil(total / size))
70 return { page: Math.min(Math.max(0, page), pages - 1), pages }
71}
72
73/** Partes de una fila como en fausto-board: letra de tipo con color, etiqueta `#N titulo` (sin tecla ni posicion) y `tras #M`. */
74export function rowParts(
75 item: BoardItem,
76 numWidth: number,
77 titleMax: number,
78): { letter: string; color: string; label: string; after: string } {
79 const badge = typeBadge(item.tipo)
80 return {
81 letter: badge.letter,
82 color: badge.color,
83 label: rowText(item, numWidth, titleMax),
84 after: reasonOf(item),
85 }
86}
87
88/** Fila de un issue en PR: letra de tipo con color y `#N titulo… · PR #X` (sin tecla, toda atenuada en la consola). */
89export function inPrRowParts(item: InPrItem, numWidth: number, titleMax: number): { letter: string; color: string; label: string } {
90 const badge = typeBadge(item.tipo)
91 const suffix = ` · PR #${item.pr}`
92 return {
93 letter: badge.letter,
94 color: badge.color,
95 label: `${padEnd(`#${item.number}`, numWidth)} ${clip(item.title, Math.max(1, titleMax - suffix.length))}${suffix}`,
96 }
97}
98
99export type BoardRow = { kind: 'launch'; item: BoardItem } | { kind: 'inpr'; item: InPrItem }
100
101/** Filas de la lista: primero los lanzables y despues los issues en PR, en el orden en que llegan. */
102export function boardRowsOf(list: BoardList | null): BoardRow[] {
103 if (!list) return []
104 return [
105 ...list.items.map((item): BoardRow => ({ kind: 'launch', item })),
106 ...(list.inPr ?? []).map((item): BoardRow => ({ kind: 'inpr', item })),
107 ]
108}
109
110/** Cabecera de la lista: `listos N` (solo lanzables) y, con issues en PR, `· en PR M`. */
111export function listosTextOf(list: BoardList): string {
112 const m = list.inPr?.length ?? 0
113 return `listos ${list.items.length}${m > 0 ? ` · en PR ${m}` : ''}`
114}
115
116/** Etiqueta del boton: `#issue titulo`; la tecla la dibuja el boton y el tipo va en su letra. */
117export function rowText(item: BoardItem, numWidth: number, titleMax: number): string {
118 return `${padEnd(`#${item.number}`, numWidth)} ${clip(item.title, titleMax)}`
119}
120
121/** Pie sin las teclas `1`/`4` (la consola las pinta como botones): solo infra y ciclos, que condicionan el lanzamiento. */
122export function footerRestOf(list: BoardList, afterButtons: boolean): string {
123 const rest = [
124 list.infra.length > 0 ? `infra: ${list.infra.map(n => `#${n}`).join(' ')}` : '',
125 list.cycleCount > 0 ? `${list.cycleCount} en ciclo` : '',
126 ]
127 .filter(Boolean)
128 .join(' · ')
129 return rest && afterButtons ? ` · ${rest}` : rest
130}
131
132/** Cantidad de issues de una linea de lanzamiento (`/mefisto:sequential 7 8` -> 2). */
133export function launchCountOf(line: string | null): number {
134 return (line ?? '').split(/\s+/).filter(t => /^\d+$/.test(t)).length
135}
136
137export function isMefistoManifest(raw: string): boolean {
138 try {
139 return (JSON.parse(raw) as { name?: unknown }).name === 'mefisto'
140 } catch {
141 return false
142 }
143}
144
145export function transcriptPathOf(configDir: string, cwd: string, sessionId: string): string {
146 return `${configDir}/projects/${cwd.replace(/[^A-Za-z0-9]/g, '-')}/${sessionId}.jsonl`
147}
148
149/** La ultima fila `agent-setting` del transcript de la sesion, o null. */
150export function agentSettingOf(transcript: string): string | null {
151 let found: string | null = null
152 for (const line of transcript.split('\n')) {
153 if (!line.includes('"agent-setting"')) continue
154 try {
155 const row = JSON.parse(line)
156 if (row.type === 'agent-setting' && typeof row.agentSetting === 'string') found = row.agentSetting
157 } catch {
158 continue
159 }
160 }
161 return found
162}
163
164/** El `--agent` de una linea de comando de Claude Code (`--agent x` o `--agent=x`), o null. */
165export function agentFlagOf(cmdline: string): string | null {
166 const m = /(?:^|\s)--agent(?:=|\s+)(\S+)/.exec(cmdline)
167 return m ? (m[1] ?? null) : null
168}
169
170// ---- Incremento 2: seguimiento de corridas (MEF-ADR-0055 decision 1: lector puro) ----
171
172export const RUNS_POLL_MS = 5_000
173export const STATUS_FILE_RE = /^pipeline-status-(tdd|tooling|infra)-(\d+)(?:-(.+))?\.json$/
174export const HISTORY_FILE = 'pipeline-history.jsonl'
175export const DISMISSED_STORE_KEY = 'fausto-blood-pact.dismissed'
176const PRUNE_GRACE_MS = 24 * 60 * 60 * 1000
177
178/** Directorio de estado del checkout principal: el padre de `--git-common-dir`, nunca el worktree. */
179export function stateDirOf(gitCommonDir: string, cwd: string): string {
180 const abs = gitCommonDir.startsWith('/') ? gitCommonDir : `${cwd.replace(/\/+$/, '')}/${gitCommonDir}`
181 const common = abs.replace(/\/+$/, '').replace(/\/\.git$/, '')
182 return `${common}/.mefisto/pipeline`
183}
184
185/** Raiz del repo (checkout principal) a partir del directorio de estado. */
186export function repoRootOf(stateDir: string): string {
187 return stateDir.replace(/\/\.mefisto\/pipeline$/, '')
188}
189
190type StatusJson = {
191 issue?: string | number | null
192 pipeline?: string
193 variant?: string | null
194 started?: string
195 updated?: string
196 stage?: string
197 state?: string
198 hold?: { next_probe?: string | null } | null
199 agents?: Record<string, { result?: string | null; duration?: number | null } | null> | null
200 log?: string | null
201 title?: string | null
202 last_error?: string | null
203}
204
205/** Parseo de un status; null si no es de un pipeline conocido o no es JSON valido. */
206export function parseStatus(fileName: string, raw: string): PipelineRun | null {
207 const m = STATUS_FILE_RE.exec(fileName)
208 if (!m) return null
209 let json: StatusJson
210 try {
211 json = JSON.parse(raw) as StatusJson
212 } catch {
213 return null
214 }
215 const issue = Number(json.issue ?? m[2])
216 if (!Number.isFinite(issue)) return null
217 return {
218 issue,
219 pipeline: m[1] as PipelineKind,
220 variant: json.variant ?? m[3] ?? null,
221 started: json.started ?? '',
222 updated: json.updated ?? '',
223 stage: json.stage ?? '',
224 state: json.state ?? '',
225 nextProbe: json.hold?.next_probe ?? null,
226 agents: stepsOfAgents(json.agents),
227 title: typeof json.title === 'string' ? json.title : '',
228 log: typeof json.log === 'string' && json.log !== '' ? json.log : null,
229 ...(typeof json.last_error === 'string' && json.last_error !== '' ? { lastError: json.last_error } : {}),
230 }
231}
232
233/** Pasos de `status.agents` en su orden; un `result` desconocido o vacio es `pending`. */
234export function stepsOfAgents(agents: StatusJson['agents']): RunStep[] {
235 if (!agents || typeof agents !== 'object') return []
236 return Object.entries(agents).map(([name, v]) => {
237 const r = v?.result
238 const result: RunStep['result'] = r === 'passed' || r === 'running' || r === 'failed' ? r : 'pending'
239 const d = v?.duration
240 return typeof d === 'number' && d > 0 ? { name, result, duration: d } : { name, result }
241 })
242}
243
244export const isActive = (r: PipelineRun) => r.state === 'running' || r.state === 'hold'
245export const isFailure = (r: PipelineRun) => r.state === 'failed' || r.state === 'blocked' || r.state === 'gaps'
246
247/** Agente en curso: `<n>-<agente>` -> agente; `setup`/`scaffold` y cualquier otro stage, tal cual. */
248export function agentOf(stage: string): string {
249 const m = /^\d+-(.+)$/.exec(stage)
250 return m ? (m[1] as string) : stage
251}
252
253/** Hora local HH:MM de un timestamp ISO (`next_probe` viaja en UTC con `Z`); el texto original si no se puede leer. */
254export function clockOf(iso: string): string {
255 const ms = Date.parse(iso)
256 if (Number.isNaN(ms)) return iso
257 const d = new Date(ms)
258 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
259}
260
261/** Minutos enteros desde `started` (`YYYYMMDD-HHMMSS` de los pipelines o ISO, hora local) hasta `nowMs`; null si no parsea. */
262export function minutesSince(started: string, nowMs: number): number | null {
263 const ms = Date.parse(/^\d{8}-\d{6}$/.test(started)
264 ? `${started.slice(0, 4)}-${started.slice(4, 6)}-${started.slice(6, 8)}T${started.slice(9, 11)}:${started.slice(11, 13)}:${started.slice(13, 15)}`
265 : started)
266 return Number.isNaN(ms) ? null : Math.max(0, Math.floor((nowMs - ms) / 60_000))
267}
268
269/** `#N pipeline agente Mm`; en `hold`, `rate limit · sonda HH:MM` en lugar del agente. */
270export function runLine(run: PipelineRun, nowMs: number): string {
271 const what = run.state === 'hold' ? `rate limit · sonda ${run.nextProbe ? clockOf(run.nextProbe) : '?'}` : agentOf(run.stage)
272 const mins = minutesSince(run.started, nowMs)
273 return `#${run.issue} ${run.pipeline}${run.variant ? `/${run.variant}` : ''} ${what}${mins === null ? '' : ` ${mins}m`}`
274}
275
276export function runKey(repo: string, run: PipelineRun): string {
277 return [repo, run.pipeline, run.issue, run.variant ?? '', run.started].join('|')
278}
279
280/** Clave de descarte (repo + pipeline + issue + variante + started). */
281export const dismissKey = runKey
282
283export type HistoryEntry = { issue: string; pipeline: string; variant: string | null; started: string; pr: string | null; title?: string }
284
285export function parseHistory(raw: string): HistoryEntry[] {
286 const out: HistoryEntry[] = []
287 for (const line of raw.split('\n')) {
288 if (line.trim() === '') continue
289 try {
290 const j = JSON.parse(line) as Record<string, unknown>
291 out.push({
292 issue: String(j.issue ?? ''),
293 pipeline: String(j.pipeline ?? ''),
294 variant: typeof j.variant === 'string' ? j.variant : null,
295 started: String(j.started ?? ''),
296 pr: typeof j.pr === 'string' || typeof j.pr === 'number' ? String(j.pr) : null,
297 title: typeof j.title === 'string' ? j.title : '',
298 })
299 } catch {
300 continue
301 }
302 }
303 return out
304}
305
306/** Numero de PR de la ultima entrada del historial para ese issue, pipeline y `started`; null si no hay. */
307export function prOf(entries: HistoryEntry[], run: PipelineRun): string | null {
308 for (let i = entries.length - 1; i >= 0; i -= 1) {
309 const e = entries[i] as HistoryEntry
310 if (e.issue === String(run.issue) && e.pipeline === run.pipeline && e.started === run.started) {
311 const m = e.pr ? /(\d+)\s*$/.exec(e.pr) : null
312 return m ? (m[1] as string) : null
313 }
314 }
315 return null
316}
317
318export type RunsView = { runs: PipelineRun[]; results: PipelineResult[]; seen: Record<string, PipelineRun> }
319
320/**
321 * Une el status actual con lo que la sesion vio activo: un status de fallo es `✗ <stage>`;
322 * una corrida vista activa cuyo status desaparecio es `✓ PR #X` (el exito se reconoce por la desaparicion).
323 */
324export function reconcile(
325 repo: string,
326 statuses: PipelineRun[],
327 seen: Record<string, PipelineRun>,
328 history: HistoryEntry[],
329 dismissed: ReadonlySet<string>,
330 carried: PipelineResult[] = [],
331): RunsView {
332 const present = new Set(statuses.map(r => runKey(repo, r)))
333 const results: PipelineResult[] = carried.filter(r => !present.has(r.key))
334 const nextSeen: Record<string, PipelineRun> = {}
335 for (const [key, run] of Object.entries(seen)) {
336 if (present.has(key)) continue
337 const pr = prOf(history, run)
338 results.push({ key, issue: run.issue, pipeline: run.pipeline, ok: true, text: pr ? `✓ PR #${pr}` : '✓ completado' })
339 }
340 const runs: PipelineRun[] = []
341 for (const run of statuses) {
342 const key = runKey(repo, run)
343 if (isActive(run)) {
344 runs.push(run)
345 nextSeen[key] = run
346 } else if (isFailure(run)) {
347 results.push({ key, issue: run.issue, pipeline: run.pipeline, ok: false, text: `✗ ${run.stage}` })
348 }
349 }
350 runs.sort((a, b) => a.started.localeCompare(b.started) || a.issue - b.issue)
351 return { runs, results: results.filter(r => !dismissed.has(r.key)), seen: nextSeen }
352}
353
354/** Linea de un resultado: `#N pipeline ✗ stage` o `#N pipeline ✓ PR #X`. */
355export function resultLine(r: PipelineResult): string {
356 return `#${r.issue} ${r.pipeline} ${r.text}`
357}
358
359export type BandView = 'runs' | 'ready-with-results' | 'ready'
360
361/** Las corridas toman la banda solo con al menos una activa; sin activas se ven los listos (y los resultados al pie). */
362export function bandViewOf(runs: readonly PipelineRun[], results: readonly PipelineResult[]): BandView {
363 if (runs.some(isActive)) return 'runs'
364 return results.length > 0 ? 'ready-with-results' : 'ready'
365}
366
367/** Texto de un resultado en el pie: `✓#N PR #X` o `✗#M <stage>`. */
368export function resultFooterItem(r: PipelineResult): string {
369 const m = /^([✓✗])\s*(.*)$/u.exec(r.text)
370 return m ? `${m[1]}#${r.issue}${m[2] ? ` ${m[2]}` : ''}` : `#${r.issue} ${r.text}`
371}
372
373/** `resultados: ✓#N PR #X · ✗#M stage` recortado a `max` columnas; lo que no cabe se resume en `+N`. */
374export function resultsFooterText(results: readonly PipelineResult[], max: number): string {
375 const head = 'resultados: '
376 const items = results.map(resultFooterItem)
377 for (let shown = items.length; shown >= 1; shown -= 1) {
378 const hidden = items.length - shown
379 const text = `${head}${items.slice(0, shown).join(' · ')}${hidden > 0 ? ` +${hidden}` : ''}`
380 if (text.length <= max) return text
381 }
382 return clip(`${head}${items[0] ?? ''}${items.length > 1 ? ` +${items.length - 1}` : ''}`, max)
383}
384
385/** Descarta de `dismissed` las claves del repo sin status vivo y con mas de un dia (gracia para otros panes). */
386export function pruneDismissed(dismissed: string[], repo: string, liveKeys: ReadonlySet<string>, nowMs: number): string[] {
387 return dismissed.filter(key => {
388 if (!key.startsWith(`${repo}|`) || liveKeys.has(key)) return true
389 const mins = minutesSince(key.split('|')[4] ?? '', nowMs)
390 return mins === null || mins * 60_000 < PRUNE_GRACE_MS
391 })
392}
393
394// ---- Incremento 3: lanzar trabajo (el comando se escribe en el prompt, nunca se envia) ----
395
396export const SEQUENTIAL_COMMAND = '/mefisto:sequential'
397export const PARALLEL_COMMAND = '/mefisto:parallel'
398export const ROW_KEYS = ['5', '6', '7', '8', '9'] as const
399export const CANCEL = 'Cancelar'
400export const INFRA_FIRST = 'Infra primero'
401export const WITHOUT_INFRA = 'Seguir sin infra'
402export const WITH_MERGE = 'Con merge'
403export const ONLY_PR = 'Solo PR'
404
405export type LaunchKind = 'sequential' | 'parallel'
406export type LaunchOption = { label: string; text: string | null }
407export type LaunchPlan =
408 | { kind: 'fill'; text: string }
409 | { kind: 'ask'; question: string; options: LaunchOption[] }
410 | { kind: 'none'; message: string }
411
412/** Flags de next-order que fijan las lineas de lanzamiento que la consola escribe. */
413export const NEXT_ORDER_ARGS = ['--json', '--launch-command', SEQUENTIAL_COMMAND, '--parallel-command', PARALLEL_COMMAND]
414
415/** La linea de la tecla (`1` sequential, `4` parallel) tal como la entrego next-order; null si no hay. */
416export function launchLineOf(list: BoardList, kind: LaunchKind): string | null {
417 return kind === 'sequential' ? list.launch : (list.parallel?.launch ?? null)
418}
419
420/** `1`/`4`: escribe la linea; con infra lanzable ofrece desarrollarla antes (sin exigirlo). */
421export function planLaunch(list: BoardList, kind: LaunchKind): LaunchPlan {
422 const line = launchLineOf(list, kind)
423 if (!line) return { kind: 'none', message: `No hay linea de ${kind} para lanzar.` }
424 const first = list.infra[0]
425 if (first === undefined) return { kind: 'fill', text: line }
426 return {
427 kind: 'ask',
428 question: `Hay ${list.infra.length} issue(s) de infra lanzables (${list.infra.map(n => `#${n}`).join(' ')}). ¿Desarrollarlos antes?`,
429 options: [
430 { label: INFRA_FIRST, text: `/mefisto:infra ${first}` },
431 { label: WITHOUT_INFRA, text: line },
432 { label: CANCEL, text: null },
433 ],
434 }
435}
436
437/** `5`-`9` y `lanzar <n>`: opciones segun el `tipo` del issue; sin tipo lanzable no hay dialogo. */
438export function planIssue(item: BoardItem): LaunchPlan {
439 const n = item.number
440 const options = (pr: LaunchOption[]): LaunchPlan => ({
441 kind: 'ask',
442 question: `¿Cómo desarrollar #${n}?`,
443 options: [...pr, { label: CANCEL, text: null }],
444 })
445 switch (item.tipo) {
446 case 'feature':
447 case 'refactor':
448 case 'projection':
449 return options([
450 { label: WITH_MERGE, text: `${SEQUENTIAL_COMMAND} ${n}` },
451 { label: ONLY_PR, text: `/mefisto:implement ${n}` },
452 ])
453 case 'tooling':
454 return options([
455 { label: WITH_MERGE, text: `${SEQUENTIAL_COMMAND} ${n}` },
456 { label: ONLY_PR, text: `/mefisto:tooling ${n}` },
457 ])
458 case 'infra':
459 return options([{ label: ONLY_PR, text: `/mefisto:infra ${n}` }])
460 default:
461 return { kind: 'none', message: `#${n} no tiene un tipo lanzable.` }
462 }
463}
464
465/** Texto a escribir segun la respuesta del dialogo: comparacion exacta; cierre o texto libre no escriben nada. */
466export function answerText(options: LaunchOption[], answer: unknown): string | null {
467 if (typeof answer !== 'string') return null
468 return options.find(o => o.label === answer)?.text ?? null
469}
470
471export type LaunchTarget = { kind: 'launch'; launch: LaunchKind } | { kind: 'issue'; issue: number } | { kind: 'invalid'; message: string }
472
473/** Argumento de `/fausto-blood-pact lanzar`: vacio o `sequential` -> 1, `parallel` -> 4, `<n>` -> ese issue si es lanzable. */
474export function parseLaunchArg(arg: string, list: BoardList): LaunchTarget {
475 const a = arg.trim()
476 if (a === '' || a === 'sequential') return { kind: 'launch', launch: 'sequential' }
477 if (a === 'parallel') return { kind: 'launch', launch: 'parallel' }
478 if (/^\d+$/.test(a)) {
479 const n = Number(a)
480 return list.items.some(i => i.number === n)
481 ? { kind: 'issue', issue: n }
482 : { kind: 'invalid', message: `#${n} no está entre los lanzables.` }
483 }
484 return { kind: 'invalid', message: 'Uso: /fausto-blood-pact lanzar [sequential|parallel|<n>]' }
485}
486
487// ---- Incremento 4: la mascota (MEF-ADR-0055 decision 10/11; lector puro: pose del status y de los events.jsonl) ----
488
489export type MascotPose = { role: Role; state: string }
490export type LastEvent = { kind: 'tool' | 'text'; tool: string }
491
492/** Rol de la mascota segun el sufijo del agente (el prefijo `<n>-` del stage se ignora); sin agente conocido, desarrollador. */
493export function roleOfAgent(agent: string): Role {
494 const name = agentOf(agent)
495 if (/(^|-)(test-writer|coverage-gate)$/.test(name)) return 'tester'
496 if (/(^|-)reviewer$/.test(name)) return 'revisor'
497 if (/(^|-)infra-writer$/.test(name)) return 'infraestructura'
498 return 'desarrollador'
499}
500
501/** La corrida activa con `updated` mas reciente (a igualdad, la de `started` mas reciente); null sin corridas activas. */
502export function activeRunOf(runs: readonly PipelineRun[]): PipelineRun | null {
503 let best: PipelineRun | null = null
504 for (const r of runs) {
505 if (!isActive(r)) continue
506 if (!best || r.updated.localeCompare(best.updated) > 0 || (r.updated === best.updated && r.started.localeCompare(best.started) > 0)) best = r
507 }
508 return best
509}
510
511export const LOGS_DIR = 'logs'
512
513/** Prefijo del `log_base` por pipeline: "" en tdd, `tooling-` e `iac-`. */
514export function logPrefixOf(pipeline: PipelineKind): string {
515 return pipeline === 'tooling' ? 'tooling-' : pipeline === 'infra' ? 'iac-' : ''
516}
517
518/** `<prefijo>stage-<stage>-<started>-issue-<n>[-<variante>]`: lo que precede a `-attempt-<k>.events.jsonl`. */
519export function eventsLogBase(run: PipelineRun): string {
520 return `${logPrefixOf(run.pipeline)}stage-${run.stage}-${run.started}-issue-${run.issue}${run.variant ? `-${run.variant}` : ''}`
521}
522
523/** Nombre del `events.jsonl` del intento mas alto de la corrida entre los nombres del directorio de logs; null si no hay. */
524export function eventsFileOf(run: PipelineRun, names: readonly string[]): string | null {
525 const base = `${eventsLogBase(run)}-attempt-`
526 let best: string | null = null
527 let bestAttempt = -1
528 for (const raw of names) {
529 const name = raw.trim()
530 if (!name.startsWith(base)) continue
531 const m = /^(\d+)\.events\.jsonl$/.exec(name.slice(base.length))
532 if (!m) continue
533 const attempt = Number(m[1])
534 if (attempt > bestAttempt) {
535 bestAttempt = attempt
536 best = name
537 }
538 }
539 return best
540}
541
542/** Ultimo evento relevante del `events.jsonl` (run-events v1): `tool.started` o `message` del assistant con texto; null si no hay. */
543export function lastEventOf(raw: string): LastEvent | null {
544 const lines = raw.split('\n')
545 for (let i = lines.length - 1; i >= 0; i -= 1) {
546 const line = (lines[i] ?? '').trim()
547 if (line === '') continue
548 let ev: Record<string, unknown>
549 try {
550 ev = JSON.parse(line) as Record<string, unknown>
551 } catch {
552 continue
553 }
554 if (ev.type === 'tool.started') return { kind: 'tool', tool: typeof ev.tool === 'string' ? ev.tool : '' }
555 if (ev.type === 'message' && ev.role === 'assistant' && typeof ev.text === 'string' && ev.text.trim() !== '') return { kind: 'text', tool: '' }
556 }
557 return null
558}
559
560const EDIT_TOOLS = /^(Edit|Write|MultiEdit|NotebookEdit)$/
561
562/** Pose de la corrida activa: herramienta trabaja (o despliega), texto o sin eventos piensa, edicion del revisor corrige. */
563export function poseOfRun(run: PipelineRun, last: LastEvent | null): MascotPose {
564 const role = roleOfAgent(agentOf(run.stage))
565 if (role === 'infraestructura') return { role, state: 'desplegando' }
566 if (last?.kind !== 'tool') return { role, state: 'pensando' }
567 if (role === 'revisor' && EDIT_TOOLS.test(last.tool)) return { role, state: 'corrigiendo' }
568 return { role, state: 'trabajando' }
569}
570
571/** Pose con solo resultados: `✓` revisor aprobado (infra arriba), `✗` desarrollador error (infra caido); null sin resultados. */
572export function poseOfResults(results: readonly PipelineResult[]): MascotPose | null {
573 const r = results[results.length - 1]
574 if (!r) return null
575 const isInfra = r.pipeline === 'infra'
576 if (r.ok) return isInfra ? { role: 'infraestructura', state: 'arriba' } : { role: 'revisor', state: 'aprobado' }
577 return isInfra ? { role: 'infraestructura', state: 'caido' } : { role: 'desarrollador', state: 'error' }
578}
579
580// ---- Incremento 5: mergear / ver el PR de una corrida terminada ----
581export const PR_CHECK_MS = 15_000
582export const MERGE_ALL = 'Todos'
583export const MERGE_CANCEL = 'Cancelar'
584const MERGE_MAX_OPTIONS = 3
585
586export type ResultPr = { pr: string; issue: number; pipeline: PipelineKind; key: string }
587
588/** Numero de PR de un resultado `✓ PR #X`; null si es `✗` o `✓ completado`. */
589export function prOfResult(r: PipelineResult): string | null {
590 return r.ok ? (/^✓ PR #(\d+)/.exec(r.text)?.[1] ?? null) : null
591}
592
593/** PRs de los `✓` visibles, sin repetir, del mas reciente (numero mayor) al mas antiguo. */
594export function resultPrs(results: PipelineResult[]): ResultPr[] {
595 const found = new Map<string, ResultPr>()
596 for (const r of results) {
597 const pr = prOfResult(r)
598 if (pr && !found.has(pr)) found.set(pr, { pr, issue: r.issue, pipeline: r.pipeline, key: r.key })
599 }
600 return [...found.values()].sort((a, b) => Number(b.pr) - Number(a.pr))
601}
602
603const prLabel = (p: ResultPr) => `#${p.pr} · #${p.issue} ${p.pipeline}`
604
605/** Opciones del dialogo de merge: con un PR, ese y cancelar; con varios, "Todos" y hasta 3 PRs mas recientes. */
606export function mergeOptions(prs: ResultPr[]): string[] {
607 if (prs.length === 1 && prs[0]) return [`Mergear #${prs[0].pr}`, MERGE_CANCEL]
608 return [MERGE_ALL, ...prs.slice(0, MERGE_MAX_OPTIONS).map(prLabel)]
609}
610
611/** Opciones de "cual PR ver": hasta 3 PRs mas recientes; los demas numeros van en la opcion de texto. */
612export function viewOptions(prs: ResultPr[]): string[] {
613 return prs.slice(0, MERGE_MAX_OPTIONS).map(prLabel)
614}
615
616/**
617 * Argumentos de /mefisto:merge a partir de la respuesta (opciones marcadas unidas por ", " y/o texto libre):
618 * solo numeros de PRs `✓` conocidos, nunca `--all`. Null si no queda ninguno (cancelar o nada elegido).
619 */
620export function mergeArgsOf(answer: string | null, options: string[], prs: ResultPr[]): string | null {
621 return argsOfAnswer(answer, options, prs.map(p => p.pr))
622}
623
624/** Comun a ambos dialogos de merge: un solo numero exige su opcion; "Todos" pasa `allArg` si lo hay, o todos los listados; si no, elegidos + texto libre. */
625function argsOfAnswer(answer: string | null, options: string[], numbersListed: string[], allArg: string | null = null): string | null {
626 if (answer === null) return null
627 if (numbersListed.length === 1) return answer === options[0] && numbersListed[0] ? numbersListed[0] : null
628 if (answer.includes(MERGE_ALL)) return allArg ?? numbersListed.join(' ')
629 const known = new Set(numbersListed)
630 let rest = answer
631 const numbers: string[] = []
632 for (const option of options) {
633 if (option === MERGE_ALL || !rest.includes(option)) continue
634 rest = rest.replace(option, '')
635 const n = /^#(\d+)/.exec(option)?.[1]
636 if (n) numbers.push(n)
637 }
638 numbers.push(...(rest.match(/\d+/g) ?? []))
639 const picked = [...new Set(numbers)].filter(n => known.has(n))
640 return picked.length > 0 ? picked.join(' ') : null
641}
642
643/** El PR que eligio la persona para verlo: un numero de la respuesta que sea de un `✓`. */
644export function viewPrOf(answer: string | null, prs: ResultPr[]): string | null {
645 if (answer === null) return null
646 const known = new Set(prs.map(p => p.pr))
647 const n = (/#(\d+)/.exec(answer)?.[1] ?? /\d+/.exec(answer)?.[0]) ?? null
648 return n && known.has(n) ? n : null
649}
650
651/** Numeros de PR de un argumento de comando (`merge 12 13`, `#12`); invalid = los que no son de un `✓`. */
652export function parsePrArgs(arg: string, prs: ResultPr[]): { prs: string[]; invalid: string[] } {
653 const known = new Set(prs.map(p => p.pr))
654 const given = [...new Set((arg.match(/\d+/g) ?? []))]
655 return { prs: given.filter(n => known.has(n)), invalid: given.filter(n => !known.has(n)) }
656}
657
658/** Toast del merge: en infra el issue lo cierra el job `apply` de CI tras el merge (MEF-ADR-0022). */
659export function mergeToast(args: string, prs: ResultPr[]): string {
660 const nums = args.split(' ')
661 const hasInfra = prs.some(p => nums.includes(p.pr) && p.pipeline === 'infra')
662 return `/mefisto:merge ${args} en cola${hasInfra ? ' · el issue de infra se cierra cuando termine el apply de CI' : ''}`
663}
664
665// ---- Incremento 6: mergear PRs abiertos desde el reposo (decision 11: referencia de experiencia) ----
666export const OPEN_PRS_ARGS = ['pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,title,isDraft,headRefName']
667
668export type OpenPr = { number: string; title: string; isFieldNote: boolean }
669
670/** Rama de los PRs de field notes del planner: `docs/planner-field-notes-*`. */
671export const isFieldNoteBranch = (branch: string): boolean => /^docs\/planner-field-notes-/.test(branch)
672
673/** PRs abiertos que no son borradores (field notes marcadas con `isFieldNote`); el mas reciente (numero mayor) primero. Vacio si no es JSON. */
674export function parseOpenPrs(raw: string): OpenPr[] {
675 let rows: unknown
676 try {
677 rows = JSON.parse(raw)
678 } catch {
679 return []
680 }
681 if (!Array.isArray(rows)) return []
682 const out: OpenPr[] = []
683 for (const r of rows as Record<string, unknown>[]) {
684 if (!r || typeof r.number !== 'number' || r.isDraft === true) continue
685 out.push({
686 number: String(r.number),
687 title: typeof r.title === 'string' ? r.title : '',
688 isFieldNote: typeof r.headRefName === 'string' && isFieldNoteBranch(r.headRefName),
689 })
690 }
691 return out.sort((a, b) => Number(b.number) - Number(a.number))
692}
693
694const openPrLabel = (p: OpenPr) => `#${p.number} ${clip(p.title, 60)}`.trim()
695
696/** Opciones del dialogo: con un PR, ese y cancelar; con varios, "Todos" y los 3 mas recientes. */
697export function openPrOptions(prs: OpenPr[]): string[] {
698 if (prs.length === 1 && prs[0]) return [openPrLabel(prs[0]), MERGE_CANCEL]
699 return [MERGE_ALL, ...prs.slice(0, MERGE_MAX_OPTIONS).map(openPrLabel)]
700}
701
702/** Argumentos de /mefisto:merge: "Todos" es `--all`; si no, los elegidos y los del texto libre. */
703export function openPrArgsOf(answer: string | null, options: string[], prs: OpenPr[]): string | null {
704 return argsOfAnswer(answer, options, prs.map(p => p.number), '--all')
705}
706
707// ---- Incremento 7: seguir un sequential como lote (MEF-ADR-0055 decision 10/11; #2202 escribe el status) ----
708export const BATCH_STATUS_FILE = 'pipeline-status-batch.json'
709/** Senal de parada suave (MEF-ADR-0017), relativa a la raiz del checkout principal. */
710export const BATCH_STOP_FILE = 'pipeline-state/batch-stop'
711export const BATCH_STOP_ANSWER = 'Detener tras el actual'
712export const BATCH_KEEP_ANSWER = 'Seguir'
713
714export type BatchIssueStatus = 'pendiente' | 'en-curso' | 'mergeado' | 'fallido' | 'aplazado' | 'saltado'
715export type BatchState = 'running' | 'completed' | 'failed' | 'stopped'
716export type BatchIssue = { issue: number; status: BatchIssueStatus; pr: string | null; detail: string }
717export type BatchStatus = {
718 pipeline: string
719 started: string
720 state: BatchState
721 current: number | null
722 stopRequested: boolean
723 holdSeconds: number
724 issues: BatchIssue[]
725 /** Ruta del log del lote (`log` del status), que acumula todos los issues. */
726 log?: string
727}
728
729const BATCH_ISSUE_STATUSES: readonly string[] = ['pendiente', 'en-curso', 'mergeado', 'fallido', 'aplazado', 'saltado']
730const BATCH_STATES: readonly string[] = ['running', 'completed', 'failed', 'stopped']
731
732export function batchStatusPath(stateDir: string): string {
733 return `${stateDir.replace(/\/+$/, '')}/${BATCH_STATUS_FILE}`
734}
735
736/** Ruta de la senal de parada: la raiz del checkout principal (donde `batch-pipeline.sh` lee su cwd), nunca el worktree. */
737export function batchStopPath(repoRoot: string): string {
738 return `${repoRoot.replace(/\/+$/, '')}/${BATCH_STOP_FILE}`
739}
740
741function prNumberOf(value: unknown): string | null {
742 if (typeof value === 'number') return String(value)
743 if (typeof value !== 'string') return null
744 return /(\d+)\s*$/.exec(value)?.[1] ?? null
745}
746
747/** Parseo de `pipeline-status-batch.json`; null si no es JSON valido o no trae un `state` conocido. */
748export function parseBatchStatus(raw: string): BatchStatus | null {
749 let json: Record<string, unknown>
750 try {
751 const parsed: unknown = JSON.parse(raw)
752 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
753 json = parsed as Record<string, unknown>
754 } catch {
755 return null
756 }
757 if (typeof json.state !== 'string' || !BATCH_STATES.includes(json.state)) return null
758 const issues: BatchIssue[] = []
759 for (const row of Array.isArray(json.issues) ? (json.issues as Record<string, unknown>[]) : []) {
760 const issue = Number(row?.issue)
761 if (!Number.isFinite(issue)) continue
762 const status = typeof row.status === 'string' && BATCH_ISSUE_STATUSES.includes(row.status) ? (row.status as BatchIssueStatus) : 'pendiente'
763 issues.push({ issue, status, pr: prNumberOf(row.pr), detail: typeof row.detail === 'string' ? row.detail : '' })
764 }
765 const current = Number(json.current)
766 return {
767 pipeline: typeof json.pipeline === 'string' ? json.pipeline : 'sequential',
768 started: typeof json.started === 'string' ? json.started : '',
769 state: json.state as BatchState,
770 current: json.current !== null && json.current !== undefined && json.current !== '' && Number.isFinite(current) ? current : null,
771 stopRequested: json.stop_requested === true,
772 holdSeconds: typeof json.hold_seconds === 'number' && json.hold_seconds > 0 ? json.hold_seconds : 0,
773 issues,
774 ...(typeof json.log === 'string' && json.log !== '' ? { log: json.log } : {}),
775 }
776}
777
778export const isBatchRunning = (b: BatchStatus) => b.state === 'running'
779
780/** Pose del lote sin corrida activa, como la cinta interna: terminado es el revisor aprobado; el desarrollador no tiene `aprobado`. */
781export function poseOfBatch(b: { state: BatchState }): MascotPose {
782 if (b.state === 'failed') return { role: 'desarrollador', state: 'error' }
783 if (b.state === 'completed') return { role: 'revisor', state: 'aprobado' }
784 return { role: 'desarrollador', state: 'pensando' }
785}
786
787export type BatchCounts = { merged: number; failed: number; deferred: number; skipped: number; total: number }
788
789export function batchCounts(b: BatchStatus): BatchCounts {
790 const count = (s: BatchIssueStatus) => b.issues.filter(i => i.status === s).length
791 return { merged: count('mergeado'), failed: count('fallido'), deferred: count('aplazado'), skipped: count('saltado'), total: b.issues.length }
792}
793
794/** Marca de la cola: `✓` mergeado, `●` en curso, `✗` fallido, `⏸` aplazado, `-` saltado, `·` pendiente. */
795export function batchMark(status: BatchIssueStatus): string {
796 switch (status) {
797 case 'mergeado':
798 return '✓'
799 case 'en-curso':
800 return '●'
801 case 'fallido':
802 return '✗'
803 case 'aplazado':
804 return '⏸'
805 case 'saltado':
806 return '-'
807 default:
808 return '·'
809 }
810}
811
812/** Cola en una linea, separada por ` ─ `: `✓ #12 ─ ● #13 reviewer ─ ⏸ #14`; el issue en curso lleva su paso si se conoce. */
813export function batchQueueText(b: BatchStatus, step?: string | null): string {
814 return batchQueueMarks(b, step).map((m, n) => `${n > 0 ? ' \u2500 ' : ''}${m.text}`).join('')
815}
816
817/** Marcas de la cola con color (undefined = atenuado): `✓` success, `●` warning, `✗` error, `⏸` y `○` atenuados. */
818export function batchQueueMarks(b: BatchStatus, step?: string | null): { text: string; color: string | undefined }[] {
819 const cur = batchCurrentOf(b)
820 return b.issues.map(i => {
821 const color = i.status === 'mergeado' ? 'success' : i.status === 'en-curso' ? 'warning' : i.status === 'fallido' ? 'error' : undefined
822 const mark = i.status === 'pendiente' ? '\u25cb' : batchMark(i.status)
823 const withStep = step && cur && cur.issue === i.issue && i.status === 'en-curso' ? ` ${step}` : ''
824 return { text: `${mark} #${i.issue}${withStep}`, color }
825 })
826}
827
828/** Cabecera del lote en curso: `sequential M/N` (M = mergeados + fallidos), tiempo `MM:SS` desde `started` y, con parada pedida, `se detiene tras #N`. */
829export function batchRunningHeader(b: BatchStatus, nowMs: number): { progress: string; time: string; stopNote: string } {
830 const c = batchCounts(b)
831 const parsed = stampToMs(b.started) || Date.parse(b.started)
832 const startedMs = Number.isNaN(parsed) ? 0 : parsed
833 return {
834 progress: `sequential ${c.merged + c.failed}/${c.total}`,
835 time: startedMs > 0 ? elapsedText(nowMs - startedMs) : '',
836 stopNote: b.stopRequested ? `se detiene tras #${b.current ?? batchCurrentOf(b)?.issue ?? '\u2026'}` : '',
837 }
838}
839
840/** El eslabon en curso: `current` del status o, si no, el primero `en-curso`; null si no hay. */
841export function batchCurrentOf(b: BatchStatus): BatchIssue | null {
842 return b.issues.find(i => i.issue === b.current) ?? b.issues.find(i => i.status === 'en-curso') ?? null
843}
844
845/** PR del eslabon en curso o, si aun no tiene, el del ultimo `mergeado` con PR; null sin PR. */
846export function batchPrOf(b: BatchStatus): string | null {
847 const current = batchCurrentOf(b)
848 if (current?.pr) return current.pr
849 for (let i = b.issues.length - 1; i >= 0; i -= 1) {
850 const row = b.issues[i] as BatchIssue
851 if (row.status === 'mergeado' && row.pr) return row.pr
852 }
853 return null
854}
855
856/** Corrida suelta del eslabon en curso (su propio status), para pipeline, agente, tiempo y mascota. */
857export function batchRunOf(b: BatchStatus, runs: readonly PipelineRun[]): PipelineRun | null {
858 const current = batchCurrentOf(b)
859 if (!current) return null
860 return runs.filter(r => r.issue === current.issue && isActive(r)).sort((a, c) => c.updated.localeCompare(a.updated))[0] ?? null
861}
862
863/** Espera por rate limit en curso del eslabon: `en espera por rate limit · próxima sonda HH:MM`; vacio si no esta en `hold`. */
864export function batchHoldLine(run: PipelineRun | null): string {
865 if (!run || run.state !== 'hold') return ''
866 return `en espera por rate limit · próxima sonda ${run.nextProbe ? clockOf(run.nextProbe) : '?'}`
867}
868
869/** Minutos de espera por rate limit acumulados, como `Mm`; vacio sin espera. */
870export function holdText(holdSeconds: number): string {
871 return holdSeconds > 0 ? `${Math.max(1, Math.round(holdSeconds / 60))}m` : ''
872}
873
874export type IssueStats = { durationMs: number; costUsd: number | null; title: string | null; finishedMs: number }
875
876/** `YYYYMMDD-HHMMSS` a milisegundos locales; 0 si no tiene ese formato. */
877export function stampToMs(stamp: string): number {
878 const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})$/.exec(stamp)
879 if (!m) return 0
880 const [y = 0, mo = 1, d = 1, h = 0, mi = 0, s = 0] = m.slice(1).map(Number)
881 return new Date(y, mo - 1, d, h, mi, s).getTime()
882}
883
884/** Pipelines publicados que escriben el historial de un issue del lote. */
885export const BATCH_HISTORY_PIPELINES = ['tdd', 'tooling', 'iac']
886
887type StatsEntry = {
888 issue?: string
889 pipeline?: string
890 started?: string
891 finished?: string
892 title?: string
893 agents?: Record<string, { metrics?: { estimated_cost_usd?: number | null } }>
894}
895
896/**
897 * Duracion y costo de la ultima corrida de cada issue en el historial, arrancada en o despues de `sinceMs`.
898 * El costo suma `agents.*.metrics.estimated_cost_usd` (null si ningun agente lo informa).
899 */
900export function issueStatsFromHistory(raw: string, issues: readonly string[], sinceMs: number): Record<string, IssueStats> {
901 const out: Record<string, IssueStats> = {}
902 for (const line of raw.split('\n')) {
903 let h: StatsEntry
904 try {
905 h = JSON.parse(line)
906 } catch {
907 continue
908 }
909 const issue = String(h.issue ?? '')
910 if (!BATCH_HISTORY_PIPELINES.includes(h.pipeline ?? '') || !issues.includes(issue) || !h.started || !h.finished) continue
911 const startedMs = stampToMs(h.started)
912 const finishedMs = new Date(h.finished).getTime()
913 if (startedMs + 1000 < sinceMs || Number.isNaN(finishedMs)) continue
914 const costs = Object.values(h.agents ?? {})
915 .map(a => a.metrics?.estimated_cost_usd)
916 .filter((c): c is number => typeof c === 'number')
917 out[issue] = {
918 durationMs: Math.max(0, finishedMs - startedMs),
919 costUsd: costs.length > 0 ? costs.reduce((x, y) => x + y, 0) : null,
920 title: typeof h.title === 'string' && h.title !== '' ? h.title : null,
921 finishedMs,
922 }
923 }
924 return out
925}
926
927/** Issues sin estadisticas o con estadisticas sin titulo: un titulo vacio en cache no se corrige solo. */
928export function statsPending(issues: readonly string[], stats: Record<string, IssueStats>): string[] {
929 return issues.filter(issue => !stats[issue] || stats[issue].title === null)
930}
931
932export const fmtCost = (usd: number | null) => (usd === null ? '$?' : `$${usd.toFixed(2)}`)
933
934/** Total de lo terminado: duracion sumada y costo sumado (sin contar los que no lo informan). */
935export function statsTotal(stats: IssueStats[]): IssueStats {
936 const costs = stats.map(s => s.costUsd).filter((c): c is number => c !== null)
937 return {
938 durationMs: stats.reduce((a, s) => a + s.durationMs, 0),
939 costUsd: costs.length > 0 ? costs.reduce((a, c) => a + c, 0) : null,
940 title: null,
941 finishedMs: 0,
942 }
943}
944
945/** Titulo recortado con `...` a `width` columnas y rellenado a ese ancho (vacio si no hay titulo o espacio). */
946export function fitTitle(title: string | null | undefined, width: number): string {
947 if (width <= 0) return ''
948 const t = (title ?? '').trim()
949 return padEnd(t.length > width ? `${t.slice(0, width - 1)}…` : t, width)
950}
951
952/** Ancho de la columna de titulo de la tabla de cierre; 0 si no cabe un titulo legible. */
953export function summaryTitleWidth(inner: number): number {
954 const w = Math.min(60, inner - 38)
955 return w < 8 ? 0 : w
956}
957
958/** Resumen de cierre con marcas: `✓ N mergeados · ✗ N fallidos · ⏸ N aplazados · espera Xm` (omite lo que esta en cero). */
959export function batchSummaryMarks(b: BatchStatus): string {
960 const c = batchCounts(b)
961 const hold = holdText(b.holdSeconds)
962 return [
963 `✓ ${c.merged} mergeados`,
964 c.failed > 0 ? `✗ ${c.failed} fallidos` : '',
965 c.deferred > 0 ? `⏸ ${c.deferred} aplazados` : '',
966 hold ? `espera ${hold}` : '',
967 ]
968 .filter(Boolean)
969 .join(' · ')
970}
971
972/** Estado del cierre en la cabecera: `terminado`, `detenido` o `con fallos`. */
973export function batchEndLabel(state: BatchState): string {
974 return state === 'completed' ? 'terminado' : state === 'stopped' ? 'detenido' : 'con fallos'
975}
976
977/** Fila de la tabla de cierre (sin la marca): issue, titulo, PR, duracion y costo; `…` sin entrada de historial. */
978export function closeRowText(i: BatchIssue, st: IssueStats | undefined, titleW: number): { lead: string; trail: string } {
979 const lead = `${padEnd(`#${i.issue}`, 7)} ${titleW > 0 ? `${fitTitle(st?.title, titleW)} ` : ''}${padEnd(i.pr ? `PR #${i.pr}` : 'sin PR', 10)} `
980 return { lead, trail: st ? `${padEnd(elapsedText(st.durationMs), 8)} ${fmtCost(st.costUsd)}` : '…' }
981}
982
983/** Fila `●` del issue en curso: `#N`, titulo, `PR #X` o `…`, tiempo desde `startedMs` y `…` de costo. */
984export function runningRowText(issue: number, pr: string | null, title: string | null, startedMs: number, nowMs: number, titleW: number): { lead: string; trail: string } {
985 const lead = `${padEnd(`#${issue}`, 7)} ${titleW > 0 ? `${fitTitle(title, titleW)} ` : ''}${padEnd(pr ? `PR #${pr}` : '…', 10)} `
986 return { lead, trail: `${padEnd(startedMs > 0 ? elapsedText(nowMs - startedMs) : '…', 8)} …` }
987}
988
989/** Corrida de la fila `●` y, si ya termino, el instante en que se congela su tiempo. */
990export type CurrentRow = { run: PipelineRun; endMs: number | null }
991
992/**
993 * Fila `●` del lote en curso: la corrida activa del eslabon; si su status ya no esta activo mientras el issue
994 * espera su merge, la ultima vista, con el tiempo congelado en `nowMs` (como la cinta interna). Null sin lote en curso.
995 */
996export function nextCurrentRow(b: BatchStatus, live: PipelineRun | null, prev: CurrentRow | null, nowMs: number): CurrentRow | null {
997 if (!isBatchRunning(b)) return null
998 if (live) return { run: live, endMs: null }
999 const cur = batchCurrentOf(b)
1000 if (!prev || !cur || prev.run.issue !== cur.issue || stampToMs(prev.run.started) < stampToMs(b.started)) return null
1001 return prev.endMs === null ? { run: prev.run, endMs: nowMs } : prev
1002}
1003
1004/** Total con el issue en curso: suma su tiempo transcurrido a los terminados; el costo sigue siendo solo el de los terminados. */
1005export function totalWithRunning(total: IssueStats, startedMs: number, nowMs: number): IssueStats {
1006 return startedMs > 0 ? { ...total, durationMs: total.durationMs + Math.max(0, nowMs - startedMs) } : total
1007}
1008
1009/** Fila `total` de la tabla de cierre, alineada con las columnas de `closeRowText`. */
1010export function closeTotalText(count: number, total: IssueStats, titleW: number): string {
1011 const titleCol = titleW > 0 ? titleW + 1 : 0
1012 return ` total ${padEnd(String(count), 12 + titleCol)} ${padEnd(elapsedText(total.durationMs), 8)} ${fmtCost(total.costUsd)}`
1013}
1014
1015/** Momento de cierre del lote: el ultimo `finished` del historial entre sus issues; null sin entradas. */
1016export function batchEndFromStats(stats: Record<string, IssueStats>): number | null {
1017 const all = Object.values(stats).map(s => s.finishedMs)
1018 return all.length > 0 ? Math.max(...all) : null
1019}
1020
1021/** Issues que pasaron a `mergeado` entre dos lecturas; con `prev` vacio no hay toasts (el primer vistazo no anuncia). */
1022export function newlyMerged(prev: readonly BatchIssue[] | null, next: readonly BatchIssue[]): BatchIssue[] {
1023 if (!prev) return []
1024 const before = new Map(prev.map(i => [i.issue, i.status]))
1025 return next.filter(i => i.status === 'mergeado' && before.get(i.issue) !== 'mergeado')
1026}
1027
1028/** Clave de descarte persistente del lote: repo + `started`. */
1029export function batchDismissKey(repo: string, b: BatchStatus): string {
1030 return [repo, 'batch', b.started].join('|')
1031}
1032
1033/** Pregunta del dialogo de parada. */
1034export function stopQuestion(b: BatchStatus): string {
1035 return `¿Detener el sequential tras ${b.current ? `#${b.current}` : 'el issue en curso'}?`
1036}
1037
1038/** `1` se ofrece solo con el lote corriendo y sin parada pedida. */
1039export const canStopBatch = (b: BatchStatus | null): boolean => b !== null && isBatchRunning(b) && !b.stopRequested
1040
1041// ---- Incremento 8: la cinta de merge en vivo (el estado vive en $.state; no toca `.mefisto/pipeline/`) ----
1042export const MERGE_POLL_MS = 5_000
1043export const MERGE_RIBBON_HIDE_MS = 15_000
1044
1045/** Argumentos de un merge de `pr-sync.sh` (`--merge`): los numeros de PR o `--all`; null si el comando no es un merge de ese script. */
1046export function mergeRunArgsOf(command: string): string | null {
1047 const m = /pr-sync\.sh["']?(?=\s|$|[;&|])([^;&|]*)/.exec(command)
1048 if (!m) return null
1049 const tokens = (m[1] ?? '').split(/\s+/).filter(t => t !== '')
1050 if (!tokens.includes('--merge')) return null
1051 if (tokens.includes('--all')) return '--all'
1052 return tokens.filter(t => /^\d+$/.test(t)).join(' ')
1053}
1054
1055/** Los PRs de la cinta: con `--all`, los abiertos que se pasen; si no, los numeros de los argumentos, con el titulo que se conozca. */
1056export function mergePrsOf(args: string, open: readonly OpenPr[]): PactMergePr[] {
1057 const pending = (num: string, title: string): PactMergePr => ({ num, title, estado: 'pendiente' })
1058 if (/(^|\s)--all(\s|$)/.test(args)) return open.map(p => pending(p.number, p.title))
1059 const nums = [...new Set(args.match(/\d+/g) ?? [])]
1060 return nums.map(n => pending(n, open.find(p => p.number === n)?.title ?? ''))
1061}
1062
1063/** Pasa a `mergeado` los PRs pendientes indicados; devuelve la misma cinta si nada cambio. Un mergeado no vuelve atras. */
1064export function withMerged(run: PactMerge, merged: readonly string[]): PactMerge {
1065 if (!run.prs.some(p => p.estado === 'pendiente' && merged.includes(p.num))) return run
1066 return { ...run, prs: run.prs.map(p => (p.estado === 'pendiente' && merged.includes(p.num) ? { ...p, estado: 'mergeado' } : p)) }
1067}
1068
1069/** Cierra la cinta: lo que siga pendiente queda `fallido` (`✗ no mergeado`). */
1070export function finishMerge(run: PactMerge, now: number): PactMerge {
1071 if (run.finishedMs !== null) return run
1072 return { ...run, prs: run.prs.map(p => (p.estado === 'pendiente' ? { ...p, estado: 'fallido' } : p)), finishedMs: now }
1073}
1074
1075export function mergeCounts(run: PactMerge) {
1076 return {
1077 pending: run.prs.filter(p => p.estado === 'pendiente').length,
1078 merged: run.prs.filter(p => p.estado === 'mergeado').length,
1079 failed: run.prs.filter(p => p.estado === 'fallido').length,
1080 }
1081}
1082
1083/** Cabecera de la cinta: `merge N/M` (N cuenta los mergeados) y, al terminar, `terminado`. */
1084export function mergeRibbonHeader(run: PactMerge, nowMs: number): string {
1085 const c = mergeCounts(run)
1086 const mins = Math.max(0, Math.floor(((run.finishedMs ?? nowMs) - run.startedMs) / 60_000))
1087 return `merge ${c.merged}/${run.prs.length} · ${mins}m${run.finishedMs === null ? '' : ' · terminado'}`
1088}
1089
1090/** Linea de un PR: `· #12 titulo` pendiente, `✓` mergeado, `✗ ... no mergeado` fallido. */
1091export function mergeRibbonLine(p: PactMergePr, max: number): string {
1092 const mark = p.estado === 'mergeado' ? '✓' : p.estado === 'fallido' ? '✗' : '·'
1093 const tail = p.estado === 'fallido' ? ' · no mergeado' : ''
1094 const head = `${mark} #${p.num}`
1095 const room = max - head.length - tail.length - 1
1096 const title = p.title.trim() === '' || room < 2 ? '' : ` ${clip(p.title, room)}`
1097 return `${head}${title}${tail}`
1098}
1099
1100/** Filas de la cinta: los pendientes primero, luego los fallidos y, al final, los mergeados. */
1101export function mergeRibbonRows(run: PactMerge): PactMergePr[] {
1102 return [
1103 ...run.prs.filter(p => p.estado === 'pendiente'),
1104 ...run.prs.filter(p => p.estado === 'fallido'),
1105 ...run.prs.filter(p => p.estado === 'mergeado'),
1106 ]
1107}
1108
1109/** Toast de cierre: `N mergeados · M fallidos`. */
1110export function mergeSummaryText(run: PactMerge): string {
1111 const c = mergeCounts(run)
1112 return `${c.merged} mergeados · ${c.failed} fallidos`
1113}
1114
1115/** Vencimiento al dibujar: una cinta terminada hace mas de 15 s se oculta; una en curso, nunca. */
1116export function isMergeRibbonExpired(run: PactMerge | null, nowMs: number): boolean {
1117 return run !== null && run.finishedMs !== null && nowMs - run.finishedMs > MERGE_RIBBON_HIDE_MS
1118}
1119
1120/** Precedencia de la banda: el lote de sequential primero, luego la cinta de merge vigente, luego corridas y reposo. */
1121export function mergeRibbonShown(batch: BatchStatus | null, run: PactMerge | null, nowMs: number): PactMerge | null {
1122 return batch === null && run !== null && !isMergeRibbonExpired(run, nowMs) ? run : null
1123}
1124
1125// ---- Incremento 9: la bitacora (boton `3: bitacora N` y la cinta del historiador) ----
1126export const HISTORIAN_DONE_MS = 8_000
1127export const NOTES_POLL_MS = 3_000
1128export const FIELD_NOTES_DIR = 'docs/bitacora/field-notes'
1129export const PROCESSED_NOTES_DIR = `${FIELD_NOTES_DIR}/procesadas`
1130export const BITACORA_PR_ARGS = ['pr', 'list', '--state', 'open', '--limit', '50', '--json', 'number,title,headRefName,files']
1131const AGENT_ACTIVE = new Set(['pending', 'running', 'waiting'])
1132
1133/** El tipo del agente lleva el prefijo del plugin (`mefisto:historiador`); se acepta con o sin el. */
1134export const isHistorianType = (type: string): boolean => /(^|:)historiador$/.test(type)
1135
1136/** Un agente de `$.agent.list()` que aun no termina. */
1137export const isAgentActive = (status: string): boolean => AGENT_ACTIVE.has(status)
1138
1139/** Field notes `.md` de `docs/bitacora/field-notes/` (sin bajar a `procesadas/`). */
1140export function fieldNotesIn(names: readonly string[]): number {
1141 return names.filter(n => n.endsWith('.md')).length
1142}
1143
1144/** N de `3: bitacora N`: las field notes de main mas los PRs de field notes abiertos. */
1145export const bitacoraCount = (fieldNotes: number | null, prs: readonly OpenPr[]): number => (fieldNotes ?? 0) + prs.filter(p => p.isFieldNote).length
1146
1147/** Pregunta del dialogo de integrar la bitacora. */
1148export function bitacoraQuestion(local: number, prCount: number): string {
1149 return `¿Integrar la bitácora? ${local} field notes en main${prCount > 0 ? ` y ${prCount} en PRs sin mergear` : ''}`
1150}
1151
1152export const bitacoraIntegrateLabel = (prCount: number): string => (prCount > 0 ? `Mergear sus ${prCount} PRs e integrar` : 'Integrar')
1153
1154/** El prompt de usuario: mergear los PRs de field notes, traer main al dia y correr /mefisto:bitacora. */
1155export function bitacoraPrompt(fieldNotePrs: readonly (number | string)[]): string {
1156 const merge = fieldNotePrs.length > 0
1157 ? `mergea los PRs de field notes ${fieldNotePrs.map(n => `#${n}`).join(' ')} con /mefisto:merge, `
1158 : ''
1159 return `Integra la bitacora: ${merge}pon el checkout en main al dia (git switch main && git pull --ff-only) y luego corre /mefisto:bitacora.`
1160}
1161
1162/** Estado de la cinta del historiador; `prev` tal cual si nada cambio. */
1163export function historianFrom(prev: Historian | null, active: boolean, now: number): Historian | null {
1164 if (active) return prev && !prev.finishedMs ? prev : { startedMs: now, finishedMs: null, notes: [], pr: null }
1165 return prev && !prev.finishedMs ? { ...prev, finishedMs: now } : prev
1166}
1167
1168/** Terminada hace mas de `HISTORIAN_DONE_MS` (sin PR esperando al usuario) la cinta no existe; en curso nunca vence. */
1169export function liveHistorian(h: Historian | null, nowMs: number): Historian | null {
1170 if (!h || !h.finishedMs || h.pr) return h
1171 return nowMs - h.finishedMs > HISTORIAN_DONE_MS ? null : h
1172}
1173
1174const FIELD_NOTE_PATH = /^docs\/bitacora\/field-notes\/([^/]+\.md)$/
1175
1176/** Field notes a integrar: las locales (`.md`) y las de las rutas de los PRs de field notes, sin repetir. */
1177export function fieldNoteNamesOf(local: readonly string[], prPaths: readonly string[]): string[] {
1178 const fromPrs = prPaths.map(p => FIELD_NOTE_PATH.exec(p)?.[1]).filter((n): n is string => !!n)
1179 return [...new Set([...local.filter(n => n.endsWith('.md')), ...fromPrs])].sort()
1180}
1181
1182export const pendingNotes = (names: readonly string[]): BitacoraNote[] => names.map(name => ({ name, estado: 'pendiente' }))
1183
1184/** Pasa a procesada cada nota que ya aparece en `procesadas/`; `h` tal cual si nada cambio. */
1185export function withProcessedNotes<T extends { notes: BitacoraNote[] }>(h: T, processed: readonly string[]): T {
1186 const done = new Set(processed)
1187 if (!h.notes.some(n => n.estado === 'pendiente' && done.has(n.name))) return h
1188 return { ...h, notes: h.notes.map(n => (n.estado === 'pendiente' && done.has(n.name) ? { ...n, estado: 'procesada' } : n)) }
1189}
1190
1191/** Filas de la cinta: las pendientes `●` primero y luego las procesadas `✓`. */
1192export function orderedNotes(notes: readonly BitacoraNote[]): BitacoraNote[] {
1193 return [...notes.filter(n => n.estado === 'pendiente'), ...notes.filter(n => n.estado === 'procesada')]
1194}
1195
1196export const noteLine = (n: BitacoraNote): string => `${n.estado === 'procesada' ? '✓' : '●'} ${n.name}`
1197
1198/** `mm:ss` (o `h:mm:ss`). */
1199export function elapsedText(ms: number): string {
1200 const total = Math.max(0, Math.floor(ms / 1000))hooks/types/index.d.ts 161 lines1export type BoardItem = {
2 number: number
3 title: string
4 tipo: string | null
5 after: number[]
6 hasDepsSection: boolean
7}
8
9export type BoardList = {
10 items: BoardItem[]
11 blockedCount: number
12 cycleCount: number
13 launch: string | null
14 /** Numeros de los `tipo:infra` lanzables, en el orden de items. */
15 infra: number[]
16 /** Lote de `/mefisto:parallel` calculado por next-order. */
17 parallel: { issues: number[]; launch: string | null } | null
18 /** Issues con PR abierto (`inPr[]` de next-order): se ven con su PR, sin tecla; ausente con un script viejo. */
19 inPr?: InPrItem[]
20 error: string | null
21}
22
23export type InPrItem = { number: number; title: string; tipo: string | null; pr: number }
24
25export type PipelineKind = 'tdd' | 'tooling' | 'infra'
26
27/** Un `pipeline-status-*.json` ya parseado; lo que la consola muestra de una corrida. */
28export type PipelineRun = {
29 issue: number
30 pipeline: PipelineKind
31 variant: string | null
32 started: string
33 updated: string
34 stage: string
35 state: string
36 nextProbe: string | null
37 /** Pasos de `status.agents` en su orden (#2320). */
38 agents?: RunStep[]
39 /** Ruta del log del pipeline (`status.log`). */
40 log?: string | null
41 /** Titulo del issue (`status.title`). */
42 title?: string
43 /** Ultimo error del status (`last_error`) de una corrida fallida. */
44 lastError?: string
45}
46
47/** Una linea del pane de log: evento del agente o linea del log del pipeline (`log`, atenuada). */
48export type PaneLine = { kind: 'start' | 'tool' | 'fail' | 'done' | 'log'; text: string }
49
50/** Un agente del status: `pending` cubre todo `result` vacio o desconocido. */
51export type RunStep = { name: string; result: 'passed' | 'running' | 'failed' | 'pending'; /** Segundos del paso (`agents.<x>.duration`). */ duration?: number }
52
53/** Una corrida terminada pendiente de descartar: `✗ <stage>` o `✓ PR #X`. */
54export type PipelineResult = { key: string; issue: number; pipeline: PipelineKind; text: string; ok: boolean }
55
56/** Una fila de la cinta de merge de la consola. */
57export type PactMergePr = { num: string; title: string; estado: 'pendiente' | 'mergeado' | 'fallido' }
58
59/** La cinta de merge en curso de la consola; `finishedMs` null mientras corre. */
60export type PactMerge = { prs: PactMergePr[]; startedMs: number; finishedMs: number | null }
61
62/** Una field note que integra el historiador: pendiente hasta que aparece en `procesadas/`. */
63export type BitacoraNote = { name: string; estado: 'pendiente' | 'procesada' }
64
65/** El PR de bitacora que dejo el historiador, abierto a la espera de mergearlo o cerrarlo. */
66export type BitacoraPr = { number: number; title: string }
67
68/** El subagente historiador escribiendo la bitacora en esta sesion (lo lanza /mefisto:bitacora). */
69export type Historian = { startedMs: number; finishedMs: number | null; notes: BitacoraNote[]; pr: BitacoraPr | null }
70
71export type BoardTab = 'borrador' | 'listo'
72
73/** Lo que el planner esta haciendo: refinar un borrador o explorar una idea. */
74export type BoardFocus = {
75 kind: 'refinar' | 'explorar'
76 issue: number | null
77 topic: string
78 created: number[]
79 startedMs: number
80}
81
82/** Resumen breve que la banda muestra al cerrar un foco. */
83export type BoardFlash = { text: string; untilMs: number }
84
85declare module 'claude-code' {
86 interface PluginState {
87 mefisto: {
88 isActive: boolean
89 isPlannerSession: boolean
90 isExpanded: boolean
91 tab: BoardTab
92 page: number
93 frame: 0 | 1
94 stepsInTurn: number
95 isWorking: boolean
96 focus: BoardFocus | null
97 isConfirmingClose: boolean
98 flash: BoardFlash | null
99 refine: BoardList | null
100 develop: BoardList | null
101 updatedMs: number
102 signature: string
103 known: number[]
104 pendingCount: number
105 version: string | null
106 pactIsActive: boolean
107 pactList: BoardList | null
108 pactPage: number
109 pactRuns: PipelineRun[]
110 pactResults: PipelineResult[]
111 pactLastEvent: { kind: 'tool' | 'text'; tool: string } | null
112 pactBandLines: string[]
113 pactOpenPrs: { number: string; title: string; isFieldNote: boolean }[]
114 pactFieldNotes: number | null
115 pactHistorian: Historian | null
116 pactBatch: {
117 pipeline: string
118 started: string
119 state: 'running' | 'completed' | 'failed' | 'stopped'
120 current: number | null
121 stopRequested: boolean
122 holdSeconds: number
123 issues: { issue: number; status: 'pendiente' | 'en-curso' | 'mergeado' | 'fallido' | 'aplazado' | 'saltado'; pr: string | null; detail: string }[]
124 } | null
125 pactBatchStats: {
126 stats: Record<string, { durationMs: number; costUsd: number | null; title: string | null; finishedMs: number }>
127 endedMs: number | null
128 }
129 /** Fila `●` del sequential en curso: su corrida y, si espera el merge, el instante en que se congela su tiempo (#2361). */
130 pactBatchCurrent: { run: PipelineRun; endMs: number | null } | null
131 /** Lote parallel en curso (#2449), leido de `pipeline-status-parallel.json`; null si no corre. */
132 pactParallel: {
133 started: string
134 state: 'running' | 'completed' | 'failed' | 'stopped'
135 stopRequested: boolean
136 log?: string
137 issues: {
138 issue: number
139 pipeline: string | null
140 status: 'pendiente' | 'en-curso' | 'terminado' | 'fallido' | 'aplazado' | 'saltado'
141 pr: string | null
142 startedMs: number
143 finishedMs: number
144 detail: string
145 }[]
146 } | null
147 pactParallelStats: Record<string, { durationMs: number; costUsd: number | null; title: string | null; finishedMs: number }>
148 /** Banda de cada issue en curso del parallel: su corrida, sus ultimas lineas y su ultimo evento (para la pose). */
149 pactParallelBands: Record<string, { run: PipelineRun | null; lines: string[]; last: { kind: 'tool' | 'text'; tool: string } | null }>
150 pactParallelPage: number
151 /** PRs del lote parallel ya mergeados desde la consola. */
152 pactParallelMerged: string[]
153 pactMerge: PactMerge | null
154 pactLogLines: PaneLine[]
155 pactPaneRun: PipelineRun | null
156 pactTick: number
157 pactVersion: string | null
158 }
159 }
160}
161