SLOPSHOPPER

puente-gentle

Puente con Gentle Shell (Pi): consulta a otro orquestador como par, con su propia metodología, en los puntos de decisión.

paneguardcommandtoastprompttool
v0.1.0MITupdated 2026-10-24Gagaismo/orca-stack/mods/puente-gentle
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · puente-gentle
│ ┃ Gentle Shell ✕ › fix the failing auth test and add an audit log call │ ┃ Todavía no hay consultas. Usá /pi o dejá que │ ┃ Claude consulte a Gentle Shell. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /pi │ ⎿ puente-gentle: Uso: /pi <tema>: <pregunta> (por ejemplo: /pi pr │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Gentle Shell
Todavía no hay consultas. Usá /pi o dejá que Claude consulte a Gentle Shell.
README

orca-stack

Instala de una vez el stack de agentes que uso para trabajar con Orca: la política del stack, las skills propias, los wrappers de proveedores, Pi con Gentle Shell y los mods de Claude Code. Todo en un comando, con respaldo de lo que toca y con vuelta atrás.

¿Cómo se usa día a día? Leé el manual de uso: comandos, mods, marchas, cuándo conviene usarlo y cuándo no, casos borde y manejo. Marca lo que está solo en main y todavía no salió en un release.

npx github:Gagaismo/orca-stack#v0.16.1 global     # instalación a nivel usuario
npx github:Gagaismo/orca-stack#v0.16.1 init       # cablea el proyecto actual
npx github:Gagaismo/orca-stack#v0.16.1 doctor     # verifica que todo funcione de verdad
npx github:Gagaismo/orca-stack#v0.16.1 remove     # deshace lo que instaló global
npx github:Gagaismo/orca-stack#v0.16.1 sesiones   # lista las sesiones recientes de Claude, Pi y agy (para `/retro`)
npx github:Gagaismo/orca-stack#v0.16.1 despachar 12 agy   # desde el checkout principal: despacha el ticket #12 al agente
npx github:Gagaismo/orca-stack#v0.16.1 revisar 15 pi      # despacha el review del PR #15
npx github:Gagaismo/orca-stack#v0.16.1 brief-revision 15 --modelo <modelo>   # modo un-agente: worktree y brief de review para un subagente
npx github:Gagaismo/orca-stack#v0.16.1 consultas 42 57    # filtra y avisa consultas nuevas en issues y PRs en curso
npx github:Gagaismo/orca-stack#v0.16.1 avisar 42 <url>    # Proactive: le toca el timbre al worker de #42 con la URL de la respuesta
npx github:Gagaismo/orca-stack#v0.16.1 vigilar 42 57      # el Monitor de la tanda: solo eventos de sus PRs, hasta tanda-cerrada

¿Primera vez, o un proyecto nuevo o ya empezado? Seguí la guía de setup: tiene un cuestionario que dice qué configurar en cada caso.

Cero dependencias, Node 20 o más nuevo. Funciona en Windows, macOS y Linux.

Qué instala

global (idempotente; todo archivo que modifica se respalda antes en ~/.orca-stack/backups/<fecha>/ (nunca al lado del archivo, para que ningún agente cargue el respaldo)):

QuéDónde
Política del stack: ORCA-STACK.md y ROLE-BRIEFS.md~/orca/stack/
Wrappers claude-orca-stack, codex-orca-stack, agy-orca-stack (.cmd en Windows, .sh en el resto), cada uno con --orca-stack-self-test~/orca/stack/scripts/
Skills propias: orca-stack-policy, orca-setup, ponytail, ponytail-review, ponytail-audit, ponytail-debt, ponytail-help~/.claude/skills/ y ~/.agents/skills/
Ocho mods de Claude Code (ver abajo) y sus rutas en env.CLAUDE_CODE_PLUGIN_DIRS~/.claude/mods/ y ~/.claude/settings.json
Nada de metodología en ~/.claude/CLAUDE.md: si un global anterior dejó ahí el bloque <!-- orca-stack:begin --> … <!-- orca-stack:end -->, lo saca (con respaldo). También achica el bloque que gentle-ai escribe ahí (ver abajo)~/.claude/CLAUDE.md
Pi: gentle-pi@4.2.0 y pi-claude-bridge@0.9.2 con pi install (pi install npm:gentle-pi@4.2.0), más npm i -g gentle-pi@4.2.0 (comando gentle-shell). Necesita Pi 1.2.0 o más nuevo: con un Pi anterior no instala gentle-pi y falla~/.pi/agent/ y npm global
Comando orca-stack, para usar desde cualquier repo sin npx ni redWindows: prefijo global de npm si esta en PATH, con shims .cmd y sin extension para PowerShell y Git Bash. Otros sistemas: primer directorio escribible del PATH. La copia queda en ~/.orca-stack/cli/; si falta el destino compartido, se usa ~/.orca-stack/bin/ y global imprime como agregarlo al PATH
Registro de lo instalado, para remove~/.orca-stack/state.json
Capa personal de configuración~/.orca-stack/config.json

Gentle Shell se actualiza volviendo a correr global con la versión nueva de orca-stack. Desde gentle-pi 4.2.0, gentle-shell update reinstala solo el paquete global dueño del Pi que corre, y si no puede probar qué paquete global es dueño de Pi, no toca nada.

Los wrappers se llaman distinto del binario real a propósito: así nunca se llaman a sí mismos. Cada uno fija los marcadores ORCA_STACK_*, busca el binario real en el PATH, pasa los argumentos tal cual y devuelve su código de salida.

global instala herramientas, skills, mods y wrappers, pero ningún texto de metodología: una sesión de Claude en un proyecto sin .orca-stack.json no recibe nada del stack por esta vía. La metodología llega por el proyecto, con init (el contrato y las líneas de la política en AGENTS.md, y @AGENTS.md en CLAUDE.md). Del CLAUDE.md global global solo saca el bloque entre orca-stack:begin y orca-stack:end (o orca-stack:auto, el viejo) que dejó una versión anterior, y respeta todo lo demás. Con settings.json hace algo parecido: solo suma sus carpetas a CLAUDE_CODE_PLUGIN_DIRS (con el separador de tu sistema), conserva las que ya había y no toca ninguna otra clave.

El bloque gentle-ai:sdd-orchestrator (v2/v3) o gentle-ai:orchestrator (v4) de ~/.claude/CLAUDE.md (unos 16 KB: coordinación, delegación, tabla de modelos y el flujo de cada versión) se carga en cada sesión. Por eso global lo achica según gentle.orchestrator en ~/.orca-stack/config.json:

  • "lazy" (por defecto): guarda el texto completo, tal cual lo escribió gentle-ai, en ~/.orca-stack/gentle/orchestrator.md y deja entre los marcadores un puntero corto (empieza con <!-- orca-stack:gentle-lazy v1 -->). El puntero dice que ODD es el flujo predeterminado y que la sesión que orquesta (main) debe leer la copia completa; también exige presentar completos los menús y pedidos de consentimiento, sin responder por el humano. Hace respaldo, es idempotente, respeta --dry-run e imprime cuántos KB ahorró. Con marcadores incompletos, repetidos o desordenados no escribe nada y dice por qué. Se omite mientras el RDD de gentle-ai esté prendido (o no se pueda leer): el bloque trae su contrato de review y el puntero lo apagaría en silencio; si ya estaba en lazy, global lo restaura desde la copia.
  • "full": deja el bloque como lo escribe gentle-ai (y, si estaba en lazy, lo restaura desde la copia, con respaldo; si la copia falta, avisa que corras gentle-ai sync). Con el RDD de gentle-ai apagado (gentle-ai review mode status dice off), además recorta las secciones de review, que no hacen nada y se cargan igual (unos 26 KB); si RDD está prendido o gentle-ai no está instalado, ese recorte se omite y dice por qué.

gentle-ai sync reescribe el bloque entre los marcadores (reemplaza el contenido, no duplica ni valida un hash), así que después de cada sync hay que correr orca-stack global de nuevo, que además refresca la copia y el puntero. doctor avisa si la sync lo reescribió, si falta la copia o si todavía está en la ruta antigua. Para volver al bloque completo: poné "gentle": { "orchestrator": "full" } y corré orca-stack global, o corré gentle-ai sync. orca-stack remove también lo restaura desde la copia. La clave antigua gentle.sddOrchestrator sigue funcionando durante la migración; doctor sugiere renombrarla y, si están las dos, gentle.orchestrator tiene prioridad. global mueve la copia antigua sdd-orchestrator.md a orchestrator.md; si existen ambas, conserva la más nueva por fecha de modificación y respalda la otra.

gentle-ai v4. v4 retiró SDD y OpenSpec: ODD es su único flujo y gentle-ai sync renombra el bloque en el lugar a gentle-ai:orchestrator, con el orquestador ODD adentro y las mismas secciones de review. global, doctor y remove reconocen los dos nombres: el modo lazy, el recorte y la restauración funcionan igual; el puntero indica que ODD es el flujo predeterminado y que la sesión main lee la copia completa. La copia queda en ~/.orca-stack/gentle/orchestrator.md. Para pasar a v4 en Windows (necesita Go 1.25.10 o más nuevo en el PATH):

go install github.com/gentleman-programming/gentle-ai/v4/cmd/gentle-ai@v4.1.1
gentle-ai sync
npx github:Gagaismo/orca-stack global

La sync deja el bloque completo y la copia vieja (de v2) queda desactualizada: doctor avisa que corras orca-stack global, que guarda el texto de v4 en la copia y vuelve a dejar el puntero.

Los mods

Son plugins de Claude Code que se recargan en caliente (.claude-plugin/plugin.json + hooks/). Se activan con la variable CLAUDE_CODE_PLUGIN_DIRS, que global completa por vos; se cargan en las sesiones que abras después.

ModQué haceConfig
tablero-despachoTablero de PRs abiertos con checks, review y worktrees (/tablero). Usa gh.Los atajos de despacho aparecen solo si hay despacho
guardia-despachoBloquea o corrige las llamadas a tus scripts de despacho y revisión según reglas del proyecto. Siempre activo, con o sin despacho: niega gh pr merge si el worker de ese PR sigue activo; pregunta qué perfil de gentle-pi usa un despacho a pi (--perfil-pi); rechaza orca worktree rm y git worktree remove si la rama de ese worktree tiene commits que no están en ningún remoto, porque orca worktree rm borra también la rama local. Si no puede resolver la rama, rechazaLas reglas de despacho están apagadas salvo que haya despacho
puente-gentleConsulta a Gentle Shell (Pi) como otro orquestador par (/pi, /gentle). La instrucción de consultar y la herramienta consultar_gentle_shell aparecen solo en un repo con .orca-stack.json. Para consultar sobre un PR o un issue, pasale pr o issue en vez de pegar el cuerpo, los comentarios o el diff en el planteo: el mod los lee con gh y se los da a Pi en archivos bajo <git-common-dir>/orca-stack/gentle/ (Pi sigue sin gh). Frena el merge de un PR grande sin consulta y el de uno que toca riesgo sin sus reviews limpios (de pi, o de dos familias de modelo que no sean la de pi si el PR lo escribió pi)humano, riesgo, agentes.pi.claudeConfigDir
bandeja-mensajesCaptura los bloques `mensaje <destinatario> que redacta Claude y deja copiarlos o guardarlosmensajes.destinatarios
grilling-okResponde con un clic (o con un ok) a las preguntas Q1…Qn de una sesión de grilling—
modo-autonomoInstrucción permanente de trabajo autónomo hasta la meta, con recordatorio anti-parada acotado—
marchas/marcha muestra o cambia la marcha de main: Lazy, Medium o Proactive; cada sesión nueva empieza en Medium; avisa en una línea cuando el modo autónomo coincide con Lazy, Proactive o ultracode—
reloj-cacheMuestra cuánto falta para que venza el caché del prompt y ofrece /compactar-ya—

El mod marchas actúa solo en el checkout principal de un repo con .orca-stack.json o .orca-stack.local.json cuyo contrato incluye la sección Marchas. Para mostrar la marcha actual, usá /marcha; para cambiarla, /marcha lazy, /marcha medium o /marcha proactive. Para apagarlo, corré claude plugin disable marchas@inline --scope user; usá --scope local para este repo en esta máquina o --scope project para el equipo.

Prerrequisitos

  • Node.js 20 o más nuevo (Pi pide Node 22.19 o más nuevo).
  • Git y GitHub CLI (gh), para el tablero y para el puente.
  • Claude Code, para los mods.
  • En Windows, el postinstall de gentle-pi compila el binario de gentle-ai con Go (1.25.10 o más nuevo): si pi install de gentle-pi falla, revisá que go esté en el PATH.

global detecta estas herramientas, no las instala; si faltan, imprime el comando oficial de cada una: Orca, engram, gentle-ai y Pi.

Uso

orca-stack global [--dry-run] [--force] [--skip-pi] [--limpiar-sdd] [--humano <nombre>]
orca-stack init   [--dry-run]
orca-stack doctor [--offline] [--skip-pi]
orca-stack remove [--dry-run] [--with-pi]
orca-stack sesiones [--desde <AAAA-MM-DD>] [--limite <n>]
orca-stack despachar <issue> <agente> [--nota "<texto>"] [--confirmado] [--perfil-pi <nombre>] [--dry-run]
orca-stack revisar <pr> <agente> [--nota "<texto>"] [--confirmado] [--perfil-pi <nombre>] [--dry-run]
orca-stack consultas <n...>
orca-stack avisar <issue|pr> <url-del-comentario> [--dry-run]
orca-stack reanudar <issue> <url-del-comentario> [--confirmado] [--dry-run]
orca-stack vigilar <n...> [--cada <segundos>] [--una-vez] [--dry-run] [--consultas]
orca-stack vigilar --merge-de-main <pr>
  • --dry-run cuenta cada acción sin escribir nada.
  • reanudar retoma una TUI detenida o relanza al worker en el mismo worktree con su brief original y la URL de respuesta.
  • --force reemplaza archivos que ya existían y no son de orca-stack (por ejemplo, una skill tuya llamada igual). Sin --force se saltean con un aviso ⚠ y quedan como estaban; con --force se respaldan antes.
  • global --limpiar-sdd respalda en ~/.orca-stack/backups/sdd-<fecha>/ y mueve solo restos conocidos; doctor lista los que encuentra y muestra el comando exacto. Los nombres desconocidos nunca se mueven y global sin esta opción no limpia nada. Si algún movimiento falla, informa qué quedó pendiente; podés volver a ejecutar el mismo comando.
  • init escribe en el AGENTS.md del proyecto el bloque <!-- orca-stack:begin --> … <!-- orca-stack:end --> con el contrato de trabajo completo (assets/stack/CONTRATO.md, igual en todos los proyectos) y las líneas de la política; a CLAUDE.md le pone un bloque corto con @AGENTS.md. Además crea .orca-stack.json y .orca-stack.local.json si faltan y agrega este último a .gitignore. Es idempotente y respalda lo que modifica. Los valores propios de cada proyecto no van en el bloque: viven en .orca-stack.json.
  • orca-setup es la skill con la que la sesión de main entrevista al humano, en una sola ronda, para completar .orca-stack.json ("setup": "completo"). La ofrece sola cuando falta y doctor avisa si quedó pendiente.
  • sesiones es de solo lectura: lista las sesiones recientes de Claude Code (~/.claude/projects y, si está, la carpeta de agentes.pi.claudeConfigDir), de Pi (~/.pi/agent/sessions) y de agy (~/.gemini/antigravity-cli, solo con Node 22.13 o más nuevo). Por sesión muestra la herramienta, la carpeta, inicio y fin, las llamadas, tus mensajes, las llamadas con error y los resultados de más de 15k caracteres. Es la entrada para quien corre /retro de Matt: --desde fija el día de inicio (por defecto, los últimos 2 días) y --limite cuántas sesiones (por defecto, 10).
  • consultas <n...> filtra y avisa consultas nuevas en issues o PRs de una tanda. Consulta gh api user en ejecución, busca comentarios de la cuenta del stack que empiecen con Consulta: e imprime consulta nueva en #<n> una sola vez por comentario, guardando los IDs en .git/orca-stack/consultas-reportadas.json.
  • vigilar <n...> es el Monitor de una tanda (<n...>, los issues de la tanda): stdout lleva solo eventos, uno por línea, y todo diagnóstico va a stderr. Cada --cada segundos (por defecto 60) lee gh pr list --state all (sin --state no aparecen los PRs mergeados ni cerrados) y emite pr-abierto, ci-verde, ci-roja (con los checks que fallaron), pr-mergeado, pr-cerrado, vigilar-ciego (tres vueltas seguidas sin poder leer GitHub, una vez por corte; nunca dice que no hay PRs) y, cuando terminaron todos los items, tanda-cerrada, y sale con 0. Un PR es del issue por su referencia de cierre, por la rama del worktree de este repo enlazado al issue (buscado como en avisar) o por una línea Closes #<n> en su cuerpo, nunca por el nombre de la rama; un issue cerrado sin PR cuenta como terminado. De dos corridas de un mismo check en un commit cuenta la última, y cada corrida que termina en rojo es un ci-roja, también un gh run rerun --failed que vuelve a fallar en el mismo commit; la misma corrida leída de nuevo no se repite. Lo emitido queda en .git/orca-stack/vigilar.json: rearmado con los mismos argumentos, retoma sin repetir nada. --una-vez consulta una vez y sale, --dry-run además no escribe nada, y --consultas corre en cada vuelta el chequeo de consultas para los mismos items, así Proactive sigue con un solo Monitor. Como todas las sesiones comparten la cuenta de gh, un merge de main se ve igual que uno del humano: main corre vigilar --merge-de-main <pr> justo antes de cada intento de gh pr merge <pr> (y de nuevo después de gh pr update-branch), que registra el head del PR en .git/orca-stack/vigilar-merges.json; un merge de ese head hecho dentro de los 30 minutos siguientes al registro (según el mergedAt del PR) no emite pr-mergeado, aunque el watcher lo vea más tarde. Con un PR ya mergeado o cerrado, --merge-de-main sale con 1 y no registra nada. El watcher solo lee ese archivo.
  • avisar <issue|pr> <url-del-comentario> es el timbre de Proactive: cuando main responde la pregunta de un worker, le escribe en su terminal una sola línea fija, Message from main: <url>, con la URL del comentario y nada de su texto. Encuentra la terminal por el worktree de este repo enlazado a <n> en orca worktree ps (con un PR, el de la rama del PR), buscado solo entre los de git worktree list, porque los selectores issue:<n> y branch: de Orca abarcan todos los repos; lista sus terminales con orca terminal list --worktree path:<ruta> y se niega si alguna no trae ese worktreePath. Si un rebote dejó dos, elige la del agente vivo según orca worktree ps. Manda solo mientras el turno del worker está en curso (estado working en Orca y el indicador de turno del agente en pantalla: el spinner de Claude, o en pi el marco del prompt de Gentle Shell con su fase, como ╭─ ❀ implementing…): se niega si el turno ya terminó, si la terminal muestra un shell o un diálogo, o si hay más de un agente vivo. Avisa a claude y a pi; se niega con codex y agy hasta que pasen su prueba de Enter a mitad de turno. Se niega si el comentario no es de la cuenta del stack (gh api user), si no está en <issue|pr> o si no empieza con Respuesta de main: o Respuesta del humano: (la misma cuenta publica las Consulta: de los workers). Envía una sola vez con --wait-submit: sin recibo de entrega informa la falla y no reenvía. --dry-run muestra la línea y la terminal elegida sin enviar nada. main nunca arma el timbre con llamadas sueltas a orca.
  • despachar y revisar (agentes: claude, agy, codex, pi) corren desde el checkout principal de un repo con el setup completo. Se niegan si el agente no está en agentes.usa, si está en agentes.preguntarAntes (repetí con --confirmado cuando el humano dijo que sí), si el issue está cerrado o asignado, si el revisor es el implementador del PR (línea Implementador:) o corre un modelo de su misma familia (sale de agentes.modelos; pi y claude sí se revisan entre sí), si el agente tiene una regla guardia.bloquear vigente, o si ya hay un worktree o un agente vivo para ese ticket. Antes de tocar nada hacen git fetch origin y comprueban que cada ruta que cita el brief (armado desde assets/stack/brief-ticket.md o brief-revision.md) exista en origin/<ramaBase> (en revisar, en la rama del PR): una ruta que falta o que git ignora aborta sin asignar ni crear nada. Si pasa todo, despachar asigna el issue (el assignee es el cerrojo y lo maneja el comando: no se asigna antes), y ambos crean el worktree con orca worktree create (así lo ve Orca), escriben el brief en ~/orca/briefs/, lanzan el agente en una terminal de Orca y le mandan el brief. despachar imprime Rama: <rama> con el nombre devuelto por Orca; en --dry-run aclara que Orca define la rama al crear el worktree. Después de confirmar el inicio, despachar, revisar y rebote leen tres veces la pantalla de cada terminal salvo pi, con pausas de 5 segundos: fallan si ven un mensaje de cuota o si el último renglón no vacío volvió al prompt de PowerShell (PS <unidad>:\...>). No detectan prompts de bash ni cmd.exe. Si algo falla después de crear el worktree, el mensaje lista lo que quedó (assignee, worktree, brief) y cómo recuperarlo, porque el cerrojo rechaza un reintento. Pi se lanza como TUI interactiva, como los demás agentes: pi --no-skills --skill <skills de gentle-pi> --session-id <id> --no-approve --exclude-tools ask_user_choice,ask_user_question "<brief>". Orca lo muestra en su tarjeta con sus estados y un turno que espera una verificación en segundo plano sigue cuando esta termina; nada espera a una persona (sin las herramientas de diálogo y sin el aviso de confianza del proyecto). El lanzamiento cuenta como iniciado cuando aparece una sesión nueva de Pi en ese worktree: si no aparece, despachar, revisar y rebote se niegan. A diferencia de la consulta, puede ejecutar git, gh y la suite. --nota agrega texto al brief y --dry-run muestra el plan y el brief sin escribir nada. Los modelos salen de agentes.modelos de tu config personal: un texto, { "modelo", "esfuerzo" } o { "implementar": {…}, "revisar": {…} } por agente.
  • --perfil-pi <nombre> (solo con pi) fija qué perfil de modelos de gentle-pi usa ese despacho, sin tocar el perfil global activo. Los perfiles viven en ~/.pi/gentle-ai/profiles.json; el comando se niega si el nombre no existe o si el clon ya fija otro perfil (<git-common-dir>/gentle-ai/profile-pin.json, que gana en silencio sobre el del worktree). Después de crear el worktree escribe el pin .pi/gentle-ai/profile.json ahí (gentle-pi lo lee en cada lanzamiento de subagente) y, si git no lo ignora, agrega /.pi/gentle-ai/profile.json a <git-common-dir>/info/exclude, así que nunca se commitea. Si el pin ya está versionado en el repo, lo deja como está cuando declara el mismo perfil y se niega (sin escribir) si declara otro; si git sigue sin ignorarlo después de la entrada (por ejemplo un .gitignore con !.pi/gentle-ai/profile.json), también se niega. Un thinking inválido en el perfil se avisa y se ignora. Como un pin no mueve al orquestador, lanza pi con --model <orchestrator.model del perfil> --thinking <orchestrator.thinking>. Con --dry-run cuenta todo esto sin escribir. agentes.pi.perfil: "<nombre>" lo fija para todos los despachos a pi y el flag gana. Sin el flag y sin agentes.pi.perfil (o con "preguntar"), despachar, revisar y rebote (este, si el worktree no tiene pin) se niegan antes de asignar o crear nada, también con --dry-run: Falta el perfil de Pi: pasá --perfil-pi <nombre> (hay: <names>) o poné agentes.pi.perfil en la config ("global" usa el perfil activo global a propósito). Con agentes.pi.perfil: "global" pi corre en el perfil activo global, como antes, e imprime perfil de Pi: global (activo: <nombre>); si profiles.json tiene un perfil llamado global, el valor es ambiguo y se niega, y si no tiene un perfil activo (o el activo no existe), también se niega, porque no hay perfil que comprobar. Solo se lanzan perfiles cuyo orquestador y subagentes usan claude-bridge/…, anthropic/… (el login OAuth de Anthropic en pi) u openai/…: con cualquier otro proveedor se niega y nombra cada agente y modelo; doctor avisa de cada perfil guardado que rompe esta regla. Cada lanzamiento de pi imprime perfil de Pi: <nombre> (fuente: flag | config | pin | global) y el brief guarda la misma línea. reanudar relanza un worker de pi con el orquestador del pin de su worktree; si el pin nombra un perfil que ya no existe, se niega y pide repetir con --perfil-pi <nombre>, que reescribe el pin.
  • guardia-despacho pregunta ese perfil por vos: cuando Claude corre orca-stack despachar|revisar <n> pi sin --perfil-pi y agentes.pi.perfil no es un nombre ni "global", abre el diálogo "Perfil Pi" con los perfiles de profiles.json en su orden (máximo cuatro opc
Source 4 files
hooks/register.tsx 451 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { Intercambio } from '../types'
4import {
5  BIG_PR_LINES,
6  ISSUE_FIELDS,
7  NOT_JSON,
8  PLANTEO_STORED,
9  PR_FIELDS_PRELOAD,
10  TIMEOUT_MS,
11  bigPrReason,
12  buildArgs,
13  buildMessage,
14  clock,
15  consultEnv,
16  diffUnavailable,
17  engramDir,
18  firstLine,
19  interpret,
20  isPathAbsolute,
21  issueFile,
22  joinPath,
23  launcherPath,
24  loadMemoria,
25  merges,
26  parsePiArgs,
27  piClaudeConfigDir,
28  piPrompt,
29  prFacts,
30  prFile,
31  prSize,
32  precargaSection,
33  preloadInputError,
34  readError,
35  remember,
36  riskDeny,
37  riskyFile,
38  section,
39  skillsInGlobal,
40  skillsInPi,
41  slug,
42  str,
43  truncate,
44  vista,
45} from './puente'
46import type { Memoria, Outcome } from './puente'
47import { hasProjectConfig, loadConfig } from './orca-config'
48import type { Host } from './orca-config'
49
50const PANE = 'gentle'
51const TOOL = 'mcp__puente-gentle__consultar_gentle_shell'
52const temas = { plugin: 'puente-gentle', key: 'temas' } as const
53const sel = { plugin: 'puente-gentle', key: 'sel' } as const
54
55const load = async ($: EngineInterface): Promise<Memoria> => loadMemoria(await $.store.get('temas'))
56
57const publish = async ($: EngineInterface, memoria: Memoria): Promise<void> => {
58  const list = vista(memoria)
59  await $.state.set(temas, list)
60  const current = (await $.state.get(sel)).value
61  if (current === undefined || !list.some(one => one.tema === current)) {
62    await $.state.set(sel, list[0]?.tema ?? '')
63  }
64}
65
66// The engine's `$` cannot cross an import: the config module gets these closures instead.
67const hostOf = ($: EngineInterface): Host => ({
68  home: async () => (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')),
69  exists: path => $.fs.exists(path),
70  read: path => $.fs.read(path),
71  git: argv => $.process.run(argv, { timeoutMs: 10_000 }),
72  now: () => $.clock.now(),
73})
74
75const homeDir = async ($: EngineInterface): Promise<string> =>
76  (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? ''
77
78const isWindows = async ($: EngineInterface): Promise<boolean> => (await $.env.get('OS')) === 'Windows_NT'
79
80// The launcher: node on the user's own Pi (~/.pi/agent, where Gentle Shell is installed and configured),
81// so multi-line arguments survive (a .cmd shim would cut them). Otherwise `pi` from the PATH.
82const launcher = async ($: EngineInterface): Promise<string[]> => {
83  const home = await homeDir($)
84  if (home !== '') {
85    const entry = launcherPath(home)
86    if (await $.fs.exists(entry)) {
87      return ['node', entry]
88    }
89  }
90
91  return [(await isWindows($)) ? 'pi.cmd' : 'pi']
92}
93
94// Gentle Shell's own skills dir, resolved from Pi's install first and the npm-global one second.
95// undefined when neither exists: the consult then loads no skills at all.
96const gentleSkills = async ($: EngineInterface): Promise<string | undefined> => {
97  const home = await homeDir($)
98  if (home !== '') {
99    const inPi = skillsInPi(home)
100    if (await $.fs.exists(inPi)) {
101      return inPi
102    }
103  }
104  try {
105    const npm = await $.process.run([(await isWindows($)) ? 'npm.cmd' : 'npm', 'root', '-g'], { timeoutMs: 15_000 })
106    if (npm.exitCode === 0 && npm.stdout.trim() !== '') {
107      const inGlobal = skillsInGlobal(npm.stdout.trim().split('\n')[0] ?? '')
108      if (await $.fs.exists(inGlobal)) {
109        return inGlobal
110      }
111    }
112  } catch {
113    // npm missing: no skills
114  }
115
116  return undefined
117}
118
119// Personal config only: where Pi's Claude provider gets its credentials (a separate account from this session's).
120const claudeConfigDir = async ($: EngineInterface): Promise<string | undefined> => {
121  const home = await homeDir($)
122  if (home === '') {
123    return undefined
124  }
125  const file = joinPath(home, '.orca-stack', 'config.json')
126  try {
127    return piClaudeConfigDir((await $.fs.exists(file)) ? await $.fs.read(file) : undefined, home)
128  } catch {
129    return undefined
130  }
131}
132
133// One gh read for the preload, run like the merge gate's (no cwd: the session's repo). An output the engine cut
134// counts as a failure, so a preloaded text is never passed on half.
135const ghRead = async ($: EngineInterface, argv: string[]): Promise<{ stdout: string } | { detail: string }> => {
136  try {
137    const run = await $.process.run(['gh', ...argv], { timeoutMs: 30_000 })
138    if (run.exitCode !== 0) {
139      return { detail: firstLine(run.stderr) || `gh salió con ${run.exitCode}` }
140    }
141
142    return run.isStdoutTruncated ? { detail: 'la salida pasa de 4 MiB y quedaría recortada' } : { stdout: run.stdout }
143  } catch (error) {
144    return { detail: error instanceof Error ? error.message : String(error) }
145  }
146}
147
148// Reads the issue and the PR with gh, then writes them under <git-common-dir>/orca-stack/gentle/, which Pi's read
149// reaches from any checkout of the repo. Nothing is written unless every view answered.
150const preload = async (
151  $: EngineInterface,
152  pr: number | undefined | null,
153  issue: number | undefined | null,
154): Promise<{ precarga: string } | { error: string }> => {
155  if (pr == null && issue == null) {
156    return { precarga: '' }
157  }
158  const files: { name: string; text: string }[] = []
159  let head: { pr: number; headRefOid: string } | undefined
160  if (issue != null) {
161    const read = await ghRead($, ['issue', 'view', String(issue), '--json', ISSUE_FIELDS])
162    const text = 'stdout' in read ? issueFile(read.stdout) : undefined
163    if (text === undefined) {
164      return { error: readError('el issue', issue, 'gh issue view', 'detail' in read ? read.detail : NOT_JSON) }
165    }
166    files.push({ name: `issue-${issue}.md`, text })
167  }
168  if (pr != null) {
169    const read = await ghRead($, ['pr', 'view', String(pr), '--json', PR_FIELDS_PRELOAD])
170    const view = 'stdout' in read ? prFile(read.stdout) : undefined
171    if (view === undefined) {
172      return { error: readError('el PR', pr, 'gh pr view', 'detail' in read ? read.detail : NOT_JSON) }
173    }
174    head = { pr, headRefOid: view.headRefOid }
175    const name = `pr-${pr}-${view.headRefOid.slice(0, 7)}`
176    files.push({ name: `${name}.md`, text: view.text })
177    // GitHub refuses very large diffs: the consult still runs, with the file list instead.
178    const diff = await ghRead($, ['pr', 'diff', String(pr)])
179    const list = 'detail' in diff ? await ghRead($, ['pr', 'view', String(pr), '--json', 'files']) : undefined
180    files.push({
181      name: `${name}.diff`,
182      text: 'stdout' in diff ? diff.stdout : diffUnavailable(pr, diff.detail, list !== undefined && 'stdout' in list ? list.stdout : undefined),
183    })
184  }
185  let common = ''
186  try {
187    const git = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], { timeoutMs: 10_000 })
188    common = git.exitCode === 0 ? firstLine(git.stdout) : ''
189  } catch {
190    common = ''
191  }
192  if (common === '') {
193    return { error: 'No encontré la carpeta git del repo con git rev-parse. No consulté a Gentle Shell.' }
194  }
195  if (!isPathAbsolute(common)) {
196    return { error: `La carpeta git del repo devuelta por git rev-parse no es una ruta absoluta (${common}). No consulté a Gentle Shell.` }
197  }
198  const paths: string[] = []
199  for (const file of files) {
200    const path = joinPath(common, 'orca-stack', 'gentle', file.name)
201    try {
202      await $.fs.write(path, file.text)
203    } catch (error) {
204      return { error: `No pude escribir ${path}: ${error instanceof Error ? error.message : String(error)}. No consulté a Gentle Shell.` }
205    }
206    paths.push(path)
207  }
208
209  return { precarga: precargaSection(paths, head) }
210}
211
212const consult = async (
213  $: EngineInterface,
214  modelo: string,
215  tema: string,
216  planteo: string,
217  pregunta: string,
218  precarga = '',
219): Promise<Outcome> => {
220  $.ui.toast(`Consultando a Gentle Shell (${tema})…`)
221  let outcome: Outcome
222  try {
223    const prefix = await launcher($)
224    const skills = await gentleSkills($)
225    const message = precarga === '' ? buildMessage(planteo, pregunta) : `${buildMessage(planteo, pregunta)}\n\n${precarga}`
226    const run = await $.process.run([...prefix, ...buildArgs(tema, modelo, message, skills)], {
227      env: consultEnv(engramDir(await homeDir($)), await claudeConfigDir($)),
228      // Pi in print mode waits for stdin to close: an open stdin hangs it forever.
229      stdin: '',
230      timeoutMs: TIMEOUT_MS,
231    })
232    outcome = interpret(run)
233  } catch (error) {
234    outcome = {
235      ok: false,
236      error: `No pude lanzar Gentle Shell: ${error instanceof Error ? error.message : String(error)}`,
237    }
238  }
239  if (outcome.ok) {
240    const item: Intercambio = {
241      at: await $.clock.now(),
242      pregunta,
243      planteo: truncate(planteo, PLANTEO_STORED),
244      respuesta: outcome.respuesta,
245    }
246    const memoria = remember(await load($), tema, item)
247    await $.store.set('temas', memoria)
248    await publish($, memoria)
249    $.ui.toast(`Gentle Shell respondió (${tema})`)
250  } else {
251    $.ui.toast(outcome.error)
252  }
253
254  return outcome
255}
256
257// A plugin tool's result is a string, a content array, or nothing: a plain string is the simplest valid shape.
258const textResult = (text: string) => ({ result: text })
259
260// Big PRs need a consult before they merge, only where the consult tool exists (a project with orca-stack config);
261// PRs touching a `riesgo` path need clean reviews of their head commit (riskDeny).
262const PR_FIELDS = 'additions,deletions,files,headRefOid,body,comments,reviews'
263
264const gate = async ($: EngineInterface, command: string) => {
265  for (const merge of merges(command)) {
266    let stdout: string | undefined
267    try {
268      const argv = ['gh', 'pr', 'view', merge.number, '--json', PR_FIELDS]
269      if (merge.repo !== undefined) {
270        argv.push('-R', merge.repo)
271      }
272      const run = await $.process.run(argv, { timeoutMs: 30000 })
273      stdout = run.exitCode === 0 ? run.stdout : undefined
274    } catch {
275      stdout = undefined
276    }
277    if (stdout === undefined) {
278      continue
279    }
280    const total = prSize(stdout)
281    if (
282      total !== undefined &&
283      total > BIG_PR_LINES &&
284      !(await load($))[`pr-${merge.number}`]?.length &&
285      (await hasProjectConfig(hostOf($)))
286    ) {
287      return { deny: bigPrReason(merge.number, total) }
288    }
289    const config = await loadConfig(hostOf($))
290    const globs = config.riesgo
291    const facts = Array.isArray(globs) && globs.length > 0 ? prFacts(stdout) : undefined
292    const risky = facts === undefined ? undefined : riskyFile(facts.files, globs ?? [])
293    const denied = facts === undefined || risky === undefined ? undefined : riskDeny(merge.number, risky, facts, config, await $.clock.now())
294    if (denied !== undefined) {
295      return { deny: denied }
296    }
297  }
298
299  return undefined
300}
301
302export const register: Register = (on, options) => {
303  const modelo = str(options['modelo']).trim()
304
305  on('session.start', async ($, e, next) => {
306    await $.command.register({
307      name: 'pi',
308      description: 'Consulta a Gentle Shell: /pi <tema>: <pregunta>',
309    })
310    await $.command.register({
311      name: 'gentle',
312      description: 'Abre el panel con las consultas a Gentle Shell',
313    })
314    // The tool (and the criterio section below) only exist in a repo with orca-stack config: `global` carries no methodology.
315    if (await hasProjectConfig(hostOf($))) {
316      await $.tool.register({
317        name: 'consultar_gentle_shell',
318        description:
319          'Consulta a Gentle Shell (Pi), otro orquestador par con otra metodología, en modo solo lectura. ' +
320          'Usalo en puntos de decisión. El planteo va neutral: problema, restricciones, nuestra propuesta y archivos relevantes.',
321        inputSchema: {
322          type: 'object',
323          properties: {
324            tema: { type: 'string', description: 'Slug corto del tema, por ejemplo pr-612 o auditoria. Misma conversaci\u00f3n por tema.' },
325            planteo: { type: 'string', description: 'Contexto neutral: el problema, las restricciones, nuestra propuesta actual y las rutas relevantes.' },
326            pregunta: { type: 'string', description: 'Lo que querés que opine.' },
327            pr: {
328              type: 'integer',
329              minimum: 1,
330              description: 'Opcional: número de PR. El mod lo lee con gh (cuerpo, comentarios, reviews y diff) y se lo pasa en archivos; no lo pegues en el planteo.',
331            },
332            issue: {
333              type: 'integer',
334              minimum: 1,
335              description: 'Opcional: número de issue. El mod lo lee con gh (cuerpo y comentarios) y se lo pasa en un archivo; no lo pegues en el planteo.',
336            },
337          },
338          required: ['tema', 'planteo', 'pregunta'],
339        },
340      })
341    }
342    await publish($, await load($))
343
344    return next(e)
345  })
346
347  // The tool the model calls.
348  on('tool.call', { tool: TOOL }, async ($, e) => {
349    const tema = slug(str(e['tema']))
350    const planteo = str(e['planteo'])
351    const pregunta = str(e['pregunta'])
352    if (tema === '' || planteo.trim() === '' || pregunta.trim() === '') {
353      return textResult(JSON.stringify({ error: 'Faltan tema, planteo o pregunta.' }))
354    }
355    const invalid = preloadInputError('pr', e['pr']) ?? preloadInputError('issue', e['issue'])
356    if (invalid !== undefined) {
357      return textResult(JSON.stringify({ tema, error: invalid }))
358    }
359    const loaded = await preload($, e['pr'] as number | undefined | null, e['issue'] as number | undefined | null)
360    if ('error' in loaded) {
361      return textResult(JSON.stringify({ tema, error: loaded.error }))
362    }
363    const outcome = await consult($, modelo, tema, planteo, pregunta, loaded.precarga)
364
365    return textResult(
366      JSON.stringify(outcome.ok ? { tema, respuesta: outcome.respuesta } : { tema, error: outcome.error }),
367    )
368  })
369
370  on('command.run', { command: 'pi' }, async ($, e) => {
371    const parsed = parsePiArgs(e.args)
372    if (parsed === undefined) {
373      return { text: 'Uso: /pi <tema>: <pregunta>  (por ejemplo: /pi pr-612: ¿ves riesgo en este merge?)' }
374    }
375    // Submitted from a timer so the command returns before the turn starts.
376    $.clock.after(0, () => {
377      void $.prompt.submit({ text: piPrompt(parsed.tema, parsed.pregunta), asUser: true })
378    })
379
380    return { text: `Consultando a Gentle Shell (tema ${parsed.tema})…` }
381  })
382
383  on('command.run', { command: 'gentle' }, async $ => {
384    await publish($, await load($))
385    await $.ui.open({ id: PANE, title: 'Gentle Shell' })
386
387    return { text: 'Panel de Gentle Shell abierto.' }
388  })
389
390  on('tool.call', { tool: 'Bash' }, async ($, e, next) => (await gate($, e.command)) ?? next(e))
391  on('tool.call', { tool: 'PowerShell' }, async ($, e, next) => (await gate($, e.command)) ?? next(e))
392
393  on('prompt.compose', async ($, e, next) => {
394    const composed = await next(e)
395    if (!(await hasProjectConfig(hostOf($)))) {
396      return composed
397    }
398    const humano = (await loadConfig(hostOf($))).humano
399
400    return {
401      sections: [
402        ...composed.sections,
403        { id: 'puente-gentle:criterio', text: section(typeof humano === 'string' ? humano : ''), scope: 'session' as const },
404      ],
405    }
406  })
407
408  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
409    const { Box, Button, Text } = $.ui.resolve(e)
410    const { value: list = [] } = await $.state.get(temas)
411    const { value: chosen = '' } = await $.state.get(sel)
412    if (list.length === 0) {
413      return <Text dimColor>Todavía no hay consultas. Usá /pi o dejá que Claude consulte a Gentle Shell.</Text>
414    }
415
416    return (
417      <Box flexDirection="column" gap={1}>
418        {list.map(entry => (
419          <Box key={`row:${entry.tema}`} flexDirection="column">
420            <Button
421              key={`tema:${entry.tema}`}
422              label={`${entry.tema === chosen ? '▾' : '▸'} ${entry.tema} (${entry.items.length})`}
423              onPress={async () => {
424                await $.state.set(sel, entry.tema)
425              }}
426            />
427            {entry.tema === chosen
428              ? entry.items.slice(0, 10).map((item, i) => (
429                  <Box key={`item:${entry.tema}:${i}`} flexDirection="column" marginLeft={2}>
430                    <Text bold>
431                      {clock(item.at)} · {item.pregunta}
432                    </Text>
433                    <Text>{item.respuesta}</Text>
434                    <Button
435                      key={`copy:${entry.tema}:${i}`}
436                      label="Copiar respuesta"
437                      onPress={async press => {
438                        const copied = await $.ui.copy({ text: item.respuesta, surface: press.surface })
439                        $.ui.toast(copied.isCopied ? 'Copiado' : 'No pude copiar: probá seleccionando el texto')
440                      }}
441                    />
442                  </Box>
443                ))
444              : null}
445          </Box>
446        ))}
447      </Box>
448    )
449  })
450}
451
hooks/puente.ts 623 lines
1import type { Intercambio } from '../types'
2import { FAMILIES, blockOf, familyOf } from './orca-config'
3import type { StackConfig } from './orca-config'
4
5export const READ_ONLY_TOOLS = 'read,grep,find,ls,codemode'
6// Variables this session inherits from its Orca terminal. A consult must not carry them: Pi's Orca
7// extensions would report as this terminal (Orca then sees this pane as `pi`), and the ORCA_STACK_* markers
8// belong to our stack, not to Gentle Shell's. Set over the host environment, an empty value unsets them.
9export const ORCA_VARS_CLEARED = [
10  'ORCA_AGENT_HOOK_ENDPOINT', 'ORCA_AGENT_HOOK_PORT', 'ORCA_AGENT_HOOK_TOKEN', 'ORCA_AGENT_HOOK_ENV',
11  'ORCA_AGENT_HOOK_VERSION', 'ORCA_AGENT_HOOK_TRANSPORT', 'ORCA_AGENT_LAUNCH', 'ORCA_AGENT_LAUNCH_TOKEN',
12  'ORCA_AGENT_PANE', 'ORCA_PANE_KEY', 'ORCA_TAB_ID', 'ORCA_WORKTREE_ID', 'ORCA_TERMINAL_HANDLE',
13  'ORCA_STACK_AGENT', 'ORCA_STACK_MODE', 'ORCA_STACK_POLICY_PATH', 'ORCA_STACK_PONYTAIL_LEVEL',
14  'ORCA_STACK_CAVEMAN_LEVEL',
15] as const
16
17// claudeConfigDir: the Claude account Pi's provider (pi-claude-bridge) uses; unset = the host's own.
18export const consultEnv = (engramPath: string, claudeConfigDir?: string): Record<string, string> => ({
19  ENGRAM_DATA_DIR: engramPath,
20  ...Object.fromEntries(ORCA_VARS_CLEARED.map(name => [name, ''])),
21  ...(claudeConfigDir === undefined ? {} : { CLAUDE_CONFIG_DIR: claudeConfigDir }),
22})
23
24// agentes.pi.claudeConfigDir from the text of the PERSONAL config (~/.orca-stack/config.json) only:
25// a committed project file must not redirect where Pi's credentials come from. A leading ~ is the home.
26export const piClaudeConfigDir = (personalConfig: string | undefined, home: string): string | undefined => {
27  if (personalConfig === undefined) {
28    return undefined
29  }
30  let dir: unknown
31  try {
32    dir = (JSON.parse(personalConfig.replace(/^/, '')) as { agentes?: { pi?: { claudeConfigDir?: unknown } } })
33      .agentes?.pi?.claudeConfigDir
34  } catch {
35    return undefined
36  }
37  if (typeof dir !== 'string' || dir.trim() === '') {
38    return undefined
39  }
40  const value = dir.trim()
41
42  if (value === '~') {
43    return home
44  }
45
46  return value.startsWith('~/') || value.startsWith('~\\') ? joinPath(home, value.slice(2)) : value
47}
48// Paths are built with the separator the base already uses (C:\Users\x on Windows, /home/x elsewhere).
49export const joinPath = (base: string, ...parts: string[]): string => {
50  const sep = base.includes('\\') ? '\\' : '/'
51  let root = base
52  while (root.length > 1 && (root.endsWith('/') || root.endsWith('\\'))) {
53    root = root.slice(0, -1)
54  }
55
56  return [root, ...parts].join(sep)
57}
58
59export const isPathAbsolute = (path: string): boolean =>
60  path.startsWith('/') || path.startsWith('\\') || /^[a-zA-Z]:[/\\]/.test(path)
61
62export const engramDir = (home: string): string => joinPath(home, '.gentle-shell', 'engram')
63export const launcherPath = (home: string): string => joinPath(home, '.pi', 'agent', 'bin', 'pi-launcher.js')
64
65// Gentle Shell's own skills (the only ones the consult loads: ~/.agents/skills holds our methodology,
66// which Pi would otherwise pick up). Pi's own package dir first, then the npm-global install.
67export const skillsInPi = (home: string): string =>
68  joinPath(home, '.pi', 'agent', 'npm', 'node_modules', 'gentle-pi', 'skills')
69export const skillsInGlobal = (npmRoot: string): string => joinPath(npmRoot.trim(), 'gentle-pi', 'skills')
70export const TIMEOUT_MS = 10 * 60 * 1000
71export const AUTH_MESSAGE =
72  'Gentle Shell no tiene una cuenta conectada: abrí una terminal, corré pi y usá /login.'
73export const BIG_PR_LINES = 400
74export const MAX_PER_TEMA = 20
75export const MAX_TEMAS = 30
76export const PLANTEO_STORED = 2000
77export const PLANTEO_SENT = 12000
78
79export const MARCO =
80  'Claude, otro orquestador del proyecto que trabaja con otra metodología, te consulta como par. ' +
81  'Trabajá con tu propio criterio y tu propia forma de trabajar; no adoptes la de quien te consulta. ' +
82  'Podés leer el código que necesites (solo lectura). ' +
83  'Respondé: cómo leés el problema, en qué coincidís y en qué no y por qué, qué riesgos ves, y qué harías distinto. ' +
84  'Si te falta información, decí cuál. ' +
85  'Estás en modo no interactivo: no uses herramientas de preguntas al usuario; poné tus preguntas en la respuesta.'
86
87export const section = (humano: string): string =>
88  'Gentle Shell (Pi) es otro orquestador, par con otra metodología; consultalo con `consultar_gentle_shell` en los puntos de decisión: ' +
89  'elegir entre enfoques, después de una propuesta o diseño, antes de mergear PRs grandes, y cuando la causa de un bug sigue sin estar clara después de un intento.\n' +
90  'El planteo va neutral: el problema, las restricciones, nuestra propuesta y los archivos. ' +
91  'Si la consulta es sobre un PR o un issue, pasá `pr` o `issue` en vez de pegar el cuerpo, los comentarios o el diff en el planteo: el mod los lee con gh y se los pasa en archivos. ' +
92  'No le mandes reglas del stack de Orca ni de nuestra metodología; AGENTS.md lo lee él solo.\n' +
93  `Si discrepa en algo material, mostrale ${humano.trim() === '' ? 'al usuario' : `a ${humano.trim()}`} las dos posturas con sus razones; no descartes su opinión por tu cuenta.`
94
95export const truncate = (text: string, max: number): string =>
96  text.length <= max ? text : `${text.slice(0, max)}… [recortado]`
97
98// A safe session-id / store key: lowercase, ascii, dashes.
99export const slug = (text: string): string =>
100  text
101    .normalize('NFD')
102    .replace(/[\u0300-\u036f]/g, '')
103    .toLowerCase()
104    .replace(/[^a-z0-9._-]+/g, '-')
105    .replace(/^-+|-+$/g, '')
106    .slice(0, 40)
107
108export const buildMessage = (planteo: string, pregunta: string): string =>
109  `## Planteo\n${truncate(planteo.trim(), PLANTEO_SENT)}\n\n## Pregunta\n${pregunta.trim()}`
110
111// Arguments after the launcher: every flag the bridge relies on, in one place.
112// --model is only passed when an override is set; otherwise Gentle Shell's own config picks the model.
113export const buildArgs = (tema: string, modelo: string, message: string, skills?: string): string[] => [
114  '-p',
115  '--mode',
116  'json',
117  '--no-skills',
118  ...(skills === undefined ? [] : ['--skill', skills]),
119  '--session-id',
120  `gentle-${tema}`,
121  '--tools',
122  READ_ONLY_TOOLS,
123  ...(modelo.trim() === '' ? [] : ['--model', modelo.trim()]),
124  '--append-system-prompt',
125  MARCO,
126  message,
127]
128
129// ---- preload: an issue or a PR, read with gh by the mod (Pi has no gh) and written to files Pi reads --------------
130// The message is a command-line argument, capped near 32767 characters on Windows: preloaded texts never go in it.
131
132export const ISSUE_FIELDS = 'number,title,url,body,comments'
133export const PR_FIELDS_PRELOAD = 'number,title,url,baseRefName,headRefOid,body,comments,reviews'
134
135// Absent (undefined or null), or a positive integer: anything else is refused before running gh.
136export const preloadInputError = (field: 'pr' | 'issue', value: unknown): string | undefined =>
137  value === undefined || value === null || (typeof value === 'number' && Number.isInteger(value) && value > 0)
138    ? undefined
139    : `El campo ${field} tiene que ser un entero positivo; recibí ${JSON.stringify(value)}. No consulté a Gentle Shell.`
140
141export const firstLine = (text: string): string => text.trim().split(/\r?\n/)[0] ?? ''
142
143export const readError = (what: 'el PR' | 'el issue', n: number, call: string, detail: string): string =>
144  `No pude leer ${what} #${n} con ${call}: ${detail}. No consulté a Gentle Shell.`
145
146export const NOT_JSON = 'la respuesta no es JSON válido'
147
148type Note = { author?: { login?: unknown }; createdAt?: unknown; submittedAt?: unknown; state?: unknown; body?: unknown }
149type Entry = { heading: string; at: string; body: string }
150
151export const str = (value: unknown): string => (typeof value === 'string' ? value : '')
152const parseObject = (stdout: string): Record<string, unknown> | undefined => {
153  try {
154    const data: unknown = JSON.parse(stdout)
155
156    return data !== null && typeof data === 'object' && !Array.isArray(data) ? (data as Record<string, unknown>) : undefined
157  } catch {
158    return undefined
159  }
160}
161const notes = (value: unknown): Note[] => (Array.isArray(value) ? (value as Note[]) : [])
162const entry = (heading: string, at: string, body: unknown, state = ''): Entry => ({
163  heading: [heading, at, state].filter(part => part !== '').join(' · '),
164  at,
165  body: str(body).trim(),
166})
167const entries = (title: string, list: Entry[]): string =>
168  `## ${title} (${list.length}), del más viejo al más nuevo\n` +
169  [...list]
170    .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
171    .map(one => `\n### ${one.heading}\n\n${one.body === '' ? '(sin texto)' : one.body}\n`)
172    .join('')
173
174// `gh issue view --json number,title,url,body,comments`, as a file; undefined when it is not a JSON object.
175export const issueFile = (stdout: string): string | undefined => {
176  const data = parseObject(stdout)
177  if (data === undefined) {
178    return undefined
179  }
180  const comments = notes(data['comments']).map(one => entry(str(one.author?.login), str(one.createdAt), one.body))
181
182  return `# Issue #${String(data['number'])}: ${str(data['title'])}\n\nURL: ${str(data['url'])}\n\n## Cuerpo\n\n${str(data['body']).trim()}\n\n${entries('Comentarios', comments)}`
183}
184
185// `gh pr view --json number,title,url,baseRefName,headRefOid,body,comments,reviews`, as a file with its head commit;
186// undefined when it is not a JSON object with a head commit of 40 hex characters.
187export const prFile = (stdout: string): { text: string; headRefOid: string } | undefined => {
188  const data = parseObject(stdout)
189  const headRefOid = str(data?.['headRefOid'])
190  if (data === undefined || !/^[0-9a-f]{40}$/.test(headRefOid)) {
191    return undefined
192  }
193  const list = [
194    ...notes(data['comments']).map(one => entry(`Comentario de ${str(one.author?.login)}`, str(one.createdAt), one.body)),
195    ...notes(data['reviews']).map(one => entry(`Review de ${str(one.author?.login)}`, str(one.submittedAt), one.body, str(one.state))),
196  ]
197  const text =
198    `# PR #${String(data['number'])}: ${str(data['title'])}\n\n` +
199    `URL: ${str(data['url'])}\nRama base: ${str(data['baseRefName'])}\nCommit de cabeza: ${headRefOid}\n\n` +
200    `## Cuerpo\n\n${str(data['body']).trim()}\n\n${entries('Comentarios y reviews', list)}`
201
202  return { text, headRefOid }
203}
204
205// The .diff file when `gh pr diff` gave nothing usable: why, and the files of `gh pr view <n> --json files` if it answered.
206export const diffUnavailable = (n: number, detail: string, filesStdout: string | undefined): string => {
207  const files = filesStdout === undefined ? [] : notes(parseObject(filesStdout)?.['files'])
208  const list = (files as { path?: unknown; additions?: unknown; deletions?: unknown }[])
209    .map(one => `- ${str(one.path)} (+${String(one.additions ?? 0)} -${String(one.deletions ?? 0)})\n`)
210    .join('')
211
212  return `diff no disponible: ${detail}\n${list === '' ? '' : `\nArchivos del PR (gh pr view ${n} --json files):\n${list}`}`
213}
214
215// The one section the message gains: where the files are and, for a PR, its full head commit.
216export const precargaSection = (paths: string[], head?: { pr: number; headRefOid: string }): string =>
217  '## Precarga\n' +
218  'Lo que sigue lo leyó el mod de GitHub con gh antes de lanzarte (vos no tenés gh); leé estos archivos con read:\n' +
219  paths.map(path => `- ${path}\n`).join('') +
220  (head === undefined ? '' : `Commit de cabeza del PR #${head.pr}: ${head.headRefOid}\n`)
221
222type Block = { type?: string; text?: string }
223type Message = {
224  role?: string
225  content?: unknown
226  stopReason?: string
227  errorMessage?: string
228}
229
230const textOf = (message: Message): string => {
231  if (typeof message.content === 'string') {
232    return message.content
233  }
234  if (!Array.isArray(message.content)) {
235    return ''
236  }
237
238  return (message.content as Block[])
239    .filter(block => block?.type === 'text' && typeof block.text === 'string')
240    .map(block => block.text)
241    .join('')
242}
243
244export type Parsed = { text: string; error?: string }
245
246type StreamEvent = {
247  type?: string
248  message?: Message
249  assistantMessageEvent?: { type?: string; delta?: string }
250}
251
252// The JSONL stream: the last completed assistant message is the answer (message_end is authoritative).
253export const parseStream = (stdout: string): Parsed => {
254  let last: Message | undefined
255  let deltas = ''
256  for (const raw of stdout.split('\n')) {
257    const line = raw.trim()
258    if (!line.startsWith('{')) {
259      continue
260    }
261    let event: StreamEvent
262    try {
263      event = JSON.parse(line) as StreamEvent
264    } catch {
265      continue
266    }
267    if (event.type === 'message_start' && event.message?.role === 'assistant') {
268      deltas = ''
269    } else if (event.type === 'message_update' && event.assistantMessageEvent?.type === 'text_delta') {
270      deltas += event.assistantMessageEvent.delta ?? ''
271    } else if (event.type === 'message_end' && event.message?.role === 'assistant') {
272      last = event.message
273    }
274  }
275  if (last === undefined) {
276    return { text: deltas.trim() }
277  }
278  const text = textOf(last).trim() || deltas.trim()
279  if (last.stopReason === 'error' || last.stopReason === 'aborted') {
280    return { text, error: last.errorMessage ?? `Gentle Shell terminó con ${last.stopReason}` }
281  }
282
283  return { text }
284}
285
286const AUTH = /no api key|\/login|not logged|unauthori[sz]ed|\b401\b|invalid api key|authentication|credential/i
287
288export const isAuthError = (text: string): boolean => AUTH.test(text)
289
290export type Outcome = { ok: true; respuesta: string } | { ok: false; error: string }
291
292export const interpret = (run: { exitCode: number; stdout: string; stderr: string }): Outcome => {
293  const parsed = parseStream(run.stdout)
294  const diagnostics = `${run.stderr}\n${parsed.error ?? ''}`
295  if (isAuthError(diagnostics)) {
296    return { ok: false, error: AUTH_MESSAGE }
297  }
298  if (run.exitCode !== 0 || parsed.error !== undefined) {
299    const detail = truncate((parsed.error ?? run.stderr).trim().split('\n')[0] ?? '', 300)
300
301    return { ok: false, error: `Gentle Shell falló (salida ${run.exitCode})${detail ? `: ${detail}` : ''}` }
302  }
303  if (parsed.text === '') {
304    return { ok: false, error: 'Gentle Shell no devolvió texto.' }
305  }
306
307  return { ok: true, respuesta: parsed.text }
308}
309
310// /pi <tema>: <pregunta>  - or just a question, whose first words become the tema.
311export const parsePiArgs = (args: string): { tema: string; pregunta: string } | undefined => {
312  const text = args.trim()
313  if (text === '') {
314    return undefined
315  }
316  const prefixed = /^([A-Za-z0-9._-]{1,40})\s*:\s*([\s\S]+)$/.exec(text)
317  if (prefixed?.[1] !== undefined && prefixed[2] !== undefined) {
318    const tema = slug(prefixed[1])
319    if (tema !== '') {
320      return { tema, pregunta: prefixed[2].trim() }
321    }
322  }
323  const derived = slug(text.split(/\s+/).slice(0, 4).join(' '))
324
325  return { tema: derived === '' ? 'consulta' : derived, pregunta: text }
326}
327
328export const piPrompt = (tema: string, pregunta: string): string =>
329  `Consultá a Gentle Shell (tema ${tema}) sobre: ${pregunta}. ` +
330  'Usá consultar_gentle_shell con un planteo neutral y después mostrame las dos posturas.'
331
332// ---- stored exchanges -------------------------------------------------------
333
334export type Memoria = Record<string, Intercambio[]>
335
336export const loadMemoria = (kept: unknown): Memoria =>
337  kept !== null && typeof kept === 'object' && !Array.isArray(kept) ? (kept as Memoria) : {}
338
339export const remember = (memoria: Memoria, tema: string, item: Intercambio): Memoria => {
340  const next: Memoria = { ...memoria, [tema]: [item, ...(memoria[tema] ?? [])].slice(0, MAX_PER_TEMA) }
341  const newest = (key: string): number => next[key]?.[0]?.at ?? 0
342  const kept = Object.keys(next)
343    .sort((a, b) => newest(b) - newest(a))
344    .slice(0, MAX_TEMAS)
345
346  return Object.fromEntries(kept.map(key => [key, next[key] ?? []]))
347}
348
349// Temas newest first, for the pane.
350export const vista = (memoria: Memoria): { tema: string; items: Intercambio[] }[] =>
351  Object.entries(memoria)
352    .map(([tema, items]) => ({ tema, items }))
353    .sort((a, b) => (b.items[0]?.at ?? 0) - (a.items[0]?.at ?? 0))
354
355// ---- merge gate -------------------------------------------------------------
356
357// Split a command on && || ; | and newlines, outside quotes.
358export const segments = (command: string): string[] => {
359  const out: string[] = []
360  let current = ''
361  let quote = ''
362  for (const ch of command) {
363    if (quote !== '') {
364      current += ch
365      if (ch === quote) {
366        quote = ''
367      }
368    } else if (ch === '"' || ch === "'") {
369      quote = ch
370      current += ch
371    } else if (ch === '&' || ch === '|' || ch === ';' || ch === '\n' || ch === '\r') {
372      out.push(current)
373      current = ''
374    } else {
375      current += ch
376    }
377  }
378  out.push(current)
379
380  return out.map(one => one.trim()).filter(one => one !== '')
381}
382
383const words = (segment: string): string[] =>
384  (segment.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map(word => word.replace(/^["']|["']$/g, ''))
385
386const VALUE_FLAGS = new Set(['-b', '--body', '-F', '--body-file', '-t', '--subject', '-A', '--author-email', '--match-head-commit'])
387const REPO_FLAGS = new Set(['-R', '--repo'])
388
389export type Merge = { number: string; repo?: string }
390
391// Every `gh pr merge <n>` in the command; a merge without a number is skipped.
392export const merges = (command: string): Merge[] => {
393  const found: Merge[] = []
394  for (const segment of segments(command)) {
395    const w = words(segment)
396    if (w[0] !== 'gh' && w[0] !== 'gh.exe') {
397      continue
398    }
399    let repo: string | undefined
400    const rest: string[] = []
401    for (let i = 1; i < w.length; i += 1) {
402      const word = w[i] ?? ''
403      if (REPO_FLAGS.has(word)) {
404        repo = w[i + 1]
405        i += 1
406      } else if (word.startsWith('--repo=')) {
407        repo = word.slice(7)
408      } else {
409        rest.push(word)
410      }
411    }
412    if (rest[0] !== 'pr' || rest[1] !== 'merge') {
413      continue
414    }
415    for (let i = 2; i < rest.length; i += 1) {
416      const word = rest[i] ?? ''
417      if (VALUE_FLAGS.has(word)) {
418        i += 1
419        continue
420      }
421      const match = /^(\d+)$/.exec(word) ?? /\/pull\/(\d+)/.exec(word)
422      if (match?.[1] !== undefined) {
423        found.push(repo === undefined ? { number: match[1] } : { number: match[1], repo })
424        break
425      }
426    }
427  }
428
429  return found
430}
431
432export const bigPrReason = (n: string, total: number): string =>
433  `PR #${n} grande (${total} líneas): consultá a Gentle Shell (tema pr-${n}) antes de mergear.`
434
435export const prSize = (stdout: string): number | undefined => {
436  try {
437    const data = JSON.parse(stdout) as { additions?: unknown; deletions?: unknown }
438    if (typeof data.additions === 'number' && typeof data.deletions === 'number') {
439      return data.additions + data.deletions
440    }
441  } catch {
442    // fall through
443  }
444
445  return undefined
446}
447
448// ---- risk-path trigger ------------------------------------------------------------------------
449
450// Minimal glob: * and ? stay inside one path segment, ** crosses segments, `**/` may match nothing,
451// a trailing / means "everything under". Node 20 has no path.matchesGlob.
452export const globToRegExp = (glob: string): RegExp => {
453  const g = glob.endsWith('/') ? `${glob}**` : glob
454  let out = ''
455  for (let i = 0; i < g.length; i += 1) {
456    const ch = g[i] ?? ''
457    if (ch === '*' && g[i + 1] === '*') {
458      i += 1
459      if (g[i + 1] === '/') {
460        i += 1
461        out += '(?:.*/)?'
462      } else {
463        out += '.*'
464      }
465    } else if (ch === '*') {
466      out += '[^/]*'
467    } else if (ch === '?') {
468      out += '[^/]'
469    } else {
470      out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&')
471    }
472  }
473
474  return new RegExp(`^${out}$`)
475}
476
477export const riskyFile = (files: string[], globs: string[]): string | undefined => {
478  const patterns = globs.filter(one => typeof one === 'string' && one.trim() !== '').map(one => globToRegExp(one.trim()))
479
480  return files.find(file => patterns.some(pattern => pattern.test(file.replace(/\\/g, '/'))))
481}
482
483export type PrFacts = { files: string[]; headRefOid: string; bodies: string[]; implementer: string | undefined }
484
485// Same parse as src/despacho.mjs (revisar): the first `Implementador: <agent>` line of the PR body, lowercased.
486export const implementerOf = (body: string): string | undefined =>
487  /^\s*Implementador:\s*(\S+)/im.exec(body)?.[1]?.trim().toLowerCase()
488
489// `gh pr view --json files,headRefOid,body,comments,reviews`: `gh pr review --comment` bodies live in `reviews`,
490// plain PR comments in `comments`. The PR body only says who implemented it; it is never a review.
491export const prFacts = (stdout: string): PrFacts | undefined => {
492  try {
493    const data = JSON.parse(stdout) as {
494      files?: { path?: unknown }[]
495      headRefOid?: unknown
496      body?: unknown
497      comments?: { body?: unknown }[]
498      reviews?: { body?: unknown }[]
499    }
500    if (typeof data.headRefOid !== 'string' || !Array.isArray(data.files)) {
501      return undefined
502    }
503    const bodies = [...(data.comments ?? []), ...(data.reviews ?? [])]
504      .map(one => one?.body)
505      .filter((body): body is string => typeof body === 'string')
506
507    return {
508      files: data.files.map(one => one?.path).filter((path): path is string => typeof path === 'string'),
509      headRefOid: data.headRefOid,
510      bodies,
511      implementer: typeof data.body === 'string' ? implementerOf(data.body) : undefined,
512    }
513  } catch {
514    return undefined
515  }
516}
517
518export type Review = { reviewer: string; clean: boolean }
519
520// The reviews of exactly this commit: `Revisor: <agent>` and `Commit: <sha>` among the first lines of one body (the
521// sha may be abbreviated to 7+ characters). Clean: the first non-empty line after `## BLOQUEA` is `nada`.
522export const reviewsOf = (bodies: string[], headRefOid: string): Review[] =>
523  bodies.flatMap(body => {
524    const lines = body.split(/\r?\n/).map(line => line.trim())
525    const head = lines.slice(0, 5)
526    const reviewer = head.map(line => /^Revisor:\s*(\S+)$/i.exec(line)?.[1]).find(name => name !== undefined)
527    const commit = head.map(line => /^Commit:\s*([0-9a-f]{7,40})$/i.exec(line)?.[1]).find(sha => sha !== undefined)
528    if (reviewer === undefined || commit === undefined || !headRefOid.toLowerCase().startsWith(commit.toLowerCase())) {
529      return []
530    }
531    const at = lines.findIndex(line => /^##\s*BLOQUEA\b/i.test(line))
532    const verdict = at < 0 ? undefined : lines.slice(at + 1).find(line => line !== '')
533
534    return [{ reviewer: reviewer.toLowerCase(), clean: verdict?.toLowerCase() === 'nada' }]
535  })
536
537// Why a PR touching a riesgo path cannot merge yet, or undefined. Every review counted is of the head commit.
538// - A review of the head commit with blockers stops it: on a riesgo path the human settles a blocker, not main.
539// - Implemented by pi: clean reviews from two model families other than pi's. A family comes from the model each
540//   reviewer has configured to review (familyOf); a reviewer whose model has no known family does not count.
541// - Implemented by anyone else: a clean pi review, the second review the contract asks for.
542export const riskDeny = (n: string, file: string, facts: PrFacts, config: StackConfig, now: number): string | undefined => {
543  const sha = facts.headRefOid.slice(0, 7)
544  const prefix = `PR #${n} toca una ruta de riesgo (${file})`
545  const agents: readonly string[] = FAMILIES.agents
546  if (facts.implementer === undefined || !agents.includes(facts.implementer)) {
547    return (
548      `${prefix} y su body no tiene una línea "Implementador: <agente>" con uno de ${agents.join(', ')}: ` +
549      `sin ella no sé quién puede revisarlo. Agregala con \`gh pr edit ${n} --body-file <archivo>\`.`
550    )
551  }
552  const reviews = reviewsOf(facts.bodies, facts.headRefOid)
553  const blocked = reviews.find(review => !review.clean)
554  if (blocked !== undefined) {
555    return (
556      `${prefix} y el review de ${blocked.reviewer} sobre el commit ${sha} tiene bloqueos. ` +
557      'En una ruta de riesgo un bloqueo no se salda con "Decidido por main": corregilo y pedí un review nuevo, o pasale la decisión al humano.'
558    )
559  }
560  const reviewers = [...new Set(reviews.map(review => review.reviewer))]
561  if (facts.implementer !== 'pi') {
562    return reviewers.includes('pi')
563      ? undefined
564      : `${prefix}: falta un review de pi sobre el commit ${sha}. Corré \`orca-stack revisar ${n} pi\` y mergeá cuando el review esté limpio.`
565  }
566
567  const own = familyOf(config, 'pi', 'ticket').family
568  const covered = new Set<string>()
569  const skipped: string[] = []
570  for (const reviewer of reviewers) {
571    const { family, model } = familyOf(config, reviewer, 'review')
572    if (!agents.includes(reviewer)) {
573      skipped.push(`${reviewer}: no es un agente del stack`)
574    } else if (family === undefined && model === undefined) {
575      skipped.push(`${reviewer}: no tiene modelo para revisar en agentes.modelos, así que no sé su familia`)
576    } else if (family === undefined) {
577      skipped.push(`${reviewer}: su modelo ${model} no tiene una familia reconocida (agregá su patrón en FAMILIES)`)
578    } else if (family !== own) {
579      covered.add(family)
580    }
581  }
582  if (covered.size >= 2) {
583    return undefined
584  }
585
586  // Who can still add a family: in agentes.usa (as revisar reads it), not blocked, with a known family that is neither
587  // pi's nor covered. Within a family, an agent that needs no OK from the human goes first.
588  const usa = config.agentes?.usa ?? []
589  const ask = config.agentes?.preguntarAntes ?? []
590  const options = new Map<string, string>()
591  for (const agent of agents) {
592    const { family } = familyOf(config, agent, 'review')
593    if (usa.includes(agent) && blockOf(config, agent, now) === undefined && family !== undefined && family !== own && !covered.has(family)) {
594      const current = options.get(family)
595      if (current === undefined || (ask.includes(current) && !ask.includes(agent))) options.set(family, agent)
596    }
597  }
598  const have = covered.size === 0 ? 'Hay 0' : `Hay 1 (${[...covered].join(', ')})`
599  const notCounted = skipped.length === 0 ? '' : ` No cuento ${skipped.join('; ')}.`
600  const missing = 2 - covered.size
601  const picks = [...options.values()].slice(0, missing)
602  const codexBlocked = usa.includes('codex') && blockOf(config, 'codex', now) !== undefined
603  const next =
604    picks.length < missing
605      ? codexBlocked
606        ? ' Esper\u00E1 a que codex vuelva.'
607        : ` Con los agentes disponibles (agentes.usa, sin bloqueos) no alcanzan las familias: decidilo con el humano.`
608      : ` Corré ${picks.map(agent => `\`orca-stack revisar ${n} ${agent}\``).join(' y ')}.` +
609        picks.filter(agent => ask.includes(agent)).map(agent => ` ${agent} está en preguntarAntes: pedile el OK al humano y agregá --confirmado.`).join('')
610
611  return (
612    `${prefix} y lo escribió pi: faltan reviews limpios sobre el commit ${sha} de dos familias de modelo distintas ` +
613    `que no sean la de pi (${own ?? '?'}). ${have}.${notCounted}${next}`
614  )
615}
616
617export const clock = (at: number): string => {
618  const d = new Date(at)
619  const pad = (n: number): string => String(n).padStart(2, '0')
620
621  return `${pad(d.getDate())}/${pad(d.getMonth() + 1)} ${pad(d.getHours())}:${pad(d.getMinutes())}`
622}
623
hooks/orca-config.ts 279 lines
1// Config resolution shared by the orca-stack mods. A plugin can only import files of its own folder,
2// so this file is copied verbatim into each mod that needs it (hooks/orca-config.ts); the repo's
3// tests fail if a copy drifts from this one (edit shared/orca-config.ts, then run `npm run sync-shared`).
4//
5// Three layers, later ones override earlier ones:
6//   1. ~/.orca-stack/config.json        (personal)
7//   2. <repo>/.orca-stack.json          (committed project rules)
8//   3. <repo>/.orca-stack.local.json    (gitignored, local/sensitive)
9// <repo> is the main checkout, even when the session runs inside a git worktree.
10
11export type BlockRule = { agente: string; hasta: string; motivo?: string }
12
13export type StackConfig = {
14  humano?: string
15  mensajes?: { destinatarios?: string[] }
16  despacho?: { script?: string; revisar?: string }
17  riesgo?: string[] // path globs whose change needs a second review before merging (pi, or two other model families when pi wrote it)
18  agentes?: {
19    usa?: string[]
20    preguntarAntes?: string[]
21    modelos?: Record<string, unknown>
22    pi?: { perfil?: string; claudeConfigDir?: string } // perfil: gentle-pi profile name, or "preguntar" (the default)
23  }
24  guardia?: {
25    bloquear?: BlockRule[]
26    modeloClaude?: string
27  }
28}
29
30// Model families. Two agents whose models share a family share blind spots: one does not review the other, and
31// they do not count as two independent reviews. The family comes from the model in `agentes.modelos` (the one the
32// launcher passes with --model): its name, without the provider prefix, against `patterns`, in order. An agent
33// with no model takes `defaults`; pi is `fixed`, because its launcher never passes a model. A model that matches
34// no pattern has no family: nothing is proved about it.
35// The literal between the markers is JSON: src/despacho.mjs keeps the same one, and test/units.test.mjs compares them.
36// BEGIN FAMILIES
37export const FAMILIES = {
38  "agents": ["claude", "agy", "codex", "pi"],
39  "fixed": { "pi": "claude" },
40  "defaults": { "claude": "claude", "codex": "gpt", "agy": "gemini" },
41  "patterns": [
42    ["claude", "^(claude|opus|sonnet|haiku|fable)"],
43    ["gpt", "^(gpt|codex|o\\d)"],
44    ["gemini", "^gemini"],
45    ["glm", "^glm"]
46  ]
47} as const
48// END FAMILIES
49
50const isPlain = (value: unknown): value is Record<string, unknown> =>
51  value !== null && typeof value === 'object' && !Array.isArray(value)
52
53export const familyOfModel = (model: string): string | undefined => {
54  const name = model.trim().toLowerCase().split('/').pop() ?? ''
55
56  return FAMILIES.patterns.find(([, pattern]) => new RegExp(pattern).test(name))?.[0]
57}
58
59// agentes.modelos.<agent>: "model", { modelo, esfuerzo } or { implementar: {...}, revisar: {...} } (as src/despacho.mjs).
60export const modelFor = (config: StackConfig, agent: string, mode: 'ticket' | 'review'): string | undefined => {
61  let entry = config.agentes?.modelos?.[agent]
62  if (isPlain(entry) && (entry['implementar'] !== undefined || entry['revisar'] !== undefined)) {
63    entry = entry[mode === 'review' ? 'revisar' : 'implementar']
64  }
65  const model = typeof entry === 'string' ? entry : isPlain(entry) ? entry['modelo'] : undefined
66
67  return typeof model === 'string' && model.trim() !== '' ? model.trim() : undefined
68}
69
70// The family `agent` runs on to implement ('ticket') or to review; `model` is the configured one, for messages.
71export const familyOf = (
72  config: StackConfig,
73  agent: string,
74  mode: 'ticket' | 'review',
75): { family: string | undefined; model: string | undefined } => {
76  const fixed = (FAMILIES.fixed as Record<string, string>)[agent]
77  if (fixed !== undefined) {
78    return { family: fixed, model: undefined }
79  }
80  const model = modelFor(config, agent, mode)
81
82  return { family: model === undefined ? (FAMILIES.defaults as Record<string, string>)[agent] : familyOfModel(model), model }
83}
84
85// "2026-10-29" -> local midnight of that day; an agent is blocked while now < that instant.
86export const parseUntil = (date: string): number | undefined => {
87  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date.trim())
88  if (match === null) {
89    return undefined
90  }
91  const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]
92  const at = new Date(year, month - 1, day)
93  // Round trip: 2026-02-30 would silently become 2026-03-02.
94  if (at.getFullYear() !== year || at.getMonth() !== month - 1 || at.getDate() !== day) {
95    return undefined
96  }
97
98  return at.getTime()
99}
100
101// Why `agent` cannot be dispatched now, or undefined. A rule with a bad date stops it too: a block must not
102// vanish because of a typo.
103export const blockOf = (config: StackConfig, agent: string, now: number): string | undefined => {
104  for (const rule of config.guardia?.bloquear ?? []) {
105    if (typeof rule?.agente !== 'string' || rule.agente.toLowerCase() !== agent.toLowerCase()) {
106      continue
107    }
108    const until = typeof rule.hasta === 'string' ? parseUntil(rule.hasta) : undefined
109    if (until === undefined) {
110      return `La regla guardia.bloquear de ${agent} tiene una fecha "hasta" que no es AAAA-MM-DD (${String(rule.hasta)}): corregila antes de despacharlo.`
111    }
112    if (now < until) {
113      return typeof rule.motivo === 'string' && rule.motivo.trim() !== '' ? rule.motivo : `${agent} está bloqueado hasta el ${rule.hasta}.`
114    }
115  }
116
117  return undefined
118}
119
120// Plain objects merge key by key; anything else (arrays included) is replaced by the later layer.
121const mergePlain = (...layers: unknown[]): Record<string, unknown> => {
122  const out: Record<string, unknown> = {}
123  for (const layer of layers) {
124    if (!isPlain(layer)) {
125      continue
126    }
127    for (const [key, value] of Object.entries(layer)) {
128      const before = out[key]
129      out[key] = isPlain(value) && isPlain(before) ? mergePlain(before, value) : value
130    }
131  }
132
133  return out
134}
135
136// One exception: `guardia.bloquear` adds up across the layers, so a block in one layer cannot be dropped by another.
137export const mergeConfig = (...layers: unknown[]): StackConfig => {
138  const out = mergePlain(...layers) as StackConfig
139  const rules = layers.flatMap(layer => {
140    const guardia = isPlain(layer) ? layer['guardia'] : undefined
141    const list = isPlain(guardia) ? guardia['bloquear'] : undefined
142
143    return Array.isArray(list) ? (list as BlockRule[]) : []
144  })
145  if (rules.length > 0) {
146    out.guardia = { ...out.guardia, bloquear: rules }
147  }
148
149  return out
150}
151
152export const parseJson = (text: string): unknown => {
153  try {
154    return JSON.parse(text.replace(/^/, ''))
155  } catch {
156    return undefined
157  }
158}
159
160const slashed = (path: string): string => {
161  let out = path.split('\\').join('/')
162  while (out.length > 1 && out.endsWith('/')) {
163    out = out.slice(0, -1)
164  }
165
166  return out
167}
168
169// Output of `git rev-parse --path-format=absolute --git-common-dir --show-toplevel`:
170// the main checkout is the parent of the common `.git` dir; a bare repo falls back to the toplevel.
171export const repoRootFrom = (stdout: string): string | undefined => {
172  const [common, top] = stdout.split(/\r?\n/).map(line => line.trim())
173  if (common !== undefined && common !== '') {
174    const dir = slashed(common)
175    if (dir.endsWith('/.git')) {
176      return dir.slice(0, -'/.git'.length)
177    }
178  }
179
180  return top === undefined || top === '' ? undefined : slashed(top)
181}
182
183// The engine's `$` cannot cross an import, so the host passes the few operations this module needs
184// as closures: { home: async () => (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')), exists: p => $.fs.exists(p), read: p => $.fs.read(p),
185// git: argv => $.process.run(argv, { timeoutMs: 10_000 }), now: () => $.clock.now() }.
186export type Host = {
187  home: () => Promise<string | undefined>
188  exists: (path: string) => Promise<boolean>
189  read: (path: string) => Promise<string>
190  git: (argv: string[]) => Promise<{ exitCode: number; stdout: string }>
191  now: () => Promise<number>
192}
193
194export const homeOf = async (host: Host): Promise<string | undefined> => {
195  let home: string | undefined
196  try {
197    home = await host.home()
198  } catch {
199    home = undefined
200  }
201
202  return home === undefined || home === '' ? undefined : slashed(home)
203}
204
205const readLayer = async (host: Host, path: string): Promise<unknown> => {
206  try {
207    if (!(await host.exists(path))) {
208      return undefined
209    }
210
211    return parseJson(await host.read(path))
212  } catch {
213    return undefined
214  }
215}
216
217export const repoRoot = async (host: Host): Promise<string | undefined> => {
218  try {
219    const git = await host.git(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel'])
220
221    return git.exitCode === 0 ? repoRootFrom(git.stdout) : undefined
222  } catch {
223    return undefined
224  }
225}
226
227// Whether the repo opted into orca-stack, with `.orca-stack.json` or `.orca-stack.local.json`: mods that inject text
228// into the session, or that gate on it, only do so in such a project.
229export const hasProjectConfig = async (host: Host): Promise<boolean> => {
230  const root = await repoRoot(host)
231  if (root === undefined) {
232    return false
233  }
234  for (const name of ['.orca-stack.json', '.orca-stack.local.json']) {
235    try {
236      if (await host.exists(`${root}/${name}`)) {
237        return true
238      }
239    } catch {
240      // An unreadable layer counts as missing.
241    }
242  }
243
244  return false
245}
246
247const loadFor = async (host: Host, home: string | undefined, root: string | undefined): Promise<StackConfig> =>
248  mergeConfig(
249    home === undefined ? undefined : await readLayer(host, `${home}/.orca-stack/config.json`),
250    root === undefined ? undefined : await readLayer(host, `${root}/.orca-stack.json`),
251    root === undefined ? undefined : await readLayer(host, `${root}/.orca-stack.local.json`),
252  )
253
254// Never throws: a missing or broken layer is skipped.
255export const loadConfig = async (host: Host): Promise<StackConfig> =>
256  loadFor(host, await homeOf(host), await repoRoot(host))
257
258// loadConfig with a short memory, for hooks that run on every tool call. The memory is keyed by the
259// resolved home and repo root, so switching to another checkout never serves the previous one's rules.
260let remembered: { key: string; at: number; config: StackConfig } | undefined
261
262export const currentConfig = async (host: Host, maxAgeMs = 30_000): Promise<StackConfig> => {
263  const home = await homeOf(host)
264  const root = await repoRoot(host)
265  const key = `${home ?? ''}|${root ?? ''}`
266  const now = await host.now()
267  if (remembered !== undefined && remembered.key === key && now - remembered.at < maxAgeMs) {
268    return remembered.config
269  }
270  const config = await loadFor(host, home, root)
271  remembered = { key, at: now, config }
272
273  return config
274}
275
276export const forgetConfig = (): void => {
277  remembered = undefined
278}
279
types/index.d.ts 15 lines
1export type Intercambio = {
2  at: number
3  pregunta: string
4  planteo: string
5  respuesta: string
6}
7
8export type TemaVista = { tema: string; items: Intercambio[] }
9
10declare module 'claude-code' {
11  interface PluginState {
12    'puente-gentle': { temas: TemaVista[]; sel: string }
13  }
14}
15