SLOPSHOPPER

orquestrador

Painel lateral e flow declarado para orquestrar changes com várias sessões do Claude Code: grill, mockup, plano OpenSpec, fases com gates de qualidade, PR, QA…

panebandguardcommandprompttool
v0.13.1MITupdated 2026-10-23chacal88/orquestrador/orquestrador
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · orquestrador
│ ┃ 🧭 Orquestrador ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ card:self │ ⏺ Read(src/auth.ts) │ ┃ │ │ ⎿ Read 6 lines │ ┃ │ Sem lista de tarefas ainda │ ⏺ Update(src/auth.ts) │ ┃ ╰──────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ Sessões filhas indisponíveis: o app não ⎿ 3 pass, 1 fail │ ┃ expõe a lista de sessões aqui. │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /orquestrador │ ⎿ orquestrador: Painel do orquestrador aberto. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · 🧭 Orquestrador
╭──────────────────────────────────────────────────────────╮ │ card:self │ │ │ │ Sem lista de tarefas ainda │ ╰──────────────────────────────────────────────────────────╯ Sessões filhas indisponíveis: o app não expõe a lista de sessões aqui.
Pane · ⚙️ Workflows
Workflows ───────────────────────────────────────────────────────────… Os caminhos que uma change pode seguir neste projeto, e o que vale para todos eles. ╭─────────────────────────────────────────────────────────── │ Este projeto ╭──────────────────────────────────────────── │ │ inativo neste clone │ ╰──────────────────────────────────────────── │ │ O orquestrador está quieto aqui: sem painel abrindo │ sozinho, sem regras do flow e sem barrar merge. As │ configurações abaixo ficam guardadas, sem efeito. │ │ Idioma Português nas caixas e nos textos │ │ Merge Na main, por squash ╭────────────────────────── │ │ você faz │ ╰────────────────────────── │ │ Deploy Espera o CI ╭────────────────────────────────── │ │ você confirma │ ╰────────────────────────────────── │ │ Vale para os passos de merge e deploy de todos os │ workflows, a menos que um passo diga outra coisa. │ │ [ Ativar neste clone ] [ Configurar ] ╰─────────────────────────────────────────────────────────── PADRÕES DO PLUGIN ╭──────────────────────────────────────────────────────────╮ │ wf-open:completo 13 passos │ │ Do entendimento ao arquivamento: grill com o dono, │ │ mockup quando a change é visual, plano OpenSpec revisado │ │ e liberado pelo dono, fases com seus portões, revisão, │ │ PR, QA e produção. │ │ ╭──────────────────────────────────────────────────────╮ │ │ │ sem passo de merge │ │ │ ╰──────────────────────────────────────────────────────╯ │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ wf-open:rapido 9 passos │ │ Para changes pequenas: plano curto (proposta e tarefas), │ │ fases, revisão de qualidade, checagem, PR, QA e │ │ produção. │ │ ╭──────────────────────────────────────────────────────╮ │ │ │ sem passo de merge │ │ │ ╰──────────────────────────────────────────────────────╯ │ ╰──────────────────────────────────────────────────────────╯ Novo workflow Nome: ex.: Dev e master ⏎ ok Como ele aparece na lista. O id do arquivo sai do nome. Começar de: Do zero — nenhum passo ▾ Partindo de um existente, ele guarda só o que você mudar. [ Criar e editar ]
README

Orquestrador

Plugin para o Claude Code que orquestra uma change com várias sessões em paralelo e mostra tudo num painel lateral: em que passo o trabalho está, o que cada sessão está fazendo, quais gates de qualidade passaram e o que espera uma decisão sua.

A Claude Code plugin (mod) that orchestrates a change across parallel sessions through a declared flow, with a live side panel and owner decisions as panel buttons. The UI speaks Brazilian Portuguese or English, set per project (see "Idioma").

O que ele faz

  • Flow declarado. O trabalho segue um flow escrito em arquivo, passo a passo. Cada passo diz quem responde:
  • sessão: uma sessão faz o trabalho e informa o resultado;
  • automático: o mod observa um comando rodar, e o código de saída decide;
  • dono: só um clique seu no painel responde, e nenhuma sessão responde por você.
  • Dois flows prontos:
  • completo: grill → mockup → plano OpenSpec → validação → revisão do plano → liberação do dono pelo plan mode → fases → revisão de código → checagem final → PR → QA → produção → arquivamento;
  • rapido, para correções pequenas.
  • Um projeto pode ter flows próprios em .orquestrador/flows/*.json, escritos do zero ou derivados de outro (veja Workflows do projeto).
  • Ao iniciar uma change, a coordenação sempre mostra os workflows disponíveis para você escolher.
  • Passos descritos a fundo, com agente especialista. Cada passo diz o que recebe, o que produz e o que bloqueia. Cada passo de sessão nomeia o agente que o executa, com modelo e esforço. O plugin traz nove agentes em orquestrador/agents/: planejador, revisor-plano, executor, revisor-codigo, abre-pr, publicador, merge, merge-pelo-workflow e deploy. Um projeto troca qualquer um deles com um arquivo de mesmo nome em .orquestrador/agents/.
  • Revisão do PR, merge e deploy como passos. Servem para projetos trunk-based (um merge na main) e para projetos dev/master (merge em dev para o QA, em master para a produção).
  • Merge automático, com dois agentes à escolha no passo. merge (o padrão) só mergeia com o PR aprovado no GitHub, o CI verde e os portões finais passados. merge-pelo-workflow mergeia quando o workflow aprovou (a revisão de código do flow aprovada, os portões finais passados e o CI verde se houver) e não exige aprovação no GitHub. O mod recusa gh pr merge antes da revisão do PR e, enquanto um passo de revisão de código (agente revisor-codigo ou id revisao-codigo) antes do merge não estiver aprovado desde a última volta do flow; recusa --admin sempre. Um passo de revisão de código (agente revisor-codigo ou id revisao-codigo) precisa declarar o outcome aprovado, que a coordenação reporta; o flow que não o declara é recusado ao carregar. O PR da change é reconhecido também pela nota do passo que o abre (agente abre-pr ou publicador).
  • Deploy: espera o deploy do CI, roda rotinas fora do CI, ou faz os dois; pode ser automático, logo depois do merge.
  • Painel ⚙️ Workflows (/orquestrador-workflows). Fica separado do painel 🧭 e mostra os workflows disponíveis com a configuração de cada passo. Ali você também cria e edita os workflows do projeto.
  • Gates de qualidade por fase. São checagens como testes, lint, check.sh, openspec validate, print da tela e revisão de regras:
  • comprovação: o mod só aceita um gate quando vê o comando rodar e passar;
  • validade: editar arquivos depois da comprovação desatualiza o gate;
  • pulo: só você pula um gate, com dois cliques.
  • Painel lateral (/orquestrador). Mostra o andamento da change, o OpenSpec (proposta, tarefas e evidência), os gates do flow, o que precisa de você e as tarefas de cada fase com a sessão que as executa. Uma faixa acima do campo de mensagem resume o estado.
  • Grill com respostas no painel. As rodadas de perguntas viram critérios de aceite, e você responde cada pergunta num campo do próprio painel.
  • Sessões em paralelo. Cada fase roda numa sessão própria, com teto de 3 sessões vivas. As sessões entram sozinhas no grupo da change na barra lateral e são arquivadas quando a fase fecha.
  • Seguir o flow sem clique. Opção do cartão "Este projeto" no painel ⚙️. Desligada por padrão e só nesta máquina. Ligada, o painel avisa a coordenação cada vez que uma sessão do flow termina, e ela abre as próximas sessões em seu nome, sem cartão para clicar. Se o flow não anda depois de vários avisos, o painel para de avisar e mostra um aviso ao dono.
  • Jira com o seu ok. O painel avisa quando uma issue deve mudar de estado e só a move depois do seu clique.

A skill change-orchestrator, que vem junto, ensina a sessão coordenadora a seguir o flow: ela pergunta ao mod qual é o próximo passo em vez de decidir sozinha.

Requisitos

  • Claude Code com suporte a mods (plugins de function hooks).
  • O app desktop do Claude Code para a experiência completa: painel lateral, plan mode e gestão de sessões e da barra lateral. No terminal, o painel e o flow funcionam, mas as ações sobre outras sessões dependem das ferramentas do app.
  • Opcional: OpenSpec no projeto e o conector Atlassian para o Jira.

Instalação

Dentro do Claude Code:

/plugin marketplace add chacal88/orquestrador
/plugin install orquestrador@orquestrador

Ou pelo terminal:

claude plugin marketplace add chacal88/orquestrador
claude plugin install orquestrador@orquestrador

Depois de instalar, reinicie o app ou rode /reload-plugins.

Instalar num projeto

Num projeto novo, rode na sessão:

/orquestrador:instalar

A skill instalar analisa o projeto (CI, testes, cobertura, lint, tipos, build, formatação, OpenSpec, branch padrão e proteção), roda cada comando candidato uma vez e recomenda só os que passam. Depois pergunta, um bloco por vez e sempre com a recomendação: o workflow base, os portões, o merge, o deploy e o idioma. Com o seu ok, grava .orquestrador/config.json e .orquestrador/flows/<id>.json, confere que o mod os carrega e commita numa branch, sem push. Ela nunca ativa o orquestrador: no fim, abra /orquestrador-workflows e aperte "Ativar neste clone" no cartão "Este projeto" (veja Ativar neste clone).

Uso

  1. Instalado, o plugin fica quieto até você ativá-lo no clone (veja Ativar neste clone).
  2. Peça à sessão para orquestrar uma change, ou use a skill change-orchestrator.
  3. Escolha um dos workflows que a coordenação mostra e abra o painel com /orquestrador.
  4. Acompanhe pelo painel e responda os seus passos pelos botões.

Para ver ou editar os workflows do projeto, abra /orquestrador-workflows.

Ativar neste clone

As configurações do projeto ficam em .orquestrador/config.json e vão para o git. O que liga o orquestrador é local, deste clone, e nunca vai para o repositório: quem clona o projeto não é afetado.

  • Quieto sem ativação. Num clone que não foi ativado, o plugin não abre o painel 🧭 sozinho, não desenha a faixa acima do prompt, não põe regras do flow na conversa e não recusa merge nem portões. /orquestrador e /orquestrador-workflows continuam disponíveis, e o cartão "Este projeto" do painel ⚙️ mostra o estado "inativo neste clone". Uma change com flow em andamento no clone continua funcionando mesmo sem ativação, para nada parar no meio.
  • Ativar. No painel ⚙️ Workflows, "Este projeto" → "Ativar neste clone": escolha o nível e confirme.
  • Barrar (padrão): segue o flow e recusa merge e deploy fora dele, --admin e portões abertos.
  • Lembrar: o flow e as regras entram na conversa, mas nada é bloqueado; cada recusa do "barrar" vira só um aviso (merge com --admin, merge sem revisão e pulo de portões passam; ficam no log do flow e no painel). Os registros de portão do mod continuam protegidos. O .claude/settings.local.json é só do painel. O que vale é o nível que o painel gravou: o plugin guarda esse nível no estado dele (que nenhuma ferramenta do modelo grava), por repositório. Uma marca "lembrar" que o painel não gravou (escrita à mão ou pelo modelo) vale como "barrar" e o painel avisa para confirmar; "barrar" vale sempre; uma marca apagada fora do painel também vale "barrar". Se a marca ou os flows não puderem ser lidos, o plugin falha fechado ("barrar"); só a ausência confirmada de marca e de flow deixa o clone quieto. Além disso, com o plugin ativo, Edit, Write ou shell que mencionem o arquivo são recusados (comparação sem diferenciar maiúsculas); essa recusa por texto é só uma primeira barreira, fácil de contornar. Num clone inativo o arquivo é livre. "Barrar" é um freio do plugin, não uma barreira. A trava de verdade é a proteção de branch do GitHub (revisão obrigatória, sem --admin). Um hook que o modelo ponha em outro arquivo de settings (por exemplo .claude/settings.json ou os do usuário) fica fora do alcance do plugin. Com o clone ativo, o cartão oferece "Trocar para lembrar/barrar" e "Desativar neste clone".
  • O que é gravado, e só isso, em .claude/settings.local.json do repositório principal (as worktrees usam o dele; o Claude Code recarrega o arquivo sem reiniciar):
  {
    "env": { "ORQUESTRADOR": "barrar" },
    "hooks": {
      "SessionStart": [
        { "hooks": [ { "type": "command", "command": "printf '%s\\n' \"Orquestrador ativo neste clone (nível: ${ORQUESTRADOR:-barrar}). …\" # orquestrador:ativar" } ] }
      ]
    }
  }

env.ORQUESTRADOR é a marca (barrar ou lembrar); o hook SessionStart imprime um lembrete do flow e das regras, que entra como contexto de cada sessão. O hook se reconhece pelo # orquestrador:ativar no fim do comando.

  • Desativar tira só a marca e esse hook, preserva todo o resto do arquivo e remove as chaves env e hooks que ficarem vazias. Um settings.local.json que não seja um JSON válido não é gravado: o painel diz por quê e o arquivo fica como está.
  • Fora do git. O Claude Code põe .claude/settings.local.json no exclude global do git ao criá-lo; se o plugin criar o arquivo e ele não estiver ignorado, acrescenta a linha ao .git/info/exclude do clone, nunca ao .gitignore. Hooks do git e CLAUDE.local.md não são usados.

Workflows do projeto

Um projeto tem os workflows padrão (completo, rapido) e os seus, em .orquestrador/flows/<id>.json. Um workflow do projeto com o mesmo id de um padrão passa a valer no lugar dele. Uma change em andamento continua com o workflow com que começou, mesmo que o arquivo mude depois.

Pelo painel ⚙️ Workflows

/orquestrador-workflows abre e fecha o painel. Ele pode ficar aberto ao lado do 🧭.

  • Visão: a lista de workflows, com a origem de cada um (padrão, do projeto ou derivado de outro) e os arquivos com erro. Ao abrir um workflow, você vê os passos em ordem. Cada passo mostra:
  • quem responde e o que entra, sai e bloqueia;
  • o agente, de onde ele vem, o modelo e o esforço;
  • o comando, quando há;
  • no merge, a branch, o método e se é automático;
  • no deploy, o CI, as rotinas e se é automático.
  • Edição: "Novo workflow", do zero ou a partir de outro, ou "Editar" num existente. Num passo aberto você pode:
  • ligá-lo ou desligá-lo, e subi-lo ou descê-lo;
  • trocar o agente, o modelo e o esforço;
  • configurar merge e deploy;
  • acrescentar um passo depois dele, da biblioteca ou novo.

Tudo fica em rascunho até você clicar em "Salvar" ou "Descartar".

  • Salvar: o mod confere o workflow como se fosse carregá-lo. Se algo estiver inválido, mostra o erro e não grava nada. Com base, grava no formato derivado; do zero, grava os passos completos. Editar um padrão cria o workflow do projeto de mesmo id, com aviso.

Workflow derivado

Parte de outro (padrão ou do projeto) e diz só o que muda. Exemplo de um projeto trunk-based, com revisão do PR, merge automático na main e deploy pelo CI com uma rotina a mais:

{
  "id": "trunk",
  "title": "Trunk-based",
  "base": "completo",
  "remove": ["mockup", "qa"],
  "add": [
    { "after": "pr", "step": "revisao-pr" },
    { "after": "revisao-pr", "step": { "use": "merge", "merge": { "branch": "main", "auto": true } } },
    { "after": "merge", "step": { "use": "deploy", "deploy": { "ci": true, "commands": ["npm run migrate:prod"], "auto": true } } }
  ],
  "override": { "revisao-codigo": { "model": "claude-sonnet-5-5" } }
}
  • remove: os passos que saem. O mod liga o passo anterior ao seguinte. O laço executar não pode sair.
  • add: { "after": "<id>", "step": ... }. O step pode ser:
  • um id da biblioteca;
  • { "use": "<id da biblioteca>", ...ajustes }, com id próprio quando há mais de um, como merge-dev e merge-main;
  • um passo completo.
  • override: campos por passo, sem mudar id nem kind.
  • order: os ids na ordem final, opcional.

Num projeto dev/master, use dois merges: merge-dev (com "branch": "dev"), seguido do QA, e merge-main (com "branch": "master"), seguido da produção.

Biblioteca de passos

  • revisao-pr: passo do dono. Você revisa e aprova o PR no GitHub e aperta "PR aprovado". Enquanto ele não for respondido, o mod recusa o gh pr merge da change.
  • merge, com { "branch", "method", "auto" }. O método padrão é squash.
  • Com auto: false, o passo é seu: o botão, ou o mod vê o seu gh pr merge passar.
  • Com auto: true, o passo é automático. A coordenação confere a aprovação e o CI e roda gh pr merge --<method> sozinha. O --admin é sempre recusado.
  • "agent": "merge" (padrão) exige a aprovação no GitHub e o CI verde. "agent": "merge-pelo-workflow" troca a aprovação no GitHub pela do workflow: a revisão de código do flow aprovada, os portões finais passados e o CI verde se houver. O painel explica os dois no passo Merge.

Publicação automática (este repositório)

O Rápido deste repositório (.orquestrador/flows/rapido.json, com o .orquestrador/config.json) publica sem a conferência do dono: planejar, validar, executar, revisão de código, checagem (plugin test), tipos (tsc), publicar, merge automático com merge-pelo-workflow, deploy automático (as rotinas de update do plugin, vindas do config.json), lançar a versão (release) e fim. O /reload-plugins segue com você: nenhuma rotina o roda.

  • deploy, com { "ci", "commands", "auto" }.
  • ci: espera o deploy do CI. O botão "Deploy do CI concluído" confirma, ou o mod vê gh run watch … --exit-status passar.
  • commands: as rotinas fora do CI, rodadas na ordem, cada uma como comando próprio.
  • O passo só avança com tudo cumprido. As rotinas também contam como sinal do passo producao.
  • Também estão na biblioteca os passos dos workflows padrão, como qa, producao e mockup, para reaproveitar.

Agentes

Cada passo pode ter agent, model, effort e details (inputs, produces, blocks). flow status diz à coordenação qual agente usar no passo atual, com o caminho do arquivo. Para trocar um agente num projeto, crie .orquestrador/agents/<nome>.md com o mesmo nome do agente do plugin.

Workflow do zero

Formato:

{
  "id": "investigacao",
  "title": "Investigação",
  "description": "Descobrir a causa de um problema.",
  "steps": [
    { "id": "grill", "title": "Entendimento", "kind": "owner",
      "outcomes": { "fechado": { "label": "Entendimento fechado", "next": "investigar" } } },
    { "id": "investigar", "title": "Investigar", "kind": "session",
      "outcomes": { "concluido": { "label": "Fatos levantados", "next": "revisao" } } },
    { "id": "revisao", "title": "Revisão do dono", "kind": "owner",
      "outcomes": { "aprovado": { "label": "Aprovar", "next": "fim" },
                    "aprofundar": { "label": "Aprofundar", "next": "investigar" } } }
  ]
}

Tipos de passo: session, automatic (com command), owner e loop (sobre as fases do tasks.md). Campos opcionais: maxAttempts (padrão 3, depois escala para o dono), when: "visual", detect, cleanup, jira, details, agent, model, effort, merge e deploy.

title, description e label aceitam texto simples ou um texto por idioma, como { "pt-BR": "Investigar", "en": "Investigate" }. Quando falta o idioma pedido, o painel usa o outro.

Idioma

Cada projeto escolhe o idioma em .orquestrador/config.json, em dois eixos independentes:

{ "language": { "ui": "en", "content": "pt-BR" } }
  • ui, caixas e títulos: cabeçalhos das caixas, botões, status, a faixa acima do prompt, os avisos, os títulos dos passos do flow e os rótulos das respostas.
  • content, descrições e textos da change: a descrição do flow e de cada passo. Também o idioma em que a sessão coordenadora escreve proposta, tarefas, perguntas do grill, títulos e notas das fases e perguntas ao dono. O mod informa esse idioma nas respostas das ferramentas flow e plano.

Idiomas: pt-BR e en. "language": "en" vale para os dois eixos. Sem o arquivo, fica pt-BR nos dois. Um valor desconhecido também fica em pt-BR, e o painel avisa. O exemplo acima mostra as fases em inglês e os textos dos itens em português.

Configurações do projeto

O mesmo .orquestrador/config.json guarda o padrão dos passos de merge e deploy de todos os workflows do projeto, ao lado do language:

{
  "language": { "ui": "pt-BR", "content": "pt-BR" },
  "merge": { "auto": false, "branch": "main", "method": "squash" },
  "deploy": { "auto": false, "ci": true, "commands": ["npm run migrate:prod"] }
}
  • Herança: um passo merge ou deploy recebe do projeto cada campo que o workflow não escreveu. Um campo escrito no workflow vence. auto do projeto decide se um passo da biblioteca (use: "merge" / use: "deploy") é do dono ou automático; um passo escrito à mão mantém o tipo que declarou. Uma change em andamento segue com o flow com que começou.
  • Valor errado: vira um aviso com o nome do campo e é ignorado, nunca adivinhado.
  • Onde ver: flow status e flow list dizem quais campos vieram do projeto.
  • Painel ⚙️ Workflows: o cartão "Este projeto", no topo, resume idioma, merge e deploy; "Configurar" abre a edição em rascunho (nada é gravado até "Salvar", que só muda as chaves alteradas e preserva as outras do arquivo). O bloco "Nos workflows" mostra se cada workflow usa o do projeto, tem valor próprio ("Passar a usar o do projeto") ou não tem passo de merge/deploy ("Acrescentar merge e deploy"); as duas ações pedem confirmação e gravam pelo mesmo caminho do editor de workflows.

Desenvolvimento

O código fica em orquestrador/hooks/, os tipos em orquestrador/types/ e os testes em orquestrador/tests/.

claude plugin test orquestrador
claude plugin validate orquestrador

O plano e o histórico de decisões estão em orquestrador/proposal.md, orquestrador/tasks.md e orquestrador/evidence.md.

Licença

MIT. Veja LICENSE.

Source 25 files
hooks/register.tsx 2196 lines
1import { update } from 'claude-code'
2import type { EngineInterface, Register, ToolCallResult } from 'claude-code'
3
4import type {
5  ActivationLevel,
6  ActivityRecord,
7  Attention,
8  FlowDef,
9  FlowEvent,
10  FlowState,
11  FlowView,
12  GateAttempt,
13  GateCheck,
14  GrillAnswer,
15  PrepState,
16  PrepView,
17  GateRecord,
18  GateSkip,
19  GateView,
20  JiraIssue,
21  Languages,
22  JiraMove,
23  JiraTransition,
24  OpenSpecView,
25  OrchestrationRun,
26  PanelView,
27  PlanItem,
28  SessionCard,
29  SessionRow,
30  Waiting,
31} from '../types'
32import {
33  FINAL_SCOPE,
34  GATE_IDS,
35  ARCHIVE_COMMAND,
36  GH_MERGE,
37  MAX_LIVE_SESSIONS,
38  PROTECTED_DIR,
39  familyCheck,
40  gateViews,
41  isOpenGate,
42  liveSessions,
43  isChangeBranch,
44  mergeCalls,
45  opaqueMerge,
46  mergeTarget,
47  mergeWindow,
48  classifyBash,
49  executedText,
50  keepAttempt,
51  mergeRecords,
52  observeTool,
53  phaseRefusal,
54} from './gates'
55import type { MergeCall, MergeTarget } from './gates'
56import {
57  DEFAULT_FLOW_IDS,
58  applyOutcome,
59  automaticOutcome,
60  currentStep,
61  describeFlow,
62  describeStepAgent,
63  describeWorkflow,
64  detectedOutcome,
65  executedTextShort,
66  noteOwnerStep,
67  observeDeploy,
68  pendingReview,
69  pendingCodeReview,
70  flowView,
71  outcomeLabel,
72  stepTitle,
73  ownerPress,
74  pressedToast,
75  wakePrompt,
76  startFlow,
77} from './flow'
78import type { Moved } from './flow'
79import { closePhase, finishLoop, isClosed, loopRefusal, loopUnits, phaseSessions, uncommitted, unitRefusal, withEvents } from './lifecycle'
80import {
81  MOCKUP_STEP,
82  RELEASE_OUTCOME,
83  RELEASE_STEP,
84  answersPrompt,
85  approvePlan,
86  attachMockup,
87  describePrep,
88  emptyPrep,
89  grillMarkdown,
90  parseRoundItems,
91  planVerdict,
92  pressMockup,
93  ownerAnswers,
94  prepView,
95  recordRound,
96  rejectPlan,
97} from './grill'
98import { bandSummary, parseEvents, stepTimes } from './glance'
99import { DEFAULT_LANGUAGES, contentRule, uiText } from './i18n'
100import type { UiText } from './i18n'
101import { renderBand, renderPane } from './pane'
102import { readActivation, readAutowake, registryDir } from './activation'
103import { STOP_AS_USER, childStops, eligibleChildren, flowProgress, sessionRef, stopPrompt } from './wake'
104import { WORKFLOWS_PANE, drawWorkflows, startWorkflowsLoad, toggleWorkflowsPane } from './workflows-pane'
105import { findAgent, loadConfig as loadProjectConfig, loadFlows } from './flow-files'
106import { firstSite, issueUrl, jiraKeys, moveFor, parseIssue, parseTransitions, wishes } from './jira'
107import { changeDir, openSpecView } from './openspec'
108import {
109  activityFor,
110  activityKey,
111  applyPlanUpdate,
112  changePrs,
113  closedByFlow,
114  finishedSessionIds,
115  completePlan,
116  parseRun,
117  parseSessionRows,
118  findGroupId,
119  groupIds,
120  groupsLegible,
121  inPlan,
122  startedSessionId,
123  groupName,
124  phaseCounts,
125  phaseViews,
126  repoWebUrl,
127  runKey,
128  sessionActivityKey,
129  toCard,
130  withFlowStatus,
131} from './model'
132
133const PANE = 'orquestrador'
134/** Typed as string: the laid MCP types predate this mod's own tool. */
135const PLAN_TOOL: string = 'mcp__orquestrador__plano'
136const FLOW_TOOL: string = 'mcp__orquestrador__flow'
137const LIST_SESSIONS = 'mcp__ccd_session_mgmt__list_sessions'
138const GET_SESSION = 'mcp__ccd_session_mgmt__get_session'
139const OPEN_SESSION = 'mcp__ccd_window__open_session_in'
140const LIST_GROUPS = 'mcp__ccd_sidebar__list_groups'
141const CREATE_GROUP = 'mcp__ccd_sidebar__create_group'
142const MOVE_SESSIONS = 'mcp__ccd_sidebar__move_sessions'
143const DELETE_GROUP = 'mcp__ccd_sidebar__delete_group'
144const REFRESH_MS = 15_000
145/** Jira is asked again at most this often; the panel refreshes every 15 s. */
146const JIRA_TTL_MS = 120_000
147
148const VIEW = { plugin: 'orquestrador', key: 'view' } as const
149const PLAN = { plugin: 'orquestrador', key: 'plan' } as const
150const COLLAPSED = { plugin: 'orquestrador', key: 'collapsed' } as const
151const WAITING = { plugin: 'orquestrador', key: 'waiting' } as const
152const ANSWERED = { plugin: 'orquestrador', key: 'answered' } as const
153const GATES_SEEN = { plugin: 'orquestrador', key: 'gates' } as const
154const EDITED_AT = { plugin: 'orquestrador', key: 'editedAt' } as const
155const TRIED = { plugin: 'orquestrador', key: 'tried' } as const
156const SELF_ID = { plugin: 'orquestrador', key: 'selfId' } as const
157const ACTIVITY_TTL_MS = 7 * 24 * 60 * 60 * 1000
158const PANE_OPEN = { plugin: 'orquestrador', key: 'paneOpen' } as const
159const REMINDED = { plugin: 'orquestrador', key: 'reminded' } as const
160const RUNNING = { plugin: 'orquestrador', key: 'running' } as const
161const AUTOWAKE_SEEN = { plugin: 'orquestrador', key: 'autowake-seen' } as const
162const AUTOWAKE_PENDING = { plugin: 'orquestrador', key: 'autowake-pending' } as const
163const AUTOWAKE_BRAKE = { plugin: 'orquestrador', key: 'autowake-brake' } as const
164/** Stops of one child told while the flow does not move (`flowProgress`), before the mod stops telling that child. */
165const AUTOWAKE_MAX_SAME_CHILD = 3
166/** Stops told to the coordination while the flow does not move, any child, before the mod stops telling at all. */
167const AUTOWAKE_MAX_SAME_PROGRESS = 10
168const GRILL_DRAFTS = { plugin: 'orquestrador', key: 'grillDrafts' } as const
169const START_SESSION = 'mcp__ccd_session__start_session'
170const TRANSITION_SUFFIX = '__transitionJiraIssue'
171const ARCHIVE_SESSION = 'mcp__ccd_session_mgmt__archive_session'
172const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
173
174const GATES_DESCRIPTION =
175  `Gate ids this phase must pass before it may be marked done or its session archived: ${GATE_IDS.join(', ')}. ` +
176  'The mod watches the phase session run them (it never re-runs them); only the owner can skip one, from the panel.'
177
178const PLAN_SCHEMA = {
179  type: 'object',
180  properties: {
181    change: { type: 'string', description: 'Change id (e.g. the OpenSpec change folder name).' },
182    changePath: {
183      type: 'string',
184      description:
185        'Path to the change folder (absolute, or relative to this checkout); the panel reads its ' +
186        'tasks.md, proposal.md and evidence.md from there.',
187    },
188    jira: { type: 'string', description: 'Jira issue key of the whole change (e.g. the epic), "PROJ-123".' },
189    jiraSite: {
190      type: 'string',
191      description: 'Jira site host, e.g. "acme.atlassian.net"; omit to use the Atlassian connector\'s first site.',
192    },
193    waves: {
194      type: 'array',
195      description: 'Waves in order; a wave holds phases that may run in parallel.',
196      items: {
197        type: 'object',
198        properties: {
199          title: { type: 'string' },
200          jira: { type: 'string', description: 'Jira issue key this wave maps to, if any.' },
201          summary: {
202            type: 'string',
203            description: 'What this wave delivers and why it comes at this point, in 1-2 plain sentences (pt-BR).',
204          },
205          phases: {
206            type: 'array',
207            items: {
208              type: 'object',
209              properties: {
210                id: { type: 'string', description: 'Short phase id, e.g. "4.x".' },
211                title: { type: 'string' },
212                icon: { type: 'string', description: 'The phase icon from the orchestrator table.' },
213                tasks: { type: 'string', description: 'Task numbers, e.g. "4.1–4.3".' },
214                status: { type: 'string', enum: ['pending', 'running', 'blocked', 'done'] },
215                session: {
216                  type: 'string',
217                  description: 'The session doing it: its name, id or a unique part of its title.',
218                },
219                dependsOn: { type: 'array', items: { type: 'string' }, description: 'Phase ids it waits on.' },
220                note: { type: 'string', description: 'One line: result, blocker or next step.' },
221                jira: { type: 'string', description: 'Jira issue key this phase maps to, e.g. "PROJ-45".' },
222                gates: { type: 'array', items: { type: 'string', enum: GATE_IDS }, description: GATES_DESCRIPTION },
223                summary: {
224                  type: 'string',
225                  description:
226                    'What this phase is about, in 1-3 plain sentences (pt-BR): what it changes and why. ' +
227                    'Shown when the owner hovers the phase, so they recall it long after planning.',
228                },
229              },
230              required: ['id', 'title', 'status'],
231            },
232          },
233        },
234        required: ['phases'],
235      },
236    },
237    finalGates: {
238      type: 'array',
239      items: { type: 'string', enum: GATE_IDS },
240      description:
241        'Gates the whole change passes once, at the end (e.g. "check"): until they pass, `gh pr merge` is refused ' +
242        'in this session. Prefer heavy gates here over repeating them in every phase.',
243    },
244    ownerQuestions: {
245      type: 'array',
246      description: 'Decisions pending on the owner, each with a recommendation and where it lives.',
247      items: {
248        type: 'object',
249        properties: {
250          question: { type: 'string', description: 'The decision, as a question (pt-BR).' },
251          recommendation: {
252            type: 'string',
253            description: 'What you recommend; "Aceitar" sends it back to you as the owner\'s answer.',
254          },
255          session: { type: 'string', description: 'The session it concerns, when not this one.' },
256          pr: { type: 'number', description: 'The PR number it concerns, if any.' },
257          gate: {
258            type: 'object',
259            description:
260              'When the question is whether to skip a gate: the phase id (or "final" for finalGates) and the gate. ' +
261              'The panel then offers that skip on the question itself; "Aceitar" never skips a gate.',
262            properties: {
263              phase: { type: 'string' },
264              gate: { type: 'string', enum: GATE_IDS },
265            },
266            required: ['phase', 'gate'],
267          },
268        },
269        required: ['question'],
270      },
271    },
272  },
273  required: ['change', 'waves'],
274}
275
276type CallResult = { text?: string; deny?: string; isError?: boolean }
277
278/** The app's own tools are not in this mod's typed tool list until it loads beside them. */
279const callTool = ($: EngineInterface, input: Record<string, unknown>): Promise<CallResult> =>
280  $.tool.call(input as never) as Promise<CallResult>
281
282const baseDir = async ($: EngineInterface): Promise<string> => registryDir($)
283
284const readJson = async <T,>($: EngineInterface, path: string): Promise<T | undefined> => {
285  try {
286    if (!(await $.fs.exists(path))) return undefined
287    return JSON.parse(await $.fs.read(path)) as T
288  } catch {
289    return undefined
290  }
291}
292
293/**
294 * This session's id in the app's list, asked once and kept: `$.session.id()` names the
295 * transcript, which is not the id the family's rows carry. Undefined outside the app.
296 */
297const selfId = async ($: EngineInterface): Promise<string | undefined> => {
298  const { value: known } = await $.state.get(SELF_ID)
299  if (known !== undefined) return known
300  if (!(await canCall($, GET_SESSION))) return undefined
301  const [row] = parseSessionRows((await callTool($, { tool: GET_SESSION, session_id: 'self' })).text)
302  if (row !== undefined) await $.state.set(SELF_ID, row.sessionId)
303  return row?.sessionId
304}
305
306/** Keyed by the session's id when known, so a phase in the coordinator's folder has a file of its own. */
307const activityPath = async ($: EngineInterface, sessionId: string | undefined, cwd: string): Promise<string> =>
308  `${await baseDir($)}/sessions/${sessionId === undefined ? activityKey(cwd) : sessionActivityKey(sessionId)}.json`
309
310const publishActivity = async ($: EngineInterface, lastTool: string | undefined): Promise<void> => {
311  // root, not cwd: a shell `cd` inside the session must not move where it publishes
312  const cwd = await $.session.root()
313  const sessionId = await selfId($).catch(() => undefined)
314  const { value: plan = [] } = await $.state.get(PLAN)
315  const { value: waiting } = await $.state.get(WAITING)
316  const { records, editedAt, tried } = await ownCheck($)
317  const record: ActivityRecord = {
318    sessionId, cwd, plan, lastTool, waiting: waiting ?? undefined, updatedAt: await $.clock.now(), gates: records, editedAt, tried,
319  }
320  await $.fs.write(await activityPath($, sessionId, cwd), JSON.stringify(record))
321}
322
323const ownCheck = async ($: EngineInterface): Promise<GateCheck> => {
324  const { value: records = {} } = await $.state.get(GATES_SEEN)
325  const { value: editedAt } = await $.state.get(EDITED_AT)
326  const { value: tried = [] } = await $.state.get(TRIED)
327  return { records, editedAt: editedAt ?? undefined, tried }
328}
329
330/** Sets or clears why this session stands still; other sessions' panels read it from the activity file. */
331const setWaiting = async ($: EngineInterface, waiting: Omit<Waiting, 'since'> | null): Promise<void> => {
332  const value = waiting === null ? null : { ...waiting, since: await $.clock.now() }
333  await $.state.set(WAITING, value)
334  await publishActivity($, undefined).catch(() => undefined)
335}
336
337const toolLabel = (tool: string): string => tool.replace(/^mcp__[^_]+(?:_[^_]+)*?__/, '').replace(/_/g, ' ')
338
339const canCall = async ($: EngineInterface, tool: string): Promise<boolean> => {
340  const tools = await $.tool.list()
341  return tools.some(t => t.name === tool)
342}
343
344const loadRun = async ($: EngineInterface, cwd: string): Promise<OrchestrationRun | undefined> => {
345  const dir = `${await baseDir($)}/runs`
346  if (!(await $.fs.exists(dir))) return undefined
347  const files = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.json'))
348  const runs = await Promise.all(files.map(f => readJson<OrchestrationRun>($, `${dir}/${f.name}`)))
349  return runs
350    .filter((run): run is OrchestrationRun => run?.coordinatorCwd === cwd)
351    .sort((a, b) => b.updatedAt - a.updatedAt)[0]
352}
353
354const describeError = (step: string, error: unknown): string =>
355  `${step}: ${error instanceof Error ? error.message.slice(0, 160) : 'falhou'}`
356
357/** $.state takes JSON data only: an `undefined` field anywhere refuses the whole write. */
358const asJson = <T,>(value: T): T => JSON.parse(JSON.stringify(value)) as T
359
360const loadSessions = async (
361  $: EngineInterface,
362  base: string,
363  ownPlan: PlanItem[],
364): Promise<{ self: SessionCard | undefined; children: SessionCard[] }> => {
365  const [selfRow] = parseSessionRows((await callTool($, { tool: GET_SESSION, session_id: 'self' })).text)
366  const family = parseSessionRows((await callTool($, { tool: LIST_SESSIONS, linked: true, limit: 50 })).text)
367  const grouped =
368    selfRow?.groupId === undefined
369      ? []
370      : parseSessionRows((await callTool($, { tool: LIST_SESSIONS, group: selfRow.groupId, limit: 50 })).text)
371
372  const others = new Map<string, SessionRow>()
373  for (const row of [...family, ...grouped]) {
374    if (!row.isArchived && row.sessionId !== selfRow?.sessionId) others.set(row.sessionId, row)
375  }
376  const dir = `${base}/sessions`
377  const files = (await $.fs.exists(dir)) ? await $.fs.list(dir) : []
378  // a file per session id is never removed (the mod cannot delete), so a refresh skips the
379  // ones untouched for a week instead of opening every session this machine ever ran
380  const cutoff = (await $.clock.now()) - ACTIVITY_TTL_MS
381  const fresh = files.filter(f => f.name.endsWith('.json') && f.mtimeMs >= cutoff)
382  const records = (await Promise.all(fresh.map(f => readJson<ActivityRecord>($, `${dir}/${f.name}`)))).filter(
383    (r): r is ActivityRecord => r !== undefined,
384  )
385  const children = [...others.values()].map(row => toCard(row, activityFor(records, row, selfRow?.cwd)))
386  const self =
387    selfRow === undefined
388      ? undefined
389      : { ...toCard(selfRow, undefined), plan: ownPlan, hasActivity: true, gates: await ownCheck($) }
390  return { self, children }
391}
392
393const readText = async ($: EngineInterface, path: string): Promise<string | undefined> =>
394  (await $.fs.exists(path)) ? $.fs.read(path) : undefined
395
396/** The project's languages from `<repo>/.orquestrador/config.json`, read fresh: an edit shows on the next refresh. */
397const loadConfig = async ($: EngineInterface): Promise<{ languages: Languages; problems: string[] }> => loadProjectConfig($)
398
399/** The owner's words now, for a toast raised outside the pane. */
400const textNow = async ($: EngineInterface): Promise<UiText> =>
401  uiText((await loadConfig($).catch(() => ({ languages: DEFAULT_LANGUAGES }))).languages.ui)
402
403const loadOpenSpec = async ($: EngineInterface, run: OrchestrationRun, t: UiText): Promise<OpenSpecView | undefined> => {
404  if (run.changePath === undefined) return undefined
405  const home = (await $.env.get('HOME')) ?? ''
406  const dir = changeDir(run.changePath.replace(/^~(?=\/)/, home), run.coordinatorCwd)
407  const [tasks, proposal, evidence] = await Promise.all(
408    ['tasks.md', 'proposal.md', 'evidence.md'].map(name => readText($, `${dir}/${name}`)),
409  )
410  if (tasks === undefined && proposal === undefined) return undefined
411  return openSpecView({ tasks, proposal, evidence }, t)
412}
413
414/** The module's own memory: it starts over on a reload, which only costs one fresh fetch. */
415const jiraCache = new Map<string, { issue: JiraIssue; at: number }>()
416
417const findTool = async ($: EngineInterface, suffix: string): Promise<string | undefined> =>
418  (await $.tool.list()).find(t => t.name.endsWith(suffix))?.name
419
420/**
421 * Status and title of every issue the plan names, through whichever Atlassian connector
422 * this session has. Without one, or with no site it can reach, each key keeps its link only.
423 */
424const loadJira = async (
425  $: EngineInterface,
426  run: OrchestrationRun,
427  t: UiText,
428): Promise<{ issues: Record<string, JiraIssue>; note: string | undefined }> => {
429  const keys = jiraKeys(run)
430  if (keys.length === 0) return { issues: {}, note: undefined }
431  const linkOnly = (site: string | undefined, note: string) => ({
432    issues: Object.fromEntries(
433      keys.map(key => [key, { key, title: undefined, status: undefined, category: 'unknown' as const, url: issueUrl(site, key) }]),
434    ),
435    note,
436  })
437  const getIssue = await findTool($, '__getJiraIssue')
438  const getSites = await findTool($, '__getAccessibleAtlassianResources')
439  if (getIssue === undefined || getSites === undefined) {
440    return linkOnly(run.jiraSite, t.jira.unavailable)
441  }
442  const site = firstSite((await callTool($, { tool: getSites })).text)
443  const host = run.jiraSite ?? site?.url
444  if (host === undefined) {
445    return linkOnly(run.jiraSite, t.jira.noSite)
446  }
447  const cloudId = run.jiraSite ?? site?.cloudId ?? host
448  const now = await $.clock.now()
449  const failed: string[] = []
450  const issues = await Promise.all(
451    keys.map(async (key): Promise<JiraIssue> => {
452      const cached = jiraCache.get(key)
453      if (cached !== undefined && now - cached.at < JIRA_TTL_MS) return cached.issue
454      const ran = await callTool($, {
455        tool: getIssue,
456        cloudId,
457        issueIdOrKey: key,
458        fields: ['summary', 'status'],
459      }).catch(() => ({ isError: true }) as CallResult)
460      const issue = parseIssue(ran.isError === true ? undefined : ran.text, key, host)
461      if (issue.status === undefined) failed.push(key)
462      else jiraCache.set(key, { issue, at: now })
463      return issue
464    }),
465  )
466  return {
467    issues: Object.fromEntries(issues.map(issue => [issue.key, issue])),
468    note: failed.length === 0 ? undefined : t.jira.couldNotRead(failed.join(', ')),
469  }
470}
471
472/** The connector's cloud id for the plan's site, or why there is none (said to the owner as is). */
473const jiraConnection = async (
474  $: EngineInterface,
475  run: OrchestrationRun,
476  t: UiText,
477): Promise<{ cloudId: string; getTransitions: string; transition: string | undefined } | { note: string }> => {
478  const getTransitions = await findTool($, '__getTransitionsForJiraIssue')
479  const getSites = await findTool($, '__getAccessibleAtlassianResources')
480  if (getTransitions === undefined || getSites === undefined) {
481    return { note: t.jira.notAuthenticated }
482  }
483  const site = firstSite((await callTool($, { tool: getSites })).text)
484  const cloudId = run.jiraSite ?? site?.cloudId
485  if (cloudId === undefined) return { note: t.jira.noSiteShort }
486  return { cloudId, getTransitions, transition: await findTool($, TRANSITION_SUFFIX) }
487}
488
489const transitionCache = new Map<string, { list: JiraTransition[]; at: number }>()
490
491const issueTransitions = async (
492  $: EngineInterface,
493  conn: { cloudId: string; getTransitions: string },
494  issue: JiraIssue,
495  fresh: boolean,
496): Promise<JiraTransition[] | undefined> => {
497  const id = `${issue.key}|${issue.status}`
498  const now = await $.clock.now()
499  const cached = transitionCache.get(id)
500  if (!fresh && cached !== undefined && now - cached.at < JIRA_TTL_MS) return cached.list
501  const ran = await callTool($, { tool: conn.getTransitions, cloudId: conn.cloudId, issueIdOrKey: issue.key }).catch(
502    () => ({ isError: true }) as CallResult,
503  )
504  if (ran.isError === true) return undefined
505  const list = parseTransitions(ran.text)
506  transitionCache.set(id, { list, at: now })
507  return list
508}
509
510/** The issues the flow's current step says should change state; the panel offers each move, nothing moves here. */
511const loadJiraMoves = async (
512  $: EngineInterface,
513  run: OrchestrationRun | undefined,
514  state: FlowState | undefined,
515  issues: Record<string, JiraIssue>,
516  t: UiText,
517): Promise<JiraMove[]> => {
518  if (run === undefined || state === undefined || (state.status !== 'running' && state.status !== 'done')) return []
519  const stepId = state.status === 'done' ? state.flow.steps.at(-1)?.id : state.current
520  if (stepId === undefined) return []
521  const wanted = wishes(run, state.flow.steps, stepId)
522  if (wanted.length === 0) return []
523  const conn = await jiraConnection($, run, t)
524  const moves: JiraMove[] = []
525  for (const wish of wanted) {
526    const issue = issues[wish.key]
527    const note = 'note' in conn ? conn.note : undefined
528    const transitions =
529      'note' in conn || issue === undefined || issue.status === undefined ? undefined : await issueTransitions($, conn, issue, false)
530    const move = moveFor(wish, issue, transitions, stepId, note)
531    if (move !== undefined) moves.push(move)
532  }
533  return moves
534}
535
536/**
537 * The owner's "Mover no Jira" press, the only road to transitionJiraIssue: the transition is looked up again,
538 * then approved for that one call, which the tool.call hook refuses otherwise.
539 */
540const pressJiraMove = async ($: EngineInterface, change: string, key: string, transitionId: string): Promise<void> => {
541  const run = await loadRun($, await $.session.root())
542  if (run === undefined) return
543  const t = await textNow($)
544  const conn = await jiraConnection($, run, t)
545  if ('note' in conn || conn.transition === undefined) {
546    $.ui.toast(t.jira.notMoved(key, 'note' in conn ? conn.note : t.jira.noTransitionTool))
547    return
548  }
549  const issue = (await loadJira($, run, t)).issues[key]
550  const transitions = issue === undefined ? undefined : await issueTransitions($, conn, issue, true)
551  const hit = transitions?.find(tr => tr.id === transitionId)
552  if (issue === undefined || hit === undefined) {
553    $.ui.toast(t.jira.notMoved(key, t.jira.goneTransition))
554    await refreshQuietly($)
555    return
556  }
557  approvedMove = `${key}|${transitionId}`
558  const ran = await callTool($, {
559    tool: conn.transition,
560    cloudId: conn.cloudId,
561    issueIdOrKey: key,
562    transition: { id: transitionId },
563  })
564    .catch(() => ({ isError: true }) as CallResult)
565    .finally(() => {
566      approvedMove = undefined
567    })
568  if (ran.isError === true || ran.deny !== undefined) {
569    $.ui.toast(t.jira.refused(key, ran.text?.slice(0, 120)))
570    return
571  }
572  jiraCache.delete(key)
573  transitionCache.clear()
574  const state = await loadFlowState($, change)
575  if (state !== undefined) {
576    const log = await flowFile($, change, 'ndjson')
577    const note = `${key}: "${issue.status ?? '?'}" → "${hit.to ?? hit.name}" (transição "${hit.name}"), pelo clique do dono`
578    const event: FlowEvent = { seq: state.seq, at: await $.clock.now(), kind: 'jira-moved', step: state.current, by: 'owner', note }
579    await inFlowQueue(async () => {
580      const prior = (await readText($, log)) ?? ''
581      await $.fs.write(log, `${prior}${JSON.stringify(event)}\n`)
582    })
583  }
584  $.ui.toast(t.jira.moved(key, hit.to ?? hit.name))
585  await refreshQuietly($)
586}
587
588/** The one move the owner approved, while its call runs. */
589let approvedMove: string | undefined
590
591/**
592 * Each source fails on its own: a broken session list never hides the plan, and the panel names what failed.
593 * `wake` only for the clock's tick: a refresh run inside a tool call (a flow report) cannot submit a prompt,
594 * which would wait on the turn the call holds, and the stop it took would be lost.
595 */
596const refresh = async ($: EngineInterface, wake = false): Promise<void> => {
597  await restoreActivity($).catch(() => undefined)
598  const problems: string[] = []
599  const cwd = await $.session.root()
600  const base = await baseDir($)
601  const { value: ownPlan = [] } = await $.state.get(PLAN)
602  const config = await loadConfig($).catch(error => {
603    problems.push(describeError('config', error))
604    return { languages: DEFAULT_LANGUAGES, problems: [] }
605  })
606  problems.push(...config.problems)
607  const { languages } = config
608  const t = uiText(languages.ui)
609
610  const run = await loadRun($, cwd).catch(error => {
611    problems.push(describeError('plano', error))
612    return undefined
613  })
614
615  let sessions: { self: SessionCard | undefined; children: SessionCard[] } = { self: undefined, children: [] }
616  try {
617    if (await canCall($, LIST_SESSIONS)) sessions = await loadSessions($, base, ownPlan)
618    else problems.push(t.warning.noSessions)
619  } catch (error) {
620    problems.push(describeError('sessões', error))
621  }
622  if (wake) await wakeCoordination($, cwd, run, sessions).catch(error => $.ui.log(`orquestrador: ${describeError('aviso', error)}`))
623
624  const openspec =
625    run === undefined
626      ? undefined
627      : await loadOpenSpec($, run, t).catch(error => {
628          problems.push(describeError('openspec', error))
629          return undefined
630        })
631  const jira =
632    run === undefined
633      ? { issues: {}, note: undefined }
634      : await loadJira($, run, t).catch(error => ({ issues: {}, note: describeError('jira', error) }))
635
636  const skips = run === undefined ? {} : await loadSkips($, run.change).catch(() => ({}))
637  const flow = await loadFlowView($, run, cwd, languages).catch(error => {
638    problems.push(describeError('flow', error))
639    return undefined
640  })
641  const flowState = flow === undefined ? undefined : await loadFlowState($, flow.change).catch(() => undefined)
642  const jiraMoves = await loadJiraMoves($, run, flowState, jira.issues, t).catch(error => {
643    problems.push(describeError('jira', error))
644    return []
645  })
646  const prep = flow === undefined ? undefined : await loadPrepView($, flow.change).catch(() => undefined)
647  const flowTimes = flow === undefined ? undefined : await loadFlowTimes($, flow.change).catch(() => undefined)
648
649  const repoUrl = await $.session
650    .repo()
651    .then(repo => repoWebUrl(repo?.remote))
652    .catch(() => undefined)
653
654  const view: PanelView = {
655    ...sessions,
656    run: run === undefined ? undefined : withFlowStatus(run, flowState),
657    repoUrl,
658    openspec,
659    jira: jira.issues,
660    jiraNote: jira.note,
661    jiraMoves,
662    skips,
663    flow,
664    prep,
665    ...(flowTimes === undefined ? {} : { flowTimes }),
666    languages,
667    updatedAt: await $.clock.now(),
668    warning: problems.length === 0 ? undefined : problems.join(' · '),
669  }
670  await $.state.set(VIEW, asJson(view))
671}
672
673const refreshQuietly = async ($: EngineInterface, wake = false): Promise<void> => {
674  try {
675    await activeMode($) // keeps "is a flow running here" warm for the renders, which cannot write it
676    await refresh($, wake)
677  } catch (error) {
678    $.ui.log(`orquestrador: ${describeError('refresh', error)}`)
679  }
680}
681
682/**
683 * "Seguir o flow sem clique": when a child of the flow this session coordinates ends its turn, tells the
684 * coordination with a prompt of its own, which the app takes as the owner's turn. Only with the clone active,
685 * the owner's option on, a flow `running` and this session its `coordinatorSession` (the mod of a child in the
686 * same folder stays quiet). While the coordination works, the stops wait and go in one prompt once it stops.
687 * With the clone inactive or the option off nothing is watched, and what was kept goes, so turning it on later
688 * tells no old stop. One look at a time (`waking`): two refreshes that overlap tell a stop once.
689 */
690let waking = false
691
692const wakeCoordination = async (
693  $: EngineInterface,
694  root: string,
695  run: OrchestrationRun | undefined,
696  family: { self: SessionCard | undefined; children: SessionCard[] },
697): Promise<void> => {
698  if (waking) return
699  waking = true
700  try {
701    await wakeOnce($, root, run, family)
702  } finally {
703    waking = false
704  }
705}
706
707const forgetWatch = async ($: EngineInterface): Promise<void> => {
708  const [seen, pending, brake] = await Promise.all([$.state.get(AUTOWAKE_SEEN), $.state.get(AUTOWAKE_PENDING), $.state.get(AUTOWAKE_BRAKE)])
709  if (seen.value != null) await $.state.set(AUTOWAKE_SEEN, null)
710  if (pending.value != null) await $.state.set(AUTOWAKE_PENDING, null)
711  if (brake.value != null) await $.state.set(AUTOWAKE_BRAKE, null)
712}
713
714const wakeOnce = async (
715  $: EngineInterface,
716  root: string,
717  run: OrchestrationRun | undefined,
718  { self, children }: { self: SessionCard | undefined; children: SessionCard[] },
719): Promise<void> => {
720  if ((await readActivation($).catch(() => undefined))?.level === undefined || !(await readAutowake($))) {
721    await forgetWatch($)
722    return
723  }
724  if (self === undefined) return
725  const flow = await currentFlow($, root)
726  if (flow === undefined || flow.coordinatorSession !== self.sessionId) return
727  const plan = run?.change === flow.change ? run : undefined
728  // the children of earlier changes never count: the flow's own `earlier`, and the other flows' sessions
729  const excluded = [...(flow.earlier ?? []), ...(await siblingFlows($, flow.change, root)).flatMap(s => s.sessions ?? [])]
730  const { value: seen } = await $.state.get(AUTOWAKE_SEEN)
731  const eligible = eligibleChildren(plan, { sessions: flow.sessions ?? [], excluded }, self.sessionId, children)
732  const looked = childStops(seen ?? {}, eligible, await $.clock.now())
733  const { value: before } = await $.state.get(AUTOWAKE_PENDING)
734  const pending = [...new Set([...(before ?? []), ...looked.stopped.map(sessionRef)])]
735  await $.state.set(AUTOWAKE_SEEN, asJson(looked.seen))
736  if (self.isRunning || pending.length === 0) {
737    if (pending.length !== (before ?? []).length) await $.state.set(AUTOWAKE_PENDING, pending)
738    return
739  }
740  await $.state.set(AUTOWAKE_PENDING, null)
741  // a brake against a loop: the same child told a few times while the flow does not move stops being told,
742  // and so does any child once the coordination was told too many times (a new child on each stop is a loop too)
743  const { value: brake } = await $.state.get(AUTOWAKE_BRAKE)
744  const key = flowProgress(flow, plan)
745  const same = brake?.key === key ? brake : undefined
746  const told = same?.told ?? {}
747  const sent = same?.sent ?? 0
748  const capped = sent >= AUTOWAKE_MAX_SAME_PROGRESS
749  const fresh = capped ? [] : pending.filter(id => (told[id] ?? 0) < AUTOWAKE_MAX_SAME_CHILD)
750  const braked = pending.filter(id => !fresh.includes(id))
751  const warned = same?.warned === true || braked.length > 0
752  await $.state.set(AUTOWAKE_BRAKE, {
753    key,
754    told: { ...told, ...Object.fromEntries(fresh.map(id => [id, (told[id] ?? 0) + 1])) },
755    // one stop told is one, however many children it names
756    sent: sent + (fresh.length > 0 ? 1 : 0),
757    warned,
758  })
759  if (braked.length > 0 && same?.warned !== true) {
760    $.ui.toast(
761      capped
762        ? `Orquestrador: o flow de ${flow.change} parece parado: ${AUTOWAKE_MAX_SAME_PROGRESS} avisos à coordenação sem o flow andar. ` +
763            'Parei de avisar até o flow andar.'
764        : `Orquestrador: o flow de ${flow.change} parece parado: ${braked.join(', ')} terminou o turno mais de ${AUTOWAKE_MAX_SAME_CHILD} ` +
765            'vezes sem o flow andar. Parei de avisar a coordenação sobre essa sessão até o flow andar.',
766    )
767  }
768  if (fresh.length === 0) return
769  void $.prompt.submit({ text: stopPrompt(fresh), ...(STOP_AS_USER ? { asUser: true as const } : {}) }).catch(error => $.ui.log(`orquestrador: ${describeError('aviso', error)}`))
770}
771
772/**
773 * The change this coordination works on: the flow `running` it started (the mod of a child in the same
774 * folder is not its coordinator), else the plan published last. The flow wins: a new change has no plan yet.
775 */
776const currentFlow = async ($: EngineInterface, root: string): Promise<FlowState | undefined> => {
777  const self = await selfId($).catch(() => undefined)
778  return (await allFlowStates($))
779    .filter(s => s.status === 'running' && ownsFlow(s, root) && (s.coordinatorSession === undefined || s.coordinatorSession === self))
780    .sort((a, b) => b.startedAt - a.startedAt)[0]
781}
782
783const currentChange = async ($: EngineInterface, root: string): Promise<string | undefined> =>
784  (await currentFlow($, root))?.change ?? (await loadRun($, root).catch(() => undefined))?.change
785
786/** The coordination's other changes' flows, which keep their own children and group. */
787const siblingFlows = async ($: EngineInterface, change: string, root: string): Promise<FlowState[]> =>
788  (await allFlowStates($)).filter(s => s.change !== change && ownsFlow(s, root))
789
790/**
791 * Files the coordinator and the children of this change under the change's sidebar group, creating
792 * the group once. Runs on each plan publish and after each start_session, so a new phase session
793 * never lands ungrouped. Children of other changes stay out, and the ones the app dragged along with
794 * the coordinator go back to their own group.
795 */
796const groupFamily = async ($: EngineInterface, change: string, started?: string): Promise<string | undefined> => {
797  if (!(await canCall($, MOVE_SESSIONS))) return 'sidebar indisponível para agrupar'
798  const root = await $.session.root()
799  const [self] = parseSessionRows((await callTool($, { tool: GET_SESSION, session_id: 'self' })).text)
800  const listedFamily = await callTool($, { tool: LIST_SESSIONS, linked: true, limit: 50 }).catch(() => ({ isError: true }) as CallResult)
801  const family = listedFamily.isError === true ? [] : parseSessionRows(listedFamily.text)
802  const children = family.filter(row => self !== undefined && !row.isArchived && row.startedBy === self.sessionId)
803
804  const flow = await loadFlowState($, change)
805  const others = await siblingFlows($, change, root)
806  const state = flow !== undefined && ownsFlow(flow, root) ? flow : undefined
807  let fresh: string[] = []
808  if (state?.status === 'running') {
809    // the rows carry no creation date, so the flow keeps the children it opened: the ones no flow has claimed.
810    // A flow that could not list the children at its start (no `earlier`) adopts only the one just started.
811    const claimed = new Set([...others, state].flatMap(s => [...(s.sessions ?? []), ...(s.earlier ?? [])]))
812    const listedNow = listedFamily.isError === true || state.earlier === undefined ? [] : children.map(c => c.sessionId)
813    fresh = [...new Set([...(started === undefined ? [] : [started]), ...listedNow])].filter(id => !claimed.has(id))
814  }
815
816  const listed = await callTool($, { tool: LIST_GROUPS }).catch(() => ({ isError: true }) as CallResult)
817  // an error text is "do not know", never "no such group": creating one now would duplicate it
818  if (listed.isError === true || listed.deny !== undefined || !groupsLegible(listed.text)) {
819    $.ui.log(`orquestrador: list_groups não respondeu; o grupo de ${change} fica para o próximo gancho`)
820    if (state !== undefined) await keepGrouping($, change, fresh, undefined)
821    return undefined
822  }
823  const name = groupName(change)
824  const known = groupIds(listed.text)
825  let groupId = state?.groupId !== undefined && known.includes(state.groupId) ? state.groupId : findGroupId(listed.text, name)
826  if (groupId === undefined) groupId = findGroupId((await callTool($, { tool: CREATE_GROUP, name })).text)
827  if (groupId === undefined) return `não consegui criar o grupo ${name}`
828  const kept = state === undefined ? undefined : await keepGrouping($, change, fresh, groupId)
829
830  const run = await loadRun($, root).catch(() => undefined)
831  const plan = run?.change === change ? run : undefined
832  const mine = new Set(kept?.sessions ?? [])
833  const loose = children.filter(row => (mine.has(row.sessionId) || inPlan(plan, row)) && row.groupId !== groupId)
834  const moveSelf = self?.groupId !== groupId
835  const ids = [...(moveSelf ? ['self'] : []), ...loose.map(row => row.sessionId)]
836  if (ids.length > 0) await callTool($, { tool: MOVE_SESSIONS, session_ids: ids, group_id: groupId })
837
838  if (moveSelf) {
839    // the app moves the nested children with their mother: send the ones of other changes back
840    const after = parseSessionRows((await callTool($, { tool: LIST_SESSIONS, linked: true, limit: 50 })).text)
841    for (const other of others) {
842      if (other.groupId === undefined || !known.includes(other.groupId)) continue
843      const own = new Set(other.sessions ?? [])
844      const strays = after.filter(row => !row.isArchived && own.has(row.sessionId) && row.groupId !== other.groupId)
845      if (strays.length > 0) {
846        await callTool($, { tool: MOVE_SESSIONS, session_ids: strays.map(row => row.sessionId), group_id: other.groupId })
847      }
848    }
849  }
850  return undefined
851}
852
853/**
854 * What the grouping adds to the flow, merged into the flow as it is on disk now: the sidebar calls in
855 * between may let a `flow report` write it, and the grouping only owns `sessions` and `groupId`.
856 */
857const keepGrouping = ($: EngineInterface, change: string, fresh: readonly string[], groupId: string | undefined): Promise<FlowState | undefined> =>
858  inFlowQueue(async () => {
859    const now = await loadFlowState($, change)
860    if (now === undefined) return undefined
861    const sessions = [...new Set([...(now.sessions ?? []), ...fresh])]
862    const added = sessions.length !== (now.sessions ?? []).length
863    const regrouped = groupId !== undefined && now.groupId !== groupId
864    if (!added && !regrouped) return now
865    const merged: FlowState = { ...now, ...(added ? { sessions } : {}), ...(regrouped ? { groupId } : {}) }
866    // already merged with the disk, and its groupId is the new one: written as it is
867    await writeFlowNow($, merged, [])
868    return merged
869  })
870
871/** One grouping at a time: two start_session at once would both miss the group and create it twice. */
872let grouping: Promise<void> = Promise.resolve()
873
874const groupQuietly = ($: EngineInterface, change: string | undefined, started?: string): Promise<void> => {
875  if (change === undefined) return Promise.resolve()
876  const turn = grouping.then(async () => {
877    try {
878      const problem = await groupFamily($, change, started)
879      if (problem !== undefined) $.ui.toast(`Orquestrador: ${problem}`)
880    } catch (error) {
881      $.ui.log(`orquestrador: ${describeError('agrupar', error)}`)
882    }
883  })
884  grouping = turn
885  return turn
886}
887
888const gatesFile = async ($: EngineInterface, change: string, ext: 'json' | 'ndjson'): Promise<string> =>
889  `${await baseDir($)}/gates/${runKey(change)}.${ext}`
890
891const loadSkips = async ($: EngineInterface, change: string): Promise<Record<string, GateSkip>> =>
892  (await readJson<{ skips?: Record<string, GateSkip> }>($, await gatesFile($, change, 'json')))?.skips ?? {}
893
894/** Append-only trail of skips and refusals, one JSON line each, for the owner to audit later. */
895const logGateEvent = async ($: EngineInterface, change: string, event: Record<string, unknown>): Promise<void> => {
896  const path = await gatesFile($, change, 'ndjson')
897  const prior = (await readText($, path)) ?? ''
898  await $.fs.write(path, `${prior}${JSON.stringify({ at: await $.clock.now(), ...event })}\n`)
899}
900
901/** Only the panel calls this, on the owner's press: the model has no path to a skip. */
902const skipGate = async ($: EngineInterface, change: string, view: GateView): Promise<void> => {
903  const skips = await loadSkips($, change)
904  await $.fs.write(
905    await gatesFile($, change, 'json'),
906    JSON.stringify({ skips: { ...skips, [view.skipKey]: { at: await $.clock.now() } } }),
907  )
908  await logGateEvent($, change, { kind: 'skipped', key: view.skipKey, state: view.state, by: 'owner' })
909}
910
911type Family = { self: SessionCard | undefined; children: SessionCard[] }
912
913const loadFamily = async ($: EngineInterface): Promise<Family | undefined> => {
914  if (!(await canCall($, LIST_SESSIONS))) return undefined
915  const { value: ownPlan = [] } = await $.state.get(PLAN)
916  return loadSessions($, await baseDir($), ownPlan)
917}
918
919/**
920 * Every phase that may not close or archive yet, with the reason. A phase with no session is the
921 * coordinator's own; a session the app cannot list proves nothing, so its gates stay open.
922 */
923const phaseRefusals = (
924  run: OrchestrationRun,
925  family: Family | undefined,
926  self: GateCheck,
927  skips: Readonly<Record<string, GateSkip>>,
928  include: (phase: OrchestrationRun['waves'][number]['phases'][number], card: SessionCard | undefined) => boolean,
929): string[] =>
930  phaseViews(run, family?.children ?? [])
931    .flat()
932    .flatMap(phase => {
933      if (phase.gates === undefined || !include(phase, phase.card)) return []
934      const own = phase.session === undefined
935      const check = own ? self : (phase.card?.gates ?? { records: {}, editedAt: undefined })
936      const where = own ? 'this session' : phase.card === undefined ? `session "${phase.session}" (not found)` : `session "${phase.card.title}"`
937      const refusal = phaseRefusal(phase, gateViews(phase.gates, phase.id, check, skips).filter(isOpenGate), where, check.tried)
938      return refusal === undefined ? [] : [refusal]
939    })
940
941const finalOpenGates = async ($: EngineInterface, run: OrchestrationRun, family: Family | undefined): Promise<GateView[]> => {
942  if (run.finalGates === undefined) return []
943  const check = familyCheck([await ownCheck($), ...(family?.children ?? []).map(c => c.gates)])
944  return gateViews(run.finalGates, FINAL_SCOPE, check, await loadSkips($, run.change)).filter(isOpenGate)
945}
946
947const publishPlan = async ($: EngineInterface, input: Record<string, unknown>): Promise<ToolCallResult<string>> => {
948  const cwd = await $.session.root()
949  const parsed = parseRun(input, cwd, await $.clock.now())
950  if ('error' in parsed) return { result: `Plan not published: ${parsed.error}`, isError: true as const }
951  const before = await readJson<OrchestrationRun>($, `${await baseDir($)}/runs/${runKey(parsed.change)}.json`)
952  const wasDone = new Set(before?.waves.flatMap(w => w.phases.filter(p => p.status === 'done').map(p => p.id)) ?? [])
953  // a phase the loop already closed, or any phase once the flow is over, passed its gates there
954  const flowState = await loadFlowState($, parsed.change).catch(() => undefined)
955  const refusals = phaseRefusals(
956    parsed,
957    await loadFamily($),
958    await ownCheck($),
959    await loadSkips($, parsed.change),
960    phase => phase.status === 'done' && !wasDone.has(phase.id) && !closedByFlow(flowState, phase.id),
961  )
962  if (refusals.length > 0) {
963    await logGateEvent($, parsed.change, { kind: 'refused', action: 'done', reasons: refusals })
964    return {
965      result: `Plan not published: ${refusals.join(' | ')} Publish it again with that phase still running.`,
966      isError: true as const,
967    }
968  }
969  await $.fs.write(`${await baseDir($)}/runs/${runKey(parsed.change)}.json`, JSON.stringify(parsed))
970  await groupQuietly($, parsed.change)
971  await refreshQuietly($)
972  await showPane($)
973  const counts = phaseCounts(parsed)
974  return {
975    result:
976      `Plan published for ${parsed.change}: ${counts.done} done, ${counts.running} running, ` +
977      `${counts.blocked} blocked, ${counts.pending} pending. ${contentRule((await loadConfig($)).languages)}`,
978  }
979}
980
981/**
982 * Opens a session from the panel: beside this one when it is this session's own child (the
983 * only kind the app lets a session place), else through the app's `claude://` link, which the
984 * pane cannot follow itself. Says where to look when neither works.
985 */
986const openSession = async ($: EngineInterface, card: SessionCard, ownId: string | undefined): Promise<void> => {
987  if (ownId !== undefined && card.startedBy === ownId) {
988    const ran = await callTool($, { tool: OPEN_SESSION, session_id: card.sessionId, target: 'split' }).catch(
989      () => ({ isError: true }) as CallResult,
990    )
991    if (ran.isError !== true && ran.deny === undefined) return
992  }
993  if (card.link !== undefined && card.link.startsWith('claude://')) {
994    const opened = await $.process.run(['open', card.link], { timeoutMs: 5_000 }).catch(() => undefined)
995    if (opened?.exitCode === 0) return
996  }
997  $.ui.toast((await textNow($)).toast.cannotOpen(card.title))
998}
999
1000const PLAN_FAILED = { result: 'Plan not published: the orchestrator panel failed to store it.', isError: true } as const
1001const FLOW_FAILED = { result: 'Flow: the orchestrator failed to read or store the flow; nothing changed. Try again.', isError: true } as const
1002
1003/** The gates' files are the mod's alone: a record or a skip written by the model would forge a pass. */
1004/** Commands that only read: the gate files may be looked at, never written from a shell. */
1005const READ_ONLY_COMMANDS = new Set(['ls', 'cat', 'head', 'tail', 'grep', 'rg', 'find', 'wc', 'stat', 'jq', 'diff', 'file', 'du'])
1006
1007/** The folder named with or without its trailing slash: `rm -rf ~/.claude/orquestrador` must not slip through. */
1008const MENTIONS_PROTECTED_DIR = /\.claude\/orquestrador(?=$|[\/\s"'])/i
1009
1010const isReadOnlyCommand = (command: string): boolean => {
1011  const quiet = command.replace(/\d?>&\d|\d?>\s*\/dev\/null/g, '')
1012  if (quiet.includes('>')) return false
1013  return quiet
1014    .split(/&&|\|\||[|;]/)
1015    .map(part => part.trim())
1016    .filter(part => part !== '')
1017    .every(part => {
1018      const words = part.split(/\s+/).filter(w => !/^\w+=/.test(w))
1019      const head = words[0]?.split('/').pop() ?? ''
1020      return READ_ONLY_COMMANDS.has(head) && !(head === 'find' && /-delete|-exec|-ok\b|-fprint/.test(part))
1021    })
1022}
1023
1024const touchesGateFiles = (tool: string, input: Record<string, unknown>): boolean => {
1025  if (EDIT_TOOLS.has(tool)) {
1026    const path = input.file_path ?? input.notebook_path
1027    return typeof path === 'string' && path.includes(PROTECTED_DIR)
1028  }
1029  return (
1030    tool === 'Bash' &&
1031    typeof input.command === 'string' &&
1032    MENTIONS_PROTECTED_DIR.test(input.command) &&
1033    !isReadOnlyCommand(input.command)
1034  )
1035}
1036
1037/**
1038 * The activation file is the owner's, written by the panel alone: a mark or a hook the model planted there
1039 * (Edit, Write or a shell) would switch the guards off or run its own command. A first line of defense by the text
1040 * of the call, easy to get around; what actually holds is that the level counts only as the panel recorded it
1041 * (`readActivation`). It applies only where the mod is active: an inactive clone's file is free, as before.
1042 */
1043const SETTINGS_FILE = /(^|\/)\.claude\/settings\.local\.json$/i // APFS ignores case
1044const MENTIONS_SETTINGS = /settings\.local\.json/i
1045const touchesSettings = (tool: string, input: Record<string, unknown>): boolean => {
1046  if (EDIT_TOOLS.has(tool)) {
1047    const path = input.file_path ?? input.notebook_path
1048    return typeof path === 'string' && SETTINGS_FILE.test(path)
1049  }
1050  return tool === 'Bash' && typeof input.command === 'string' && MENTIONS_SETTINGS.test(input.command) && !isReadOnlyCommand(input.command)
1051}
1052
1053/** Every change this checkout coordinates: its published plan and its flow, either may be missing. */
1054const ownChanges = async (
1055  $: EngineInterface,
1056  root: string,
1057): Promise<{ run: OrchestrationRun | undefined; flow: FlowState | undefined }[]> => {
1058  const flows = (await allFlowStates($)).filter(s => ownsFlow(s, root))
1059  const runs = await Promise.all(flows.map(async s => readJson<OrchestrationRun>($, `${await baseDir($)}/runs/${runKey(s.change)}.json`)))
1060  const changes = flows.map((flow, i) => ({ run: runs[i], flow }))
1061  const run = await loadRun($, root)
1062  return run === undefined || flows.some(f => f.change === run.change) ? changes : [...changes, { run, flow: undefined }]
1063}
1064
1065/**
1066 * Rigid: a fourth live phase session slows the owner's machine, so there is no way around it. Only
1067 * sessions with live work count; the refusal says why each one does.
1068 */
1069const refuseStart = async ($: EngineInterface): Promise<string | undefined> => {
1070  const { value: ownPlan = [] } = await $.state.get(PLAN)
1071  const { self, children } = await loadSessions($, await baseDir($), ownPlan)
1072  if (self === undefined) return 'the orchestrator could not read this session, so it cannot count the live phase sessions.'
1073  const finished = finishedSessionIds(await ownChanges($, await $.session.root()), children)
1074  const live = liveSessions(children, self.sessionId, self.cwd, finished)
1075  if (live.length < MAX_LIVE_SESSIONS) return undefined
1076  return (
1077    `${live.length} phase sessions are alive: ${live.map(l => `${l.session.name ?? l.session.title} (${l.why})`).join(', ')}; ` +
1078    `the ceiling is ${MAX_LIVE_SESSIONS}. A session counts only while it runs, waits on the owner or has open tasks; ` +
1079    'one whose phase or flow finished or whose PR merged or closed does not. Wait for one to finish, or archive one ' +
1080    '(its gates must have passed), before starting another.'
1081  )
1082}
1083
1084const refuseArchive = async ($: EngineInterface, sessionId: unknown): Promise<string | undefined> => {
1085  if (typeof sessionId !== 'string' || sessionId === 'self') return undefined
1086  const run = await loadRun($, await $.session.root())
1087  if (run === undefined) return undefined
1088  const refusals = phaseRefusals(
1089    run,
1090    await loadFamily($),
1091    await ownCheck($),
1092    await loadSkips($, run.change),
1093    (phase, card) => phase.status !== 'done' && card?.sessionId === sessionId,
1094  )
1095  if (refusals.length === 0) return undefined
1096  await logGateEvent($, run.change, { kind: 'refused', action: 'archive', reasons: refusals })
1097  return refusals.join(' | ')
1098}
1099
1100/** The head branch of the PR a merge names: the checkout's own branch when it names none. */
1101const mergeHead = async ($: EngineInterface, selector: string | undefined, target: MergeTarget, root: string): Promise<string | undefined> => {
1102  if (target.branch !== undefined) return target.branch
1103  const argv =
1104    selector === undefined
1105      ? ['git', '-C', root, 'branch', '--show-current']
1106      : ['gh', 'pr', 'view', selector, '--json', 'headRefName', '--jq', '.headRefName']
1107  const ran = await $.process.run(argv, { cwd: root, timeoutMs: 15_000 }).catch(() => undefined)
1108  const branch = ran?.exitCode === 0 ? ran.stdout.trim() : ''
1109  return branch === '' ? undefined : branch
1110}
1111
1112/**
1113 * Whether a merge is of the change's own PR: its number is bound to a phase session, named by
1114 * the plan or cited by the flow's PR step, or its head branch is a phase session's or carries
1115 * the change id. A PR whose head branch cannot be read is taken as the change's, and so is a
1116 * GraphQL merge, which names its PR by a node id: the gate fails closed.
1117 */
1118const mergesChangePr = async (
1119  $: EngineInterface,
1120  call: MergeCall,
1121  run: OrchestrationRun,
1122  flow: FlowState | undefined,
1123  family: Family | undefined,
1124  root: string,
1125): Promise<boolean> => {
1126  if (call.via === 'graphql') return true
1127  const selector = call.selector
1128  const target = mergeTarget(selector)
1129  const { numbers, branches } = changePrs(run, flow, family?.children ?? [])
1130  if (target.number !== undefined && numbers.has(target.number)) return true
1131  const head = await mergeHead($, selector, target, root)
1132  return head === undefined || isChangeBranch(head, run.change, branches)
1133}
1134
1135/**
1136 * From an orchestrated checkout no merge goes with `--admin`, nor with an argument the mod cannot
1137 * read (`$VAR`, `$(…)`). The change's own PR, while its flow runs up to the step before the
1138 * archive, also waits for the flow's PR review before that merge and for the final gates; a
1139 * finished or aborted flow holds back nothing but those two. Every form `mergeCalls` reads counts:
1140 * `gh pr merge` with or without flags before `pr`, `gh api …/pulls/<n>/merge`, GraphQL's
1141 * `mergePullRequest`, quoted, continued, or inside `bash -c`/`sh -c`/`eval`. A line that names `gh`
1142 * and a merge the mod cannot read as one (`opaqueMerge`) is refused: the guard fails closed.
1143 */
1144const refuseMerge = async ($: EngineInterface, command: string): Promise<string | undefined> => {
1145  const calls = mergeCalls(command)
1146  const opaque = opaqueMerge(command)
1147  if (calls.length === 0 && opaque === undefined) return undefined
1148  const root = await $.session.root()
1149  const run = await loadRun($, root)
1150  if (run === undefined) return undefined
1151  const held: string[] = []
1152  const reasons: string[] = []
1153  if (opaque !== undefined) {
1154    held.push('opaque')
1155    reasons.push(
1156      `\`${opaque}\` runs a \`gh\` merge the mod cannot read (behind another program, from a script on stdin, or ` +
1157        'under a name a variable holds), so it cannot check the review, the gates or `--admin`. Run `gh pr merge` ' +
1158        'itself, with the PR and the flags written out.',
1159    )
1160  }
1161  if (calls.some(c => c.admin)) {
1162    held.push('--admin')
1163    reasons.push('`--admin` skips the branch protection (GitHub approval and green CI); merge without it, never around them.')
1164  }
1165  const blind = calls.find(c => c.dynamic)
1166  if (blind !== undefined) {
1167    held.push('$')
1168    reasons.push(
1169      `\`${blind.text}\` takes an argument from a variable or \`$(…)\`: the mod cannot see what it carries ` +
1170        '(an `--admin`, another PR). Write the PR and the flags out in the command.',
1171    )
1172  }
1173  const flow = await loadFlowState($, run.change)
1174  const family = await loadFamily($)
1175  let change = false
1176  if (flow === undefined || mergeWindow(flow)) {
1177    for (const call of calls) change ||= await mergesChangePr($, call, run, flow, family, root)
1178  }
1179  if (change) {
1180    const review = flow === undefined ? undefined : pendingReview(flow)
1181    if (review !== undefined) {
1182      held.push(review.id)
1183      const press = Object.values(review.outcomes)[0]?.label ?? review.id
1184      reasons.push(
1185        `the PR review "${review.id}" (${review.title}) of ${run.change} is not answered yet: the owner approves the PR ` +
1186          `on GitHub and presses "${press}" in the panel before it merges.`,
1187      )
1188    }
1189    const code = flow === undefined ? undefined : pendingCodeReview(flow)
1190    if (code !== undefined) {
1191      held.push(code.id)
1192      reasons.push(
1193        `the code review "${code.id}" (${code.title}) of ${run.change} has no "aprovado" since the flow last entered it: ` +
1194          "the flow's reviewer approves before the PR merges (a turn back to run again clears it).",
1195      )
1196    }
1197    const open = run.finalGates === undefined ? [] : await finalOpenGates($, run, family)
1198    if (open.length > 0) {
1199      held.push(...open.map(v => v.gate))
1200      reasons.push(
hooks/gates.ts 647 lines
1import type { FlowState, GateAttempt, GateCheck, GateRecord, GateSkip, GateState, GateView, Phase, PlanItem, Waiting } from '../types'
2
3/** The most phase sessions alive at once: more of them slows the owner's machine down. */
4export const MAX_LIVE_SESSIONS = 3
5
6type BashMatcher = { kind: 'bash'; pattern: RegExp }
7type ToolMatcher = { kind: 'tool'; matches: (tool: string, input: Record<string, unknown>) => boolean; passes: (text: string) => boolean }
8
9type GateDef = { label: string; how: string; matcher: BashMatcher | ToolMatcher }
10
11const isScreenshot = (tool: string, input: Record<string, unknown>): boolean => {
12  if (/(Claude_Browser|claude-in-chrome)__computer$/.test(tool)) return input.action === 'screenshot' || input.action === 'zoom'
13  if (/Claude_Code_iOS_Simulator__control$/.test(tool)) return input.action === 'screenshot'
14  if (/(Claude_Browser|claude-in-chrome)__browser_batch$/.test(tool) && Array.isArray(input.actions)) {
15    return input.actions.some(
16      (a: unknown) => (a as { input?: { action?: unknown } } | null)?.input?.action === 'screenshot',
17    )
18  }
19  return false
20}
21
22/**
23 * A package manager running a script, with the flags a monorepo puts before it:
24 * `pnpm --filter api test`, `pnpm -F api lint`, `pnpm -r test`, `yarn workspace api test`.
25 * A flag's value is any word but the script verbs, so `pnpm -r test` reads `-r` alone.
26 */
27const PACKAGE_SCRIPT =
28  String.raw`\b(npm|pnpm|yarn|bun)\b(\s+workspace\s+\S+)?` +
29  String.raw`(\s+-{1,2}[\w-]+(=\S+|\s+(?!-|run\b|exec\b|test\b|lint\b)[^\s;&|]+)?)*\s+(run\s+)?`
30
31/** A turbo task, alone or among others: `pnpm turbo lint --filter=api`, `npx turbo run build test`. */
32const TURBO_TASK = String.raw`\bturbo\s+(run\s+)?([\w@][\w:#@/.-]*\s+)*?`
33
34const REVIEWER = /adr-reviewer|spec-reviewer|reviewer-architecture|reviewer-quality/
35
36export const GATES: Readonly<Record<string, GateDef>> = {
37  testes: {
38    label: 'testes',
39    how: 'a test command (vitest, jest, pytest, npm test, claude plugin test…) exiting 0',
40    matcher: {
41      kind: 'bash',
42      pattern: new RegExp(
43        String.raw`\b(vitest|jest|pytest|mocha|go test|cargo test|playwright test|claude plugin test)\b|` +
44          String.raw`${PACKAGE_SCRIPT}test(:\S+)?\b|${TURBO_TASK}test(:\S+)?\b`,
45      ),
46    },
47  },
48  lint: {
49    label: 'lint',
50    how: 'a lint/format check (eslint, prettier --check, ruff, biome, npm run lint…) exiting 0',
51    matcher: {
52      kind: 'bash',
53      pattern: new RegExp(
54        String.raw`\b(eslint|prettier\s+(--check|-c)|ruff|biome\s+(check|lint|ci)|stylelint|black\s+--check|flake8)\b|` +
55          String.raw`${PACKAGE_SCRIPT}(lint|format:check)\b|${TURBO_TASK}(lint|format:check)\b`,
56      ),
57    },
58  },
59  check: {
60    label: 'check.sh',
61    how: '`sh scripts/check.sh` exiting 0',
62    matcher: { kind: 'bash', pattern: /\bscripts\/check\.sh\b/ },
63  },
64  openspec: {
65    label: 'openspec',
66    how: '`openspec validate` exiting 0',
67    matcher: { kind: 'bash', pattern: /\bopenspec(\.js)?\s+validate\b/ },
68  },
69  visual: {
70    label: 'visual',
71    how: 'a screenshot taken in the browser pane, Chrome or the iOS simulator',
72    matcher: { kind: 'tool', matches: isScreenshot, passes: () => true },
73  },
74  regras: {
75    label: 'regras',
76    how: 'a rules review (adr-reviewer, spec-reviewer, reviewer-architecture or reviewer-quality agent) approving',
77    matcher: {
78      kind: 'tool',
79      matches: (tool, input) => tool === 'Agent' && typeof input.subagent_type === 'string' && REVIEWER.test(input.subagent_type),
80      passes: text => /\b(approved|aprovad[oa]|no violations?|nenhuma viola)/i.test(text) && !/\b(rejected|reprovad[oa])\b/i.test(text),
81    },
82  },
83}
84
85export const GATE_IDS = Object.keys(GATES)
86
87/** Gate ids a plan names, checked against the catalogue. */
88export const parseGates = (raw: unknown, where: string): string[] | { error: string } | undefined => {
89  if (raw === undefined) return undefined
90  if (!Array.isArray(raw)) return { error: `${where}: \`gates\` must be a list of gate ids.` }
91  const ids = [...new Set(raw.filter((g): g is string => typeof g === 'string').map(g => g.trim()))]
92  const unknown = ids.filter(id => GATES[id] === undefined)
93  if (unknown.length > 0) {
94    return { error: `${where}: unknown gate ${unknown.join(', ')}; known gates are ${GATE_IDS.join(', ')}.` }
95  }
96  return ids.length === 0 ? undefined : ids
97}
98
99/** One step of a command line and the operator that ends it ('' for the last). */
100type Step = { text: string; then: string }
101
102/** `&&`, `||`, `;`, a newline, a pipe or a lone `&` (not the one in `2>&1` or `&>`). */
103const SEPARATOR = /&&|\|\||\|&?|;|\n|(?<![<>&])&(?![&>])/g
104
105const stepsOf = (code: string): Step[] => {
106  const steps: Step[] = []
107  let from = 0
108  for (const match of code.matchAll(SEPARATOR)) {
109    steps.push({ text: code.slice(from, match.index), then: match[0] })
110    from = (match.index ?? 0) + match[0].length
111  }
112  steps.push({ text: code.slice(from), then: '' })
113  return steps.filter((step, i) => step.text.trim() !== '' || i === steps.length - 1)
114}
115
116const short = (text: string): string => text.replace(/\s+/g, ' ').trim().slice(0, 40)
117
118/**
119 * Why an exit 0 of `code` does not prove the gate its step `index` ran, or undefined when it
120 * does. The shell hands back the exit code of the last thing it ran: `npm test | tail` and
121 * `npm test; echo done` "pass" whatever the tests did, and `npm test || true` always exits 0.
122 * Steps joined by `&&` after the gate run only when it passed; `set -e` and `pipefail` make a
123 * failure end the command.
124 */
125export const exitMask = (code: string, index: number, steps: readonly Step[] = stepsOf(code)): string | undefined => {
126  const before = steps.slice(0, index).map(s => s.text).join(' ')
127  const errexit = /\bset\s+-\w*e/.test(before) || /\bset\s+-o\s+errexit\b/.test(before)
128  const pipefail = /pipefail/.test(code)
129  let start = index
130  while (start > 0 && !/^(;|\n|&)$/.test(steps[start - 1]!.then)) start -= 1
131  const list = steps.slice(start)
132  const or = list.slice(0, list.findIndex(s => /^(;|\n|&)$/.test(s.then)) + 1 || list.length).find(s => s.then === '||')
133  if (or !== undefined) return `\`||\` after "${short(or.text)}" makes the command exit 0 whatever the gate did`
134  const own = steps[index]!
135  if (own.then === '&') return 'it ran in the background (`&`), so its exit code was never seen'
136  if (own.then.startsWith('|') && !pipefail) return `its output is piped (\`| ${short(steps[index + 1]?.text ?? '')}\`), so the exit code is the pipe's last command's, not the gate's`
137  if (errexit) return undefined
138  for (const [i, step] of steps.slice(index).entries()) {
139    if (step.then === ';' || step.then === '\n' || step.then === '&') {
140      const next = steps[index + i + 1]?.text ?? ''
141      return `it is followed by \`${step.then === '\n' ? '⏎' : step.then} ${short(next)}\`, so the exit code is that later command's; run the gate alone or join with \`&&\``
142    }
143  }
144  return undefined
145}
146
147/** Whether an exit 0 of `command` proves nothing about every step `pattern` finds in it. */
148export const masksExitCode = (command: string, pattern: RegExp): boolean => {
149  const steps = stepsOf(command)
150  return steps.every((step, i) => !pattern.test(step.text) || exitMask(command, i, steps) !== undefined)
151}
152
153/**
154 * The words the shell runs, without the text it only carries: a heredoc body or a quoted
155 * string that mentions `npm test` writes a file, it does not run the tests.
156 */
157export const executedText = (command: string): string =>
158  command
159    .replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2\b/g, '<<heredoc')
160    .replace(/'[^']*'/g, "''")
161    .replace(/"(?:[^"\\]|\\.)*"/g, '""')
162
163/** A command that looks like a gate attempt even when no gate counted it, for the refusal to quote. */
164const LOOKS_LIKE_GATE = /\b(test|tests|lint|vitest|jest|pytest|prettier|eslint|check|validate|format)\b/
165
166/** What one finished Bash command proves, gate by gate, and why any gate it ran did not count. */
167export const classifyBash = (
168  command: string,
169  failed: boolean,
170  at: number,
171): { records: GateRecord[]; attempt: GateAttempt | undefined } => {
172  const code = executedText(command)
173  const steps = stepsOf(code)
174  const records: GateRecord[] = []
175  const why: string[] = []
176  for (const [gate, def] of Object.entries(GATES)) {
177    if (def.matcher.kind !== 'bash') continue
178    const pattern = def.matcher.pattern
179    const indices = steps.flatMap((step, i) => (pattern.test(step.text) ? [i] : []))
180    if (indices.length === 0) continue
181    const evidence = (i: number): string => steps[i]!.text.replace(/\s+/g, ' ').trim().slice(0, 60)
182    if (failed) {
183      records.push({ gate, result: 'failed', evidence: evidence(indices[0]!), at })
184      continue
185    }
186    const proven = indices.find(i => exitMask(code, i, steps) === undefined)
187    if (proven !== undefined) records.push({ gate, result: 'passed', evidence: evidence(proven), at })
188    else why.push(`${gate} not counted: ${exitMask(code, indices.at(-1)!, steps)}`)
189  }
190  const looksLike = records.length === 0 && why.length === 0 && LOOKS_LIKE_GATE.test(code)
191  const reason = why.length > 0 ? why.join('; ') : looksLike ? 'matches no gate command' : undefined
192  return {
193    records,
194    attempt: reason === undefined ? undefined : { command: command.replace(/\s+/g, ' ').trim().slice(0, 160), why: reason, at },
195  }
196}
197
198/** What one finished Bash command proves, gate by gate. */
199export const observeBash = (command: string, failed: boolean, at: number): GateRecord[] =>
200  classifyBash(command, failed, at).records
201
202/** The attempts a refusal quotes: the newest last, at most this many. */
203export const MAX_ATTEMPTS = 5
204
205export const keepAttempt = (attempts: readonly GateAttempt[], attempt: GateAttempt): GateAttempt[] =>
206  [...attempts, attempt].slice(-MAX_ATTEMPTS)
207
208/** What one finished non-Bash tool call proves: a screenshot, a reviewer's verdict. */
209export const observeTool = (
210  tool: string,
211  input: Record<string, unknown>,
212  failed: boolean,
213  text: string,
214  at: number,
215): GateRecord[] =>
216  Object.entries(GATES).flatMap(([gate, def]): GateRecord[] => {
217    if (def.matcher.kind !== 'tool' || !def.matcher.matches(tool, input)) return []
218    const passed = !failed && def.matcher.passes(text)
219    const what = tool === 'Agent' ? `agente ${String(input.subagent_type)}` : 'screenshot'
220    return [{ gate, result: passed ? 'passed' : 'failed', evidence: what, at }]
221  })
222
223/** The latest record per gate wins: a fresh pass clears an old failure and the reverse. */
224export const mergeRecords = (
225  records: Readonly<Record<string, GateRecord>>,
226  observed: readonly GateRecord[],
227): Record<string, GateRecord> => {
228  const next = { ...records }
229  for (const record of observed) {
230    const prior = next[record.gate]
231    if (prior === undefined || prior.at <= record.at) next[record.gate] = record
232  }
233  return next
234}
235
236/** Edits made after a pass leave it unproven for the code as it now stands. */
237export const gateState = (
238  record: GateRecord | undefined,
239  editedAt: number | undefined,
240  skip: GateSkip | undefined,
241): GateState => {
242  if (record?.result === 'passed' && (editedAt === undefined || editedAt <= record.at)) return 'passed'
243  if (skip !== undefined) return 'skipped'
244  if (record === undefined) return 'pending'
245  return record.result === 'failed' ? 'failed' : 'stale'
246}
247
248export const skipKey = (scope: string, gate: string): string => `${scope}:${gate}`
249export const FINAL_SCOPE = '*final'
250
251export const gateViews = (
252  gates: readonly string[] | undefined,
253  scope: string,
254  check: GateCheck,
255  skips: Readonly<Record<string, GateSkip>>,
256): GateView[] =>
257  (gates ?? []).map(gate => {
258    const record = check.records[gate]
259    const skip = skips[skipKey(scope, gate)]
260    return {
261      gate,
262      label: GATES[gate]?.label ?? gate,
263      state: gateState(record, check.editedAt, skip),
264      evidence: record?.evidence,
265      at: record?.at,
266      skipKey: skipKey(scope, gate),
267    }
268  })
269
270export const isOpenGate = (view: GateView): boolean => view.state !== 'passed' && view.state !== 'skipped'
271
272/** Final gates are proven by whichever session of the family ran them last. */
273export const familyCheck = (checks: readonly GateCheck[]): GateCheck => {
274  const records: Record<string, GateRecord> = {}
275  let editedAt: number | undefined
276  for (const check of checks) {
277    for (const record of Object.values(check.records)) {
278      const prior = records[record.gate]
279      if (prior === undefined || prior.at < record.at) records[record.gate] = record
280    }
281    if (check.editedAt !== undefined && (editedAt === undefined || check.editedAt > editedAt)) editedAt = check.editedAt
282  }
283  return { records, editedAt }
284}
285
286const STATE_WORD: Record<GateState, string> = {
287  passed: 'passed',
288  failed: 'failed',
289  pending: 'not run',
290  stale: 'stale (files edited after it passed)',
291  skipped: 'skipped by the owner',
292}
293
294/** The session's latest commands that looked like a gate run and why none counted, newest last. */
295const attemptsLine = (tried: readonly GateAttempt[] | undefined): string =>
296  tried === undefined || tried.length === 0
297    ? ' No command there looked like a gate run.'
298    : ` Last commands seen there that did not count: ${tried.map(t => `\`${t.command}\` → ${t.why}`).join('; ')}.`
299
300/** Why a phase cannot close yet, in the words the model reads; undefined when it can. */
301export const phaseRefusal = (
302  phase: Pick<Phase, 'id' | 'title'>,
303  open: readonly GateView[],
304  where: string,
305  tried?: readonly GateAttempt[],
306): string | undefined =>
307  open.length === 0
308    ? undefined
309    : `phase ${phase.id} (${phase.title}) cannot close: ` +
310      open.map(v => `${v.gate} ${STATE_WORD[v.state]} — needs ${GATES[v.gate]?.how ?? v.gate}`).join('; ') +
311      ` (checked in ${where}).` +
312      (open.some(v => v.state === 'pending') ? attemptsLine(tried) : '') +
313      ` Run the gate in that session as a command of its own (no \`| tail\`, no \`; echo $?\` after it), or ask the owner: ` +
314      `only they can skip a gate, from the panel — publish an ownerQuestion with \`gate: {phase: "${phase.id}", gate}\` ` +
315      'so the panel offers the skip itself.'
316
317/** What the ceiling reads of a session: the app's row, plus its activity file when there is one. */
318type CeilingRow = {
319  sessionId: string
320  startedBy: string | undefined
321  isArchived: boolean
322  cwd?: string
323  isRunning?: boolean
324  prState?: string | undefined
325  waiting?: Waiting | undefined
326  plan?: readonly PlanItem[]
327}
328
329/**
330 * Why a phase session still weighs on the owner's machine, or undefined when it does not. It
331 * counts only with live work: running now, waiting on the owner, or with open tasks in its list.
332 * With its phase or flow finished, or its PR merged or closed, it is done whatever it shows.
333 */
334export const aliveReason = (row: CeilingRow, finished: ReadonlySet<string> = new Set()): string | undefined => {
335  if (finished.has(row.sessionId)) return undefined
336  const pr = row.prState?.toUpperCase()
337  if (pr === 'MERGED' || pr === 'CLOSED') return undefined
338  if (row.isRunning === true) return 'running now'
339  if (row.waiting !== undefined) return `waiting on the owner (${row.waiting.kind})`
340  const open = (row.plan ?? []).filter(item => item.status !== 'completed').length
341  return open > 0 ? `${open} open task${open === 1 ? '' : 's'} in its list` : undefined
342}
343
344/**
345 * Phase sessions still alive, each with why it counts: started by this session, not archived,
346 * and with live work (see `aliveReason`). A session in the coordinator's own folder is a side
347 * chat or fork the owner opened, not a phase: phases always run in a worktree of their own.
348 */
349export const liveSessions = <T extends CeilingRow>(
350  rows: readonly T[],
351  selfId: string | undefined,
352  selfCwd?: string,
353  finished?: ReadonlySet<string>,
354): { session: T; why: string }[] =>
355  selfId === undefined
356    ? []
357    : rows.flatMap(row => {
358        if (row.startedBy !== selfId || row.isArchived || (selfCwd !== undefined && row.cwd === selfCwd)) return []
359        const why = aliveReason(row, finished)
360        return why === undefined ? [] : [{ session: row, why }]
361      })
362
363/**
364 * A command that may merge a PR through `gh`, in any form: the cheap test that sends it to the
365 * merge guard, which reads it word by word (`mergeCalls`). Raw text on purpose: a quoted, wrapped
366 * or continued merge still goes to the guard, and the guard holds when the mod fails.
367 */
368export const GH_MERGE = /\bgh\b[\s\S]*merge/i
369export const ARCHIVE_COMMAND = /\bopenspec(\.js)?\s+archive\b/
370export const PROTECTED_DIR = '/.claude/orquestrador/'
371
372/**
373 * Whether a change's final gates still hold back a merge: while its flow runs, up to the step
374 * before the archive. The change's PR merges between `pr` and `producao` (QA tests the PR, the
375 * deploy ships the merge); from the archive on, the only PR left moves the change folder. A
376 * finished or aborted flow gates nothing.
377 */
378export const mergeWindow = (state: Pick<FlowState, 'status' | 'current' | 'flow'>): boolean => {
379  if (state.status === 'done' || state.status === 'aborted') return false
380  const steps = state.flow.steps
381  const archive = steps.findIndex(s => s.cleanup || (s.command !== undefined && ARCHIVE_COMMAND.test(s.command)))
382  const at = steps.findIndex(s => s.id === state.current)
383  return archive === -1 || at === -1 || at < archive
384}
385
386/** `gh pr merge` flags that take a value, so the value is not read as the PR. */
387const MERGE_VALUE_FLAGS = new Set(['-b', '--body', '-F', '--body-file', '-t', '--subject', '-A', '--author-email', '--match-head-commit', '-R', '--repo'])
388
389/** `gh` flags before the command that take a value. */
390const GH_VALUE_FLAGS = new Set(['-R', '--repo', '--hostname'])
391
392/** One word as the shell hands it to the program, and whether a `$` or `` ` `` makes it unknowable here. */
393type Word = { text: string; dynamic: boolean }
394
395/** The commands a command line runs, each as its words, and the scripts of its `$(…)` and `` `…` ``. */
396const splitWords = (code: string): { commands: Word[][]; nested: string[] } => {
397  const commands: Word[][] = []
398  const nested: string[] = []
399  let words: Word[] = []
400  let word: Word | undefined
401  const add = (text: string, dynamic = false): void => {
402    word ??= { text: '', dynamic: false }
403    word.text += text
404    word.dynamic ||= dynamic
405  }
406  const endWord = (): void => {
407    if (word !== undefined) words.push(word)
408    word = undefined
409  }
410  const endCommand = (): void => {
411    endWord()
412    if (words.length > 0) commands.push(words)
413    words = []
414  }
415  /** The text up to the `)` that closes the `$(` before `from`, and where it ends. */
416  const substitution = (from: number): [string, number] => {
417    let depth = 1
418    let i = from
419    for (; i < code.length && depth > 0; i++) {
420      if (code[i] === '(') depth += 1
421      else if (code[i] === ')') depth -= 1
422    }
423    return [code.slice(from, i - 1), i]
424  }
425  let i = 0
426  while (i < code.length) {
427    const c = code[i]!
428    if (c === '\\') {
429      if (code[i + 1] !== '\n') add(code[i + 1] ?? '')
430      i += 2
431    } else if (c === "'") {
432      const end = code.indexOf("'", i + 1)
433      add(code.slice(i + 1, end === -1 ? code.length : end))
434      i = end === -1 ? code.length : end + 1
435    } else if (c === '"') {
436      add('')
437      i += 1
438      while (i < code.length && code[i] !== '"') {
439        const d = code[i]!
440        if (d === '\\' && i + 1 < code.length) {
441          if (code[i + 1] !== '\n') add('"\\$`'.includes(code[i + 1]!) ? code[i + 1]! : `\\${code[i + 1]}`)
442          i += 2
443        } else if (d === '$' && code[i + 1] === '(') {
444          const [inner, end] = substitution(i + 2)
445          nested.push(inner)
446          add(code.slice(i, end), true)
447          i = end
448        } else if (d === '`') {
449          const end = code.indexOf('`', i + 1)
450          nested.push(code.slice(i + 1, end === -1 ? code.length : end))
451          add(code.slice(i, end === -1 ? code.length : end + 1), true)
452          i = end === -1 ? code.length : end + 1
453        } else {
454          add(d, d === '$')
455          i += 1
456        }
457      }
458      i += 1
459    } else if (c === '$' && code[i + 1] === '(') {
460      const [inner, end] = substitution(i + 2)
461      nested.push(inner)
462      add(code.slice(i, end), true)
463      i = end
464    } else if (c === '`') {
465      const end = code.indexOf('`', i + 1)
466      nested.push(code.slice(i + 1, end === -1 ? code.length : end))
467      add(code.slice(i, end === -1 ? code.length : end + 1), true)
468      i = end === -1 ? code.length : end + 1
469    } else if (c === '#' && word === undefined) {
470      const end = code.indexOf('\n', i)
471      i = end === -1 ? code.length : end
472    } else if (c === ' ' || c === '\t') {
473      endWord()
474      i += 1
475    } else if (c === '&' && (/[<>]$/.test(word?.text ?? '') || code[i + 1] === '>')) {
476      add(c) // `2>&1`, `&>`: a redirection, not a separator
477      i += 1
478    } else if (';&|\n()'.includes(c)) {
479      endCommand()
480      i += 1
481    } else {
482      add(c, c === '$')
483      i += 1
484    }
485  }
486  endCommand()
487  return { commands, nested }
488}
489
490/** Words that run the command after them: `env`, `time`, `command`, a `VAR=value` before it… */
491const PREFIX_WORDS = new Set(['{', '!', 'if', 'then', 'else', 'elif', 'while', 'until', 'do', 'time', 'command', 'exec', 'nohup', 'env', 'sudo'])
492const SHELLS = /(^|\/)(ba|z|da|k)?sh$/
493
494/**
495 * Every command a command line runs, as its words: across line continuations and quotes, and
496 * into the scripts `bash -c`/`sh -c`/`eval` run and the `$(…)` it substitutes. A heredoc body is
497 * text, not commands.
498 */
499export const commandsRun = (command: string, depth = 0): Word[][] => {
500  if (depth > 4) return []
501  // the body goes, the rest of the opening line stays: `cat <<'EOF' | bash` still pipes into a shell
502  const code = command.replace(/<<-?\s*(['"]?)(\w+)\1([^\n]*)\n[\s\S]*?\n\s*\2\b/g, '<<heredoc$3')
503  const { commands, nested } = splitWords(code)
504  const out: Word[][] = []
505  for (const words of commands) {
506    let at = 0
507    while (at < words.length && (PREFIX_WORDS.has(words[at]!.text) || /^[A-Za-z_]\w*=/.test(words[at]!.text))) at += 1
508    const run = words.slice(at)
509    const head = run[0]?.text ?? ''
510    if (head === 'eval') {
511      out.push(...commandsRun(run.slice(1).map(w => w.text).join(' '), depth + 1))
512      continue
513    }
514    if (SHELLS.test(head)) {
515      const flag = run.findIndex((w, i) => i > 0 && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(w.text))
516      const script = flag === -1 ? undefined : run[flag + 1]
517      if (script !== undefined) {
518        out.push(...commandsRun(script.text, depth + 1))
519        continue
520      }
521    }
522    if (run.length > 0) out.push(run)
523  }
524  for (const inner of nested) out.push(...commandsRun(inner, depth + 1))
525  return out
526}
527
528/**
529 * A PR merge one command runs: `gh pr merge`, `gh api …/pulls/<n>/merge` or `gh api graphql` with
530 * `mergePullRequest`. `selector` is the PR it names (number, URL or branch; for the API, `<n>`);
531 * a GraphQL merge names its PR by node id, which the mod cannot read. `dynamic` is set when an
532 * argument carries a `$` the mod cannot see through.
533 */
534export type MergeCall = {
535  via: 'pr' | 'api' | 'graphql'
536  selector: string | undefined
537  admin: boolean
538  dynamic: boolean
539  text: string
540}
541
542const mergeCall = (words: readonly Word[]): MergeCall | undefined => {
543  if (!/(^|\/)gh$/.test(words[0]?.text ?? '')) return undefined
544  let at = 1
545  while (at < words.length && words[at]!.text.startsWith('-')) at += GH_VALUE_FLAGS.has(words[at]!.text) ? 2 : 1
546  const sub = words[at]?.text
547  const args = words.slice(at + 1)
548  const text = words.map(w => w.text).join(' ').replace(/\s+/g, ' ').slice(0, 80)
549  const dynamic = args.some(w => w.dynamic)
550  if (sub === 'pr') {
551    let verb = 0
552    while (verb < args.length && args[verb]!.text.startsWith('-')) verb += GH_VALUE_FLAGS.has(args[verb]!.text) ? 2 : 1
553    if (args[verb]?.text !== 'merge') return undefined
554    const rest = args.slice(verb + 1)
555    let selector: string | undefined
556    for (let i = 0; i < rest.length && selector === undefined; i++) {
557      const word = rest[i]!.text
558      if (!word.startsWith('-')) selector = word
559      else if (MERGE_VALUE_FLAGS.has(word)) i += 1
560    }
561    const admin = rest.some(w => w.text === '--admin' || w.text.startsWith('--admin='))
562    return { via: 'pr', selector, admin, dynamic, text }
563  }
564  if (sub !== 'api') return undefined
565  const pull = args.map(w => w.text.match(/(?:^|\/)pulls\/([^/\s]+)\/merge\b/)?.[1]).find(n => n !== undefined)
566  if (pull !== undefined) return { via: 'api', selector: pull, admin: false, dynamic, text }
567  if (args.some(w => w.text === 'graphql') && args.some(w => /mergePullRequest/.test(w.text))) {
568    return { via: 'graphql', selector: undefined, admin: false, dynamic, text }
569  }
570  return undefined
571}
572
573/** The PR merges a command runs, in any of the forms `commandsRun` reaches. */
574export const mergeCalls = (command: string): MergeCall[] =>
575  commandsRun(command).flatMap(words => mergeCall(words) ?? [])
576
577/** Programs that only print, read or move around what they are given: a merge in their arguments does not run. */
578const INERT = new Set([
579  'echo', 'printf', 'cat', 'grep', 'egrep', 'rg', 'head', 'tail', 'less', 'jq', 'wc', 'sort', 'uniq', 'diff',
580  'cd', 'ls', 'pwd', 'true', 'false', 'test', '[', 'mkdir', 'touch', 'cp', 'mv', 'tee',
581  // the shell's own loop and branch words run nothing by themselves: what they wrap is judged as its own command
582  'for', 'select', 'case', 'esac', 'done', 'fi', 'read', 'break', 'continue', '[[', ']]', '}',
583])
584
585/** A `git` that runs a command of its own: an alias with `!`, `rebase --exec`/`-x`, `filter-branch`, `bisect run`. */
586const gitRuns = (words: readonly Word[]): boolean => {
587  const texts = words.map(w => w.text)
588  return (
589    texts.some(t => /^alias\.[^=]*=\s*!/.test(t)) ||
590    texts.includes('filter-branch') ||
591    (texts.includes('rebase') && texts.some(t => t === '-x' || t === '--exec' || t.startsWith('--exec='))) ||
592    (texts.includes('bisect') && texts.includes('run'))
593  )
594}
595
596const namesMerge = (text: string): boolean => /\bgh\b/.test(text) && /merge/i.test(text)
597
598/**
599 * A command line that names `gh` and a merge the mod cannot read as one: the `gh` runs behind
600 * another program (`xargs`, `find -exec`, `timeout`, `nice`, `sudo -u`, `env -u`…), from a script
601 * a shell reads on stdin (a heredoc or a pipe into `bash`), through a `git` that runs commands, or
602 * under a name a variable holds (`$G pr merge`). Its text when it is that, so the guard fails
603 * closed; undefined when every command is a `gh` the mod reads or a program that only prints.
604 *
605 * With no merge read on the line, any such command counts. With one read, each other command is
606 * judged on its own, so a readable merge cannot cover a hidden one beside it
607 * (`gh pr merge 6 --squash && xargs gh pr merge --admin`) and `gh pr merge 6 && npm test` passes.
608 */
609export const opaqueMerge = (command: string): string | undefined => {
610  if (!namesMerge(command)) return undefined
611  const read = mergeCalls(command).length > 0
612  const hidden = commandsRun(command).find(words => {
613    const head = words[0]
614    if (head === undefined || mergeCall(words) !== undefined) return false
615    const name = head.text.split('/').pop() ?? ''
616    if (name === 'gh' && !head.dynamic) return false
617    const runs = head.dynamic || (name === 'git' ? gitRuns(words) : !INERT.has(name))
618    if (!runs) return false
619    if (!read) return true
620    const stdinShell = SHELLS.test(name) && words.slice(1).every(w => w.text.startsWith('-') || w.text.startsWith('<'))
621    return head.dynamic || stdinShell || namesMerge(words.map(w => w.text).join(' '))
622  })
623  return hidden?.map(w => w.text).join(' ').replace(/\s+/g, ' ').slice(0, 80)
624}
625
626/** The PR a `gh pr merge` names (a number, URL or branch); undefined for the current branch's. */
627export const mergeSelector = (command: string): string | undefined => mergeCalls(command)[0]?.selector
628
629export type MergeTarget = { number: number | undefined; branch: string | undefined }
630
631export const mergeTarget = (selector: string | undefined): MergeTarget => {
632  const number = selector?.match(/^#?(\d+)$/)?.[1] ?? selector?.match(/\/pull\/(\d+)/)?.[1]
633  return number === undefined ? { number: undefined, branch: selector } : { number: Number(number), branch: undefined }
634}
635
636/** PR numbers a note cites: `#801` or `…/pull/801`. */
637export const citedPrs = (text: string | undefined): number[] =>
638  [...(text ?? '').matchAll(/(?:#|\/pull\/)(\d+)\b/g)].map(m => Number(m[1]))
639
640/** A head branch is the change's when a phase session works on it or its name carries the change id. */
641export const isChangeBranch = (branch: string, change: string, branches: ReadonlySet<string>): boolean =>
642  branches.has(branch) || branch.toLowerCase().includes(change.toLowerCase())
643
644/** A step's agent names a file: lowercase words joined by hyphens, never a path. */
645export const AGENT_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/
646export const isAgentName = (name: string): boolean => AGENT_NAME.test(name)
647
hooks/flow.ts 1203 lines
1import type {
2  FlowActor,
3  FlowChoice,
4  FlowDef,
5  FlowDeploy,
6  FlowDeployProgress,
7  FlowDetect,
8  FlowEffort,
9  FlowEvent,
10  FlowMerge,
11  FlowOutcome,
12  FlowState,
13  FlowStep,
14  FlowStepDetails,
15  FlowStepKind,
16  FlowStepView,
17  FlowView,
18  Lang,
19  Languages,
20  Localized,
21  ProjectSettings,
22  Translations,
23} from '../types'
24import { libraryStep, NEXT_STEP, overlay } from './flows/library'
25import { executedText, isAgentName, masksExitCode } from './gates'
26import { DEFAULT_LANGUAGES, baseText, localize, parseLocalized, uiText } from './i18n'
27import type { UiText } from './i18n'
28import { MOCKUP_STEP } from './grill'
29import { parseJiraTarget } from './jira'
30import { DEPLOY_KEYS, MERGE_KEYS, isBranchName } from './project-config'
31
32/** The pseudo-step every flow ends on. */
33export const FLOW_END = 'fim'
34export const DEFAULT_MAX_ATTEMPTS = 3
35export const DEFAULT_FLOW_IDS = ['completo', 'rapido'] as const
36
37/** An escalation's two answers, pressed only by the owner. */
38export const escalationChoices = (t: UiText = uiText(undefined)): FlowChoice[] => [
39  { outcome: 'tentar-de-novo', label: t.escalation.retry },
40  { outcome: 'encerrar', label: t.escalation.end },
41]
42
43/** The outcome a loop step ends on, given by the mod once every phase closed. */
44export const LOOP_DONE = 'concluidas'
45
46/** Which actor may answer a step of each kind: a session never answers for the owner, a command or the loop. */
47const ANSWERED_BY: Record<FlowStepKind, FlowActor> = {
48  session: 'session',
49  loop: 'mod',
50  automatic: 'automatic',
51  owner: 'owner',
52}
53
54const KINDS = new Set<FlowStepKind>(['session', 'automatic', 'owner', 'loop'])
55const AUTOMATIC_OUTCOMES = ['passou', 'falhou']
56
57const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
58const text = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined)
59
60/** A field's per-language texts, kept only when the file gave them by language. */
61const byLang = (v: Localized | undefined): Translations | undefined => (v === undefined || typeof v === 'string' ? undefined : v)
62const perLang = (v: Localized): Translations => byLang(v) ?? {}
63
64/** A flow file, checked whole: every next step exists, every kind is known, every automatic step names its command. */
65export const parseFlow = (raw: unknown, source: string, project: ProjectSettings = {}): FlowDef | { error: string } => {
66  const fail = (why: string) => ({ error: `${source}: ${why}` })
67  if (!isRecord(raw)) return fail('a flow is a JSON object.')
68  const id = text(raw.id)
69  const flowTitle = parseLocalized(raw.title)
70  const flowDescription = parseLocalized(raw.description)
71  const title = baseText(flowTitle)
72  if (id === undefined || title === undefined) return fail('`id` and `title` are required.')
73  if (!Array.isArray(raw.steps) || raw.steps.length === 0) return fail('`steps` must be a non-empty list.')
74  const steps: FlowStep[] = []
75  for (const [i, s] of raw.steps.entries()) {
76    const where = `step ${i + 1}`
77    if (!isRecord(s)) return fail(`${where} is not an object.`)
78    const stepId = text(s.id)
79    const titles = parseLocalized(s.title)
80    const descriptions = parseLocalized(s.description)
81    const stepTitle = baseText(titles)
82    if (stepId === undefined || stepTitle === undefined) return fail(`${where}: \`id\` and \`title\` are required.`)
83    if (stepId === FLOW_END) return fail(`${where}: "${FLOW_END}" is reserved for the end of the flow.`)
84    if (steps.some(p => p.id === stepId)) return fail(`step id "${stepId}" appears twice.`)
85    const kind = s.kind as FlowStepKind
86    if (!KINDS.has(kind)) return fail(`step "${stepId}": kind must be session, automatic, owner or loop.`)
87    if (!isRecord(s.outcomes) || Object.keys(s.outcomes).length === 0) return fail(`step "${stepId}": \`outcomes\` is required.`)
88    const outcomes: Record<string, FlowOutcome> = {}
89    for (const [name, o] of Object.entries(s.outcomes)) {
90      const next = isRecord(o) ? text(o.next) : text(o)
91      if (next === undefined) return fail(`step "${stepId}", outcome "${name}": \`next\` is required.`)
92      const label = isRecord(o) ? parseLocalized(o.label) : undefined
93      const labels = byLang(label)
94      outcomes[name] = { label: baseText(label) ?? name, next, ...(labels === undefined ? {} : { labels }) }
95    }
96    const maxAttempts = s.maxAttempts === undefined ? DEFAULT_MAX_ATTEMPTS : s.maxAttempts
97    if (typeof maxAttempts !== 'number' || !Number.isInteger(maxAttempts) || maxAttempts < 1) {
98      return fail(`step "${stepId}": \`maxAttempts\` must be a whole number of at least 1.`)
99    }
100    const command = text(s.command)
101    if (kind === 'automatic') {
102      if (command === undefined) return fail(`step "${stepId}": an automatic step needs the \`command\` whose exit code decides.`)
103      const missing = AUTOMATIC_OUTCOMES.filter(o => outcomes[o] === undefined)
104      const extra = Object.keys(outcomes).filter(o => !AUTOMATIC_OUTCOMES.includes(o))
105      if (missing.length > 0 || extra.length > 0) {
106        return fail(`step "${stepId}": an automatic step has exactly the outcomes passou and falhou.`)
107      }
108    }
109    if ((s.agent === CODE_REVIEW_AGENT || stepId === CODE_REVIEW_STEP) && outcomes.aprovado === undefined) {
110      return fail(`step "${stepId}": a code review step declares the outcome aprovado, which the merge waits on.`)
111    }
112    if (s.when !== undefined && s.when !== 'visual') return fail(`step "${stepId}": \`when\` may only be "visual".`)
113    if (s.over !== undefined && s.over !== 'tasks') return fail(`step "${stepId}": \`over\` may only be "tasks".`)
114    if (kind === 'loop' && outcomes[LOOP_DONE] === undefined) {
115      return fail(`step "${stepId}": a loop step declares the outcome ${LOOP_DONE}, given when every phase closed.`)
116    }
117    const detect = parseDetect(s.detect, outcomes)
118    if (typeof detect === 'string') return fail(`step "${stepId}": ${detect}`)
119    const jira = parseJiraTarget(s.jira)
120    if (typeof jira === 'string') return fail(`step "${stepId}": ${jira}`)
121    const extras = parseExtras(s, kind, project)
122    if (typeof extras === 'string') return fail(`step "${stepId}": ${extras}`)
123    steps.push({
124      id: stepId,
125      title: stepTitle,
126      description: baseText(descriptions),
127      ...(byLang(titles) === undefined ? {} : { titles: byLang(titles) }),
128      ...(byLang(descriptions) === undefined ? {} : { descriptions: byLang(descriptions) }),
129      kind,
130      outcomes,
131      maxAttempts,
132      command,
133      requiresEvidence: s.requiresEvidence === true,
134      when: s.when === 'visual' ? 'visual' : undefined,
135      over: kind === 'loop' ? 'tasks' : undefined,
136      detect,
137      cleanup: s.cleanup === true,
138      ...(jira === undefined ? {} : { jira }),
139      ...extras,
140    })
141  }
142  watchRoutines(steps)
143  const ids = new Set(steps.map(s => s.id))
144  for (const step of steps) {
145    for (const [name, o] of Object.entries(step.outcomes)) {
146      if (o.next !== FLOW_END && !ids.has(o.next)) {
147        return fail(`step "${step.id}", outcome "${name}" goes to "${o.next}", which is no step of this flow.`)
148      }
149    }
150  }
151  return {
152    id,
153    title,
154    description: baseText(flowDescription) ?? '',
155    ...(byLang(flowTitle) === undefined ? {} : { titles: byLang(flowTitle) }),
156    ...(byLang(flowDescription) === undefined ? {} : { descriptions: byLang(flowDescription) }),
157    steps,
158  }
159}
160
161/** The step that says the change reached production; it also sees the deploy's routines. */
162export const PRODUCTION_STEP = 'producao'
163
164/**
165 * A flow with a deploy and the production step: the deploy's routines also answer production. The
166 * ones joined are kept apart in `routines`, so a derived flow starts again from production's own.
167 */
168const watchRoutines = (steps: FlowStep[]): void => {
169  const production = steps.find(s => s.id === PRODUCTION_STEP)
170  const own = production?.detect?.commands ?? []
171  const routines = [...new Set(steps.flatMap(s => s.deploy?.commands ?? []))].filter(c => !own.includes(c))
172  if (production === undefined || routines.length === 0) return
173  production.detect = { commands: [...own, ...routines], outcome: production.detect?.outcome ?? Object.keys(production.outcomes)[0]!, routines }
174}
175
176/** A detect without the deploy's routines the mod joined in: the step's own, or nothing when it had none. */
177export const ownDetect = (detect: FlowDetect | undefined): FlowDetect | undefined => {
178  if (detect === undefined) return undefined
179  const joined = detect.routines ?? []
180  const commands = detect.commands.filter(c => !joined.includes(c))
181  return commands.length === 0 ? undefined : { commands, outcome: detect.outcome }
182}
183
184/**
185 * A step's `detect`: one command or a list (`"vercel --prod"`), or `{ commands, outcome }`; the
186 * outcome may be left out when the step declares only one.
187 */
188const parseDetect = (raw: unknown, outcomes: Record<string, FlowOutcome>): FlowDetect | undefined | string => {
189  if (raw === undefined) return undefined
190  const spec = isRecord(raw) ? raw : { commands: raw }
191  const list = typeof spec.commands === 'string' ? [spec.commands] : spec.commands
192  const commands = Array.isArray(list) ? list.map(text).filter((c): c is string => c !== undefined) : []
193  if (commands.length === 0) return '`detect` needs at least one command.'
194  const names = Object.keys(outcomes)
195  const outcome = text(spec.outcome) ?? (names.length === 1 ? names[0] : undefined)
196  if (outcome === undefined || outcomes[outcome] === undefined) {
197    return `\`detect.outcome\` must name one of the step's outcomes (${names.join(', ')}).`
198  }
199  return { commands, outcome }
200}
201
202const DETAIL_KEYS = ['inputs', 'produces', 'blocks'] as const
203const EFFORTS: readonly string[] = ['low', 'medium', 'high', 'xhigh', 'max']
204const MERGE_METHODS: readonly string[] = ['squash', 'merge', 'rebase']
205
206type StepExtras = Pick<FlowStep, 'details' | 'detailsByLang' | 'agent' | 'model' | 'effort' | 'merge' | 'deploy'>
207
208/**
209 * The fields that describe a step and who runs it: `details`, `agent`, `model`, `effort`, and the
210 * `merge` or `deploy` it carries out. An agent runs a session, a loop's phases, or a merge or deploy
211 * the coordinator carries out; a merge or deploy is the owner's, or automatic with `auto`.
212 */
213const parseExtras = (s: Record<string, unknown>, kind: FlowStepKind, project: ProjectSettings): StepExtras | string => {
214  const out: StepExtras = {}
215  if (s.details !== undefined) {
216    if (!isRecord(s.details)) return '`details` is an object with inputs, produces and blocks.'
217    const unknown = Object.keys(s.details).filter(k => !(DETAIL_KEYS as readonly string[]).includes(k))
218    if (unknown.length > 0) return `\`details\` takes only inputs, produces and blocks, not ${unknown.join(', ')}.`
219    const details: FlowStepDetails = {}
220    const byLang: Partial<Record<Lang, FlowStepDetails>> = {}
221    for (const key of DETAIL_KEYS) {
222      if (s.details[key] === undefined) continue
223      const value = parseLocalized(s.details[key])
224      if (value === undefined) return `\`details.${key}\` must be text, or one text per language.`
225      details[key] = baseText(value)
226      for (const [lang, t] of Object.entries(perLang(value))) (byLang[lang as Lang] ??= {})[key] = t
227    }
228    out.details = details
229    if (Object.keys(byLang).length > 0) out.detailsByLang = byLang
230  }
231  for (const key of ['agent', 'model'] as const) {
232    if (s[key] === undefined) continue
233    const value = text(s[key])
234    if (value === undefined) return `\`${key}\` must be a name.`
235    out[key] = value
236  }
237  if (out.agent !== undefined && !isAgentName(out.agent)) return `\`agent\` "${out.agent}" must be lowercase words joined by hyphens (a-z, 0-9, -), the name of a file in agents/.`
238  if (s.effort !== undefined) {
239    if (typeof s.effort !== 'string' || !EFFORTS.includes(s.effort)) return `\`effort\` must be one of ${EFFORTS.join(', ')}.`
240    out.effort = s.effort as FlowEffort
241  }
242  if (s.merge !== undefined) {
243    const merge = parseMerge(s.merge, project.merge, kind)
244    if (typeof merge === 'string') return merge
245    out.merge = merge
246  }
247  if (s.deploy !== undefined) {
248    const deploy = parseDeploy(s.deploy, project.deploy, kind)
249    if (typeof deploy === 'string') return deploy
250    out.deploy = deploy
251  }
252  if (out.merge !== undefined && out.deploy !== undefined) return 'a step merges or deploys, not both.'
253  const runs = out.merge !== undefined ? 'merge' : out.deploy !== undefined ? 'deploy' : undefined
254  const auto = (out.merge ?? out.deploy)?.auto
255  if (runs !== undefined && kind !== (auto ? 'automatic' : 'owner')) {
256    return `a ${runs} step with \`auto: ${auto}\` is ${auto ? 'automatic' : 'an owner step'}, not ${kind}.`
257  }
258  if (out.agent !== undefined && kind !== 'session' && kind !== 'loop' && runs === undefined) {
259    return '`agent` goes only on a session or loop step, or on a merge or deploy step.'
260  }
261  return out
262}
263
264const flag = (v: unknown, name: string, fallback: boolean): boolean | string =>
265  v === undefined ? fallback : typeof v === 'boolean' ? v : `\`${name}\` must be true or false.`
266
267/** The fields a raw block lists as not written by the step (the project's value baked in), kept while they still match. */
268const bakedKeys = (raw: Record<string, unknown>, keys: readonly string[], project: Record<string, unknown> | undefined): string[] =>
269  Array.isArray(raw.fromProject)
270    ? keys.filter(k => (raw.fromProject as unknown[]).includes(k) && raw[k] !== undefined && JSON.stringify(raw[k]) === JSON.stringify(project?.[k]))
271    : []
272
273/** `merge`: the target branch, the method (squash unless said) and whether the coordinator merges by itself; what the step leaves out comes from the project. */
274const parseMerge = (raw: unknown, project: ProjectSettings['merge'], kind: FlowStepKind): FlowMerge | string => {
275  if (!isRecord(raw)) return '`merge` is an object with branch, method and auto.'
276  const baked = bakedKeys(raw, MERGE_KEYS, project as Record<string, unknown> | undefined)
277  const fromProject: string[] = []
278  let branch = text(raw.branch)
279  if (raw.branch === undefined && project?.branch !== undefined) {
280    branch = project.branch
281    fromProject.push('branch')
282  } else if (baked.includes('branch')) fromProject.push('branch')
283  if (branch === undefined) return '`merge.branch` names the branch the PR merges into.'
284  if (!isBranchName(branch)) return `\`merge.branch\` "${branch}" is not a branch name (letters, digits, . _ / -).`
285  let method: unknown = raw.method
286  if (method === undefined) {
287    method = project?.method ?? 'squash'
288    if (project?.method !== undefined) fromProject.push('method')
289  } else if (baked.includes('method')) fromProject.push('method')
290  if (typeof method !== 'string' || !MERGE_METHODS.includes(method)) return `\`merge.method\` must be one of ${MERGE_METHODS.join(', ')}.`
291  let auto = flag(raw.auto, 'merge.auto', false)
292  if (typeof auto === 'string') return auto
293  if (raw.auto === undefined && project?.auto !== undefined && project.auto === (kind === 'automatic')) {
294    auto = project.auto
295    fromProject.push('auto')
296  } else if (baked.includes('auto')) fromProject.push('auto')
297  return { branch, method: method as FlowMerge['method'], auto, ...(fromProject.length === 0 ? {} : { fromProject }) }
298}
299
300/** `deploy`: the CI's deploy waited on, routines run after the merge, or both; and whether it runs by itself. What the step leaves out comes from the project. */
301const parseDeploy = (raw: unknown, project: ProjectSettings['deploy'], kind: FlowStepKind): FlowDeploy | string => {
302  if (!isRecord(raw)) return '`deploy` is an object with ci, commands and auto.'
303  const baked = bakedKeys(raw, DEPLOY_KEYS, project as Record<string, unknown> | undefined)
304  const fromProject: string[] = []
305  let ci = flag(raw.ci, 'deploy.ci', false)
306  if (typeof ci === 'string') return ci
307  if (raw.ci === undefined && project?.ci !== undefined) {
308    ci = project.ci
309    fromProject.push('ci')
310  } else if (baked.includes('ci')) fromProject.push('ci')
311  let auto = flag(raw.auto, 'deploy.auto', false)
312  if (typeof auto === 'string') return auto
313  if (raw.auto === undefined && project?.auto !== undefined && project.auto === (kind === 'automatic')) {
314    auto = project.auto
315    fromProject.push('auto')
316  } else if (baked.includes('auto')) fromProject.push('auto')
317  let list: unknown = raw.commands === undefined ? [] : typeof raw.commands === 'string' ? [raw.commands] : raw.commands
318  if (raw.commands === undefined && project?.commands !== undefined) {
319    list = project.commands
320    fromProject.push('commands')
321  } else if (baked.includes('commands')) fromProject.push('commands')
322  if (!Array.isArray(list) || list.some(c => text(c) === undefined)) return '`deploy.commands` is a list of commands.'
323  const commands = list.map(c => text(c) as string)
324  if (!ci && commands.length === 0) return '`deploy` needs `ci: true`, `commands`, or both.'
325  const order = DEPLOY_KEYS.filter(k => fromProject.includes(k))
326  return { ci, commands, auto, ...(order.length === 0 ? {} : { fromProject: order }) }
327}
328
329/** The flows on offer: the mod's defaults, each replaced by a project's flow of the same id. */
330export const mergeFlows = (defaults: readonly FlowDef[], project: readonly FlowDef[]): Record<string, FlowDef> => {
331  const all: Record<string, FlowDef> = {}
332  for (const flow of [...defaults, ...project]) all[flow.id] = flow
333  return all
334}
335
336/** A flow file as read: its raw JSON and where it came from. */
337export type FlowSource = { source: string; raw: unknown }
338
339type RawStep = Record<string, unknown> & { id: string; outcomes: Record<string, { next: string }> }
340
341/** A value's own text list: undefined is empty, anything but a list of names is refused. */
342const names = (v: unknown): string[] | undefined =>
343  v === undefined ? [] : Array.isArray(v) && v.every(x => text(x) !== undefined) ? v.map(x => text(x) as string) : undefined
344
345/** A parsed step as a file writes it: its title, description and labels by language where it has them. */
346export const asWritten = ({ titles, descriptions, detailsByLang, ...step }: FlowStep): Record<string, unknown> => ({
347  ...step,
348  ...(step.details === undefined || detailsByLang === undefined
349    ? {}
350    : {
351        details: Object.fromEntries(
352          DETAIL_KEYS.flatMap((key): [string, Localized][] => {
353            const texts: Translations = {}
354            for (const lang of Object.keys(detailsByLang) as Lang[]) {
355              const t = detailsByLang[lang]?.[key]
356              if (t !== undefined) texts[lang] = t
357            }
358            const base = step.details?.[key]
359            return Object.keys(texts).length > 0 ? [[key, texts]] : base === undefined ? [] : [[key, base]]
360          }),
361        ),
362      }),
363  title: titles ?? step.title,
364  ...((descriptions ?? step.description) === undefined ? {} : { description: descriptions ?? step.description }),
365  outcomes: Object.fromEntries(
366    Object.entries(step.outcomes).map(([name, { labels, ...o }]) => [name, { ...o, label: labels ?? o.label }]),
367  ),
368})
369
370/**
371 * A flow file whole: one with `steps` goes straight to parseFlow; one with `base` is resolved from
372 * its base (found by `find`, which may itself be derived), then `remove` (each outcome that led to a
373 * removed step leads where that step's first outcome led, through every removed one), `add` (the
374 * step enters after `after`, whose forward outcome now leads to it, and it leads where that one
375 * led), `override` (fields laid over a step, never its id or kind) and `order`, and the result goes
376 * through parseFlow like any other.
377 */
378export const resolveFlow = (
379  raw: unknown,
380  source: string,
381  find: (id: string, from: string) => FlowSource | undefined,
382  chain: readonly { id: string; source: string }[] = [],
383  project: ProjectSettings = {},
384): FlowDef | { error: string } => {
385  if (!isRecord(raw) || raw.base === undefined) return parseFlow(raw, source, project)
386  const fail = (why: string) => ({ error: `${source}: ${why}` })
387  const id = text(raw.id)
388  if (id === undefined) return fail('`id` is required.')
389  if (raw.steps !== undefined) return fail('a flow has `base` or `steps`, not both.')
390  const baseId = text(raw.base)
391  if (baseId === undefined) return fail('`base` names the flow this one derives from.')
392  const path = [...chain, { id, source }]
393  const found = find(baseId, id)
394  if (found === undefined) return fail(`base "${baseId}" is no flow of the mod or of the project.`)
395  if (path.some(p => p.source === found.source)) {
396    return fail(`\`base\` goes round in a circle: ${[...path.map(p => p.id), baseId].join(' → ')}.`)
397  }
398  const base = resolveFlow(found.raw, found.source, find, path, project)
399  if ('error' in base) return fail(`base "${baseId}" does not resolve: ${base.error}`)
400  // each text goes back to how a file writes it, one per language, so a derived flow keeps the translations
401  let steps = (JSON.parse(JSON.stringify(base.steps)) as FlowStep[]).map(asWritten) as unknown as RawStep[]
402  // production's detect goes back to its own commands; parseFlow joins the routines of the deploy that stays
403  for (const step of steps) {
404    const own = ownDetect(step.detect as FlowDetect | undefined)
405    if (own === undefined) delete step.detect
406    else step.detect = own
407  }
408  const at = (sid: string) => steps.findIndex(s => s.id === sid)
409
410  const remove = names(raw.remove)
411  if (remove === undefined) return fail('`remove` is a list of step ids.')
412  for (const sid of remove) {
413    const step = steps[at(sid)]
414    if (step === undefined) return fail(`\`remove\`: "${sid}" is no step of ${baseId}.`)
415    if (step.kind === 'loop') return fail(`\`remove\`: "${sid}" runs the change's phases; it cannot be removed.`)
416  }
417  const gone = new Set(remove)
418  const through = (target: string, seen: readonly string[]): string | undefined => {
419    if (!gone.has(target)) return target
420    if (seen.includes(target)) return undefined
421    const first = Object.values(steps[at(target)]!.outcomes)[0]!.next
422    return through(first, [...seen, target])
423  }
424  const kept = steps.filter(s => !gone.has(s.id))
425  for (const step of kept) {
426    for (const [name, o] of Object.entries(step.outcomes)) {
427      const next = through(o.next, [])
428      if (next === undefined) return fail(`\`remove\`: step "${step.id}", outcome "${name}" leads only through removed steps.`)
429      o.next = next
430    }
431  }
432  steps = kept
433
434  if (raw.add !== undefined && !Array.isArray(raw.add)) return fail('`add` is a list of { after, step }.')
435  for (const [i, a] of ((raw.add ?? []) as unknown[]).entries()) {
436    const where = `add ${i + 1}`
437    if (!isRecord(a)) return fail(`${where} is not an object.`)
438    const after = text(a.after)
439    const anchor = after === undefined ? undefined : steps[at(after)]
440    if (anchor === undefined) return fail(`${where}: \`after\` "${after ?? ''}" is no step of the flow.`)
441    // a copy: the "$seguinte" below is filled in on the step, never on the file's own object, which resolves again the same
442    const step = libraryStep(JSON.parse(JSON.stringify(a.step ?? null)) as unknown, project)
443    if (typeof step === 'string') return fail(`${where}: ${step}`)
444    const sid = text(step.id)
445    if (sid === undefined) return fail(`${where}: the step needs an \`id\`.`)
446    if (at(sid) !== -1) return fail(`${where}: step id "${sid}" is already in the flow.`)
447    const from = at(anchor.id)
448    const forward = Object.values(anchor.outcomes).find(o => o.next === FLOW_END || at(o.next) > from)
449    if (forward === undefined) return fail(`${where}: step "${anchor.id}" has no outcome that goes forward.`)
450    const outcomes = isRecord(step.outcomes) ? step.outcomes : {}
451    for (const o of Object.values(outcomes)) {
452      if (isRecord(o) && o.next === NEXT_STEP) o.next = forward.next
453    }
454    for (const [name, o] of Object.entries(outcomes)) if (o === NEXT_STEP) outcomes[name] = forward.next
455    forward.next = sid
456    steps.splice(from + 1, 0, { ...step, id: sid } as RawStep)
457  }
458
459  if (raw.override !== undefined && !isRecord(raw.override)) return fail('`override` maps step ids to the fields that change.')
460  for (const [sid, changes] of Object.entries(raw.override ?? {})) {
461    const i = at(sid)
462    if (i === -1) return fail(`\`override\`: "${sid}" is no step of the flow.`)
463    if (!isRecord(changes)) return fail(`\`override\` of "${sid}" is an object of fields.`)
464    for (const key of ['id', 'kind'] as const) {
465      if (changes[key] !== undefined && changes[key] !== steps[i]![key]) return fail(`\`override\` of "${sid}" cannot change its \`${key}\`.`)
466    }
467    steps[i] = overlay(steps[i], changes) as RawStep
468  }
469
470  const order = raw.order === undefined ? undefined : names(raw.order)
471  if (raw.order !== undefined) {
472    const ids = steps.map(s => s.id)
473    if (order === undefined || order.length !== ids.length || new Set(order).size !== ids.length || order.some(o => !ids.includes(o))) {
474      return fail(`\`order\` names every step of the flow once: ${ids.join(', ')}.`)
475    }
476    steps = order.map(o => steps[at(o)]!)
477  }
478
479  const parsed = parseFlow(
480    {
481      id,
482      title: parseLocalized(raw.title) ?? base.titles ?? base.title,
483      description: parseLocalized(raw.description) ?? base.descriptions ?? base.description,
484      steps,
485    },
486    source,
487    project,
488  )
489  return 'error' in parsed ? parsed : { ...parsed, base: baseId }
490}
491
492/**
493 * A project's flow files resolved: a derived one finds its base among the project's other flows
494 * first, then the mod's defaults; a project flow deriving from its own id derives from the default.
495 */
496export const resolveProjectFlows = (
497  defaults: readonly FlowSource[],
498  project: readonly FlowSource[],
499  settings: ProjectSettings = {},
500): { flows: FlowDef[]; problems: string[] } => {
501  const byId = (files: readonly FlowSource[]) =>
502    Object.fromEntries(files.flatMap(f => (isRecord(f.raw) && text(f.raw.id) !== undefined ? [[text(f.raw.id) as string, f]] : [])))
503  const mine = byId(project)
504  const theirs = byId(defaults)
505  const find = (id: string, from: string) => (id === from ? undefined : mine[id]) ?? theirs[id]
506  const flows: FlowDef[] = []
507  const problems: string[] = []
508  for (const file of project) {
509    const resolved = resolveFlow(file.raw, file.source, find, [], settings)
510    if ('error' in resolved) problems.push(resolved.error)
511    else flows.push(resolved)
512  }
513  return { flows, problems }
514}
515
516export type Moved = { state: FlowState; events: FlowEvent[] }
517
518export const stepOf = (flow: FlowDef, id: string): FlowStep | undefined => flow.steps.find(s => s.id === id)
519const indexOf = (flow: FlowDef, id: string): number => flow.steps.findIndex(s => s.id === id)
520
521const applies = (step: FlowStep, state: FlowState): boolean => step.when !== 'visual' || state.traits.visual
522
523/**
524 * Enters `target`: skips steps whose trait the change lacks, forgets the outcomes of the target and
525 * every step after it (they must be done again), and counts the attempt. A session's or a command's
526 * outcome that would enter a step past its ceiling escalates to the owner instead; the owner's own
527 * press never does, since the owner already chose.
528 */
529const enter = (state: FlowState, target: string, by: FlowActor, cause: { from: string; outcome: string }, at: number): Moved => {
530  const events: FlowEvent[] = []
531  let seq = state.seq
532  const push = (e: Omit<FlowEvent, 'seq' | 'at'>) => events.push({ seq: ++seq, at, ...e })
533  let id = target
534  while (id !== FLOW_END) {
535    const step = stepOf(state.flow, id)
536    if (step === undefined || applies(step, state)) break
537    push({ kind: 'skipped', step: id, by: 'mod', note: `only when the change is ${step.when}` })
538    id = state.flow.steps[indexOf(state.flow, id) + 1]?.id ?? FLOW_END
539  }
540  if (id === FLOW_END) {
541    push({ kind: 'done', step: FLOW_END, by: 'mod' })
542    return { state: { ...state, current: FLOW_END, status: 'done', escalation: undefined, seq, updatedAt: at }, events }
543  }
544  const step = stepOf(state.flow, id) as FlowStep
545  const from = indexOf(state.flow, id)
546  const records = Object.fromEntries(
547    Object.entries(state.records).filter(([sid]) => indexOf(state.flow, sid) < from),
548  )
549  // a deploy that retries itself keeps what it saw done; coming back from a later step starts it over
550  const progress = Object.fromEntries(
551    Object.entries(state.progress ?? {}).filter(([sid]) => indexOf(state.flow, sid) < from || (sid === id && cause.from === id)),
552  )
553  // going back keeps why (e.g. QA's request), until the flow reaches that step again
554  const cause_ = state.records[cause.from]
555  const source = stepOf(state.flow, cause.from)
556  const reopened =
557    cause_ !== undefined && source !== undefined && from <= indexOf(state.flow, cause.from)
558      ? {
559          step: cause.from,
560          outcome: cause.outcome,
561          label: source.outcomes[cause.outcome]?.label ?? cause.outcome,
562          by: cause_.by,
563          at,
564          ...(cause_.note === undefined ? {} : { note: cause_.note }),
565        }
566      : state.reopened !== undefined && id !== state.reopened.step
567        ? state.reopened
568        : undefined
569  const { reopened: _drop, progress: _progress, ...rest } = state
570  state = {
571    ...rest,
572    ...(reopened === undefined ? {} : { reopened }),
573    ...(Object.keys(progress).length === 0 ? {} : { progress }),
574  }
575  const attempts = state.attempts[id] ?? 0
576  if (by !== 'owner' && attempts >= step.maxAttempts) {
577    const escalation = { step: id, from: cause.from, outcome: cause.outcome, attempts }
578    push({ kind: 'escalated', step: id, by: 'mod', note: `${attempts} attempts, the ceiling is ${step.maxAttempts}` })
579    return { state: { ...state, current: id, status: 'escalated', escalation, records, seq, updatedAt: at }, events }
580  }
581  push({ kind: 'entered', step: id, by: 'mod' })
582  return {
583    state: {
584      ...state,
585      current: id,
586      status: 'running',
587      escalation: undefined,
588      attempts: { ...state.attempts, [id]: attempts + 1 },
589      records,
590      seq,
591      updatedAt: at,
592    },
593    events,
594  }
595}
596
597/** A change starts on the flow's first step that applies to it. */
598export const startFlow = (
599  flow: FlowDef,
600  init: { change: string; coordinatorCwd: string; changePath?: string; visual: boolean },
601  at: number,
602): Moved => {
603  const blank: FlowState = {
604    change: init.change,
605    coordinatorCwd: init.coordinatorCwd,
606    ...(init.changePath === undefined ? {} : { changePath: init.changePath }),
607    flow,
608    traits: { visual: init.visual },
609    current: flow.steps[0]!.id,
610    status: 'running',
611    attempts: {},
612    records: {},
613    seq: 1,
614    startedAt: at,
615    updatedAt: at,
616  }
617  const started: FlowEvent = { seq: 1, at, kind: 'started', step: flow.id, by: 'mod', note: init.visual ? 'visual' : undefined }
618  const moved = enter(blank, flow.steps[0]!.id, 'owner', { from: '', outcome: '' }, at)
619  return { state: moved.state, events: [JSON.parse(JSON.stringify(started)) as FlowEvent, ...moved.events] }
620}
621
622const WHO: Record<FlowActor, string> = {
623  session: 'a session (through the flow tool)',
624  automatic: 'the mod, watching its command run',
625  owner: 'the owner, pressing a button in the panel',
626  mod: 'the mod, once every phase is closed (close each with action "close")',
627  detect: "the mod, seeing the step's detect command succeed",
628}
629
630/**
631 * One outcome reported for one step. Refused, with the reason in the model's words, when the flow
632 * is not on that step (no skipping ahead or back), when the step's kind is not answered by this
633 * actor, or when the step does not declare the outcome.
634 */
635export const applyOutcome = (
636  state: FlowState,
637  report: { step: string; outcome: string; by: FlowActor; note?: string },
638  at: number,
639): Moved | { error: string } => {
640  const asked = stepOf(state.flow, report.step)
641  if (asked === undefined) {
642    return { error: `flow ${state.flow.id} has no step "${report.step}"; its steps are ${state.flow.steps.map(s => s.id).join(', ')}.` }
643  }
644  if (state.status === 'done') return { error: `the flow of ${state.change} is finished; nothing is left to report.` }
645  if (state.status === 'aborted') return { error: `the owner ended the flow of ${state.change}.` }
646  const current = stepOf(state.flow, state.current) as FlowStep
647  if (state.status === 'escalated') {
648    return {
649      error:
650        `step "${current.id}" (${current.title}) hit its ceiling of ${current.maxAttempts} attempts; ` +
651        'the owner decides in the panel whether it goes again.',
652    }
653  }
654  if (report.step !== state.current) {
655    const ahead = indexOf(state.flow, report.step) > indexOf(state.flow, state.current)
656    return {
657      error:
658        `the flow of ${state.change} is on "${current.id}" (${current.title}), not on "${report.step}"` +
659        (ahead ? ': steps cannot be skipped' : '') +
660        `. "${current.id}" is answered by ${WHO[ANSWERED_BY[current.kind]]}.`,
661    }
662  }
663  const detected = report.by === 'detect' && asked.detect !== undefined
664  if (ANSWERED_BY[asked.kind] !== report.by && !detected) {
665    return { error: `step "${asked.id}" (${asked.title}) is a ${asked.kind} step: only ${WHO[ANSWERED_BY[asked.kind]]} answers it.` }
666  }
667  if (detected && report.outcome !== asked.detect?.outcome) {
668    return { error: `step "${asked.id}": a detected command gives only ${asked.detect?.outcome}.` }
669  }
670  if (asked.outcomes[report.outcome] === undefined) {
671    return { error: `step "${asked.id}" has no outcome "${report.outcome}"; it declares ${Object.keys(asked.outcomes).join(', ')}.` }
672  }
673  if (asked.deploy !== undefined && report.outcome !== 'falhou' && !ownerConfirms(state, asked, report.by, report.outcome)) {
674    return {
675      error:
676        `step "${asked.id}" (${asked.title}) moves on by itself once the mod saw the whole deploy: ` +
677        `${deployWaits(state, asked)}.`,
678    }
679  }
680  return settle(state, asked, report.outcome, report.by, report.note, at)
681}
682
683/** Records a step's outcome and enters where it leads. */
684const settle = (state: FlowState, step: FlowStep, name: string, by: FlowActor, given: string | undefined, at: number): Moved => {
685  const outcome = step.outcomes[name] as FlowOutcome
686  const note = given ?? state.pendingNote
687  const record = { outcome: name, by, at, ...(note === undefined ? {} : { note }) }
688  const reported: FlowEvent = {
689    seq: state.seq + 1,
690    at,
691    kind: 'outcome',
692    step: step.id,
693    by,
694    outcome: name,
695    ...(note === undefined ? {} : { note }),
696  }
697  const { pendingNote: _used, ...unnoted } = state
698  const moved = enter(
699    { ...unnoted, records: { ...state.records, [step.id]: record }, seq: state.seq + 1 },
700    outcome.next,
701    by,
702    { from: step.id, outcome: name },
703    at,
704  )
705  return { state: moved.state, events: [reported, ...moved.events] }
706}
707
708/** The owner's button on a deploy step that waits on the CI. */
709export const DEPLOY_CI_OUTCOME = 'ci-concluido'
710export const DEPLOY_CI_LABEL = 'Deploy do CI concluído'
711
712/** `gh run watch` / `gh run view` that fail with the run: only `--exit-status` makes their exit code the run's. */
713const CI_WATCH = /\bgh\s+run\s+(?:watch|view)\b(?=[^;&|\n]*\s--exit-status\b)/
714
715const progressOf = (state: FlowState, step: FlowStep): FlowDeployProgress =>
716  state.progress?.[step.id] ?? { ci: false, commands: [] }
717
718/** What a deploy step still waits on: the CI's deploy, then its routines in order. */
719export const deployPending = (state: FlowState, step: FlowStep): FlowDeployProgress => {
720  const done = progressOf(state, step)
721  return { ci: step.deploy?.ci === true && !done.ci, commands: (step.deploy?.commands ?? []).slice(done.commands.length) }
722}
723
724const deployWaits = (state: FlowState, step: FlowStep): string => {
725  const pending = deployPending(state, step)
726  const parts = [
727    ...(pending.ci ? ["the CI's deploy"] : []),
728    ...(pending.commands.length > 0 ? [`the routines ${pending.commands.map(c => `\`${c}\``).join(', ')}`] : []),
729  ]
730  return parts.length === 0 ? 'nothing is left' : `it still waits on ${parts.join(', then ')}`
731}
732
733/**
734 * An owner's deploy with only routines left (none from the start, or the CI's already confirmed):
735 * the owner may confirm it whole with the step's forward outcome ("Deploy concluído"), having run
736 * the routines where the mod did not see them.
737 */
738const ownerConfirms = (state: FlowState, step: FlowStep, by: FlowActor, outcome: string): boolean =>
739  step.kind === 'owner' &&
740  step.deploy !== undefined &&
741  !deployPending(state, step).ci &&
742  by === 'owner' &&
743  outcome === Object.keys(step.outcomes)[0]
744
745/** One more thing the deploy saw done; with nothing left, the step moves on. */
746const tick = (state: FlowState, step: FlowStep, done: FlowDeployProgress, by: FlowActor, note: string, at: number): Moved => {
747  const progressed: FlowState = { ...state, progress: { ...state.progress, [step.id]: done }, seq: state.seq + 1, updatedAt: at }
748  const event: FlowEvent = { seq: state.seq + 1, at, kind: 'progress', step: step.id, by, note }
749  const pending = deployPending(progressed, step)
750  if (pending.ci || pending.commands.length > 0) return { state: progressed, events: [event] }
751  const forward = step.kind === 'automatic' ? 'passou' : Object.keys(step.outcomes)[0]!
752  const moved = settle(progressed, step, forward, step.kind === 'automatic' ? 'automatic' : 'mod', undefined, at)
753  return { state: moved.state, events: [event, ...moved.events] }
754}
755
756/** The owner confirms the CI's deploy from the panel. */
757export const confirmDeployCi = (state: FlowState, stepId: string, at: number): Moved | { error: string } => {
758  const step = currentStep(state)
759  if (state.status !== 'running' || step === undefined || step.id !== stepId) return { error: `the flow of ${state.change} is not on "${stepId}".` }
760  if (step.deploy?.ci !== true) return { error: `step "${step.id}" does not wait on the CI.` }
761  const done = progressOf(state, step)
762  if (done.ci) return { error: `the CI's deploy of "${step.id}" is already confirmed.` }
763  return tick(state, step, { ...done, ci: true }, 'owner', DEPLOY_CI_LABEL, at)
764}
765
766/**
767 * One finished Bash command, read by the deploy step the flow is on: `gh run watch|view
768 * --exit-status` passing confirms the CI's deploy; a routine passing counts only after the CI
769 * (when the step waits on it) and only as the next one in order. A CI watch is read only while
770 * the step waits on the CI it has not seen yet. A masked exit code proves nothing. A failure fails an automatic deploy; an owner's deploy holds. Undefined when the
771 * command is none of the deploy's; an error when it is one but does not count.
772 */
773export const observeDeploy = (state: FlowState, command: string, failed: boolean, at: number): Moved | { error: string } | undefined => {
774  const step = currentStep(state)
775  if (state.status !== 'running' || step?.deploy === undefined) return undefined
776  const code = executedText(command)
777  const routines = step.deploy.commands.map(commandPattern)
778  const routine = routines.findIndex(p => p.test(code))
779  const pattern = routine === -1 ? (CI_WATCH.test(code) ? CI_WATCH : undefined) : routines[routine]!
780  if (pattern === undefined) return undefined
781  const what = routine === -1 ? "the CI's deploy" : `the routine \`${step.deploy.commands[routine]}\``
782  const done = progressOf(state, step)
783  // a CI watch counts, either way, only while the step still waits on the CI
784  if (routine === -1 && (!step.deploy.ci || done.ci)) return undefined
785  if (failed) {
786    return step.kind === 'automatic'
787      ? settle(state, step, 'falhou', 'automatic', `${what} failed`, at)
788      : { error: `${what} failed; the deploy holds until it passes.` }
789  }
790  if (masksExitCode(code, pattern)) return { error: `${what} ran with its exit code hidden; run it alone for it to count.` }
791  if (routine === -1) {
792    return tick(state, step, { ...done, ci: true }, 'detect', executedTextShort(command), at)
793  }
794  if (step.deploy.ci && !done.ci) return { error: `${what} ran before the CI's deploy was confirmed; it does not count.` }
795  const expected = done.commands.length
796  if (routine < expected) return { error: `${what} already passed.` }
797  if (routine > expected) {
798    return { error: `${what} ran out of order; \`${step.deploy.commands[expected]}\` comes first, so it does not count.` }
799  }
800  return tick(state, step, { ...done, commands: [...done.commands, step.deploy.commands[routine]!] }, 'detect', executedTextShort(command), at)
801}
802
803export const executedTextShort = (command: string): string => `comando: ${command.replace(/\s+/g, ' ').trim().slice(0, 80)}`
804
805/** The PR review step: no merge of the change's PR before the owner approved it. */
806export const REVIEW_STEP = 'revisao-pr'
807
808/**
809 * The PR review the flow has not answered yet and comes before its next merge (the merge step it
810 * is on, or the first one after); with no merge step ahead, any unanswered review. A finished or
811 * aborted flow waits on none.
812 */
813export const pendingReview = (state: FlowState): FlowStep | undefined => {
814  if (state.status === 'done' || state.status === 'aborted') return undefined
815  const steps = state.flow.steps
816  const at = Math.max(0, indexOf(state.flow, state.current))
817  const merge = steps.findIndex((s, i) => i >= at && s.merge !== undefined)
818  return steps
819    .slice(0, merge === -1 ? steps.length : merge)
820    .find(s => (s.id === REVIEW_STEP || s.id.startsWith(`${REVIEW_STEP}-`)) && state.records[s.id] === undefined)
821}
822
823/** The agent that merges on the workflow's own approval, with no approval on GitHub. */
824export const WORKFLOW_MERGE_AGENT = 'merge-pelo-workflow'
825
826/** The code review step the workflow itself answers. */
827export const CODE_REVIEW_AGENT = 'revisor-codigo'
828export const CODE_REVIEW_STEP = 'revisao-codigo'
829
830/**
831 * The code review step before the flow's next merge that has no "aprovado" since the flow last
832 * entered it (entering a step forgets its record and every later one, so a turn back to run again
833 * clears it). A flow whose merges are all behind it waits on none. A review that does not apply to the change is not waited on. A finished or aborted
834 * flow waits on none.
835 */
836export const pendingCodeReview = (state: FlowState): FlowStep | undefined => {
837  if (state.status === 'done' || state.status === 'aborted') return undefined
838  const steps = state.flow.steps
839  const at = Math.max(0, indexOf(state.flow, state.current))
840  const merge = steps.findIndex((s, i) => i >= at && s.merge !== undefined)
841  // every merge of the flow is behind it: the review is not waited on any more
842  if (merge === -1 && steps.some(s => s.merge !== undefined)) return undefined
843  return steps
844    .slice(0, merge === -1 ? steps.length : merge)
845    .find(
846      s =>
847        (s.agent === CODE_REVIEW_AGENT || s.id === CODE_REVIEW_STEP) &&
848        applies(s, state) &&
849        state.records[s.id]?.outcome !== 'aprovado',
850    )
851}
852
853/** The owner's answer to an escalation: go again with a fresh count, or end the flow. */
854export const resolveEscalation = (state: FlowState, choice: string, at: number): Moved | { error: string } => {
855  if (state.status !== 'escalated' || state.escalation === undefined) return { error: 'nothing is escalated.' }
856  const step = state.escalation.step
857  if (choice === 'encerrar') {
858    const event: FlowEvent = { seq: state.seq + 1, at, kind: 'aborted', step, by: 'owner' }
859    return { state: { ...state, status: 'aborted', seq: state.seq + 1, updatedAt: at }, events: [event] }
860  }
861  if (choice !== 'tentar-de-novo') return { error: `an escalation is answered with tentar-de-novo or encerrar, not "${choice}".` }
862  const retried: FlowEvent = { seq: state.seq + 1, at, kind: 'retried', step, by: 'owner' }
863  const moved = enter(
864    { ...state, attempts: { ...state.attempts, [step]: 0 }, seq: state.seq + 1 },
865    step,
866    'owner',
867    { from: state.escalation.from, outcome: state.escalation.outcome },
868    at,
869  )
870  return { state: moved.state, events: [retried, ...moved.events] }
871}
872
873/** The owner's press: an escalation's choice while one is open, else the owner step's outcome. */
874export const ownerPress = (state: FlowState, step: string, outcome: string, at: number, note?: string): Moved | { error: string } =>
875  state.status === 'escalated' && state.escalation?.step === step
876    ? resolveEscalation(state, outcome, at)
877    : outcome === DEPLOY_CI_OUTCOME
878      ? confirmDeployCi(state, step, at)
879      : applyOutcome(state, { step, outcome, by: 'owner', ...(note === undefined ? {} : { note }) }, at)
880
881/** What the owner sees after a press: the answer recorded, in their words, and where the flow went. */
882export const pressedToast = (
883  before: FlowState,
884  after: FlowState,
885  step: string,
886  outcome: string,
887  lang: Lang = DEFAULT_LANGUAGES.ui,
888): string => {
889  const t = uiText(lang)
890  const label = pressedLabel(before, step, outcome, lang)
891  const nextStep = stepOf(after.flow, after.current)
892  const next =
893    after.status === 'done'
894      ? t.toast.flowDone
895      : after.status === 'aborted'
896        ? t.toast.flowEnded
897        : t.toast.nextStep(nextStep === undefined ? after.current : stepTitle(nextStep, lang))
898  return t.toast.registered(label, next)
899}
900
901/** A step's title, description and outcome labels in a language; a flow without them keeps its plain text. */
902export const stepTitle = (step: FlowStep, lang: Lang): string => localize(step.titles, lang) ?? step.title
903const stepDescription = (step: FlowStep, lang: Lang): string | undefined =>
904  localize(step.descriptions, lang) ?? step.description
905export const outcomeLabel = (o: FlowOutcome, lang: Lang): string => localize(o.labels, lang) ?? o.label
906
907/** The button's own words, in the owner's language: the owner step's outcome label, or the escalation choice's. */
908const pressedLabel = (before: FlowState, step: string, outcome: string, lang: Lang = DEFAULT_LANGUAGES.ui): string => {
909  const declared = stepOf(before.flow, step)?.outcomes[outcome]
910  return (
911    (declared === undefined ? undefined : outcomeLabel(declared, lang)) ??
912    escalationChoices(uiText(lang)).find(c => c.outcome === outcome)?.label ??
913    (outcome === DEPLOY_CI_OUTCOME ? uiText(lang).deployCi : outcome)
914  )
915}
916
917/**
918 * What the coordinator reads after an owner press, or nothing when it has nothing to do: the flow
919 * ended, waits on the owner again, or escalated. A session, automatic or loop step is the
920 * coordinator's to drive; of the owner steps only the mockup is, since it attaches a new one.
921 */
922export const wakePrompt = (before: FlowState, after: FlowState, step: string, outcome: string, note?: string): string | undefined => {
923  if (after.status !== 'running') return undefined
924  const next = currentStep(after)
925  if (next === undefined || (next.kind === 'owner' && next.id !== MOCKUP_STEP)) return undefined
926  const noted = note === undefined ? '' : ` com a nota "${note}"`
927  return `Painel: o dono apertou "${pressedLabel(before, step, outcome)}"${noted}. Próximo passo: ${next.id} (${next.title}). Siga o flow.`
928}
929
930/** Words of a declared command, matched in what the shell ran: `openspec validate` in `npx openspec validate x --strict`. */
931const commandPattern = (command: string): RegExp =>
932  new RegExp(
933    `(^|[\\s/;&|(])${command
934      .trim()
935      .split(/\s+/)
936      .map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
937      .join('\\s+')}(?=$|[\\s;&|)])`,
938  )
939
940/**
941 * What one finished Bash command proves for an automatic step: passou on exit 0, falhou otherwise.
942 * A run whose exit code a pipe, `|| true` or a later `; cmd` hides proves a failure, never a pass.
943 */
944export const automaticOutcome = (step: FlowStep, command: string, failed: boolean): 'passou' | 'falhou' | undefined => {
945  if (step.kind !== 'automatic' || step.command === undefined || step.deploy !== undefined) return undefined
946  const code = executedText(command)
947  const pattern = commandPattern(step.command)
948  if (!pattern.test(code)) return undefined
949  if (!failed && masksExitCode(code, pattern)) return undefined
950  return failed ? 'falhou' : 'passou'
951}
952
953/** A step's detect command seen succeeding: its outcome. A masked exit code or a failure proves nothing. */
954export const detectedOutcome = (step: FlowStep, command: string, failed: boolean): string | undefined => {
955  if (step.detect === undefined || failed) return undefined
956  const code = executedText(command)
957  const seen = step.detect.commands.some(c => {
958    const pattern = commandPattern(c)
959    return pattern.test(code) && !masksExitCode(code, pattern)
960  })
961  return seen ? step.detect.outcome : undefined
962}
963
964/** A session's note for the owner step that waits now; it joins the owner's answer. */
965export const noteOwnerStep = (state: FlowState, note: string, at: number): Moved | { error: string } => {
966  const step = currentStep(state)
967  if (step === undefined || state.status !== 'running') return { error: 'no step is waiting.' }
968  if (step.kind !== 'owner') return { error: `step "${step.id}" is not the owner's; report its outcome instead.` }
969  const event: FlowEvent = { seq: state.seq + 1, at, kind: 'noted', step: step.id, by: 'session', note }
970  return { state: { ...state, pendingNote: note, seq: state.seq + 1, updatedAt: at }, events: [event] }
971}
972
973export const currentStep = (state: FlowState): FlowStep | undefined =>
974  state.status === 'done' || state.status === 'aborted' ? undefined : stepOf(state.flow, state.current)
975
976const stepView = (state: FlowState, step: FlowStep, index: number, currentIndex: number, languages: Languages): FlowStepView => {
977  const record = state.records[step.id]
978  const isCurrent = step.id === state.current && (state.status === 'running' || state.status === 'escalated')
979  const finished = state.status === 'done'
980  const state_: FlowStepView['state'] = isCurrent
981    ? 'current'
982    : record !== undefined
983      ? 'done'
984      : !applies(step, state) && (finished || index < currentIndex)
985        ? 'skipped'
986        : 'pending'
987  return {
988    id: step.id,
989    title: stepTitle(step, languages.ui),
990    description: stepDescription(step, languages.content),
991    kind: step.kind,
992    state: state_,
993    attempts: state.attempts[step.id] ?? 0,
994    maxAttempts: step.maxAttempts,
995    outcome: record?.outcome,
996    outcomeLabel: record === undefined || step.outcomes[record.outcome] === undefined
997      ? undefined
998      : outcomeLabel(step.outcomes[record.outcome]!, languages.ui),
999  }
1000}
1001
1002/** Everything the panel draws of a flow, from the saved state alone. */
1003export const flowView = (state: FlowState, languages: Languages = DEFAULT_LANGUAGES): FlowView => {
1004  const currentIndex = state.status === 'done' ? state.flow.steps.length : indexOf(state.flow, state.current)
1005  const steps = state.flow.steps.map((s, i) => stepView(state, s, i, currentIndex, languages))
1006  const step = currentStep(state)
1007  const ownerChoices: FlowChoice[] =
1008    state.status === 'escalated'
1009      ? escalationChoices(uiText(languages.ui))
1010      : step?.deploy !== undefined
1011        ? deployPending(state, step).ci
1012          ? [{ outcome: DEPLOY_CI_OUTCOME, label: uiText(languages.ui).deployCi }]
1013          : ownerConfirms(state, step, 'owner', Object.keys(step.outcomes)[0]!)
1014            ? Object.entries(step.outcomes).slice(0, 1).map(([outcome, o]) => ({ outcome, label: outcomeLabel(o, languages.ui) }))
1015            : []
1016        : step?.kind === 'owner'
1017          ? Object.entries(step.outcomes).map(([outcome, o]) => ({ outcome, label: outcomeLabel(o, languages.ui) }))
1018          : []
1019  return {
1020    change: state.change,
1021    flowId: state.flow.id,
1022    flowTitle: localize(state.flow.titles, languages.ui) ?? state.flow.title,
1023    status: state.status,
1024    current: steps.find(s => s.state === 'current'),
1025    waitingOn: step === undefined ? undefined : state.status === 'escalated' ? 'owner' : ANSWERED_BY[step.kind],
1026    ownerChoices,
1027    escalation: state.escalation,
1028    steps,
1029  }
1030}
1031
1032/** Where the flow stands, in the model's words: the step, who answers it and how. */
1033export const describeFlow = (state: FlowState): string => {
1034  const head = `Flow ${state.flow.id} for ${state.change}`
1035  if (state.status === 'done') return `${head}: finished.`
1036  if (state.status === 'aborted') return `${head}: ended by the owner.`
1037  const step = stepOf(state.flow, state.current) as FlowStep
1038  const where = `${head}: step "${step.id}" (${step.title}), attempt ${state.attempts[step.id] ?? 0} of ${step.maxAttempts}`
1039  if (state.status === 'escalated') {
1040    return `${where}; it hit its attempt ceiling and waits on the owner in the panel (retry or end the flow).`
1041  }
1042  const outcomes = Object.entries(step.outcomes).map(([o, d]) => `${o} → ${d.next}`).join(', ')
1043  const back = state.reopened
1044  const reopened =
1045    back === undefined ? '' : ` Came back from "${back.step}" (${back.label})${back.note === undefined ? '' : `: ${back.note}`}.`
1046  return describeStep(state, step, where, outcomes) + reopened
1047}
1048
1049/** Which of a merge or deploy step's values come from the project's settings rather than the workflow. */
1050const projectNote = (step: FlowStep): string => {
1051  const fields = (step.merge ?? step.deploy)?.fromProject ?? []
1052  return fields.length === 0 ? '' : ` From the project's settings (not the workflow): ${fields.join(', ')}.`
1053}
1054
1055const describeStep = (state: FlowState, step: FlowStep, where: string, outcomes: string): string =>
1056  describeStepBody(state, step, where, outcomes) + projectNote(step)
1057
1058const describeStepBody = (state: FlowState, step: FlowStep, where: string, outcomes: string): string => {
1059  if (step.deploy !== undefined) return describeDeploy(state, step, where)
1060  if (step.merge?.auto === true && step.agent === WORKFLOW_MERGE_AGENT) {
1061    return (
1062      `${where}. Merge the change's PR into ${step.merge.branch} yourself, by ${step.merge.method}, on the workflow's ` +
1063      "own approval: the flow's code review approved (declared by the coordination, which reports \"aprovado\" on the review step), the final gates passed and the CI green if the PR has checks; " +
1064      'GitHub approval is not required. Check with `gh pr view <pr> --json mergeable,statusCheckRollup`; if anything is ' +
1065      'missing, do not merge — tell the coordination. Then run ' +
1066      `\`gh pr merge <pr> --${step.merge.method}\` alone, never with --admin; the mod reads its exit code ` +
1067      `(exit 0 → ${step.outcomes.passou?.next}, otherwise → ${step.outcomes.falhou?.next}). It cannot be reported.`
1068    )
1069  }
1070  if (step.merge?.auto === true) {
1071    return (
1072      `${where}. Merge the change's PR into ${step.merge.branch} yourself, by ${step.merge.method}: first check with ` +
1073      '`gh pr view <pr> --json reviewDecision,statusCheckRollup` that it is approved on GitHub and its CI is green; ' +
1074      'if anything is missing, do not merge — tell the owner. Then run ' +
1075      `\`gh pr merge <pr> --${step.merge.method}\` alone, never with --admin; the mod reads its exit code ` +
1076      `(exit 0 → ${step.outcomes.passou?.next}, otherwise → ${step.outcomes.falhou?.next}). It cannot be reported.`
1077    )
1078  }
1079  switch (step.kind) {
1080    case 'session':
1081      return (
1082        `${where}. Open a session for this step with start_session (initiation "user_asked" with wake_when_done, the owner asked to orchestrate), ` +
1083        "using the step's agent, model and effort; do not do the step in this session. If the app refuses the start in this turn " +
1084        '(it was set off by another session\'s message or an automatic event), propose it as a card (initiation "own_initiative", same prompt), ' +
1085        'without wake_when_done (the app refuses it on a card; it wakes you when the session ends anyway), tell the owner to click it and wait; never do the step here. The session ends its turn with its result. ' +
1086        `When it answers, report one of the step's outcomes with action "report": ${outcomes}.`
1087      )
1088    case 'loop': {
1089      const closed = Object.keys(state.closed ?? {})
1090      return (
1091        `${where}. Run the phases of tasks.md, one session per phase (start_session, initiation "user_asked", never this session); close each with action "close" and its \`phase\` id once its gates ` +
1092        'passed, its tasks are ticked and its work is committed (the mod then archives its session). The step ends ' +
1093        `on its own when every phase is closed (→ ${step.outcomes[LOOP_DONE]?.next}).` +
1094        (closed.length > 0 ? ` Closed: ${closed.join(', ')}.` : '')
1095      )
1096    }
1097    case 'automatic':
1098      return (
1099        `${where}. Run \`${step.command}\` in this session; the mod reads its exit code ` +
1100        `(exit 0 → ${step.outcomes.passou?.next}, otherwise → ${step.outcomes.falhou?.next})` +
1101        (step.requiresEvidence ? ', and a pass also needs evidence.md recorded in the change folder' : '') +
1102        '. It cannot be reported.'
1103      )
1104    case 'owner':
1105      return (
1106        `${where}. Waits on the owner's press in the panel (${Object.values(step.outcomes).map(o => o.label).join(' / ')}); ` +
1107        'no session can answer it, but action "note" leaves a note that joins the answer' +
1108        (step.detect === undefined
1109          ? '.'
1110          : `. The mod also answers ${step.detect.outcome} when it sees ${step.detect.commands.map(c => `\`${c}\``).join(' or ')} succeed.`) +
1111        (step.merge === undefined
1112          ? ''
1113          : step.agent === WORKFLOW_MERGE_AGENT
1114            ? ` The merge into ${step.merge.branch} by ${step.merge.method} waits on the workflow's approval (the flow's code review approved, declared by the coordination), not on GitHub; never with --admin.`
1115            : ` The owner merges into ${step.merge.branch} by ${step.merge.method}; never with --admin.`)
1116      )
1117  }
1118}
1119
1120/** A deploy step: who starts it, what it still waits on, and how the mod sees each part done. */
1121const describeDeploy = (state: FlowState, step: FlowStep, where: string): string => {
1122  const deploy = step.deploy as FlowDeploy
1123  const pending = deployPending(state, step)
1124  const who = deploy.auto
1125    ? `${where}. Deploy by yourself right after the merge, without waiting on the owner.`
1126    : `${where}. Waits on the owner: do not start the deploy unless they ask; they confirm and run it.`
1127  const ci = pending.ci
1128    ? ` The CI's deploy: wait for it with \`gh run watch <run> --exit-status\` (or \`gh run view <run> --exit-status\`) run alone, or the owner presses "${DEPLOY_CI_LABEL}".`
1129    : deploy.ci
1130      ? " The CI's deploy is confirmed."
1131      : ''
1132  const routines =
1133    pending.commands.length > 0
1134      ? ` Routines left, each as its own command and in this order${pending.ci ? ', after the CI' : ''}: ${pending.commands.map(c => `\`${c}\``).join(', ')}.`
1135      : ''
1136  const fails = step.kind === 'automatic' ? `a failure → ${step.outcomes.falhou?.next}` : 'a failure holds the step'
1137  const [forward, first] = Object.entries(step.outcomes)[0]!
1138  const confirm = ownerConfirms(state, step, 'owner', forward) ? ` The owner may also press "${first.label}" once they ran the routines.` : ''
1139  return (
1140    `${who}${ci}${routines} The mod ticks each part it sees pass (a hidden exit code does not count) and moves on ` +
1141    `(→ ${first.next}) once all are done; ${fails}.${confirm} It cannot be reported.`
1142  )
1143}
1144
1145/** Where a step's agent file was found: the project's own, the mod's plugin, or nowhere. */
1146export type AgentFound = { source: 'project' | 'plugin'; path: string } | undefined
1147
1148const AGENT_SOURCE = { project: 'do projeto', plugin: 'do plugin' } as const
1149
1150/** The step as the model must run it: agent (and where it came from), model, effort and details. */
1151export const describeStepAgent = (step: FlowStep, found: AgentFound): string | undefined => {
1152  const lines: string[] = []
1153  if (step.agent !== undefined) {
1154    lines.push(
1155      found === undefined
1156        ? `Agente: "${step.agent}" — nenhum arquivo encontrado (nem .orquestrador/agents/${step.agent}.md no projeto nem agents/${step.agent}.md no plugin); siga a descrição do passo sem agente.`
1157        : `Agente: "${step.agent}" (${AGENT_SOURCE[found.source]}). Instruções do agente: ${found.path}`,
1158    )
1159  }
1160  if (step.model !== undefined) lines.push(`Modelo: ${step.model}`)
1161  if (step.effort !== undefined) lines.push(`Esforço: ${step.effort}`)
1162  const d = step.details
1163  if (d?.inputs !== undefined) lines.push(`Entrada: ${d.inputs}`)
1164  if (d?.produces !== undefined) lines.push(`Saída: ${d.produces}`)
1165  if (d?.blocks !== undefined) lines.push(`Bloqueia: ${d.blocks}`)
1166  if (lines.length === 0) return undefined
1167  const head = step.kind === 'loop' ? 'Cada fase deste passo usa:' : 'Neste passo:'
1168  return `${head}\n${lines.map(l => `  ${l}`).join('\n')}`
1169}
1170
1171const ANSWERER_LABEL: Record<FlowStepKind, string> = {
1172  session: 'sessão',
1173  loop: 'mod',
1174  automatic: 'mod',
1175  owner: 'dono',
1176}
1177
1178const fromProjectText = (fields: string[] | undefined): string =>
1179  fields === undefined || fields.length === 0 ? '' : ` — do projeto: ${fields.join(', ')}`
1180
1181/** One step of the sequence with who answers it and whether merge/deploy run on their own. */
1182const stepSummary = (s: FlowStep): string => {
1183  const mode = (auto: boolean) => (auto ? 'automático' : 'manual')
1184  const extra = [
1185    s.merge === undefined ? undefined : `merge ${mode(s.merge.auto)}${fromProjectText(s.merge.fromProject)}`,
1186    s.deploy === undefined ? undefined : `deploy ${mode(s.deploy.auto)}${fromProjectText(s.deploy.fromProject)}`,
1187    s.agent === undefined ? undefined : `agente ${s.agent}`,
1188  ].filter((x): x is string => x !== undefined)
1189  return `${s.id} (${[ANSWERER_LABEL[s.kind], ...extra].join(', ')})`
1190}
1191
1192/** A workflow whole for the owner's choice: title, description, origin and every step with its answerer. */
1193export const describeWorkflow = (flow: FlowDef, origin: 'default' | 'project'): string => {
1194  const from =
1195    flow.base !== undefined ? `derivado de ${flow.base}` : origin === 'project' ? 'do projeto' : 'padrão'
1196  return [
1197    `${flow.id} — ${flow.title}: ${flow.steps.map(s => s.id).join(' → ')} → fim`,
1198    `  Descrição: ${flow.description === '' ? '(sem descrição)' : flow.description}`,
1199    `  Origem: ${from}`,
1200    `  Passos: ${flow.steps.map(stepSummary).join(' → ')}`,
hooks/lifecycle.ts 150 lines
1import type { FlowEvent, FlowState, GateAttempt, GateView, OrchestrationRun, PhaseClosure, SessionRow, TaskItem } from '../types'
2import { LOOP_DONE, applyOutcome, currentStep } from './flow'
3import type { Moved } from './flow'
4import { phaseRefusal } from './gates'
5import { parseTaskItems, tasksForPhase } from './openspec'
6
7/**
8 * One phase the executar loop runs: a phase of the published plan (its tasks, gates and session),
9 * or, with no plan, a numbered section of tasks.md ("## 4. …" holds 4.1, 4.2…).
10 */
11export type LoopUnit = {
12  id: string
13  title: string
14  tasks: TaskItem[]
15  gates: string[] | undefined
16  session: string | undefined
17}
18
19/** The `## N. Title` headings of tasks.md, by section number. */
20const sectionTitles = (tasks: string): Map<string, string> =>
21  new Map(
22    tasks.split('\n').flatMap(line => {
23      const m = line.match(/^##\s+(\d+)\.?\s+(.+?)\s*$/)
24      return m === null ? [] : [[m[1] ?? '', (m[2] ?? '').trim()] as [string, string]]
25    }),
26  )
27
28/** The phases of the loop: the plan's when it names any, else the numbered sections of tasks.md. */
29export const loopUnits = (run: OrchestrationRun | undefined, tasks: string | undefined): LoopUnit[] => {
30  const items = tasks === undefined ? [] : parseTaskItems(tasks)
31  const phases = run?.waves.flatMap(w => w.phases) ?? []
32  if (phases.length > 0) {
33    return phases.map(p => ({ id: p.id, title: p.title, tasks: tasksForPhase(p.tasks, items), gates: p.gates, session: p.session }))
34  }
35  const titles = tasks === undefined ? new Map<string, string>() : sectionTitles(tasks)
36  const sections = [...new Set(items.map(i => i.id.split('.')[0] ?? ''))]
37  return sections.map(n => ({
38    id: n,
39    title: titles.get(n) ?? `Seção ${n}`,
40    tasks: items.filter(i => i.id.startsWith(`${n}.`)),
41    gates: undefined,
42    session: undefined,
43  }))
44}
45
46/** Why a phase cannot close yet: tasks left unticked in tasks.md, then its open gates. */
47export const unitRefusal = (
48  unit: LoopUnit,
49  openGates: readonly GateView[],
50  where: string,
51  tried?: readonly GateAttempt[],
52): string | undefined => {
53  const open = unit.tasks.filter(t => !t.done).map(t => t.id)
54  const tasks =
55    open.length === 0
56      ? undefined
57      : `phase ${unit.id} (${unit.title}) cannot close: tasks ${open.join(', ')} are not ticked in tasks.md.`
58  const gates = phaseRefusal(unit, openGates, where, tried)
59  return tasks === undefined && gates === undefined ? undefined : [tasks, gates].filter(Boolean).join(' ')
60}
61
62/** A closed phase stays closed while every one of its tasks is ticked; a new unticked task reopens it. */
63export const isClosed = (state: FlowState, unit: LoopUnit): boolean =>
64  state.closed?.[unit.id] !== undefined && unit.tasks.every(t => t.done)
65
66/** Whether the flow sits on a running loop step, the only time a phase may close. */
67export const loopRefusal = (state: FlowState): string | undefined => {
68  const step = currentStep(state)
69  if (state.status !== 'running' || step === undefined) return `the flow of ${state.change} is ${state.status}; no phase closes now.`
70  if (step.kind !== 'loop') return `the flow of ${state.change} is on "${step.id}" (${step.title}), not on the phase loop.`
71  return undefined
72}
73
74/** Records one closed phase and, when the mod archived it, its session; both go to the flow log. */
75export const closePhase = (
76  state: FlowState,
77  unit: LoopUnit,
78  done: { session: string | undefined; archived: boolean; note?: string },
79  at: number,
80): Moved => {
81  const step = state.current
82  const closure: PhaseClosure = {
83    at,
84    tasks: unit.tasks.map(t => t.id),
85    ...(done.session === undefined ? {} : { session: done.session }),
86    archived: done.archived,
87  }
88  const events: FlowEvent[] = [
89    { seq: state.seq + 1, at, kind: 'phase-closed', step, by: 'mod', note: `${unit.id} ${unit.title}`.trim() },
90  ]
91  if (done.session !== undefined) {
92    events.push({
93      seq: state.seq + 2,
94      at,
95      kind: 'session-archived',
96      step,
97      by: 'mod',
98      note: done.archived ? `${unit.id}: ${done.session}` : `${unit.id}: ${done.session} not archived — ${done.note ?? 'unknown'}`,
99    })
100  }
101  return {
102    state: { ...state, closed: { ...state.closed, [unit.id]: closure }, seq: state.seq + events.length, updatedAt: at },
103    events,
104  }
105}
106
107/** The loop ends, by the mod, once every phase is closed; until then the phases still open. */
108export const finishLoop = (state: FlowState, units: readonly LoopUnit[], at: number): Moved | { open: LoopUnit[] } | { error: string } => {
109  const refusal = loopRefusal(state)
110  if (refusal !== undefined) return { error: refusal }
111  if (units.length === 0) return { error: 'the change has no plan phases and no numbered tasks in tasks.md, so no phase can close.' }
112  const open = units.filter(u => !isClosed(state, u))
113  if (open.length > 0) return { open }
114  return applyOutcome(state, { step: state.current, outcome: LOOP_DONE, by: 'mod', note: `${units.length} phase(s) closed` }, at)
115}
116
117/** `git status --porcelain` output: the paths with uncommitted changes, none when clean. */
118export const uncommitted = (porcelain: string): string[] =>
119  porcelain
120    .split('\n')
121    .map(line => line.slice(3).trim())
122    .filter(path => path !== '')
123
124/**
125 * The change's phase sessions still alive in its sidebar group: those started by another member
126 * of the group (the coordinator), never this session itself. A session in the coordinator's own
127 * folder is a side chat the owner opened, not a phase: phases run in worktrees of their own.
128 */
129export const phaseSessions = (rows: readonly SessionRow[], selfId: string | undefined, coordinatorCwd: string): SessionRow[] => {
130  const members = new Set(rows.map(r => r.sessionId))
131  return rows.filter(
132    r =>
133      !r.isArchived &&
134      r.sessionId !== selfId &&
135      r.cwd !== coordinatorCwd &&
136      r.startedBy !== undefined &&
137      members.has(r.startedBy),
138  )
139}
140
141/** Puts `extra` events before the flow's closing `done` event, renumbered in order. */
142export const withEvents = (moved: Moved, extra: readonly Omit<FlowEvent, 'seq'>[]): Moved => {
143  if (extra.length === 0) return moved
144  const done = moved.events.findIndex(e => e.kind === 'done')
145  const at = done < 0 ? moved.events.length : done
146  const first = moved.events[0]?.seq ?? moved.state.seq + 1
147  const events = [...moved.events.slice(0, at), ...extra, ...moved.events.slice(at)].map((e, i) => ({ ...e, seq: first + i }))
148  return { state: { ...moved.state, seq: first + events.length - 1 }, events }
149}
150
hooks/grill.ts 274 lines
1import type { FlowEvent, FlowState, FlowView, GrillAnswer, GrillItem, PrepState, PrepView } from '../types'
2
3/**
4 * The owner steps before execution, by their ids in the flows: the grill (rounds of questions until
5 * the owner closes the understanding), the mockup (only for a visual change) and the owner's
6 * release, answered in the app's plan mode.
7 */
8export const GRILL_STEP = 'grill'
9export const MOCKUP_STEP = 'mockup'
10export const RELEASE_STEP = 'liberacao'
11export const MOCKUP_APPROVED = 'aprovado'
12export const MOCKUP_ADJUST = 'ajustes'
13export const RELEASE_OUTCOME = 'liberado'
14
15const MAX_TEXT = 2_000
16const MAX_PLAN = 8_000
17
18const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
19const text = (v: unknown, max = MAX_TEXT): string | undefined =>
20  typeof v === 'string' && v.trim() !== '' ? v.trim().slice(0, max) : undefined
21
22export const emptyPrep = (change: string): PrepState => ({ change, rounds: [], adjustments: [], planRejections: [] })
23
24/** A round's questions as the tool sends them: each with its question, and the answer and criterion once known. */
25export const parseRoundItems = (raw: unknown): GrillItem[] | { error: string } => {
26  if (!Array.isArray(raw) || raw.length === 0) {
27    return { error: '`questions` must list the round\'s questions: [{ question, answer?, criterion? }].' }
28  }
29  const items: GrillItem[] = []
30  for (const [i, q] of raw.entries()) {
31    const question = isRecord(q) ? text(q.question) : text(q)
32    if (question === undefined) return { error: `question ${i + 1} has no \`question\` text.` }
33    const answer = isRecord(q) ? text(q.answer) : undefined
34    const criterion = isRecord(q) ? text(q.criterion) : undefined
35    items.push({ question, ...(answer === undefined ? {} : { answer }), ...(criterion === undefined ? {} : { criterion }) })
36  }
37  return items
38}
39
40const onStep = (state: FlowState, step: string, what: string): string | undefined => {
41  if (state.status !== 'running' || state.current !== step) {
42    return `${what} only while the flow of ${state.change} is on "${step}"; it is on "${state.current}" (${state.status}).`
43  }
44  return undefined
45}
46
47type Prepped = { prep: PrepState; event: Pick<FlowEvent, 'kind' | 'step' | 'by' | 'note'> }
48
49/**
50 * One grill round: appended, or with `amend` merged into the latest round (answers filled by
51 * question text, new questions added). Only while the flow is on the grill; the round never closes
52 * it, since only the owner does, in the panel.
53 */
54export const recordRound = (
55  prep: PrepState,
56  state: FlowState,
57  items: readonly GrillItem[],
58  amend: boolean,
59  at: number,
60): Prepped | { error: string } => {
61  const wrong = onStep(state, GRILL_STEP, 'a grill round is recorded')
62  if (wrong !== undefined) return { error: wrong }
63  const last = prep.rounds[prep.rounds.length - 1]
64  let rounds = prep.rounds
65  if (amend && last !== undefined) {
66    const merged = [...last.items]
67    for (const item of items) {
68      const i = merged.findIndex(m => m.question === item.question)
69      if (i === -1) merged.push(item)
70      else merged[i] = { ...merged[i]!, ...item }
71    }
72    rounds = [...prep.rounds.slice(0, -1), { ...last, items: merged, at }]
73  } else {
74    rounds = [...prep.rounds, { n: prep.rounds.length + 1, at, items: [...items] }]
75  }
76  const round = rounds[rounds.length - 1]!
77  const open = round.items.filter(i => i.answer === undefined).length
78  return {
79    prep: { ...prep, rounds },
80    event: {
81      kind: 'round',
82      step: GRILL_STEP,
83      by: 'session',
84      note: `rodada ${round.n}: ${round.items.length} perguntas, ${open} em aberto`,
85    },
86  }
87}
88
89/**
90 * The owner's answers typed in the panel, merged into the latest round the way `round` with
91 * `amend: true` does; each must still be an open question of that round and none may be empty.
92 */
93export const ownerAnswers = (
94  prep: PrepState,
95  state: FlowState,
96  answers: readonly GrillAnswer[],
97  at: number,
98): Prepped | { error: string } => {
99  const filled = answers.flatMap(a => {
100    const answer = text(a.answer)
101    return answer === undefined ? [] : [{ ...a, answer }]
102  })
103  if (filled.length === 0) return { error: 'escreva a resposta antes de enviar.' }
104  const last = prep.rounds[prep.rounds.length - 1]
105  const stale = filled.find(a => last?.items.find(i => i.question === a.question && i.answer === undefined) === undefined)
106  if (stale !== undefined) return { error: `a pergunta ${stale.n} não está mais em aberto na rodada atual.` }
107  const done = recordRound(prep, state, filled.map(a => ({ question: a.question, answer: a.answer })), true, at)
108  return 'error' in done ? done : { prep: done.prep, event: { ...done.event, by: 'owner' } }
109}
110
111/** What the coordinator reads from the panel: one line per answer, as the owner's own message. */
112export const answersPrompt = (answers: readonly GrillAnswer[]): string =>
113  answers
114    .filter(a => a.answer.trim() !== '')
115    .map(a => `Resposta à pergunta ${a.n}: ${a.answer.trim()}`)
116    .join('\n')
117
118/** A URL or a file path: what the panel can show the owner as the mockup. */
119const isArtifact = (v: string): boolean =>
120  /^https?:\/\/\S+$/.test(v) || /^(\/|~\/|\.\.?\/)/.test(v) || /^[^\s:]*[/.][^\s:]*$/.test(v)
121
122/** The coordinator attaches the mockup (an Artifact URL or a file path) while the flow is on it. */
123export const attachMockup = (prep: PrepState, state: FlowState, artifact: unknown, at: number): Prepped | { error: string } => {
124  const wrong = onStep(state, MOCKUP_STEP, 'a mockup is attached')
125  if (wrong !== undefined) return { error: wrong }
126  const value = text(artifact)
127  if (value === undefined || !isArtifact(value)) {
128    return { error: '`artifact` must be the mockup\'s URL (e.g. an Artifact link) or a file path.' }
129  }
130  return {
131    prep: { ...prep, mockup: { artifact: value, at } },
132    event: { kind: 'attached', step: MOCKUP_STEP, by: 'session', note: value },
133  }
134}
135
136/**
137 * The owner's press on the mockup: approving needs an attached mockup; asking for an adjustment keeps
138 * the owner's note and the mockup it was about, and clears the mockup so a new one is attached.
139 */
140export const pressMockup = (prep: PrepState, outcome: string, note: string | undefined, at: number): PrepState | { error: string } => {
141  if (outcome === MOCKUP_APPROVED && prep.mockup === undefined) return { error: 'nenhum mockup foi anexado ainda.' }
142  if (outcome !== MOCKUP_ADJUST) return prep
143  const { mockup: _left, ...rest } = prep
144  const adjustment = {
145    note: text(note) ?? '',
146    at,
147    ...(prep.mockup === undefined ? {} : { artifact: prep.mockup.artifact }),
148  }
149  return { ...rest, adjustments: [...prep.adjustments, adjustment] }
150}
151
152type PlanRun = { result?: unknown; isError?: true; deny?: string; ref?: number; text?: string }
153
154export type PlanVerdict = { approved: true; plan: string | undefined; filePath: string | undefined } | { approved: false; feedback: string }
155
156/**
157 * What one ExitPlanMode call says of the owner's release. The tool runs only once the person
158 * approves the plan in the app's own dialog (a hook cannot dismiss it), so core's answered result
159 * is the approval and an errored call is the refusal at the dialog, its text holding the owner's
160 * words. Not counted: a call in a subagent's loop, a teammate's plan sent to its leader, a result
161 * core did not produce (no `ref`), and a plugin's deny.
162 */
163export const planVerdict = (input: { agentId?: unknown }, ran: PlanRun): PlanVerdict | undefined => {
164  if (input.agentId !== undefined || ran.deny !== undefined) return undefined
165  if (ran.isError === true) {
166    return { approved: false, feedback: text(ran.text, MAX_TEXT) ?? text(ran.result, MAX_TEXT) ?? 'plano não aprovado' }
167  }
168  if (ran.ref === undefined || !isRecord(ran.result)) return undefined
169  const result = ran.result
170  if (result.isAgent === true || result.awaitingLeaderApproval === true) return undefined
171  return { approved: true, plan: text(result.plan, MAX_PLAN), filePath: text(result.filePath) }
172}
173
174/** The owner's refusal of the execution plan, kept so the coordinator reads what to change. */
175export const rejectPlan = (prep: PrepState, feedback: string, at: number): Prepped => ({
176  prep: { ...prep, planRejections: [...prep.planRejections, { feedback, at }].slice(-10) },
177  event: { kind: 'plan-rejected', step: RELEASE_STEP, by: 'owner', note: feedback.slice(0, 300) },
178})
179
180export const approvePlan = (prep: PrepState, verdict: Extract<PlanVerdict, { approved: true }>, at: number): PrepState => ({
181  ...prep,
182  release: {
183    at,
184    ...(verdict.plan === undefined ? {} : { plan: verdict.plan }),
185    ...(verdict.filePath === undefined ? {} : { filePath: verdict.filePath }),
186  },
187})
188
189/** Every answered question becomes an acceptance criterion: its own criterion, else the answer. */
190export const criteria = (prep: PrepState): string[] =>
191  prep.rounds.flatMap(r => r.items.flatMap(i => (i.answer === undefined ? [] : [i.criterion ?? i.answer])))
192
193export const prepView = (prep: PrepState): PrepView => {
194  const last = prep.rounds[prep.rounds.length - 1]
195  const artifact = prep.mockup?.artifact
196  return {
197    change: prep.change,
198    rounds: prep.rounds.length,
199    openQuestions: last === undefined ? [] : last.items.filter(i => i.answer === undefined).map(i => i.question),
200    openItems:
201      last === undefined
202        ? []
203        : last.items.flatMap((i, k) => (i.answer === undefined ? [{ n: k + 1, question: i.question }] : [])),
204    criteria: criteria(prep),
205    ...(artifact === undefined ? {} : { mockup: artifact, mockupIsUrl: /^https?:\/\//.test(artifact) }),
206    ...(prep.adjustments.length === 0 ? {} : { lastAdjustment: prep.adjustments[prep.adjustments.length - 1]!.note }),
207    ...(prep.planRejections.length === 0 ? {} : { lastPlanFeedback: prep.planRejections[prep.planRejections.length - 1]!.feedback }),
208    released: prep.release !== undefined,
209  }
210}
211
212/**
213 * The owner buttons the panel leaves out: the release is pressed in the app's plan-mode dialog,
214 * never in the panel; the mockup is approved only once attached; and where the surface has a text
215 * field, the adjustment goes through it so the owner's note comes along.
216 */
217export const hiddenChoices = (flow: FlowView, prep: PrepView | undefined, hasInput: boolean): string[] => {
218  if (flow.status !== 'running') return []
219  switch (flow.current?.id) {
220    case RELEASE_STEP:
221      return [RELEASE_OUTCOME]
222    case MOCKUP_STEP:
223      return [...(prep?.mockup === undefined ? [MOCKUP_APPROVED] : []), ...(hasInput ? [MOCKUP_ADJUST] : [])]
224    default:
225      return []
226  }
227}
228
229/** grill.md: every round with its questions and answers, then the acceptance criteria they became. */
230export const grillMarkdown = (prep: PrepState): string => {
231  const lines = [`# Grill — ${prep.change}`, '']
232  for (const round of prep.rounds) {
233    lines.push(`## Rodada ${round.n}`, '')
234    for (const item of round.items) {
235      lines.push(`- **Pergunta:** ${item.question}`, `  **Resposta:** ${item.answer ?? '_(em aberto)_'}`)
236    }
237    lines.push('')
238  }
239  const found = criteria(prep)
240  lines.push('## Critérios de aceite', '')
241  lines.push(...(found.length === 0 ? ['_(nenhum ainda)_'] : found.map(c => `- [ ] ${c}`)), '')
242  return lines.join('\n')
243}
244
245/** What the coordinator must do on a pre-execution step, in the model's words; undefined elsewhere. */
246export const describePrep = (state: FlowState, prep: PrepState): string | undefined => {
247  if (state.status !== 'running') return undefined
248  const view = prepView(prep)
249  switch (state.current) {
250    case GRILL_STEP:
251      return (
252        `Grill: ${view.rounds} round(s) recorded, ${view.openQuestions.length} open question(s), ` +
253        `${view.criteria.length} acceptance criteria. Ask the owner one round of questions, then record it with ` +
254        'action "round" (questions with the owner\'s answers; amend: true fills the latest round). ' +
255        'Only the owner closes the understanding, in the panel.'
256      )
257    case MOCKUP_STEP:
258      return (
259        (view.mockup === undefined
260          ? 'Mockup: none attached; attach it with action "mockup" (artifact: an Artifact URL or a file path).'
261          : `Mockup attached: ${view.mockup}; the owner approves it or asks for an adjustment in the panel.`) +
262        (view.lastAdjustment === undefined ? '' : ` The owner's last adjustment: "${view.lastAdjustment}".`)
263      )
264    case RELEASE_STEP:
265      return (
266        'Release: write the execution plan and call ExitPlanMode with it; the owner\'s approval in the app\'s ' +
267        'plan dialog releases execution (no tool call can).' +
268        (view.lastPlanFeedback === undefined ? '' : ` The owner refused the last plan: "${view.lastPlanFeedback}".`)
269      )
270    default:
271      return undefined
272  }
273}
274
hooks/glance.ts 65 lines
1import type { FlowEvent, PanelView, StepTime } from '../types'
2import { uiText } from './i18n'
3import { attentionItems } from './model'
4
5/**
6 * When each step was last entered and, once it has an outcome, when it finished: from the flow's
7 * append-only log. Entering a step again starts its clock over.
8 */
9export const stepTimes = (events: readonly FlowEvent[]): Record<string, StepTime> => {
10  const times: Record<string, StepTime> = {}
11  for (const event of events) {
12    if (event.kind === 'entered') times[event.step] = { from: event.at }
13    else if (event.kind === 'outcome' && times[event.step] !== undefined) {
14      times[event.step] = { from: times[event.step]!.from, to: event.at }
15    }
16  }
17  return times
18}
19
20/** The flow's log, one JSON event per line; a torn or foreign line is skipped. */
21export const parseEvents = (text: string | undefined): FlowEvent[] =>
22  (text ?? '').split('\n').flatMap((line): FlowEvent[] => {
23    if (line.trim() === '') return []
24    try {
25      const event = JSON.parse(line) as FlowEvent
26      return typeof event.step === 'string' && typeof event.at === 'number' ? [event] : []
27    } catch {
28      return []
29    }
30  })
31
32/** How long, the way the app's background-tasks list says it: "40 s", "12 min", "2 h 5 min". */
33export const formatElapsed = (ms: number): string => {
34  const seconds = Math.max(0, Math.round(ms / 1000))
35  if (seconds < 60) return `${seconds} s`
36  const minutes = Math.floor(seconds / 60)
37  if (minutes < 60) return `${minutes} min`
38  const hours = Math.floor(minutes / 60)
39  return minutes % 60 === 0 ? `${hours} h` : `${hours} h ${minutes % 60} min`
40}
41
42export type BandSummary = {
43  /** The flow's current step in the owner's words, or where it ended. */
44  step: string | undefined
45  inFlight: number
46  waiting: number
47}
48
49/** What the thin band above the prompt says; undefined when this session orchestrates nothing. */
50export const bandSummary = (view: PanelView, answered: readonly string[]): BandSummary | undefined => {
51  if (view.flow === undefined && view.run === undefined) return undefined
52  const flow = view.flow
53  const step =
54    flow === undefined
55      ? undefined
56      : flow.status === 'done'
57        ? uiText(view.languages?.ui).band.flowDone
58        : flow.status === 'aborted'
59          ? uiText(view.languages?.ui).band.flowAborted
60          : flow.current?.title
61  const inFlight = (view.run?.waves ?? []).flatMap(w => w.phases).filter(p => p.status === 'running' || p.status === 'blocked').length
62  const waiting = attentionItems(view).filter(a => a.kind === 'flow' || !answered.includes(a.title)).length
63  return { step, inFlight, waiting }
64}
65
hooks/i18n.ts 541 lines
1import type { EvidenceState, GateState, Lang, Languages, Localized, PhaseStatus, ProjectSettings } from '../types'
2import { parseProjectBlocks } from './project-config'
3
4export const LANGS: readonly Lang[] = ['pt-BR', 'en']
5export const DEFAULT_LANG: Lang = 'pt-BR'
6export const DEFAULT_LANGUAGES: Languages = { ui: DEFAULT_LANG, content: DEFAULT_LANG }
7
8/** Where a project sets its languages, under its repository root. */
9export const CONFIG_PATH = '.orquestrador/config.json'
10
11const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
12const isLang = (v: unknown): v is Lang => typeof v === 'string' && (LANGS as readonly string[]).includes(v)
13
14/** `"en"` sets both; `{ ui, content }` sets each, a missing one stays pt-BR. An unknown value is named, never guessed. */
15export const parseLanguages = (raw: unknown): { languages: Languages; problems: string[] } => {
16  if (raw === undefined) return { languages: DEFAULT_LANGUAGES, problems: [] }
17  if (isLang(raw)) return { languages: { ui: raw, content: raw }, problems: [] }
18  if (!isRecord(raw)) {
19    return { languages: DEFAULT_LANGUAGES, problems: [`language must be ${LANGS.join(' or ')}, or { ui, content }.`] }
20  }
21  const problems: string[] = []
22  const pick = (axis: keyof Languages): Lang => {
23    const v = raw[axis]
24    if (v === undefined) return DEFAULT_LANG
25    if (isLang(v)) return v
26    problems.push(`language.${axis} "${String(v)}" is not ${LANGS.join(' or ')}.`)
27    return DEFAULT_LANG
28  }
29  return { languages: { ui: pick('ui'), content: pick('content') }, problems }
30}
31
32/** What a config file sets for the languages: only the axes it names. */
33const languagePartial = (raw: unknown): { ui?: Lang; content?: Lang; problems: string[] } => {
34  if (raw === undefined) return { problems: [] }
35  if (isLang(raw)) return { ui: raw, content: raw, problems: [] }
36  if (!isRecord(raw)) return { problems: [`language must be ${LANGS.join(' or ')}, or { ui, content }.`] }
37  const out: { ui?: Lang; content?: Lang; problems: string[] } = { problems: [] }
38  for (const axis of ['ui', 'content'] as const) {
39    const v = raw[axis]
40    if (v === undefined) continue
41    if (isLang(v)) out[axis] = v
42    else out.problems.push(`language.${axis} "${String(v)}" is not ${LANGS.join(' or ')}.`)
43  }
44  return out
45}
46
47type ConfigRead = {
48  ui?: Lang
49  content?: Lang
50  settings: Required<ProjectSettings>
51  problems: string[]
52}
53
54const readConfig = (text: string | undefined, path: string): ConfigRead => {
55  const none: ConfigRead = { settings: { merge: {}, deploy: {} }, problems: [] }
56  if (text === undefined) return none
57  let raw: unknown
58  try {
59    raw = JSON.parse(text)
60  } catch {
61    return { ...none, problems: [`${path}: not valid JSON.`] }
62  }
63  if (!isRecord(raw)) return { ...none, problems: [`${path}: a JSON object is expected.`] }
64  const lang = languagePartial(raw.language)
65  const blocks = parseProjectBlocks(raw)
66  return {
67    ...(lang.ui === undefined ? {} : { ui: lang.ui }),
68    ...(lang.content === undefined ? {} : { content: lang.content }),
69    settings: blocks.settings,
70    problems: [...lang.problems, ...blocks.problems].map(p => `${path}: ${p}`),
71  }
72}
73
74/**
75 * The project's `.orquestrador/config.json`, already read: its languages and its merge and deploy
76 * defaults. A file that is not JSON, or a value that is wrong, is named in `problems` and left out.
77 */
78export const parseConfig = (text: string | undefined): { languages: Languages; project: ProjectSettings; problems: string[] } => {
79  const read = readConfig(text, CONFIG_PATH)
80  return {
81    languages: { ui: read.ui ?? DEFAULT_LANG, content: read.content ?? DEFAULT_LANG },
82    project: read.settings,
83    problems: read.problems,
84  }
85}
86
87/** A flow field as a file writes it: plain text, or one text per language. */
88export const parseLocalized = (v: unknown): Localized | undefined => {
89  const text = (s: unknown) => (typeof s === 'string' && s.trim() !== '' ? s.trim() : undefined)
90  if (typeof v === 'string') return text(v)
91  if (!isRecord(v)) return undefined
92  const out: Partial<Record<Lang, string>> = {}
93  for (const lang of LANGS) {
94    const t = text(v[lang])
95    if (t !== undefined) out[lang] = t
96  }
97  return Object.keys(out).length === 0 ? undefined : out
98}
99
100/** The text in `lang`, else in the other language: a flow that wrote only one still reads. */
101export const localize = (v: Localized | undefined, lang: Lang): string | undefined => {
102  if (v === undefined || typeof v === 'string') return v
103  return v[lang] ?? LANGS.map(l => v[l]).find(t => t !== undefined)
104}
105
106/** The plain text a field falls back to where no language is known: pt-BR first, the mod's own. */
107export const baseText = (v: Localized | undefined): string | undefined => localize(v, DEFAULT_LANG)
108
109/** The language as the coordinator is told it. */
110export const LANG_NAME: Record<Lang, string> = { 'pt-BR': 'Brazilian Portuguese (pt-BR)', en: 'English' }
111
112/** What the coordinator is told to write the change's own texts in. */
113export const contentRule = (languages: Languages): string =>
114  `Write the change's texts (proposal, design, tasks, grill questions, plan phase titles and notes, owner ` +
115  `questions and recommendations) in ${LANG_NAME[languages.content]}; the panel shows them as written.`
116
117const pt = {
118  locale: 'pt-BR',
119  status: {
120    legend: { done: 'fechadas', running: 'em voo', blocked: 'bloqueadas', pending: 'pendentes' } as Record<PhaseStatus, string>,
121    word: { done: 'fechada', running: 'em voo', blocked: 'bloqueada', pending: 'pendente' } as Record<PhaseStatus, string>,
122  },
123  attentionKind: {
124    decision: 'Decisão',
125    permission: 'Permissão',
126    question: 'Pergunta',
127    pr: 'PR para revisar',
128    flow: 'Passo do flow',
129    jira: 'Jira',
130  },
131  evidence: {
132    missing: 'não existe',
133    stub: 'esqueleto',
134    recorded: 'registrada',
135    green: 'check.sh verde',
136    failing: 'check.sh falhou',
137  } as Record<EvidenceState, string>,
138  gate: {
139    passed: 'passou',
140    failed: 'falhou',
141    pending: 'não rodou',
142    stale: 'desatualizado',
143    skipped: 'pulado por você',
144  } as Record<GateState, string>,
145  open: 'Abrir',
146  openSession: 'Abrir sessão',
147  openPr: 'Abrir PR',
148  cancel: 'Cancelar',
149  skip: 'Pular',
150  confirmSkip: (gate: string) => `Confirmar pulo de ${gate}`,
151  skipGate: (gate: string) => `Pular portão ${gate}`,
152  session: { waiting: 'esperando você', working: 'trabalhando', idle: 'ociosa', self: 'esta sessão' },
153  jira: {
154    status: (s: string) => `Status: ${s}`,
155    noStatus: 'Sem status: o painel ainda não leu esta issue do Jira.',
156    noLink:
157      'Sem link: falta o site do Jira. Reconecte o conector Atlassian (claude.ai › Configurações › Conectores) ou informe jiraSite no plano.',
158    openIn: (key: string) => `Abrir ${key} no Jira ↗`,
159    changeIssue: 'Issue da change',
160    move: 'Mover no Jira',
161    closedButOpen: (key: string, status: string | undefined) => `Fase fechada, mas ${key} segue "${status ?? 'aberta'}" no Jira`,
162    doneButOpen: (key: string, status: string | undefined) =>
163      `${key} já está "${status ?? 'concluída'}" no Jira, mas a fase não fechou`,
164    canMove: (key: string, to: string) => `A issue ${key} pode ir para ${to}`,
165    today: (from: string) => ` Hoje: "${from}".`,
166    onlyOnPress: 'O Jira só muda quando você apertar o botão.',
167    noTransition: (key: string, to: string) => `A issue ${key} deveria ir para ${to}, mas o Jira não oferece essa transição`,
168    noneAvailable: 'nenhuma transição disponível',
169    available: (options: string) => `Disponíveis: ${options}. Ajuste o campo jira do passo no flow, ou mova na mão.`,
170    noConnector: (key: string, to: string) => `A issue ${key} deveria ir para ${to}, mas não consigo mexer no Jira`,
171    unavailable: 'Jira: conector Atlassian indisponível nesta sessão; mostrando só as chaves.',
172    noSite:
173      'Jira: o conector Atlassian está logado, mas a autorização não inclui nenhum site do Jira. Reconecte-o em claude.ai › Configurações › Conectores e marque o site na tela da Atlassian.',
174    couldNotRead: (keys: string) => `Jira: não consegui ler ${keys}.`,
175    notAuthenticated: 'o conector Atlassian não está autenticado nesta sessão (claude.ai › Configurações › Conectores).',
176    noSiteShort: 'a autorização do conector Atlassian não inclui nenhum site do Jira.',
177    notMoved: (key: string, why: string) => `Não movi ${key}: ${why}`,
178    noTransitionTool: 'o conector não oferece transitionJiraIssue.',
179    goneTransition: 'essa transição não está mais disponível. O painel vai se atualizar.',
180    moved: (key: string, to: string) => `${key} movida para ${to}.`,
181    moveFailed: (key: string) => `Não consegui mover ${key} no Jira.`,
182    refused: (key: string, why: string | undefined) => `O Jira recusou mover ${key}${why === undefined ? '.' : `: ${why}`}`,
183  },
184  openspec: {
185    proposal: 'Proposta ',
186    noCheckboxes: 'tasks.md sem caixas de seleção',
187    percentTasks: (p: number) => `${p}% das tarefas`,
188    tickedOf: (done: number, total: number) => `${done} de ${total} tarefas marcadas`,
189    sections: 'Seções do tasks.md',
190    sectionsSummary: (full: number, partial: number) => `${full} seções completas, ${partial} em andamento.`,
191    evidence: 'Evidência',
192    evidenceMissing: 'evidence.md ainda não existe.',
193    evidenceFailing: (n: number, names: string, ok: number) => `Último check.sh: ${n} falha(s) — ${names}; ${ok} ok.`,
194    evidenceGreen: (n: number) => `Último check.sh verde: ${n} verificações passaram.`,
195    evidenceStub: 'Esqueleto: nada verificado ainda, sem resultado do check.sh.',
196    evidenceRecorded: (n: number) => `${n} seção(ões) registradas, sem resumo do check.sh.`,
197  },
198  attention: {
199    title: 'Precisa de você',
200    recommendation: 'Recomendação: ',
201    accept: 'Aceitar recomendação',
202    onlyYourSkip: 'Só o seu pulo libera um portão: use Pular ao lado dele, no card da fase.',
203    permission: (what: string) => `Permissão pendente: ${what}`,
204    prOpen: (n: number) => `PR #${n} aberto`,
205    escalated: (step: string, attempts: number) => `${step}: ${attempts} tentativas sem sucesso`,
206    escalatedDetail: (flow: string, change: string) => `Flow ${flow} de ${change}: tentar de novo ou encerrar?`,
207    flowOf: (flow: string, change: string) => `Flow ${flow} de ${change}`,
208    accepted: (title: string, recommendation: string | undefined) =>
209      `Decisão do dono — "${title}": aceito a recomendação (${recommendation ?? 'a sua'}). Pode seguir.`,
210  },
211  run: {
212    phasesClosed: (done: number, total: number) => `${done} de ${total} fases fechadas`,
213    wave: (n: number) => ` · onda ${n}`,
214    working: 'Sessões trabalhando agora',
215    liveOf: (live: number, max: number) => `${live} de no máximo ${max}`,
216    atCeiling:
217      'No limite: uma nova fase só começa quando uma sessão terminar o trabalho ou for arquivada, para não pesar o computador.',
218    updated: (at: string) => `atualizado ${at}`,
219    phasesOf: (done: number, total: number) => `${done} de ${total} fases`,
220  },
221  tasks: {
222    title: 'Tarefas',
223    waveName: (n: number) => `Onda ${n}`,
224    now: 'Agora: ',
225    steps: (done: number, total: number) => `passos ${done} de ${total}`,
226    of: (done: number, total: number) => `${done} de ${total}`,
227    after: (ids: string) => `após ${ids}`,
228    closed: (n: number) => `✓ ${n} concluídas`,
229    noPlan: 'Sem plano publicado: as fases aparecem aqui quando a coordenação publicar o plano.',
230  },
231  steps: {
232    done: 'concluída',
233    skipped: 'pulada',
234    pending: 'pendente',
235    escalated: 'no limite: você decide',
236    waiting: 'esperando você',
237    running: 'em andamento',
238    attempt: (n: number, max: number) => ` · tentativa ${n} de ${max}`,
239    finalGates: 'Checagens antes de juntar o código',
240    finalGatesSummary:
241      'Rodam uma vez, com o código de todas as fases já junto; enquanto não passam, o código não é juntado na branch principal.',
242    ceiling: (max: number) => `Chegou ao limite de ${max} tentativas: escolha em "Precisa de você" se tenta de novo.`,
243    flowDone: 'Flow concluído.',
244    flowAborted: 'Flow encerrado por você.',
245    legend: '⚙ automático (um script decide) · 🤖 sessão faz · ✋ você decide no painel',
246  },
247  self: {
248    title: 'Esta sessão',
249    noList: 'Sem lista de tarefas ainda',
250    percentDone: (p: number) => `${p}% concluído`,
251    stepsOf: (done: number, total: number) => `${done} / ${total} passos`,
252    stepsOfLong: (done: number, total: number) => `${done} de ${total} passos`,
253  },
254  children: { title: 'Sessões filhas', others: 'Outras sessões', active: (n: number) => `${n} ativas` },
255  band: {
256    step: (s: string) => `passo: ${s}`,
257    inFlight: (n: number) => `${n} ${n === 1 ? 'fase em voo' : 'fases em voo'}`,
258    waiting: (n: number) => `${n} ${n === 1 ? 'pendência sua' : 'pendências suas'}`,
259    flowDone: 'flow concluído',
260    flowAborted: 'flow encerrado',
261    close: 'Fechar painel',
262    open: 'Abrir painel',
263  },
264  grill: {
265    noRounds: 'Nenhuma rodada de perguntas registrada ainda.',
266    rounds: (rounds: number, criteria: number) =>
267      `${rounds} ${rounds === 1 ? 'rodada' : 'rodadas'} · ${criteria} ${criteria === 1 ? 'critério de aceite' : 'critérios de aceite'}`,
268    open: 'Perguntas em aberto',
269    answerInChat: 'Responda no chat.',
270    placeholder: 'Escreva sua resposta e tecle Enter',
271    send: 'Enviar',
272    sendAll: (n: number) => `Enviar todas (${n})`,
273    awaitingMockup: 'Aguardando a coordenação anexar o mockup.',
274    mockup: 'Mockup:',
275    openMockup: 'Abrir mockup',
276    mockupAt: (where: string) => `Mockup: ${where}`,
277    lastAdjustment: (note: string) => `Último ajuste pedido: ${note}`,
278    adjustLabel: 'Pedir ajuste:',
279    adjustPlaceholder: 'o que mudar no mockup',
280    adjustSubmit: 'pedir ajuste',
281    releaseHint: 'Aprove o plano de execução no diálogo do plan mode do app; a liberação vem só de lá.',
282    refused: (feedback: string) => `Você recusou o último plano: ${feedback}`,
283  },
284  escalation: { retry: 'Tentar de novo', end: 'Encerrar o flow' },
285  deployCi: 'Deploy do CI concluído',
286  toast: {
287    registered: (label: string, next: string) => `Registrado: ${label}. ${next}`,
288    flowDone: 'Flow concluído.',
289    flowEnded: 'Flow encerrado.',
290    nextStep: (step: string) => `Próximo passo: ${step}.`,
291    evidenceMissing: (change: string, step: string) => `Flow ${change}: ${step} passou, mas o evidence.md ainda não foi preenchido.`,
292    deploySeen: (change: string, label: string) => `Flow ${change}: vi o deploy — ${label}.`,
293    deployRefused: (change: string, step: string, why: string) => `Flow ${change}: ${step} não contou o comando — ${why}`,
294    deployProgress: (change: string, step: string, word: 'failed' | 'part' | 'done') =>
295      `Flow ${change}: ${step} — ${{ failed: 'falhou', part: 'parte do deploy vista', done: 'deploy concluído' }[word]}.`,
296    releaseFromPlanMode: 'A liberação vem do plan mode: aprove o plano de execução no diálogo do app.',
297    notRecorded: (why: string) => `Não consegui registrar: ${why}`,
298    severalReleases: 'Vários flows esperam a liberação; aprovação do plano não registrada.',
299    cannotOpen: (title: string) => `Não consegui abrir; procure "${title}" na barra lateral.`,
300    paneFailed: 'Não consegui abrir ou fechar o painel.',
301    skipNotLoaded: 'Não consegui registrar o pulo: o painel ainda não carregou a change. Tente de novo em alguns segundos.',
302    skipped: (gate: string) => `Portão ${gate} pulado por decisão sua.`,
303    skipFailed: 'Não consegui registrar o pulo do portão.',
304    flowFailed: 'Não consegui registrar sua resposta ao flow.',
305    adjustEmpty: 'Escreva o que ajustar antes de enviar.',
306    answerEmpty: 'Escreva a resposta antes de enviar.',
307    grillFailed: 'Não consegui registrar sua resposta ao grill.',
308  },
309  command: {
310    description: 'Abre ou fecha o painel da orquestração: OpenSpec, gates, pendências e tarefas',
311    closed: 'Painel do orquestrador fechado.',
312    opened: 'Painel do orquestrador aberto.',
313    waiting: 'Painel pronto; amplie a janela para vê-lo.',
314    workflowsDescription: 'Abre ou fecha o painel ⚙️ Workflows: ver e editar os workflows do projeto',
315    workflowsClosed: 'Painel de workflows fechado.',
316    workflowsOpened: 'Painel de workflows aberto.',
317    workflowsWaiting: 'Painel de workflows pronto; amplie a janela para vê-lo.',
318  },
319  warning: {
320    noSessions: 'Sessões filhas indisponíveis: o app não expõe a lista de sessões aqui.',
321    tampered: 'A ativação foi mudada fora do painel: vale "barrar" até você confirmar por aqui (Workflows, "Este projeto").',
322    reminded: (count: number, last: string) => `Em "lembrar", ${count} recusa(s) viraram só aviso. Última: ${last}`,
323  },
324  question: 'Pergunta para você',
325}
326
327export type UiText = typeof pt
328
329const en: UiText = {
330  locale: 'en-US',
331  status: {
332    legend: { done: 'closed', running: 'in flight', blocked: 'blocked', pending: 'pending' },
333    word: { done: 'closed', running: 'in flight', blocked: 'blocked', pending: 'pending' },
334  },
335  attentionKind: {
336    decision: 'Decision',
337    permission: 'Permission',
338    question: 'Question',
339    pr: 'PR to review',
340    flow: 'Flow step',
341    jira: 'Jira',
342  },
343  evidence: {
344    missing: 'missing',
345    stub: 'stub',
346    recorded: 'recorded',
347    green: 'check.sh green',
348    failing: 'check.sh failed',
349  },
350  gate: {
351    passed: 'passed',
352    failed: 'failed',
353    pending: 'not run',
354    stale: 'stale',
355    skipped: 'skipped by you',
356  },
357  open: 'Open',
358  openSession: 'Open session',
359  openPr: 'Open PR',
360  cancel: 'Cancel',
361  skip: 'Skip',
362  confirmSkip: gate => `Confirm skipping ${gate}`,
363  skipGate: gate => `Skip gate ${gate}`,
364  session: { waiting: 'waiting on you', working: 'working', idle: 'idle', self: 'this session' },
365  jira: {
366    status: s => `Status: ${s}`,
367    noStatus: 'No status: the panel has not read this Jira issue yet.',
368    noLink:
369      'No link: the Jira site is missing. Reconnect the Atlassian connector (claude.ai › Settings › Connectors) or set jiraSite in the plan.',
370    openIn: key => `Open ${key} in Jira ↗`,
371    changeIssue: 'Change issue',
372    move: 'Move in Jira',
373    closedButOpen: (key, status) => `Phase closed, but ${key} is still "${status ?? 'open'}" in Jira`,
374    doneButOpen: (key, status) => `${key} is already "${status ?? 'done'}" in Jira, but the phase has not closed`,
375    canMove: (key, to) => `Issue ${key} can move to ${to}`,
376    today: from => ` Now: "${from}".`,
377    onlyOnPress: 'Jira only changes when you press the button.',
378    noTransition: (key, to) => `Issue ${key} should move to ${to}, but Jira offers no such transition`,
379    noneAvailable: 'no transition available',
380    available: options => `Available: ${options}. Adjust the step's jira field in the flow, or move it by hand.`,
381    noConnector: (key, to) => `Issue ${key} should move to ${to}, but I cannot reach Jira`,
382    unavailable: 'Jira: the Atlassian connector is unavailable in this session; showing the keys only.',
383    noSite:
384      'Jira: the Atlassian connector is signed in, but its authorization includes no Jira site. Reconnect it in claude.ai › Settings › Connectors and tick the site on the Atlassian screen.',
385    couldNotRead: keys => `Jira: could not read ${keys}.`,
386    notAuthenticated: 'the Atlassian connector is not authenticated in this session (claude.ai › Settings › Connectors).',
387    noSiteShort: "the Atlassian connector's authorization includes no Jira site.",
388    notMoved: (key, why) => `Did not move ${key}: ${why}`,
389    noTransitionTool: 'the connector does not offer transitionJiraIssue.',
390    goneTransition: 'that transition is no longer available. The panel will refresh.',
391    moved: (key, to) => `${key} moved to ${to}.`,
392    moveFailed: key => `Could not move ${key} in Jira.`,
393    refused: (key, why) => `Jira refused to move ${key}${why === undefined ? '.' : `: ${why}`}`,
394  },
395  openspec: {
396    proposal: 'Proposal ',
397    noCheckboxes: 'tasks.md has no checkboxes',
398    percentTasks: p => `${p}% of tasks`,
399    tickedOf: (done, total) => `${done} of ${total} tasks ticked`,
400    sections: 'tasks.md sections',
401    sectionsSummary: (full, partial) => `${full} sections complete, ${partial} in progress.`,
402    evidence: 'Evidence',
403    evidenceMissing: 'evidence.md does not exist yet.',
404    evidenceFailing: (n, names, ok) => `Last check.sh: ${n} failure(s) — ${names}; ${ok} ok.`,
405    evidenceGreen: n => `Last check.sh green: ${n} checks passed.`,
406    evidenceStub: 'Stub: nothing verified yet, no check.sh result.',
407    evidenceRecorded: n => `${n} section(s) recorded, no check.sh summary.`,
408  },
409  attention: {
410    title: 'Needs you',
411    recommendation: 'Recommendation: ',
412    accept: 'Accept recommendation',
413    onlyYourSkip: "Only your skip releases a gate: use Skip beside it, in the phase's card.",
414    permission: what => `Permission pending: ${what}`,
415    prOpen: n => `PR #${n} open`,
416    escalated: (step, attempts) => `${step}: ${attempts} attempts without success`,
417    escalatedDetail: (flow, change) => `Flow ${flow} of ${change}: try again or end it?`,
418    flowOf: (flow, change) => `Flow ${flow} of ${change}`,
419    accepted: (title, recommendation) =>
420      `Owner's decision — "${title}": I accept the recommendation (${recommendation ?? 'yours'}). Go ahead.`,
421  },
422  run: {
423    phasesClosed: (done, total) => `${done} of ${total} phases closed`,
424    wave: n => ` · wave ${n}`,
425    working: 'Sessions working now',
426    liveOf: (live, max) => `${live} of at most ${max}`,
427    atCeiling: 'At the ceiling: a new phase starts only once a session finishes its work or is archived, to spare the computer.',
428    updated: at => `updated ${at}`,
429    phasesOf: (done, total) => `${done} of ${total} phases`,
430  },
431  tasks: {
432    title: 'Tasks',
433    waveName: n => `Wave ${n}`,
434    now: 'Now: ',
435    steps: (done, total) => `steps ${done} of ${total}`,
436    of: (done, total) => `${done} of ${total}`,
437    after: ids => `after ${ids}`,
438    closed: n => `✓ ${n} done`,
439    noPlan: 'No plan published: the phases show here once the coordinator publishes the plan.',
440  },
441  steps: {
442    done: 'done',
443    skipped: 'skipped',
444    pending: 'pending',
445    escalated: 'at the ceiling: you decide',
446    waiting: 'waiting on you',
447    running: 'in progress',
448    attempt: (n, max) => ` · attempt ${n} of ${max}`,
449    finalGates: 'Checks before merging the code',
450    finalGatesSummary:
451      'They run once, with the code of every phase already together; until they pass, the code is not merged into the main branch.',
452    ceiling: max => `Reached the ceiling of ${max} attempts: choose in "Needs you" whether to try again.`,
453    flowDone: 'Flow finished.',
454    flowAborted: 'Flow ended by you.',
455    legend: '⚙ automatic (a script decides) · 🤖 a session does it · ✋ you decide in the panel',
456  },
457  self: {
458    title: 'This session',
459    noList: 'No task list yet',
460    percentDone: p => `${p}% done`,
461    stepsOf: (done, total) => `${done} / ${total} steps`,
462    stepsOfLong: (done, total) => `${done} of ${total} steps`,
463  },
464  children: { title: 'Child sessions', others: 'Other sessions', active: n => `${n} active` },
465  band: {
466    step: s => `step: ${s}`,
467    inFlight: n => `${n} ${n === 1 ? 'phase in flight' : 'phases in flight'}`,
468    waiting: n => `${n} ${n === 1 ? 'item for you' : 'items for you'}`,
469    flowDone: 'flow finished',
470    flowAborted: 'flow ended',
471    close: 'Close panel',
472    open: 'Open panel',
473  },
474  grill: {
475    noRounds: 'No round of questions recorded yet.',
476    rounds: (rounds, criteria) =>
477      `${rounds} ${rounds === 1 ? 'round' : 'rounds'} · ${criteria} ${criteria === 1 ? 'acceptance criterion' : 'acceptance criteria'}`,
478    open: 'Open questions',
479    answerInChat: 'Answer in the chat.',
480    placeholder: 'Write your answer and press Enter',
481    send: 'Send',
482    sendAll: n => `Send all (${n})`,
483    awaitingMockup: 'Waiting for the coordinator to attach the mockup.',
484    mockup: 'Mockup:',
485    openMockup: 'Open mockup',
486    mockupAt: where => `Mockup: ${where}`,
487    lastAdjustment: note => `Last adjustment asked: ${note}`,
488    adjustLabel: 'Ask for an adjustment:',
489    adjustPlaceholder: 'what to change in the mockup',
490    adjustSubmit: 'ask for adjustment',
491    releaseHint: "Approve the execution plan in the app's plan mode dialog; the release comes from there only.",
492    refused: feedback => `You refused the last plan: ${feedback}`,
493  },
494  escalation: { retry: 'Try again', end: 'End the flow' },
495  deployCi: 'CI deploy finished',
496  toast: {
497    registered: (label, next) => `Recorded: ${label}. ${next}`,
498    flowDone: 'Flow finished.',
499    flowEnded: 'Flow ended.',
500    nextStep: step => `Next step: ${step}.`,
501    evidenceMissing: (change, step) => `Flow ${change}: ${step} passed, but evidence.md is not filled in yet.`,
502    deploySeen: (change, label) => `Flow ${change}: saw the deploy — ${label}.`,
503    deployRefused: (change, step, why) => `Flow ${change}: ${step} did not count the command — ${why}`,
504    deployProgress: (change, step, word) =>
505      `Flow ${change}: ${step} — ${{ failed: 'failed', part: 'part of the deploy seen', done: 'deploy finished' }[word]}.`,
506    releaseFromPlanMode: "The release comes from plan mode: approve the execution plan in the app's dialog.",
507    notRecorded: why => `Could not record: ${why}`,
508    severalReleases: 'Several flows wait on the release; plan approval not recorded.',
509    cannotOpen: title => `Could not open it; look for "${title}" in the sidebar.`,
510    paneFailed: 'Could not open or close the panel.',
511    skipNotLoaded: 'Could not record the skip: the panel has not loaded the change yet. Try again in a few seconds.',
512    skipped: gate => `Gate ${gate} skipped by your decision.`,
513    skipFailed: 'Could not record the gate skip.',
514    flowFailed: 'Could not record your answer to the flow.',
515    adjustEmpty: 'Write what to adjust before sending.',
516    answerEmpty: 'Write the answer before sending.',
517    grillFailed: 'Could not record your answer to the grill.',
518  },
519  command: {
520    description: 'Opens or closes the orchestration panel: OpenSpec, gates, pending items and tasks',
521    closed: 'Orchestrator panel closed.',
522    opened: 'Orchestrator panel opened.',
523    waiting: 'Panel ready; widen the window to see it.',
524    workflowsDescription: "Opens or closes the ⚙️ Workflows panel: view and edit the project's workflows",
525    workflowsClosed: 'Workflows panel closed.',
526    workflowsOpened: 'Workflows panel opened.',
527    workflowsWaiting: 'Workflows panel ready; widen the window to see it.',
528  },
529  warning: {
530    noSessions: 'Child sessions unavailable: the app does not expose the session list here.',
531    tampered: 'The activation was changed outside the panel: "block" applies until you confirm it here (Workflows, "Este projeto").',
532    reminded: (count: number, last: string) => `In "remind", ${count} refusal(s) became a warning only. Last: ${last}`,
533  },
534  question: 'A question for you',
535}
536
537const TEXT: Record<Lang, UiText> = { 'pt-BR': pt, en }
538
539/** The panel's words in `lang`; no language, the mod's own pt-BR. */
540export const uiText = (lang: Lang | undefined): UiText => TEXT[lang ?? DEFAULT_LANG]
541
hooks/pane.tsx 1206 lines
1import type {
2  BoxProps,
3  ButtonProps,
4  ElementConstructor,
5  InputProps,
6  LinkProps,
7  RenderElement,
8  SvgProps,
9  TextProps,
10} from 'claude-code'
11
12import type {
13  Attention,
14  EvidenceState,
15  FlowStepKind,
16  FlowStepView,
17  GateCheck,
18  GateState,
19  GateView,
20  GrillAnswer,
21  JiraCategory,
22  OpenSpecView,
23  PanelView,
24  PhaseStatus,
25  PhaseView,
26  PlanItem,
27  SessionCard,
28} from '../types'
29import { FINAL_SCOPE, MAX_LIVE_SESSIONS, familyCheck, gateViews, isOpenGate, liveSessions } from './gates'
30import { divergence } from './jira'
31import { tasksForPhase } from './openspec'
32import { formatElapsed } from './glance'
33import { uiText } from './i18n'
34import type { Lang } from '../types'
35import type { BandSummary } from './glance'
36import { attentionItems, finishedSessionIds, nowAndNext, phaseCounts, phaseViews, planProgress } from './model'
37import { hiddenFlowChoices, prepDetails } from './prep-pane'
38
39export type PaneElements = {
40  Box: ElementConstructor<BoxProps>
41  Text: ElementConstructor<TextProps>
42  Button: ElementConstructor<ButtonProps>
43  Link: ElementConstructor<LinkProps>
44  /** Only the desktop draws Svg; elsewhere the bar is drawn with text. */
45  Svg: ElementConstructor<SvgProps> | undefined
46  /** A text field, where the surface has one (not on mobile). */
47  Input?: ElementConstructor<InputProps> | undefined
48}
49
50/** What the hooks module hands in: state it owns and the closures that reach `$`. */
51export type PaneActions = {
52  collapsed: Readonly<Record<string, boolean>>
53  answered: readonly string[]
54  canOpenBeside: (card: SessionCard) => boolean
55  toggle: (id: string, byDefault: boolean) => () => void
56  openBeside: (card: SessionCard) => () => void
57  accept: (item: Attention) => () => void
58  /** The owner's skip of one gate; the pane arms it with a first press and fires on the second. */
59  skip: (gate: GateView) => () => void
60  /** The owner's answer to a flow step: the only way an owner step moves. */
61  answerFlow: (change: string, step: string, outcome: string) => () => void
62  /** The same answer with the owner's note typed in the panel (a mockup adjustment). */
63  noteFlow: (change: string, step: string, outcome: string) => (value: string) => void
64  /** What the owner has typed in the grill's answer fields, by question text. */
65  drafts: Readonly<Record<string, string>>
66  /** Keeps one answer field's text as the owner types it. */
67  draftAnswer: (question: string) => (value: string) => void
68  /** The owner's answers to open grill questions: recorded in the round and sent as their own message. */
69  answerGrill: (change: string, answers: GrillAnswer[]) => () => void
70  /** The owner's "Mover no Jira": the only way an issue changes state. */
71  moveJira: (change: string, key: string, transitionId: string) => () => void
72}
73
74/** Hex, not theme keys: the Svg bar and the legend squares must match exactly. */
75const STATUS_HEX: Record<PhaseStatus, string> = {
76  done: '#4CAF7D',
77  running: '#D97757',
78  blocked: '#D14343',
79  pending: '#B4B2A9',
80}
81/** Pills: a soft tint behind a darker word of the same hue. */
82const PILL: Record<PhaseStatus, { bg: string; fg: string }> = {
83  running: { bg: '#FAECE7', fg: '#993C1D' },
84  done: { bg: '#EAF3DE', fg: '#27500A' },
85  pending: { bg: '#F1EFE8', fg: '#5F5E5A' },
86  blocked: { bg: '#FCEBEB', fg: '#A32D2D' },
87}
88/** Actions read as links. */
89const LINK = '#2F6FD6'
90const STATUS_ORDER: readonly PhaseStatus[] = ['done', 'running', 'blocked', 'pending']
91const ITEM_MARK: Record<PlanItem['status'], string> = { completed: '✓', in_progress: '▶', pending: '○' }
92const ITEM_STATUS: Record<PlanItem['status'], PhaseStatus> = {
93  completed: 'done',
94  in_progress: 'running',
95  pending: 'pending',
96}
97
98const JIRA_HEX: Record<JiraCategory, string> = {
99  new: STATUS_HEX.pending,
100  indeterminate: STATUS_HEX.running,
101  done: STATUS_HEX.done,
102  unknown: STATUS_HEX.pending,
103}
104const EVIDENCE_HEX: Record<EvidenceState, string> = {
105  missing: STATUS_HEX.blocked,
106  stub: STATUS_HEX.pending,
107  recorded: STATUS_HEX.running,
108  green: STATUS_HEX.done,
109  failing: STATUS_HEX.blocked,
110}
111
112/** A question asking to release a gate: "Aceitar" only messages the coordinator, which cannot skip it. */
113const asksGateSkip = (text: string): boolean =>
114  /\b(pul(ar|e|o)|liberar|libere|dispensar|skip(ping)?|release|waive|bypass)\b.*\b(port[ãa]o|portões|gates?)\b|\b(port[ãa]o|portões|gates?)\b.*\b(pular|liberar|dispensar|skip(ped)?|release[ds]?|waive[ds]?|bypass(ed)?)\b/i.test(text)
115
116const GATE_MARK: Record<GateState, string> = { passed: '✓', failed: '✗', pending: '○', stale: '⚠', skipped: '⏭' }
117const GATE_HEX: Record<GateState, string> = {
118  passed: STATUS_HEX.done,
119  failed: STATUS_HEX.blocked,
120  pending: STATUS_HEX.pending,
121  stale: '#E0A030',
122  skipped: STATUS_HEX.pending,
123}
124const NO_CHECK: GateCheck = { records: {}, editedAt: undefined }
125
126/** Who moves a step: a script, a session, or the owner's press in the panel. */
127const KIND_ICON: Record<FlowStepKind, string> = { automatic: '⚙', session: '🤖', loop: '🤖', owner: '✋' }
128const STEP_MARK: Record<FlowStepView['state'], string> = { done: '✓', current: '▶', pending: '○', skipped: '⏭' }
129
130const formatTime = (ms: number, locale: string): string =>
131  new Date(ms).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
132
133const percent = (part: number, total: number): number =>
134  total === 0 ? 0 : Math.round((part / total) * 100)
135
136const waveStatus = (phases: readonly PhaseView[]): PhaseStatus =>
137  phases.some(p => p.status === 'blocked')
138    ? 'blocked'
139    : phases.some(p => p.status === 'running')
140      ? 'running'
141      : phases.every(p => p.status === 'done')
142        ? 'done'
143        : 'pending'
144
145const barSvg = (segments: readonly { value: number; hex: string }[]): string => {
146  const total = segments.reduce((sum, s) => sum + s.value, 0)
147  let x = 0
148  const rects = segments
149    .filter(s => s.value > 0)
150    .map(s => {
151      const w = (s.value / Math.max(total, 1)) * 100
152      const rect = `<rect x="${x.toFixed(2)}" y="0" width="${Math.max(w - 0.6, 0.4).toFixed(2)}" height="4" rx="2" fill="${s.hex}"/>`
153      x += w
154      return rect
155    })
156  return (
157    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 4" preserveAspectRatio="none" width="100%" height="4">` +
158    `<rect x="0" y="0" width="100" height="4" rx="2" fill="#8884"/>${rects.join('')}</svg>`
159  )
160}
161
162
163/** Pure drawing: the hooks module owns `$` and hands in the elements, the data and the actions. */
164export const renderPane = (
165  elements: PaneElements,
166  view: PanelView,
167  ownPlan: readonly PlanItem[],
168  actions: PaneActions,
169): RenderElement => {
170  const { Box, Text, Button, Link, Svg } = elements
171  const t = uiText(view.languages?.ui)
172  const isOpen = (id: string, byDefault: boolean): boolean => !(actions.collapsed[id] ?? !byDefault)
173
174  const bar = (segments: readonly { value: number; hex: string }[], alt: string) => {
175    const total = Math.max(1, segments.reduce((a, b) => a + b.value, 0))
176    return Svg !== undefined ? (
177      <Svg source={barSvg(segments)} alt={alt} height={4} />
178    ) : (
179      <Text>
180        {segments.map(s => (
181          <Text color={s.hex}>{'━'.repeat(Math.round((s.value / total) * 24))}</Text>
182        ))}
183      </Text>
184    )
185  }
186
187  /**
188   * One line: the left side grows and shrinks (minWidth 0, or a flex child never shrinks below
189   * its text and spills past the card's border); the right side keeps its width.
190   */
191  const row = (left: RenderElement | string, right?: RenderElement | string, rightColor?: string, dim?: boolean) => (
192    <Box flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
193      <Box flexDirection="row" flexShrink={1} flexGrow={1} minWidth={0}>
194        {typeof left === 'string' ? (
195          <Text wrap="truncate-end" dimColor={dim}>
196            {left}
197          </Text>
198        ) : (
199          left
200        )}
201      </Box>
202      {right !== undefined && (
203        <Box flexDirection="row" flexShrink={0}>
204          {typeof right === 'string' ? (
205            <Text color={rightColor} dimColor={rightColor === undefined} wrap="truncate-end">
206              {right}
207            </Text>
208          ) : (
209            right
210          )}
211        </Box>
212      )}
213    </Box>
214  )
215
216  /** Status as a pill: a soft tint behind a darker word of the same hue. */
217  const pill = (status: PhaseStatus) => (
218    <Text backgroundColor={PILL[status].bg} color={PILL[status].fg}>
219      {` ${t.status.word[status]} `}
220    </Text>
221  )
222
223  /** The second level of text: what a thing is, the step it is on. */
224  const subtitle = (text: string, prefix = '') => (
225    <Text color="inactive" wrap="wrap">
226      {prefix}
227      {text}
228    </Text>
229  )
230
231  const square = (hex: string) => <Text color={hex}>■ </Text>
232
233  const summaryBox = (summary: string) => (
234    <Box borderStyle="round" borderDimColor paddingX={1} minWidth={0}>
235      <Text wrap="wrap" dimColor>
236        {summary}
237      </Text>
238    </Box>
239  )
240
241  /** ⓘ opens the summary below its row: the desktop draws no tooltip for a mod's pane, a press works everywhere. */
242  const infoButton = (id: string, summary: string | undefined): RenderElement[] =>
243    summary === undefined
244      ? []
245      : [
246          <Button key={`info:${id}`} plain dimColor={!isOpen(id, false)} onPress={actions.toggle(id, false)}>
247            ⓘ
248          </Button>,
249        ]
250
251  const summaryFor = (id: string, summary: string | undefined): RenderElement[] =>
252    summary !== undefined && isOpen(id, false) ? [summaryBox(summary)] : []
253
254  const card = (
255    id: string,
256    title: string,
257    children: RenderElement[],
258    aside?: string,
259    accent?: string,
260    byDefault = true,
261  ) => {
262    const open = isOpen(id, byDefault)
263    return (
264      <Box
265        flexDirection="column"
266        borderStyle="round"
267        borderColor={accent}
268        borderDimColor={accent === undefined}
269        paddingX={1}
270        minWidth={0}
271      >
272        <Box flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
273          <Box flexShrink={1} minWidth={0}>
274            <Button key={`card:${id}`} plain onPress={actions.toggle(id, byDefault)}>
275              <Text bold color={accent} wrap="truncate-end">
276                {title}
277              </Text>
278              <Text dimColor>{open ? ' ⌄' : ' ›'}</Text>
279            </Button>
280          </Box>
281          {aside !== undefined && (
282            <Box flexShrink={0}>
283              <Text dimColor wrap="truncate-end">
284                {aside}
285              </Text>
286            </Box>
287          )}
288        </Box>
289        {open && (
290          <Box flexDirection="column" marginTop={1} minWidth={0}>
291            {children}
292          </Box>
293        )}
294      </Box>
295    )
296  }
297
298  const group = (
299    id: string,
300    label: string,
301    count: string,
302    byDefault: boolean,
303    body: () => RenderElement[],
304    summary?: string,
305  ) => {
306    const open = isOpen(id, byDefault)
307    return (
308      <Box flexDirection="column" minWidth={0}>
309        <Box flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
310          <Box flexDirection="row" columnGap={1} alignItems="center" flexShrink={1} minWidth={0}>
311            <Button key={`group:${id}`} plain onPress={actions.toggle(id, byDefault)}>
312              <Text dimColor>{open ? '⌄ ' : '› '}</Text>
313              <Text wrap="truncate-end">{label}</Text>
314            </Button>
315            {infoButton(`summary:${id}`, summary)}
316          </Box>
317          {count !== '' && (
318            <Box flexShrink={0}>
319              <Text dimColor>{count}</Text>
320            </Box>
321          )}
322        </Box>
323        {summaryFor(`summary:${id}`, summary)}
324        {open && (
325          <Box flexDirection="column" paddingLeft={2} minWidth={0}>
326            {body()}
327          </Box>
328        )}
329      </Box>
330    )
331  }
332
333  /**
334   * "Abrir": a button in every case. The pane draws a `claude://` Link as dead text, so the
335   * hooks module opens it: beside this session when the app allows it, else through the app's link.
336   */
337  const openControl = (c: SessionCard, label = t.open, scope = ''): RenderElement | undefined =>
338    actions.canOpenBeside(c) || c.link !== undefined ? (
339      <Button key={`open:${scope}:${label}:${c.sessionId}`} plain onPress={actions.openBeside(c)}>
340        <Text color={LINK}>{`${label} ↗`}</Text>
341      </Button>
342    ) : undefined
343
344  const planRows = (plan: readonly PlanItem[]) =>
345    plan.map(item =>
346      row(
347        <Text wrap="truncate-end" dimColor={item.status === 'completed'}>
348          <Text color={STATUS_HEX[ITEM_STATUS[item.status]]}>{ITEM_MARK[item.status]} </Text>
349          {item.content}
350        </Text>,
351      ),
352    )
353
354  const sessionState = (c: SessionCard): string =>
355    c.waiting !== undefined ? t.session.waiting : c.isRunning ? t.session.working : t.session.idle
356
357  const sessionRows = (c: SessionCard): RenderElement[] => {
358    const progress = planProgress(c.plan)
359    const meta = [
360      sessionState(c),
361      c.prNumber === undefined ? undefined : `PR #${c.prNumber}${c.prState ? ` ${c.prState.toLowerCase()}` : ''}`,
362      progress.total > 0 ? `${progress.done}/${progress.total}` : undefined,
363    ]
364      .filter(Boolean)
365      .join(' · ')
366    return [
367      row(meta, openControl(c), undefined, true),
368      ...(progress.current === undefined
369        ? []
370        : [
371            row(
372              <Text wrap="truncate-end" color={STATUS_HEX.running}>
373                ▶ {progress.current}
374              </Text>,
375            ),
376          ]),
377    ]
378  }
379
380  const issues = view.jira ?? {}
381  const skips = view.skips ?? {}
382
383  /** One line per gate: its mark and what proved it, then its state or the owner's two-press skip. */
384  const gateRows = (gates: readonly GateView[]): RenderElement[] =>
385    gates.flatMap(g => {
386      const armed = isOpen(`arm:${g.skipKey}`, false)
387      const line = row(
388        <Text wrap="truncate-end" dimColor={g.state === 'passed' || g.state === 'skipped'}>
389          <Text color={GATE_HEX[g.state]}>{GATE_MARK[g.state]} </Text>
390          {g.label}
391          {g.evidence !== undefined && <Text dimColor> · {g.evidence}</Text>}
392        </Text>,
393        <Box flexDirection="row" columnGap={1} flexShrink={0}>
394          <Text color={GATE_HEX[g.state]}>{t.gate[g.state]}</Text>
395          {isOpenGate(g) && (
396            <Button key={`arm:${g.skipKey}`} plain dimColor onPress={actions.toggle(`arm:${g.skipKey}`, false)}>
397              {armed ? t.cancel : t.skip}
398            </Button>
399          )}
400        </Box>,
401      )
402      // the confirmation gets a line of its own: beside the state word it fell off a narrow pane
403      if (!isOpenGate(g) || !armed) return [line]
404      return [
405        line,
406        <Box flexDirection="row" paddingLeft={2} minWidth={0}>
407          <Button key={`skip:${g.skipKey}`} variant="primary" onPress={actions.skip(g)}>
408            {t.confirmSkip(g.label)}
409          </Button>
410        </Box>,
411      ]
412    })
413
414  /** An owner question's skip: the same two presses as beside the gate, so a gate is never skipped by one tap. */
415  const skipButtons = (g: GateView): RenderElement[] => {
416    const armed = isOpen(`arm:${g.skipKey}`, false)
417    return armed
418      ? [
419          <Button key={`skip:${g.skipKey}:ask`} variant="primary" onPress={actions.skip(g)}>
420            {t.confirmSkip(g.label)}
421          </Button>,
422          <Button key={`arm:${g.skipKey}:ask`} plain dimColor onPress={actions.toggle(`arm:${g.skipKey}`, false)}>
423            {t.cancel}
424          </Button>,
425        ]
426      : [
427          <Button key={`arm:${g.skipKey}:ask`} variant="primary" onPress={actions.toggle(`arm:${g.skipKey}`, false)}>
428            {t.skipGate(g.label)}
429          </Button>,
430        ]
431  }
432
433  /** One line per Jira key: the key as a link, its status in its category's colour, its title; then any disagreement. */
434  /** What a pressed Jira key shows: the issue as far as it is known, or why it is not. */
435  const jiraDetails = (key: string): RenderElement[] => {
436    const issue = issues[key]
437    const id = `jira:${key}`
438    if (!isOpen(id, false)) return []
439    const lines = [
440      issue?.title ?? undefined,
441      issue?.status === undefined ? undefined : t.jira.status(issue.status),
442      issue?.status === undefined ? view.jiraNote ?? t.jira.noStatus : undefined,
443      issue?.url === undefined ? t.jira.noLink : undefined,
444    ].filter((line): line is string => line !== undefined)
445    return [
446      <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} minWidth={0}>
447        {lines.map(line => (
448          <Text wrap="wrap" dimColor>
449            {line}
450          </Text>
451        ))}
452        {issue?.url !== undefined && <Link href={issue.url}>{t.jira.openIn(key)}</Link>}
453      </Box>,
454    ]
455  }
456
457  const jiraKeyButton = (key: string): RenderElement => {
458    const issue = issues[key]
459    return (
460      <Button key={`jira:${key}`} plain onPress={actions.toggle(`jira:${key}`, false)}>
461        <Text color={JIRA_HEX[issue?.category ?? 'unknown']}>
462          {issue?.status === undefined ? key : `${key} · ${issue.status}`}
463        </Text>
464        <Text dimColor>{isOpen(`jira:${key}`, false) ? ' ⌄' : ' ›'}</Text>
465      </Button>
466    )
467  }
468
469  /** Under a title that carries the key: the pressed key's details, then any disagreement with Jira. */
470  const jiraBelow = (key: string | undefined, status: PhaseStatus): RenderElement[] => {
471    if (key === undefined) return []
472    const mismatch = divergence(status, issues[key], t)
473    return [
474      ...jiraDetails(key),
475      ...(mismatch === undefined
476        ? []
477        : [
478            <Text color="warning" wrap="wrap">
479              ⚠ {mismatch}
480            </Text>,
481          ]),
482    ]
483  }
484
485  const jiraRows = (key: string | undefined, status: PhaseStatus): RenderElement[] => {
486    if (key === undefined) return []
487    const issue = issues[key]
488    const mismatch = divergence(status, issue, t)
489    return [
490      row(
491        <Box flexDirection="row" columnGap={1} flexShrink={1} minWidth={0}>
492          <Text dimColor>Jira</Text>
493          {jiraKeyButton(key)}
494          {issue?.title !== undefined && (
495            <Text wrap="truncate-end" dimColor>
496              {issue.title}
497            </Text>
498          )}
499        </Box>,
500        issue?.status,
501        issue === undefined ? undefined : JIRA_HEX[issue.category],
502      ),
503      ...jiraDetails(key),
504      ...(mismatch === undefined
505        ? []
506        : [
507            <Text color="warning" wrap="wrap">
508              ⚠ {mismatch}
509            </Text>,
510          ]),
511    ]
512  }
513
514  const openSpecCard = (spec: OpenSpecView): RenderElement => {
515    const partial = spec.sections.filter(s => s.done > 0 && s.done < s.total).length
516    const full = spec.sections.filter(s => s.total > 0 && s.done === s.total).length
517    return card(
518      'openspec',
519      'OpenSpec',
520      [
521        ...(spec.proposalTitle === undefined && spec.proposalSummary === undefined
522          ? []
523          : [
524              row(
525                <Box flexDirection="row" columnGap={1} alignItems="center" flexShrink={1} minWidth={0}>
526                  {infoButton('openspec:proposal', spec.proposalSummary)}
527                  <Text wrap="truncate-end">
528                    <Text dimColor>{t.openspec.proposal}</Text>
529                    {spec.proposalTitle ?? 'proposal.md'}
530                  </Text>
531                </Box>,
532              ),
533              ...summaryFor('openspec:proposal', spec.proposalSummary),
534            ]),
535        <Box marginTop={1} />,
536        ...(spec.total === 0
537          ? [<Text dimColor>{t.openspec.noCheckboxes}</Text>]
538          : [
539              row(t.openspec.percentTasks(percent(spec.done, spec.total)), `${spec.done} / ${spec.total}`),
540              bar(
541                [
542                  { value: spec.done, hex: STATUS_HEX.done },
543                  { value: spec.total - spec.done, hex: STATUS_HEX.pending },
544                ],
545                t.openspec.tickedOf(spec.done, spec.total),
546              ),
547              group(
548                'openspec:sections',
549                t.openspec.sections,
550                `${full}/${spec.sections.length}`,
551                true,
552                () =>
553                  spec.sections.map(section => {
554                    const status: PhaseStatus =
555                      section.done === section.total ? 'done' : section.done > 0 ? 'running' : 'pending'
556                    return row(
557                      <Text wrap="truncate-end" dimColor={status === 'done'}>
558                        {square(STATUS_HEX[status])}
559                        {section.title}
560                      </Text>,
561                      `${section.done}/${section.total}`,
562                    )
563                  }),
564                partial > 0 ? t.openspec.sectionsSummary(full, partial) : undefined,
565              ),
566            ]),
567        <Box marginTop={1} />,
568        row(
569          <Box flexDirection="row" columnGap={1} alignItems="center" flexShrink={1} minWidth={0}>
570            <Text dimColor>{t.openspec.evidence}</Text>
571            {infoButton('openspec:evidence', spec.evidenceSummary)}
572          </Box>,
573          t.evidence[spec.evidence],
574          EVIDENCE_HEX[spec.evidence],
575        ),
576        ...summaryFor('openspec:evidence', spec.evidenceSummary),
577      ],
578      spec.total === 0 ? undefined : `${spec.done}/${spec.total}`,
579    )
580  }
581
582  const cards: RenderElement[] = []
583  const run = view.run
584
585  const attention = attentionItems(view).filter(a => a.kind === 'flow' || !actions.answered.includes(a.title))
586  const hiddenFlow = hiddenFlowChoices(elements, view)
587  const attentionCard =
588    attention.length === 0
589      ? undefined
590      : card(
591        'attention',
592        t.attention.title,
593        attention.map(item => {
594          const canOpen = item.card !== undefined && item.card.sessionId !== view.self?.sessionId
595          return (
596            <Box flexDirection="column" borderStyle="round" borderColor="warning" paddingX={1} marginBottom={1} minWidth={0}>
597              <Text dimColor>{t.attentionKind[item.kind]}</Text>
598              <Text bold wrap="wrap" color="warning">
599                {item.title}
600              </Text>
601              {item.recommendation !== undefined && (
602                <Text wrap="wrap">
603                  <Text dimColor>{t.attention.recommendation}</Text>
604                  {item.recommendation}
605                </Text>
606              )}
607              {item.detail !== undefined && (
608                <Text dimColor wrap="truncate-end">
609                  {item.detail}
610                </Text>
611              )}
612              {item.kind === 'flow' && prepDetails(elements, view, actions)}
613              <Box flexDirection="row" columnGap={1} marginTop={1} flexWrap="wrap">
614                {item.skip !== undefined && skipButtons(item.skip)}
615                {item.kind === 'decision' && item.skip === undefined && item.recommendation !== undefined && !asksGateSkip(item.title) && (
616                  <Button key={`accept:${item.id}`} variant="primary" onPress={actions.accept(item)}>
617                    {t.attention.accept}
618                  </Button>
619                )}
620                {item.kind === 'decision' && item.skip === undefined && asksGateSkip(item.title) && (
621                  <Text dimColor wrap="wrap">
622                    {t.attention.onlyYourSkip}
623                  </Text>
624                )}
625                {item.flow !== undefined &&
626                  item.flow.choices.filter(c => !hiddenFlow.includes(c.outcome)).map((choice, i) => (
627                    <Button
628                      key={`flow:${item.flow!.step}:${choice.outcome}`}
629                      variant={i === 0 ? 'primary' : 'secondary'}
630                      onPress={actions.answerFlow(item.flow!.change, item.flow!.step, choice.outcome)}
631                    >
632                      {choice.label}
633                    </Button>
634                  ))}
635                {item.jira !== undefined && (
636                  <Button key={`jira-move:${item.jira.key}`} variant="primary" onPress={actions.moveJira(item.jira.change, item.jira.key, item.jira.transitionId)}>
637                    {t.jira.move}
638                  </Button>
639                )}
640                {item.prUrl !== undefined && <Link href={item.prUrl}>{t.openPr}</Link>}
641                {canOpen && item.card !== undefined && openControl(item.card, t.openSession)}
642              </Box>
643            </Box>
644          )
645        }),
646        `${attention.length}`,
647        'warning',
648      )
649
650  /** The coordinator's view of the change: how much is left, the live-session ceiling, final gates. */
651  const runCard = (): RenderElement[] => {
652    if (run === undefined) return []
653    const counts = phaseCounts(run)
654    const total = STATUS_ORDER.reduce((sum, s) => sum + counts[s], 0)
655    const flow = view.flow?.change === run.change ? { status: view.flow.status } : undefined
656    const finished = finishedSessionIds([{ run, flow }], view.children)
657    const live = liveSessions(view.children, view.self?.sessionId, view.self?.cwd, finished).length
658    const legend = STATUS_ORDER.filter(s => counts[s] > 0)
659    const byStatus = (s: PhaseStatus) =>
660      phaseViews(run, view.children).flatMap((phases, w) => phases.filter(p => p.status === s).map(p => ({ phase: p, w })))
661    const changeIssue = run.jira === undefined ? undefined : issues[run.jira]
662    const changeMismatch = divergence(total > 0 && counts.done === total ? 'done' : 'running', changeIssue, t)
663    return [
664      card(
665        'run',
666        run.jira === undefined ? run.change : `${run.change} · ${run.jira}`,
667        [
668          bar(STATUS_ORDER.map(s => ({ value: counts[s], hex: STATUS_HEX[s] })), t.run.phasesClosed(counts.done, total)),
669          <Box flexDirection="row" columnGap={2} flexWrap="wrap">
670            {legend.map(s => (
671              <Box flexDirection="row">
672                <Text color={STATUS_HEX[s]}>● </Text>
673                <Button key={`legend:${s}`} plain onPress={actions.toggle(`legend:${s}`, false)}>
674                  <Text>{`${counts[s]} ${t.status.legend[s]}`}</Text>
675                  <Text dimColor>{isOpen(`legend:${s}`, false) ? ' ⌄' : ' ›'}</Text>
676                </Button>
677              </Box>
678            ))}
679          </Box>,
680          ...legend.flatMap(s =>
681            isOpen(`legend:${s}`, false)
682              ? [
683                  <Box flexDirection="column" borderStyle="round" borderColor={STATUS_HEX[s]} paddingX={1} minWidth={0}>
684                    {byStatus(s).map(({ phase, w }) =>
685                      row(
686                        <Text wrap="truncate-end">
687                          {phase.icon ? `${phase.icon} ` : ''}
688                          {phase.title}
689                          <Text dimColor>{t.run.wave(w + 1)}</Text>
690                        </Text>,
691                        phase.card === undefined || phase.card.sessionId === view.self?.sessionId
692                          ? phase.card === undefined
693                            ? undefined
694                            : t.session.self
695                          : openControl(phase.card, t.open, `legend:${phase.id}`),
696                      ),
697                    )}
698                  </Box>,
699                ]
700              : [],
701          ),
702          ...(run.jira === undefined
703            ? []
704            : [
705                ...(changeIssue?.title !== undefined || changeIssue?.status !== undefined
706                  ? [
707                      row(
708                        <Text wrap="truncate-end" dimColor>
709                          {changeIssue?.title ?? ''}
710                        </Text>,
711                        changeIssue?.status,
712                        changeIssue === undefined ? undefined : JIRA_HEX[changeIssue.category],
713                      ),
714                    ]
715                  : []),
716                row(<Text dimColor>{t.jira.changeIssue}</Text>, jiraKeyButton(run.jira)),
717                ...jiraDetails(run.jira),
718                ...(changeMismatch === undefined
719                  ? []
720                  : [
721                      <Text color="warning" wrap="wrap">
722                        ⚠ {changeMismatch}
723                      </Text>,
724                    ]),
725              ]),
726          row(
727            <Text wrap="truncate-end" dimColor>
728              {t.run.working}
729            </Text>,
730            t.run.liveOf(live, MAX_LIVE_SESSIONS),
731            live >= MAX_LIVE_SESSIONS ? STATUS_HEX.blocked : undefined,
732          ),
733          ...(live >= MAX_LIVE_SESSIONS
734            ? [
735                <Text dimColor wrap="wrap">
736                  {t.run.atCeiling}
737                </Text>,
738              ]
739            : []),
740          ...(view.jiraNote === undefined
741            ? []
742            : [
743                <Text dimColor wrap="wrap">
744                  {view.jiraNote}
745                </Text>,
746              ]),
747          <Text dimColor>{t.run.updated(view.updatedAt === 0 ? '…' : formatTime(view.updatedAt, t.locale))}</Text>,
748        ],
749        t.run.phasesOf(counts.done, total),
750      ),
751    ]
752  }
753
754  const waves = run === undefined ? [] : phaseViews(run, view.children)
755  const { now } = run === undefined ? { now: undefined } : nowAndNext(run)
756  const waveName = (w: number) => `${t.tasks.waveName(w + 1)}${run?.waves[w]?.title ? ` · ${run.waves[w]?.title}` : ''}`
757  const phaseKey = (w: number, phase: PhaseView) => `summary:${w}:${phase.id}`
758  /** What the session doing a phase is on now, said so the owner can read it: the step, then how far. */
759  const workRows = (c: SessionCard, scope = ''): RenderElement[] => {
760    const progress = planProgress(c.plan)
761    const tasksId = `tasks:${scope}:${c.sessionId}`
762    const who = c.sessionId === view.self?.sessionId ? t.session.self : sessionState(c)
763    const pr = c.prNumber === undefined ? '' : ` · PR #${c.prNumber}`
764    const details = progress.total === 0 ? `${who}${pr}` : `${t.tasks.steps(progress.done, progress.total)} · ${who}${pr}`
765    return [
766      ...(progress.current === undefined ? [] : [subtitle(progress.current, '▶ ')]),
767      row(
768        progress.total === 0 ? (
769          <Text dimColor wrap="truncate-end">
770            {details}
771          </Text>
772        ) : (
773          <Button key={tasksId} plain onPress={actions.toggle(tasksId, false)}>
774            <Text dimColor wrap="truncate-end">
775              {details}
776            </Text>
777            <Text dimColor>{isOpen(tasksId, false) ? ' ⌄' : ' ›'}</Text>
778          </Button>
779        ),
780        c.sessionId === view.self?.sessionId ? undefined : openControl(c, t.open, scope),
781      ),
782      ...(progress.total > 0 && isOpen(tasksId, false) ? planRows(c.plan) : []),
783    ]
784  }
785
786  /** The tasks.md items a phase delivers, ticked as they are done. */
787  const phaseTasks = (phase: PhaseView): RenderElement[] => {
788    const tasks = tasksForPhase(phase.tasks, view.openspec?.items ?? [])
789    if (tasks.length === 0) return []
790    const done = tasks.filter(t => t.done).length
791    return [
792      row(<Text dimColor>tasks.md</Text>, t.tasks.of(done, tasks.length)),
793      ...tasks.map(task =>
794        row(
795          <Text wrap="truncate-end" dimColor={task.done}>
796            <Text color={task.done ? STATUS_HEX.done : STATUS_HEX.pending}>{task.done ? '✓ ' : '○ '}</Text>
797            <Text dimColor>{task.id} </Text>
798            {task.text}
799          </Text>,
800        ),
801      ),
802    ]
803  }
804
805  /** How far a phase in progress is: its tasks.md items, else its session's own steps. */
806  const phaseBar = (phase: PhaseView, worker: SessionCard | undefined): RenderElement[] => {
807    const tasks = tasksForPhase(phase.tasks, view.openspec?.items ?? [])
808    const progress = worker === undefined ? { done: 0, total: 0 } : planProgress(worker.plan)
809    const [done, total] = tasks.length > 0 ? [tasks.filter(t => t.done).length, tasks.length] : [progress.done, progress.total]
810    if (total === 0) return []
811    return [
812      bar(
813        [
814          { value: done, hex: STATUS_HEX[phase.status] },
815          { value: total - done, hex: STATUS_HEX.pending },
816        ],
817        t.tasks.of(done, total),
818      ),
819    ]
820  }
821
822  /** A title line: the icon and name in bold, its Jira key beside it. */
823  const phaseTitle = (phase: PhaseView) => (
824    <Box flexDirection="row" columnGap={1} flexShrink={1} minWidth={0}>
825      <Box flexShrink={1} minWidth={0}>
826        <Text bold wrap="truncate-end">
827          {phase.icon ? `${phase.icon} ` : ''}
828          {phase.title}
829        </Text>
830      </Box>
831      {phase.jira !== undefined && <Box flexShrink={0}>{jiraKeyButton(phase.jira)}</Box>}
832    </Box>
833  )
834
835  /** What a phase is and what happens in it: subtitle, notes, its tasks and its session. */
836  const phaseBody = (phase: PhaseView, worker: SessionCard | undefined, scope: string): RenderElement[] => [
837    ...(phase.summary === undefined ? [] : [subtitle(phase.summary)]),
838    ...(phase.note === undefined
839      ? []
840      : [
841          <Text wrap="wrap" dimColor>
842            {phase.note}
843          </Text>,
844        ]),
845    ...phaseTasks(phase),
846    ...(worker === undefined ? [] : workRows(worker, scope)),
847  ]
848
849  /** An inner card: a soft neutral border, never the status colour; the status lives in its pill. */
850  const innerCard = (children: RenderElement[]) => (
851    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} minWidth={0}>
852      {children}
853    </Box>
854  )
855
856  /** A phase in progress in full: title and pill, what it is, how far, its tasks and its session. */
857  const phaseCard = (phase: PhaseView): RenderElement => {
858    // a phase no session is named for is the coordinator's own work: show what this session is doing
859    const isActive = phase.status === 'running' || phase.status === 'blocked'
860    const worker = phase.card ?? (phase.session === undefined && isActive ? view.self : undefined)
861    return innerCard([
862      row(phaseTitle(phase), pill(phase.status)),
863      ...jiraBelow(phase.jira, phase.status),
864      ...(isActive ? phaseBar(phase, worker) : []),
865      ...phaseBody(phase, worker, `card:${phase.id}`),
866    ])
867  }
868
869  /** A later or closed phase as one clean row: icon and title left, a muted detail right; a press opens it. */
870  const phaseLine = (phase: PhaseView, w: number): RenderElement[] => {
871    const id = phaseKey(w, phase)
872    const open = isOpen(id, false)
873    const waits = phase.status === 'pending' && phase.dependsOn?.length ? t.tasks.after(phase.dependsOn.join(', ')) : undefined
874    return [
875      row(
876        <Button key={id} plain onPress={actions.toggle(id, false)}>
877          <Text dimColor={phase.status === 'done'} wrap="truncate-end">
878            {phase.icon ? `${phase.icon} ` : ''}
879            {phase.title}
880          </Text>
881          <Text dimColor>{open ? ' ⌄' : ' ›'}</Text>
882        </Button>,
883        <Box flexDirection="row" columnGap={1}>
884          {phase.jira !== undefined && jiraKeyButton(phase.jira)}
885          <Text dimColor>{waits ?? t.status.word[phase.status]}</Text>
886        </Box>,
887      ),
888      ...jiraBelow(phase.jira, phase.status),
889      ...(open ? [innerCard(phaseBody(phase, phase.card, `line:${w}:${phase.id}`))] : []),
890    ]
891  }
892
893  /** The current wave's words and issue, then every phase: in progress open, pending one line each, closed folded. */
894  const tasksCard = (): RenderElement[] => {
895    if (run === undefined) return []
896    const all = waves.flatMap((phases, w) => phases.map(phase => ({ phase, w })))
897    if (all.length === 0) return []
898    const active = all.filter(({ phase }) => phase.status === 'running' || phase.status === 'blocked')
899    const pending = all.filter(({ phase }) => phase.status === 'pending')
900    const closed = all.filter(({ phase }) => phase.status === 'done')
901    const wavePhases = now === undefined ? [] : (waves[now] ?? [])
902    return [
903      card(
904        'tasks',
905        t.tasks.title,
906        [
907          ...(now === undefined
908            ? []
909            : [
910                <Text dimColor wrap="truncate-end">
911                  {t.tasks.now}{waveName(now)}
912                </Text>,
913                ...(run.waves[now]?.summary === undefined ? [] : [subtitle(run.waves[now]?.summary ?? '')]),
914                ...jiraRows(run.waves[now]?.jira, waveStatus(wavePhases)),
915              ]),
916          ...(active.length === 0
917            ? []
918            : [
919                <Box flexDirection="column" rowGap={1} marginTop={1} minWidth={0}>
920                  {active.map(({ phase }) => phaseCard(phase))}
921                </Box>,
922              ]),
923          ...(pending.length === 0
924            ? []
925            : [
926                <Box flexDirection="column" marginTop={1} minWidth={0}>
927                  {pending.flatMap(({ phase, w }) => phaseLine(phase, w))}
928                </Box>,
929              ]),
930          ...(closed.length === 0
931            ? []
932            : [
933                <Box flexDirection="column" marginTop={1} minWidth={0}>
934                  {group('tasks:done', t.tasks.closed(closed.length), '', false, () =>
935                    closed.flatMap(({ phase, w }) => phaseLine(phase, w)),
936                  )}
937                </Box>,
938              ]),
939        ],
940        t.run.phasesOf(closed.length, all.length),
941        // only the outer box of the work in progress carries the accent
942        active.length > 0 ? STATUS_HEX.running : undefined,
943      ),
944    ]
945  }
946
947  const phaseGateViews = (phase: PhaseView): GateView[] =>
948    gateViews(
949      phase.gates,
950      phase.id,
951      phase.session === undefined ? (view.self?.gates ?? NO_CHECK) : (phase.card?.gates ?? NO_CHECK),
952      skips,
953    )
954
955  /** One phase of the loop: title and pill, its gates in one muted line ("testes ✓ lint ○"), then the open ones with the owner's skip. */
956  const loopPhase = (phase: PhaseView): RenderElement[] => {
957    const gates = phaseGateViews(phase)
958    const isActive = phase.status === 'running' || phase.status === 'blocked'
959    return [
960      row(
961        <Text wrap="truncate-end" dimColor={phase.status === 'done'}>
962          {phase.icon ? `${phase.icon} ` : ''}
963          {phase.title}
964        </Text>,
965        pill(phase.status),
966      ),
967      ...(gates.length === 0
968        ? []
969        : [
970            <Text wrap="wrap">
971              {gates.map((g, i) => (
972                <Text color={GATE_HEX[g.state]}>{`${i === 0 ? '' : ' '}${g.label} ${GATE_MARK[g.state]}`}</Text>
973              ))}
974            </Text>,
975          ]),
976      ...(isActive && gates.some(isOpenGate) ? gateRows(gates.filter(isOpenGate)) : []),
977    ]
978  }
979
980  const loopPhases = (): RenderElement[] =>
981    waves.flat().length === 0
982      ? [<Text dimColor>{t.tasks.noPlan}</Text>]
983      : waves.flat().flatMap(loopPhase)
984
985  const flow = view.flow
986  const times = view.flowTimes ?? {}
987
988  const stepWord = (step: FlowStepView): { word: string; hex: string } => {
989    if (step.state === 'done') return { word: step.outcomeLabel ?? t.steps.done, hex: STATUS_HEX.done }
990    if (step.state === 'skipped') return { word: t.steps.skipped, hex: STATUS_HEX.pending }
991    if (step.state === 'pending') return { word: t.steps.pending, hex: STATUS_HEX.pending }
992    if (flow?.status === 'escalated') return { word: t.steps.escalated, hex: STATUS_HEX.blocked }
993    return flow?.waitingOn === 'owner'
994      ? { word: t.steps.waiting, hex: GATE_HEX.stale }
995      : { word: t.steps.running, hex: STATUS_HEX.running }
996  }
997
998  const stepElapsed = (step: FlowStepView): string | undefined => {
999    const time = times[step.id]
1000    if (time === undefined || step.state === 'pending' || step.state === 'skipped') return undefined
1001    const to = time.to ?? (step.state === 'current' ? view.updatedAt : undefined)
1002    return to === undefined || to < time.from ? undefined : formatElapsed(to - time.from)
1003  }
1004
1005  /** One step per line, as the app's background-tasks list draws a task: mark, who acts, title; time and state. */
1006  const stepLine = (step: FlowStepView): RenderElement => {
1007    const { word, hex } = stepWord(step)
1008    const elapsed = stepElapsed(step)
1009    const isCurrent = step.state === 'current'
1010    return row(
1011      <Text wrap="truncate-end" bold={isCurrent} dimColor={step.state === 'done' || step.state === 'skipped'}>
1012        <Text color={hex}>{STEP_MARK[step.state]} </Text>
1013        {`${KIND_ICON[step.kind]} ${step.title}`}
1014        {step.attempts > 1 && step.state !== 'pending' && <Text dimColor>{t.steps.attempt(step.attempts, step.maxAttempts)}</Text>}
1015      </Text>,
1016      <Box flexDirection="row" columnGap={1}>
1017        {elapsed !== undefined && <Text dimColor>{elapsed}</Text>}
1018        <Text color={hex}>{word}</Text>
1019      </Box>,
1020    )
1021  }
1022
1023  const finalGateRows = (): RenderElement[] => {
1024    if (run === undefined) return []
1025    const finalGates = gateViews(
1026      run.finalGates,
1027      FINAL_SCOPE,
1028      familyCheck([view.self?.gates ?? NO_CHECK, ...view.children.map(c => c.gates ?? NO_CHECK)]),
1029      skips,
1030    )
1031    return finalGates.length === 0
1032      ? []
1033      : [
1034          group(
1035            'final-gates',
1036            t.steps.finalGates,
1037            `${finalGates.filter(g => !isOpenGate(g)).length}/${finalGates.length}`,
1038            true,
1039            () => gateRows(finalGates),
1040            t.steps.finalGatesSummary,
1041          ),
1042        ]
1043  }
1044
1045  /** The harness the change follows: the flow's steps, the phases' gates while the loop runs, the final gates. */
1046  const gatesCard = (): RenderElement[] => {
1047    const anyPhaseGates = waves.flat().some(p => (p.gates?.length ?? 0) > 0)
1048    if (flow === undefined && !anyPhaseGates && (run?.finalGates?.length ?? 0) === 0) return []
1049    if (flow === undefined) {
1050      return [card('gates', 'Gates', [...(anyPhaseGates ? loopPhases() : []), ...finalGateRows()])]
1051    }
1052    const folded = flow.steps.filter(s => s.state === 'done' || s.state === 'skipped')
1053    const shown = flow.steps.filter(s => s.state === 'current' || s.state === 'pending')
1054    const hasLoop = flow.steps.some(s => s.kind === 'loop')
1055    return [
1056      card(
1057        'gates',
1058        'Gates',
1059        [
1060          ...(folded.length === 0
1061            ? []
1062            : [group('gates:done', t.tasks.closed(folded.length), '', false, () => folded.map(stepLine))]),
1063          ...shown.map(step =>
1064            step.state === 'current' ? (
1065              <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} minWidth={0}>
1066                {stepLine(step)}
1067                {step.description !== undefined && (
1068                  <Text dimColor wrap="wrap">
1069                    {step.description}
1070                  </Text>
1071                )}
1072                {flow.status === 'escalated' && (
1073                  <Text color="warning" wrap="wrap">
1074                    {t.steps.ceiling(step.maxAttempts)}
1075                  </Text>
1076                )}
1077                {step.kind === 'loop' && <Box flexDirection="column" marginTop={1} minWidth={0}>{loopPhases()}</Box>}
1078              </Box>
1079            ) : (
1080              stepLine(step)
1081            ),
1082          ),
1083          ...(flow.status === 'done'
1084            ? [<Text color={STATUS_HEX.done}>{t.steps.flowDone}</Text>]
1085            : flow.status === 'aborted'
1086              ? [<Text color={STATUS_HEX.blocked}>{t.steps.flowAborted}</Text>]
1087              : []),
1088          ...(!hasLoop && anyPhaseGates ? [<Box flexDirection="column" marginTop={1} minWidth={0}>{loopPhases()}</Box>] : []),
1089          ...finalGateRows(),
1090          <Text dimColor wrap="wrap">
1091            {t.steps.legend}
1092          </Text>,
1093        ],
1094        `${flow.flowTitle} · ${folded.length}/${flow.steps.length}`,
1095        flow.status === 'escalated' ? STATUS_HEX.blocked : undefined,
1096      ),
1097    ]
1098  }
1099
1100  // Reading order: how much is left, what the change is (OpenSpec guides it), the harness it
1101  // follows, what needs the owner, then the phases and their tasks.
1102  cards.push(...runCard())
1103  if (view.openspec !== undefined) cards.push(openSpecCard(view.openspec))
1104  cards.push(...gatesCard())
1105  if (attentionCard !== undefined) cards.push(attentionCard)
1106  cards.push(...tasksCard())
1107
1108  const own = planProgress(ownPlan)
1109  cards.push(
1110    card(
1111      'self',
1112      t.self.title,
1113      ownPlan.length === 0
1114        ? [<Text dimColor>{t.self.noList}</Text>]
1115        : [
1116            row(t.self.percentDone(percent(own.done, own.total)), t.self.stepsOf(own.done, own.total)),
1117            bar(
1118              [
1119                { value: own.done, hex: STATUS_HEX.done },
1120                { value: own.current === undefined ? 0 : 1, hex: STATUS_HEX.running },
1121                { value: own.total - own.done - (own.current === undefined ? 0 : 1), hex: STATUS_HEX.pending },
1122              ],
1123              t.self.stepsOfLong(own.done, own.total),
1124            ),
1125            <Box marginTop={1} />,
1126            ...planRows(ownPlan),
1127          ],
1128      view.self?.branch,
1129      undefined,
1130      run === undefined,
1131    ),
1132  )
1133
1134  const used = new Set(
1135    run === undefined ? [] : phaseViews(run, view.children).flat().flatMap(p => (p.card ? [p.card.sessionId] : [])),
1136  )
1137  const loose = view.children.filter(c => !used.has(c.sessionId))
1138  if (loose.length > 0) {
1139    cards.push(
1140      card(
1141        'children',
1142        run === undefined ? t.children.title : t.children.others,
1143        loose.map(c => {
1144          const progress = planProgress(c.plan)
1145          return group(
1146            `session:${c.sessionId}`,
1147            c.title,
1148            c.waiting === undefined && !c.isRunning && progress.total > 0
1149              ? `${progress.done}/${progress.total}`
1150              : sessionState(c),
1151            c.isRunning || c.waiting !== undefined,
1152            () => [...sessionRows(c), ...planRows(c.plan)],
1153          )
1154        }),
1155        t.children.active(loose.filter(c => c.isRunning).length),
1156      ),
1157    )
1158  }
1159
1160  if (view.warning !== undefined) {
1161    cards.push(
1162      <Box paddingX={1} minWidth={0}>
1163        <Text color="warning" wrap="wrap">
1164          {view.warning}
1165        </Text>
1166      </Box>,
1167    )
1168  }
1169
1170  return (
1171    <Box flexDirection="column" rowGap={1} minWidth={0}>
1172      {cards}
1173    </Box>
1174  )
1175}
1176
1177/** The thin band above the prompt: the flow's step, phases in flight, what waits on the owner; a button for the pane. */
1178export const renderBand = (
1179  { Box, Text, Button }: Pick<PaneElements, 'Box' | 'Text' | 'Button'>,
1180  summary: BandSummary,
1181  paneOpen: boolean,
1182  togglePane: () => void,
1183  lang?: Lang,
1184): RenderElement => {
1185  const t = uiText(lang).band
1186  const parts = [
1187    summary.step === undefined ? undefined : t.step(summary.step),
1188    t.inFlight(summary.inFlight),
1189  ].filter((part): part is string => part !== undefined)
1190  return (
1191    <Box flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
1192      <Box flexShrink={1} minWidth={0}>
1193        <Text wrap="truncate-end">
1194          <Text dimColor>🧭 {parts.join(' · ')}</Text>
1195          {summary.waiting > 0 && (
1196            <Text color="warning">{` · ${t.waiting(summary.waiting)}`}</Text>
1197          )}
1198        </Text>
1199      </Box>
1200      <Button key="band:pane" plain dimColor onPress={togglePane}>
hooks/activation.ts 261 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { ActivationLevel } from '../types'
4
5/** The file the activation lives in: local to the clone, kept out of git, read by Claude Code on every change. */
6export const SETTINGS_PATH = '.claude/settings.local.json'
7export const LEVELS: readonly ActivationLevel[] = ['barrar', 'lembrar']
8/** The word in the hook's command by which "Desativar" finds the hook the mod put there, and only it. */
9export const HOOK_MARK = 'orquestrador:ativar'
10
11/** What the SessionStart hook prints: stdout of a `command` hook becomes context for the session. */
12export const HOOK_COMMAND =
13  'printf \'%s\\n\' "Orquestrador ativo neste clone (nível: ${ORQUESTRADOR:-barrar}). Siga o flow da change em andamento; ' +
14  'passos do dono, só o dono responde no painel (/orquestrador); sem merge --admin e sem pular portões." ' +
15  `# ${HOOK_MARK}`
16
17type Json = Record<string, unknown>
18const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
19
20/** The file's text as an object, or why it is not one; an empty or absent file is an empty object. */
21export const parseSettings = (text: string | undefined): { data: Json } | { error: 'notJson' | 'notObject' } => {
22  if (text === undefined || text.trim() === '') return { data: {} }
23  let parsed: unknown
24  try {
25    parsed = JSON.parse(text)
26  } catch {
27    return { error: 'notJson' }
28  }
29  return isRecord(parsed) ? { data: parsed } : { error: 'notObject' }
30}
31
32/** The level the file marks, or none: only the two known words count. */
33export const levelOf = (data: Json): ActivationLevel | undefined => {
34  const env = data.env
35  const level = isRecord(env) ? env.ORQUESTRADOR : undefined
36  return LEVELS.find(l => l === level)
37}
38
39const ours = (hook: unknown): boolean => isRecord(hook) && typeof hook.command === 'string' && hook.command.includes(HOOK_MARK)
40
41/** The SessionStart groups without the mod's hook; a group left with no hook goes too. */
42const withoutOurs = (groups: unknown): unknown[] =>
43  (Array.isArray(groups) ? groups : []).flatMap((group: unknown) => {
44    if (!isRecord(group) || !Array.isArray(group.hooks)) return [group]
45    const kept = group.hooks.filter(h => !ours(h))
46    if (kept.length === group.hooks.length) return [group]
47    return kept.length === 0 ? [] : [{ ...group, hooks: kept }]
48  })
49
50/** The settings with the mark at `level` and the mod's hook; every other key and hook as it was. */
51export const activate = (data: Json, level: ActivationLevel): Json => {
52  const next: Json = { ...data }
53  next.env = { ...(isRecord(data.env) ? data.env : {}), ORQUESTRADOR: level }
54  const hooks: Json = isRecord(data.hooks) ? { ...data.hooks } : {}
55  hooks.SessionStart = [...withoutOurs(hooks.SessionStart), { hooks: [{ type: 'command', command: HOOK_COMMAND }] }]
56  next.hooks = hooks
57  return next
58}
59
60/** The settings without the mark and the mod's hook, and without the `env`/`hooks` keys that leaves empty. */
61export const deactivate = (data: Json): Json => {
62  const next: Json = { ...data }
63  if (isRecord(data.env)) {
64    const { ORQUESTRADOR: _gone, ...env } = data.env
65    if (Object.keys(env).length === 0) delete next.env
66    else next.env = env
67  }
68  if (isRecord(data.hooks)) {
69    const { SessionStart: groups, ...hooks } = data.hooks
70    if (groups !== undefined) {
71      const kept = withoutOurs(groups)
72      if (kept.length > 0) (hooks as Json).SessionStart = kept
73    }
74    if (Object.keys(hooks).length === 0) delete next.hooks
75    else next.hooks = hooks
76  }
77  return next
78}
79
80export const settingsText = (data: Json): string => `${JSON.stringify(data, null, 2)}\n`
81
82/**
83 * The repository's main checkout and its git dir: a worktree reads the main checkout's settings,
84 * so the activation lives there. Without git, the session's own folder.
85 */
86const found = new Map<string, { root: string; gitDir: string }>()
87export async function projectRoot($: EngineInterface): Promise<{ root: string; gitDir: string | undefined }> {
88  const cwd = await $.session.root()
89  const known = found.get(cwd)
90  if (known !== undefined) return known
91  const ran = await $.process.run(['git', '-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd, timeoutMs: 10_000 }).catch(() => undefined)
92  const dir = ran?.exitCode === 0 ? ran.stdout.trim() : ''
93  if (dir.startsWith('/') && dir.endsWith('/.git')) {
94    const here = { root: dir.slice(0, -'/.git'.length), gitDir: dir }
95    found.set(cwd, here)
96    return here
97  }
98  return { root: cwd, gitDir: undefined }
99}
100
101/**
102 * What the clone's mark says and what the mod trusts. `level` is the one that counts; `tampered` is true when the
103 * file's mark differs from what the panel wrote (a "lembrar" the panel never wrote, or a mark taken away).
104 */
105export type Activation = { level: ActivationLevel | undefined; invalid: boolean; tampered: boolean }
106
107/** The mod's own folder of records (gates, runs, flows): the one `touchesGateFiles` refuses the model to write. */
108export async function registryDir($: EngineInterface): Promise<string> {
109  return `${(await $.env.get('HOME')) ?? '~'}/.claude/orquestrador`
110}
111
112type Records = Record<string, { level: ActivationLevel; at: number }>
113
114/**
115 * The level the panel itself wrote for each repository, by the main checkout's path, in `activation.json` of the
116 * registry folder: on disk, so a restart of the app (which empties the session's state) does not lose it, and in a
117 * folder no tool of the model may write. Absent is empty; a file that cannot be read or parsed throws (fail closed).
118 */
119async function readRecords($: EngineInterface): Promise<Records> {
120  const path = `${await registryDir($)}/activation.json`
121  if (!(await $.fs.exists(path))) return {}
122  const parsed: unknown = JSON.parse(await $.fs.read(path))
123  if (!isRecord(parsed)) throw new Error('activation.json is not an object')
124  return parsed as Records
125}
126
127async function recordedLevel($: EngineInterface, root: string): Promise<ActivationLevel | undefined> {
128  const entry: unknown = (await readRecords($))[root]
129  return LEVELS.find(l => isRecord(entry) && l === entry.level)
130}
131
132/** Remembers the level the panel wrote for `root` (`null`: the panel took the activation back). */
133export async function recordLevel($: EngineInterface, root: string, level: ActivationLevel | null): Promise<void> {
134  const records = await readRecords($).catch((): Records => ({})) // a broken record is the panel's to replace
135  const { [root]: _old, ...others } = records
136  const next = level === null ? others : { ...others, [root]: { level, at: Date.now() } }
137  await $.fs.write(`${await registryDir($)}/activation.json`, `${JSON.stringify(next, null, 2)}\n`)
138}
139
140type AutowakeRecords = Record<string, { on: boolean; at: number }>
141
142/**
143 * "Seguir o flow sem clique", by the main checkout's path, in `autowake.json` of the registry folder: local to the
144 * machine and out of the model's reach, like the activation's record. Here the safe side is off: an absent file, a
145 * file that cannot be read or parsed, or an entry that is not `on: true` all read as off.
146 */
147export async function readAutowake($: EngineInterface): Promise<boolean> {
148  try {
149    const path = `${await registryDir($)}/autowake.json`
150    if (!(await $.fs.exists(path))) return false
151    const parsed: unknown = JSON.parse(await $.fs.read(path))
152    const entry: unknown = isRecord(parsed) ? parsed[(await projectRoot($)).root] : undefined
153    return isRecord(entry) && entry.on === true
154  } catch {
155    return false
156  }
157}
158
159/** Turns the option on or off for this repository; the other repositories' entries stay, a broken file is replaced. */
160export async function writeAutowake($: EngineInterface, on: boolean): Promise<void> {
161  const path = `${await registryDir($)}/autowake.json`
162  const { root } = await projectRoot($)
163  let records: AutowakeRecords = {}
164  try {
165    const parsed: unknown = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : {}
166    if (isRecord(parsed)) records = parsed as AutowakeRecords
167  } catch {
168    // a broken record is the panel's to replace
169  }
170  const { [root]: _old, ...others } = records
171  const next = on ? { ...others, [root]: { on: true, at: Date.now() } } : others
172  await $.fs.write(path, `${JSON.stringify(next, null, 2)}\n`)
173}
174
175/** The file's text; `undefined` only when it is absent. A read that fails throws: it is not "absent". */
176async function readSettings($: EngineInterface, path: string): Promise<string | undefined> {
177  return (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
178}
179
180/**
181 * The level that counts, read from the file itself so it counts at once, with no restart, but only as far as the
182 * panel's record backs it: "barrar" stands alone (the strictest); "lembrar" lowers the guard, so it counts only
183 * when it is what the panel wrote; a mark with no record or another one is "barrar". A mark taken away or a file
184 * that cannot be parsed after the panel activated is still "barrar". A file that cannot be read is "barrar" too:
185 * only a confirmed absence of mark leaves the mod quiet. Throws when the state cannot be read.
186 */
187export async function readActivation($: EngineInterface): Promise<Activation> {
188  const { root } = await projectRoot($)
189  const recorded = await recordedLevel($, root)
190  let text: string | undefined
191  try {
192    text = await readSettings($, `${root}/${SETTINGS_PATH}`)
193  } catch {
194    return { level: 'barrar', invalid: true, tampered: recorded !== undefined }
195  }
196  const parsed = parseSettings(text)
197  const marked = 'error' in parsed ? undefined : levelOf(parsed.data)
198  const invalid = 'error' in parsed
199  if (marked === 'barrar') return { level: 'barrar', invalid, tampered: false }
200  if (marked === 'lembrar') return recorded === 'lembrar' ? { level: 'lembrar', invalid, tampered: false } : { level: 'barrar', invalid, tampered: true }
201  return recorded === undefined ? { level: undefined, invalid, tampered: false } : { level: 'barrar', invalid, tampered: true }
202}
203
204/**
205 * Keeps the file out of git: the clone's exclude, never the .gitignore. Only `git check-ignore` exiting 1
206 * (not ignored) adds the line; any other code (128: git failed) leaves the exclude alone. Throws when it cannot write.
207 */
208async function ensureIgnored($: EngineInterface, root: string, gitDir: string | undefined): Promise<void> {
209  if (gitDir === undefined) return
210  const ran = await $.process.run(['git', '-C', root, 'check-ignore', '-q', SETTINGS_PATH], { cwd: root, timeoutMs: 10_000 }).catch(() => undefined)
211  if (ran === undefined || ran.exitCode !== 1) return
212  const exclude = `${gitDir}/info/exclude`
213  const prior = (await readSettings($, exclude)) ?? ''
214  if (prior.split('\n').some(l => l.trim() === SETTINGS_PATH || l.trim() === `**/${SETTINGS_PATH}`)) return
215  await $.fs.write(exclude, `${prior}${prior === '' || prior.endsWith('\n') ? '' : '\n'}${SETTINGS_PATH}\n`)
216}
217
218export type Written = { ok: true } | { ok: false; error: 'notJson' | 'notObject' | 'unreadable' | 'badHooks' | 'notIgnored' }
219
220/**
221 * Turns the activation on at `level`, or off with `null`. A file that is not a JSON object, that cannot be read,
222 * or whose `hooks.SessionStart` is not a list is left untouched; so is a write with nothing to change.
223 */
224export async function writeActivation($: EngineInterface, level: ActivationLevel | null): Promise<Written> {
225  const written = await writeFile($, level)
226  // the panel's record follows the file: what the panel wrote is what the mod trusts
227  if (written.ok) {
228    await recordLevel($, (await projectRoot($)).root, level)
229    await $.state.set({ plugin: 'orquestrador', key: 'reminded' }, null) // a new level (or none) starts a new count of warnings
230  }
231  return written
232}
233
234async function writeFile($: EngineInterface, level: ActivationLevel | null): Promise<Written> {
235  const { root, gitDir } = await projectRoot($)
236  const path = `${root}/${SETTINGS_PATH}`
237  let text: string | undefined
238  try {
239    text = await readSettings($, path)
240  } catch {
241    return { ok: false, error: 'unreadable' }
242  }
243  const parsed = parseSettings(text)
244  if ('error' in parsed) return { ok: false, error: parsed.error }
245  if (level === null && text === undefined) return { ok: true }
246  const groups = isRecord(parsed.data.hooks) ? parsed.data.hooks.SessionStart : undefined
247  if (groups !== undefined && !Array.isArray(groups)) return { ok: false, error: 'badHooks' }
248  const next = settingsText(level === null ? deactivate(parsed.data) : activate(parsed.data, level))
249  if (next === text) return { ok: true }
250  if (text === undefined) {
251    // the exclude comes first: a file git would show must never exist, so a failure here writes nothing
252    try {
253      await ensureIgnored($, root, gitDir)
254    } catch {
255      return { ok: false, error: 'notIgnored' }
256    }
257  }
258  await $.fs.write(path, next) // creates `.claude/` when it is missing
259  return { ok: true }
260}
261
hooks/wake.ts 93 lines
1import type { OrchestrationRun, SessionRow } from '../types'
2import { inPlan } from './model'
3
4/** What the mod last saw of a child: running or not, its last activity, and the stop already told. */
5export type Seen = { running: boolean; activity?: string; told?: string }
6
7/**
8 * The children whose end of turn wakes the coordination: not archived, not the coordination itself, and
9 * kept in the current flow's `sessions` or tied to a phase of its plan. The children of an earlier change
10 * (`earlier`, or another flow's `sessions`) never count, even when the plan names them.
11 */
12export const eligibleChildren = <R extends SessionRow>(
13  run: OrchestrationRun | undefined,
14  flow: { sessions?: readonly string[]; excluded?: readonly string[] },
15  self: string,
16  children: readonly R[],
17): R[] => {
18  const own = new Set(flow.sessions ?? [])
19  const excluded = new Set(flow.excluded ?? [])
20  return children.filter(
21    row => !row.isArchived && row.sessionId !== self && !excluded.has(row.sessionId) && (own.has(row.sessionId) || inPlan(run, row)),
22  )
23}
24
25/**
26 * How far the flow went, for the brake against a loop: its `seq` moves only on a report, but inside the
27 * `executar` loop it stands still from phase to phase, so the phases closed in the flow and the phases done
28 * in its plan count too. The sessions it adopted do not: a coordination that opens a new child on each stop
29 * would move the key forever without the flow going anywhere. Nor does the plan's `updatedAt`: republishing
30 * the same plan is not progress.
31 */
32export const flowProgress = (
33  flow: { seq: number; closed?: Record<string, unknown> },
34  run: OrchestrationRun | undefined,
35): string => {
36  const done = (run?.waves ?? []).flatMap(wave => wave.phases).filter(phase => phase.status === 'done').length
37  return [flow.seq, Object.keys(flow.closed ?? {}).length, done].join('|')
38}
39
40/**
41 * The children that ended a turn since the last look. A child seen for the first time is only recorded, so
42 * turning the option on (or an app restart) never tells old stops. A stop is a child not running now that
43 * was running before, or whose last activity moved (a short turn between two looks); `told` keeps the stop
44 * already told, so the same stop seen twice is told once. Only the rows given are kept.
45 */
46export const childStops = <R extends SessionRow>(
47  seen: Readonly<Record<string, Seen>>,
48  rows: readonly R[],
49  now: number,
50): { seen: Record<string, Seen>; stopped: R[] } => {
51  const next: Record<string, Seen> = {}
52  const stopped: R[] = []
53  for (const row of rows) {
54    const before = seen[row.sessionId]
55    const base: Seen = { running: row.isRunning, ...(row.lastActivityAt === undefined ? {} : { activity: row.lastActivityAt }) }
56    if (before === undefined) {
57      next[row.sessionId] = base
58      continue
59    }
60    const moved = row.lastActivityAt !== undefined && row.lastActivityAt !== before.activity
61    const mark = row.lastActivityAt ?? String(now)
62    if (!row.isRunning && (before.running || moved) && before.told !== mark) {
63      stopped.push(row)
64      next[row.sessionId] = { ...base, told: mark }
65    } else {
66      next[row.sessionId] = { ...base, ...(before.told === undefined ? {} : { told: before.told }) }
67    }
68  }
69  return { seen: next, stopped }
70}
71
72/**
73 * How the stop names a child: its id only, kept to the characters of an id. The prompt is taken as the
74 * owner's turn, so nothing a session can write (its title) goes in it; the coordination reads the rest in
75 * `flow status`.
76 */
77export const sessionRef = (row: SessionRow): string => row.sessionId.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64)
78
79/**
80 * Whether the stop goes as the owner's own words. Off: the mod tells a fact, like the click's prompt. The
81 * plan B of `design.md`, should the app refuse `user_asked` after it: turn this on, and the text says it is
82 * the panel speaking for the owner's option.
83 */
84export const STOP_AS_USER = false
85
86/** What the coordination reads when children ended their turn, by id: in pt-BR, like the click's `wakePrompt`. */
87export const stopPrompt = (ids: readonly string[], asUser = STOP_AS_USER): string => {
88  const head = asUser ? 'Painel (opção "Seguir o flow sem clique" ligada por mim):' : 'Painel:'
89  return ids.length === 1
90    ? `${head} a sessão ${ids[0]} terminou o turno. Confira no flow status e siga o flow.`
91    : `${head} as sessões ${ids.join(', ')} terminaram o turno. Confira no flow status e siga o flow.`
92}
93
hooks/workflows-pane.tsx 1706 lines
1import { update } from 'claude-code'
2import type {
3  BoxProps,
4  ButtonProps,
5  ElementConstructor,
6  EngineInterface,
7  InputProps,
8  RenderElement,
9  SelectProps,
10  TextProps,
11} from 'claude-code'
12
13import type {
14  ActivationAsk,
15  ActivationLevel,
16  ConfigAsk,
17  ConfigDraft,
18  FlowDef,
19  FlowDeploy,
20  FlowMerge,
21  FlowStepDetails,
22  FlowStepKind,
23  Lang,
24  Languages,
25  ProjectSettings,
26  Translations,
27  WorkflowDraft,
28  WorkflowForms,
29} from '../types'
30import { LEVELS, readActivation, readAutowake, writeActivation, writeAutowake } from './activation'
31import { findAgent, listAgents, loadConfig, loadFlows } from './flow-files'
32import type { AgentInfo } from './flow-files'
33import { DEFAULT_FLOWS, defaultFlows } from './flows/index'
34import { LIBRARY, libraryStep } from './flows/library'
35import {
36  EMPTY_FORMS,
37  WORKFLOW_ID,
38  addLibraryStep,
39  addNewStep,
40  brokenDependents,
41  changesOf,
42  draftFile,
43  draftOf,
44  moveStep,
45  newDraft,
46  resolveCandidate,
47  setStepField,
48  slug,
49  toggleStep,
50  useProjectValues,
51} from './workflow-edit'
52import type { StepField } from './workflow-edit'
53import type { FlowSource } from './flow'
54import { CONFIG_PATH, DEFAULT_LANGUAGES, localize, parseLocalized } from './i18n'
55import { workflowsText } from './i18n-workflows'
56import {
57  applyConfigChange,
58  configChanged,
59  configChanges,
60  configText,
61  draftOfConfig,
62  effectiveDeploy,
63  effectiveMerge,
64  workflowState,
65} from './project-edit'
66import type { ConfigChange, WorkflowState } from './project-edit'
67import type { WorkflowsText } from './i18n-workflows'
68
69export const WORKFLOWS_PANE = 'orquestrador-workflows'
70export const WORKFLOWS_TITLE = '⚙️ Workflows'
71
72const SELECTED = { plugin: 'orquestrador', key: 'wfSelected' } as const
73const FOCUS = { plugin: 'orquestrador', key: 'wfFocus' } as const
74const INSERT = { plugin: 'orquestrador', key: 'wfInsert' } as const
75const DRAFT = { plugin: 'orquestrador', key: 'wfDraft' } as const
76const FORMS = { plugin: 'orquestrador', key: 'wfForms' } as const
77const NOTICE = { plugin: 'orquestrador', key: 'wfNotice' } as const
78const CFG = { plugin: 'orquestrador', key: 'wfCfgDraft' } as const
79const ASK = { plugin: 'orquestrador', key: 'wfCfgAsk' } as const
80const ACT = { plugin: 'orquestrador', key: 'wfActivate' } as const
81/** The `routineFor` value that opens "+ rotina" in the project's deploy settings. */
82const CFG_ROUTINE = ':cfg'
83
84/** Below this many columns the pane stacks what sits side by side. */
85const NARROW_COLUMNS = 44
86const LINK = '#2F6FD6'
87const ERROR = '#D14343'
88const WARN = '#B7791F'
89const OWNER = '#C2410C'
90const MOD = '#6B6A66'
91const MODELS = ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-fable-5-1']
92const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
93const LOAD = { plugin: 'orquestrador', key: 'wfLoad' } as const
94
95/**
96 * This load of the mod's code. The host keeps the pane's state through a reload of the code
97 * (`/reload-plugins`, an update), and `session.start` fires again at each load: a draft, a
98 * confirmation or a notice of an earlier load is not offered again, so a press there (an Enter on
99 * the first button, "Salvar") never writes what the owner did not open in this load.
100 */
101async function loadId($: EngineInterface): Promise<string> {
102  const { value } = await $.state.get(LOAD)
103  return value ?? ''
104}
105/** `session.start`: a new load of the mod's code begins. */
106export async function startWorkflowsLoad($: EngineInterface): Promise<void> {
107  const now = await $.clock.now()
108  await $.state.set(LOAD, `load-${now}`)
109}
110/** A notice for the owner, of this load. */
111async function noticeOf($: EngineInterface, text: string): Promise<void> {
112  const load = await loadId($)
113  await $.state.set(NOTICE, { text, load })
114}
115
116/** A Select's "nothing chosen": its options' values must be words. */
117const NONE = '-'
118/** "+ passo aqui" open at the end of a workflow that has no step yet. */
119export const INSERT_END = ':fim'
120/** The focus value that opens the "Nome e descrição" block of the edit screen. */
121export const HEAD_FOCUS = ':nome'
122/** The "+ passo aqui" choice that is no library step. */
123const NEW_STEP = 'novo'
124
125const WHO_COLOR: Record<FlowStepKind, string> = { session: LINK, owner: OWNER, automatic: MOD, loop: MOD }
126/** Who answers, as a pill: background and text colors of the mockup. */
127const WHO_PILL: Record<FlowStepKind, { bg: string; fg: string }> = {
128  session: { bg: '#E3ECFB', fg: '#1E4C9E' },
129  owner: { bg: '#FDEBDD', fg: '#9A3412' },
130  automatic: { bg: '#EDECE8', fg: '#3D3C39' },
131  loop: { bg: '#EDECE8', fg: '#3D3C39' },
132}
133const TAG_BLUE = { bg: '#EEF3FC', fg: '#1E4C9E' }
134const TAG_GRAY = { bg: '#F2F1EC', fg: '#3D3C39' }
135const TAG_GREEN = { bg: '#E6F4EA', fg: '#1E6B3A' }
136const TAG_AMBER = { bg: '#FDF3E1', fg: '#7A4A00' }
137const AMBER_BAR = '#FFF8EB'
138const AMBER_RULE = '#F0DDB8'
139const RULE = '#E4E2DC'
140const MUTED = '#5F5E5A'
141
142export type WorkflowsElements = {
143  Box: ElementConstructor<BoxProps>
144  Text: ElementConstructor<TextProps>
145  Button: ElementConstructor<ButtonProps>
146  /** Fields, where the surface has them (not on mobile). */
147  Input: ElementConstructor<InputProps> | undefined
148  Select: ElementConstructor<SelectProps> | undefined
149}
150
151/** A workflow on offer, with where it comes from. */
152export type WorkflowEntry = { flow: FlowDef; origin: string; project: boolean; replaces: boolean }
153
154/** A default workflow this project does not use because its own of the same id wins. */
155export type RetiredEntry = { flow: FlowDef; by: FlowDef }
156
157export type ConfigView = {
158  project: ProjectSettings
159  problems: string[]
160  draft: ConfigDraft | null
161  ask: ConfigAsk | null
162  states: WorkflowState[]
163  /** This clone's activation, read from its settings.local.json: the level (none: inactive), a broken file, the confirmation open. */
164  activation: { level: ActivationLevel | undefined; invalid: boolean; tampered: boolean; ask: ActivationAsk | null }
165  /** "Seguir o flow sem clique", from the mod's own record on this machine (`autowake.json`); absent is off. */
166  autowake?: boolean
167}
168
169export type WorkflowsView = {
170  entries: WorkflowEntry[]
171  retired: RetiredEntry[]
172  problems: string[]
173  selected: string | null
174  focus: string | null
175  /** Where "+ passo aqui" is open: a step id, INSERT_END, or none. */
176  insert: string | null
177  draft: WorkflowDraft | null
178  forms: WorkflowForms
179  notice: string | null
180  /** Where each agent named by the steps shown was found. */
181  agents: Record<string, 'project' | 'plugin' | null>
182  /** Every agent that can be picked, with its description and model. */
183  agentList: AgentInfo[]
184  narrow: boolean
185  /** The project's settings (config.json): what the summary shows, the edit in progress and how each workflow stands. */
186  config?: ConfigView
187  /** The project's languages: `ui` for the pane's words and titles, `content` for descriptions and details; absent, pt-BR. */
188  languages?: Languages
189}
190
191export type WorkflowsActions = {
192  open: (id: string) => () => void
193  back: () => void
194  focus: (step: string) => () => void
195  edit: (id: string) => () => void
196  form: (field: keyof WorkflowForms) => (value: string) => void
197  create: () => void
198  head: (field: 'title' | 'description') => (value: string) => void
199  toggle: (step: string) => () => void
200  move: (step: string, by: -1 | 1) => () => void
201  set: (step: string, change: StepField) => () => void
202  /** Opens (or closes) "+ passo aqui" after a step, or at the end. */
203  insert: (after: string) => () => void
204  add: () => void
205  save: () => void
206  discard: () => void
207  /** "Configurar": opens the project settings as a draft. */
208  configure: () => void
209  cfgSet: (change: ConfigChange) => () => void
210  cfgSave: () => void
211  cfgDiscard: () => void
212  /** "Acrescentar merge e deploy" / "Passar a usar o do projeto": asks for the confirmation. */
213  ask: (what: ConfigAsk['what'], id: string) => () => void
214  confirm: () => void
215  cancel: () => void
216  /** "Ativar neste clone": opens the confirmation. */
217  actOpen: () => void
218  /** The level chosen in the confirmation. */
219  actLevel: (level: ActivationLevel) => void
220  actConfirm: () => void
221  actCancel: () => void
222  /** "Trocar para …" on an active clone. */
223  actSwitch: (level: ActivationLevel) => () => void
224  actOff: () => void
225  /** "Seguir o flow sem clique": turns the option on or off on this machine. */
226  autowake: (on: boolean) => () => void
227}
228
229/** A step as the pane reads it: a flow's, or a draft's raw one. */
230type StepLike = {
231  id: string
232  /** Plain text, or one text per language (a draft's raw step). */
233  title: unknown
234  description?: unknown
235  titles?: Translations
236  descriptions?: Translations
237  kind: FlowStepKind
238  agent?: string
239  model?: string
240  effort?: string
241  command?: string
242  requiresEvidence?: boolean
243  details?: { inputs?: unknown; produces?: unknown; blocks?: unknown }
244  detailsByLang?: Partial<Record<Lang, FlowStepDetails>>
245  merge?: FlowMerge
246  deploy?: FlowDeploy
247  outcomes?: Record<string, { label?: string; next: string }>
248}
249
250const yesNo = (t: WorkflowsText, b: boolean | undefined) => (b === true ? t.yes : t.no)
251
252/** `claude-opus-5-5` as the owner reads it: Opus 5.5. */
253export const modelName = (model: string): string => {
254  const parts = model.replace(/^claude-/, '').split('-')
255  const [name = model, ...version] = parts
256  return [name.charAt(0).toUpperCase() + name.slice(1), version.join('.')].filter(x => x !== '').join(' ')
257}
258
259const effortName = (t: WorkflowsText, effort: string): string => t.effort[effort] ?? effort
260
261/** A flow's title in the ui language; its description in the content language. */
262const flowTitle = (flow: FlowDef, lang: Lang): string => localize(flow.titles, lang) ?? flow.title
263const flowDescription = (flow: FlowDef, lang: Lang): string => localize(flow.descriptions, lang) ?? flow.description
264
265/** A step's title in `lang`: a parsed step's `titles`, or a raw step's `title` written as text or per language. */
266const titleOf = (s: { id?: unknown; title?: unknown; titles?: Translations }, lang: Lang): string =>
267  localize(s.titles ?? parseLocalized(s.title), lang) ?? String(s.id ?? '')
268const descriptionOf = (s: { description?: unknown; descriptions?: Translations }, lang: Lang): string | undefined =>
269  localize(s.descriptions ?? parseLocalized(s.description), lang)
270/** One of the step's details in `lang`: a parsed step's per-language one, else the field as written (text or per language). */
271const detailOf = (s: StepLike, key: keyof FlowStepDetails, lang: Lang): string | undefined =>
272  localize(parseLocalized(s.detailsByLang?.[lang]?.[key] ?? s.details?.[key]), lang)
273
274/** Where a problem line from the loader names its file, shortened, and what is wrong with it in plain words. */
275const problemParts = (t: WorkflowsText, problem: string): { file: string; what: string } => {
276  const at = problem.indexOf(': ')
277  const path = at === -1 ? problem : problem.slice(0, at)
278  const what = at === -1 ? '' : problem.slice(at + 2)
279  const file = path.includes('.orquestrador/flows/') ? path.slice(path.indexOf('.orquestrador/flows/') + '.orquestrador/flows/'.length) : path
280  return { file, what: what === 'not valid JSON.' ? t.invalidJson : what }
281}
282
283export const renderWorkflows = (els: WorkflowsElements, view: WorkflowsView, actions: WorkflowsActions): RenderElement => {
284  const { Box, Text, Button, Input, Select } = els
285  const languages = view.languages ?? DEFAULT_LANGUAGES
286  const ui = languages.ui
287  const content = languages.content
288  const t = workflowsText(ui)
289  const yes = (b: boolean | undefined) => yesNo(t, b)
290  const title = (s: StepLike) => titleOf(s, ui)
291  const fields = Input !== undefined && Select !== undefined
292
293  const line = (text: string, color?: string, dim?: boolean) => (
294    <Text wrap="wrap" color={color} dimColor={dim}>
295      {text}
296    </Text>
297  )
298  const help = (text: string) => line(text, undefined, true)
299  const buttons = (...items: RenderElement[]) => (
300    <Box flexDirection={view.narrow ? 'column' : 'row'} flexWrap="wrap" columnGap={1} minWidth={0}>
301      {items}
302    </Box>
303  )
304  const box = (children: RenderElement[], color?: string) => (
305    <Box flexDirection="column" borderStyle="round" borderColor={color} borderDimColor={color === undefined} paddingX={1} minWidth={0}>
306      {children}
307    </Box>
308  )
309  const noFields = line(t.noFields, undefined, true)
310  /** A pill: a rounded Box with its own background, never the label between brackets. */
311  const pill = (label: string, tone: { bg: string; fg: string }) => (
312    <Box key={`wf-pill:${label}`} borderStyle="round" borderColor={tone.bg} backgroundColor={tone.bg} paddingX={1} flexShrink={0}>
313      <Text size="caption" color={tone.fg} backgroundColor={tone.bg}>
314        {label}
315      </Text>
316    </Box>
317  )
318  const tag = (label: string) => pill(label, TAG_GRAY)
319  /** A hairline under the header, cut to the width of the pane. */
320  const divider = (
321    <Box key="wf-divider" width="100%" height={1} overflow="hidden" minWidth={0}>
322      <Text color={RULE} wrap="truncate">{'─'.repeat(200)}</Text>
323    </Box>
324  )
325  /** A small section label in capitals. */
326  const label = (title: string) => (
327    <Text size="caption" weight="semibold" color={MUTED}>
328      {title.toUpperCase()}
329    </Text>
330  )
331
332  const agentModel = (name: string | undefined): string | undefined =>
333    name === undefined ? undefined : view.agentList.find(a => a.name === name)?.model
334  const originOf = (name: string): string => {
335    const found = view.agents[name]
336    return found === 'project' ? t.agentOrigin.project : found === 'plugin' ? t.agentOrigin.plugin : t.agentOrigin.missing
337  }
338
339  /** Who answers the step, in the words of the legend. */
340  const who = (s: StepLike): string =>
341    s.kind === 'session'
342      ? t.who.session
343      : s.kind === 'owner'
344        ? t.who.owner
345        : s.kind === 'loop'
346          ? t.who.loop
347          : s.merge !== undefined || s.deploy !== undefined
348            ? t.who.coordination
349            : t.who.mod
350  const whoShort = (s: StepLike): string => (s.merge !== undefined || s.deploy !== undefined ? (s.kind === 'automatic' ? t.whoTagAutomatic : t.whoTag[s.kind]) : t.whoTag[s.kind])
351
352  const modelLine = (s: StepLike): string => {
353    const fromAgent = s.model === undefined ? agentModel(s.agent) : undefined
354    const model = s.model ?? fromAgent
355    const parts = [model === undefined ? undefined : modelName(model), s.effort === undefined ? undefined : t.effortOf(effortName(t, s.effort))]
356    return parts.filter((x): x is string => x !== undefined).join(', ')
357  }
358  /** The detail row's model: the summary's, or the session's own when nothing sets one. */
359  const modelRow = (s: StepLike): string => {
360    const fromAgent = s.model === undefined ? agentModel(s.agent) : undefined
361    return modelLine(s) === '' ? t.sessionDefault : `${modelLine(s)}${fromAgent === undefined ? '' : t.fromAgentSuffix}`
362  }
363
364  /** The step's one-line summary, in plain words. */
365  const summary = (s: StepLike): string => {
366    if (s.merge !== undefined) {
367      return s.merge.auto
368        ? t.summary.mergeAuto(s.merge.method, s.merge.branch, s.agent)
369        : t.summary.mergeOwner(s.merge.method, s.merge.branch)
370    }
371    if (s.deploy !== undefined) {
372      const part = [s.deploy.ci ? t.summary.waitsCi : undefined, s.deploy.commands.length > 0 ? t.summary.runs(s.deploy.commands.join(', ')) : undefined]
373        .filter((x): x is string => x !== undefined)
374        .join(t.summary.and)
375      return `${s.deploy.auto ? t.summary.deployAuto : t.summary.deployOwner} · ${part === '' ? t.summary.noCiNoRoutines : part}`
376    }
377    if (s.kind === 'session' || s.kind === 'loop') {
378      const lead = s.kind === 'loop' ? t.summary.loopLead : t.summary.sessionLead
379      if (s.agent === undefined) return t.summary.noAgent(lead)
380      return t.summary.withAgent(lead, s.agent, modelLine(s))
381    }
382    if (s.kind === 'automatic' && s.command !== undefined) return t.summary.modSees(s.command)
383    return descriptionOf(s, content) ?? who(s)
384  }
385
386  const row = (label: string, value: string) => (
387    <Box key={`wf-row-${label}`} flexDirection={view.narrow ? 'column' : 'row'} columnGap={1} minWidth={0}>
388      <Box width={view.narrow ? undefined : 12} flexShrink={0}>
389        <Text dimColor>{label}</Text>
390      </Box>
391      <Box flexGrow={1} flexShrink={1} minWidth={0}>
392        <Text wrap="wrap">{value}</Text>
393      </Box>
394    </Box>
395  )
396
397  /** Where a rejected step goes back to: its outcomes that lead to an earlier step. */
398  const rejects = (s: StepLike, all: StepLike[]): string => {
399    const here = all.findIndex(x => x.id === s.id)
400    const back = Object.values(s.outcomes ?? {})
401      .map(o => all.findIndex(x => x.id === o.next))
402      .filter(i => i !== -1 && i < here)
403      .map(i => title(all[i]!))
404    return back.length === 0 ? t.noBack : t.backTo([...new Set(back)])
405  }
406
407  const detailRows = (s: StepLike, all: StepLike[]): RenderElement[] => {
408    const out: RenderElement[] = [row(t.rows.who, who(s))]
409    out.push(row(t.rows.agent, s.agent === undefined ? t.none : `${s.agent} (${originOf(s.agent)})`))
410    out.push(row(t.rows.model, modelRow(s)))
411    if (s.command !== undefined) out.push(row(t.rows.command, s.command))
412    if (s.merge !== undefined) out.push(row(t.rows.merge, t.mergeRow(s.merge.branch, s.merge.method, yes(s.merge.auto))))
413    if (s.merge !== undefined) out.push(row(t.merge.approvalRow, t.merge.approval(s.agent)))
414    if (s.deploy !== undefined) {
415      out.push(row(t.rows.deploy, t.deployRow(yes(s.deploy.ci), s.deploy.commands.length === 0 ? t.noneRoutine : s.deploy.commands.join(' ; '), yes(s.deploy.auto))))
416    }
417    const inputs = detailOf(s, 'inputs', content)
418    const produces = detailOf(s, 'produces', content)
419    const blocks = detailOf(s, 'blocks', content)
420    if (inputs !== undefined) out.push(row(t.rows.inputs, inputs))
421    if (produces !== undefined) out.push(row(t.rows.produces, produces))
422    out.push(row(t.rows.ifRejected, rejects(s, all)))
423    if (blocks !== undefined) out.push(row(t.rows.blocks, blocks))
424    out.push(row(t.rows.evidence, s.requiresEvidence === true ? t.evidenceRequired : t.evidenceNotRequired))
425    return out
426  }
427
428  /** The step's number inside a circle in the color of who answers it. */
429  const stepNumber = (s: StepLike, n: number | string, off = false) => {
430    const bg = off ? RULE : WHO_COLOR[s.kind]
431    return (
432      <Box width={5} flexShrink={0}>
433        <Box width={3} borderStyle="round" borderColor={bg} backgroundColor={bg} alignItems="center" justifyContent="center" flexShrink={0}>
434          <Text weight="bold" color={off ? MUTED : '#FFFFFF'} backgroundColor={bg}>{`${n}`}</Text>
435        </Box>
436      </Box>
437    )
438  }
439
440  /** A step of the workflow shown, not edited: number, title, one line, and its rows when opened. */
441  const viewStep = (s: StepLike, n: number, all: StepLike[]): RenderElement => {
442    const open = view.focus === s.id
443    return (
444      <Box key={`wf-row:${s.id}`} flexDirection="row" minWidth={0} marginTop={1}>
445        {stepNumber(s, n)}
446        <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
447          <Button key={`wf-step:${s.id}`} plain onPress={actions.focus(s.id)}>
448            <Text weight="semibold">{title(s)}</Text>
449          </Button>
450          <Text wrap="wrap" color={MUTED} size="footnote">{summary(s)}</Text>
451          {open ? <Box flexDirection="column" marginTop={1} rowGap={1} minWidth={0}>{detailRows(s, all)}</Box> : []}
452        </Box>
453      </Box>
454    )
455  }
456
457  const back = (
458    <Button key="wf-back" plain onPress={actions.back}>
459      <Text color={LINK}>{t.back}</Text>
460    </Button>
461  )
462
463  const heading = (title: string, extra?: RenderElement) => (
464    <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={1} minWidth={0}>
465      <Text size="heading" weight="semibold" wrap="wrap">{title}</Text>
466      {extra ?? []}
467    </Box>
468  )
469
470  /* ---------- edição ---------- */
471
472  const text = (key: string, label: string, value: string | undefined, apply: (v: string) => void, submit?: (v: string) => void) =>
473    Input === undefined ? (
474      noFields
475    ) : (
476      <Input
477        key={key}
478        label={label}
479        submitLabel={t.apply}
480        {...(value === undefined || value === '' ? {} : { value })}
481        onInput={apply}
482        onSubmit={submit ?? apply}
483      />
484    )
485
486  const agentSelect = (key: string, current: string | undefined, apply: (v: string) => void) => {
487    const known = view.agentList.some(a => a.name === current)
488    const options = [
489      ...view.agentList.map(a => ({ value: a.name, label: t.agentOption(a.name, a.source === 'project' ? t.agentOrigin.project : t.agentOrigin.plugin) })),
490      ...(current === undefined || known ? [] : [{ value: current, label: t.agentOption(current, t.agentOrigin.missing) }]),
491      { value: NONE, label: t.noAgentOption },
492    ]
493    return Select === undefined ? (
494      noFields
495    ) : (
496      <Select key={key} label={t.agentLabel} options={options} value={current ?? NONE} onSelect={v => apply(v === NONE ? '' : v)} />
497    )
498  }
499  const agentAbout = (name: string | undefined) => {
500    if (name === undefined) return help(t.noAgentHelp)
501    const found = view.agentList.find(a => a.name === name)
502    return help(found === undefined ? t.noAgentFile(name) : found.description)
503  }
504
505  const editCard = (s: StepLike, n: number, opts: { first: boolean; last: boolean }): RenderElement => {
506    const set = (field: 'agent' | 'model' | 'effort') => (v: string) => actions.set(s.id, { field, value: v })()
507    const takesAgent = s.kind === 'session' || s.kind === 'loop' || s.merge !== undefined || s.deploy !== undefined
508    const body: RenderElement[] = []
509    if (!fields) body.push(noFields)
510    else if (Select !== undefined) {
511      if (takesAgent) {
512        body.push(agentSelect(`wf-agent:${s.id}`, s.agent, set('agent')), agentAbout(s.agent))
513        if (s.merge !== undefined) body.push(help(t.merge.approval(s.agent)))
514      }
515      const fromAgent = agentModel(s.agent)
516      const models = [...new Set([...MODELS, ...(s.model === undefined ? [] : [s.model])])]
517      body.push(
518        <Select
519          key={`wf-model:${s.id}`}
520          label={t.modelLabel}
521          options={[
522            { value: NONE, label: fromAgent === undefined ? t.sessionDefault : t.fromAgent(modelName(fromAgent)) },
523            ...models.map(m => ({ value: m, label: modelName(m) })),
524          ]}
525          value={s.model ?? NONE}
526          onSelect={v => set('model')(v === NONE ? '' : v)}
527        />,
528        <Select
529          key={`wf-effort:${s.id}`}
530          label={t.effortLabel}
531          options={[
532            { value: NONE, label: t.sessionDefault },
533            ...[...new Set([...EFFORTS, ...(s.effort === undefined ? [] : [s.effort])])].map(e => ({ value: e, label: effortName(t, e) })),
534          ]}
535          value={s.effort ?? NONE}
536          onSelect={v => set('effort')(v === NONE ? '' : v)}
537        />,
538        help(t.modelHelp),
539      )
540      if (s.merge !== undefined) {
541        body.push(
542          text(`wf-merge-branch:${s.id}`, t.merge.branchLabel, s.merge.branch, v => actions.set(s.id, { field: 'merge', value: { branch: v.trim() } })()),
543          help(t.merge.branchHelp),
544          <Select
545            key={`wf-merge-method:${s.id}`}
546            label={t.merge.methodLabel}
547            options={Object.entries(t.methods).map(([value, label]) => ({ value, label }))}
548            value={s.merge.method}
549            onSelect={v => actions.set(s.id, { field: 'merge', value: { method: v as FlowMerge['method'] } })()}
550          />,
551        )
552      }
553    }
554    if (s.merge !== undefined) {
555      body.push(
556        buttons(
557          <Button key={`wf-merge-auto:${s.id}`} onPress={actions.set(s.id, { field: 'merge', value: { auto: !s.merge.auto } })}>
558            {t.merge.auto(yes(s.merge.auto))}
559          </Button>,
560        ),
561        help(t.merge.autoHelp(s.agent)),
562      )
563    }
564    if (s.deploy !== undefined) {
565      const deploy = s.deploy
566      const commands = (list: string[]) => actions.set(s.id, { field: 'deploy', value: { commands: list } })()
567      body.push(
568        buttons(
569          <Button key={`wf-deploy-ci:${s.id}`} onPress={actions.set(s.id, { field: 'deploy', value: { ci: !deploy.ci } })}>
570            {t.deploy.ci(yes(deploy.ci))}
571          </Button>,
572        ),
573        help(t.deploy.ciHelp),
574        line(t.deploy.routines),
575      )
576      if (fields) {
577        deploy.commands.forEach((command, i) => {
578          body.push(
579            text(
580              `wf-routine:${s.id}:${i}`,
581              t.deploy.routine(i + 1),
582              command,
583              v => {
584                if (v.trim() !== '') commands(deploy.commands.map((c, j) => (j === i ? v.trim() : c)))
585              },
586              v => commands(v.trim() === '' ? deploy.commands.filter((_, j) => j !== i) : deploy.commands.map((c, j) => (j === i ? v.trim() : c))),
587            ),
588            buttons(
589              <Button key={`wf-routine-del:${s.id}:${i}`} onPress={() => commands(deploy.commands.filter((_, j) => j !== i))}>
590                {t.deploy.removeRoutine(i + 1)}
591              </Button>,
592            ),
593          )
594        })
595        if (view.forms.routineFor === s.id) {
596          body.push(text(`wf-routine-new:${s.id}`, t.deploy.newRoutine, undefined, () => {}, v => {
597            if (v.trim() !== '') commands([...deploy.commands, v.trim()])
598            actions.form('routineFor')('')
599          }))
600        }
601      }
602      body.push(
603        buttons(
604          <Button key={`wf-routine-add:${s.id}`} onPress={() => actions.form('routineFor')(s.id)}>
605            {t.deploy.addRoutine}
606          </Button>,
607        ),
608        help(t.deploy.routinesHelp),
609        buttons(
610          <Button key={`wf-deploy-auto:${s.id}`} onPress={actions.set(s.id, { field: 'deploy', value: { auto: !deploy.auto } })}>
611            {t.deploy.auto(yes(deploy.auto))}
612          </Button>,
613        ),
614        help(t.deploy.autoHelp),
615      )
616    }
617    return box([
618      <Box key={`wf-card-head:${s.id}`} flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
619        <Button key={`wf-step:${s.id}`} plain onPress={actions.focus(s.id)}>
620          <Text weight="semibold">{`${n}. ${title(s)}`}</Text>
621        </Button>
622        {pill(whoShort(s), WHO_PILL[s.kind])}
623      </Box>,
624      line(who(s), undefined, true),
625      ...body,
626      buttons(
627        ...(opts.first ? [] : [<Button key={`wf-up:${s.id}`} onPress={actions.move(s.id, -1)}>{t.up}</Button>]),
628        ...(opts.last ? [] : [<Button key={`wf-down:${s.id}`} onPress={actions.move(s.id, 1)}>{t.down}</Button>]),
629        <Button key={`wf-toggle:${s.id}`} onPress={actions.toggle(s.id)}>
630          {t.switchOff}
631        </Button>,
632      ),
633    ])
634  }
635
636  const insertForm = (d: WorkflowDraft, after: StepLike | undefined): RenderElement => {
637    const forms = view.forms
638    const use = forms.libraryUse === '' ? NEW_STEP : forms.libraryUse
639    const libraryIds = Object.keys(LIBRARY).sort()
640    const chosen = use === NEW_STEP ? undefined : libraryStep(use)
641    const about =
642      chosen === undefined || typeof chosen === 'string'
643        ? t.insert.newAbout
644        : (descriptionOf(chosen as { description?: unknown }, content) ?? '')
645    const labelOf = (id: string): string => {
646      const step = libraryStep(id)
647      return typeof step === 'string' ? id : localize(parseLocalized(step.title), ui) ?? id
648    }
649    const body: RenderElement[] = []
650    if (Select === undefined || Input === undefined) body.push(noFields)
651    else {
652      body.push(
653        <Select
654          key="wf-add-library"
655          label={t.insert.libraryLabel}
656          options={[...libraryIds.map(id => ({ value: id, label: labelOf(id) })), { value: NEW_STEP, label: t.insert.newStepOption }]}
657          value={use}
658          onSelect={v => actions.form('libraryUse')(v === NEW_STEP ? '' : v)}
659        />,
660        help(about),
661      )
662      if (use === NEW_STEP) {
663        body.push(
664          <Input
665            key="wf-step-title"
666            label={t.insert.titleLabel}
667            submitLabel={t.ok}
668            {...(forms.stepTitle === '' ? {} : { value: forms.stepTitle })}
669            onInput={actions.form('stepTitle')}
670            onSubmit={actions.form('stepTitle')}
671          />,
672          help(t.insert.titleHelp),
673          <Select
674            key="wf-step-kind"
675            label={t.insert.kindLabel}
676            options={[
677              { value: 'session', label: t.insert.kinds.session },
678              { value: 'owner', label: t.insert.kinds.owner },
679              { value: 'automatic', label: t.insert.kinds.automatic },
680            ]}
681            value={forms.stepKind}
682            onSelect={actions.form('stepKind')}
683          />,
684        )
685        if (forms.stepKind === 'session') {
686          body.push(agentSelect('wf-step-agent', forms.stepAgent === '' ? undefined : forms.stepAgent, actions.form('stepAgent')), agentAbout(forms.stepAgent === '' ? undefined : forms.stepAgent))
687        }
688        if (forms.stepKind === 'automatic') {
689          body.push(
690            <Input
691              key="wf-step-command"
692              label={t.insert.commandLabel}
693              submitLabel={t.ok}
694              {...(forms.stepCommand === '' ? {} : { value: forms.stepCommand })}
695              onInput={actions.form('stepCommand')}
696              onSubmit={actions.form('stepCommand')}
697            />,
698            help(t.insert.commandHelp),
699          )
700        }
701      }
702    }
703    return box(
704      [
705        <Text weight="semibold" wrap="wrap">{after === undefined ? t.insert.atStart : t.insert.after(title(after))}</Text>,
706        ...body,
707        buttons(
708          <Button key="wf-add" variant="primary" onPress={actions.add}>
709            {t.insert.add}
710          </Button>,
711          <Button key="wf-add-cancel" onPress={actions.insert(String(view.insert))}>
712            {t.insert.cancel}
713          </Button>,
714        ),
715      ],
716      LINK,
717    )
718  }
719
720  /* ---------- configurações do projeto ---------- */
721
722  const notice$ = (n: string | null): RenderElement[] => (n === null ? [] : [box([line(n)])])
723
724  const cfg = view.config
725  const P = t.project
726  const rule = (key: string) => (
727    <Box key={key} width="100%" height={1} overflow="hidden" minWidth={0}>
728      <Text color={RULE} wrap="truncate">{'─'.repeat(200)}</Text>
729    </Box>
730  )
731  /** A button that says its state: filled when on. */
732  const stateButton = (key: string, label: string, on: boolean, press: () => void) =>
733    buttons(
734      <Button key={key} variant={on ? 'primary' : 'secondary'} onPress={press}>
735        {label}
736      </Button>,
737    )
738  const entryTitle = (id: string): string => {
739    const entry = view.entries.find(e => e.flow.id === id)
740    return entry === undefined ? id : flowTitle(entry.flow, ui)
741  }
742
743  /** "Nos workflows": how each workflow stands, and what can be done about it. */
744  const workflowCards = (c: ConfigView): RenderElement[] =>
745    c.states.map(state => {
746      const name = entryTitle(state.id)
747      const W = P.workflows
748      const sentence =
749        state.missing.length === 2
750          ? W.none(name)
751          : state.missing[0] === 'merge'
752            ? W.noMerge(name)
753            : state.missing[0] === 'deploy'
754              ? W.noDeploy(name)
755              : state.own.length > 0
756                ? W.own(
757                    name,
758                    state.own.map(o => {
759                      const block = o.step[o.what] as unknown as Record<string, unknown>
760                      const words = W.fieldText as Record<string, (v: never) => string>
761                      return W.ownPart(
762                        W.what[o.what],
763                        o.fields.map(f => words[f]!(block[f] as never)).join(', '),
764                      )
765                    }),
766                  )
767                : W.uses(name)
768      const rest = sentence.startsWith(name) ? sentence.slice(name.length) : ` ${sentence}`
769      const asked = c.ask !== null && c.ask.id === state.id ? c.ask : null
770      const missingNames = state.missing.map(m => W.what[m])
771      const replaces = view.entries.find(e => e.flow.id === state.id)?.project === false
772      const actions$: RenderElement[] = []
773      if (asked !== null) {
774        actions$.push(
775          line(
776            (asked.what === 'add' ? W.confirmAdd(name, missingNames) : W.confirmUse(name)) + (replaces ? W.replacesDefault(state.id) : ''),
777          ),
778          buttons(
779            <Button key="cfg-confirm" variant="primary" onPress={actions.confirm}>
780              {W.confirm}
781            </Button>,
782            <Button key="cfg-cancel" onPress={actions.cancel}>
783              {W.cancel}
784            </Button>,
785          ),
786        )
787      } else {
788        if (state.missing.length > 0) {
789          actions$.push(
790            buttons(
791              <Button key={`cfg-add:${state.id}`} onPress={actions.ask('add', state.id)}>
792                {W.add(name, missingNames)}
793              </Button>,
794            ),
795          )
796        }
797        if (state.own.length > 0) {
798          actions$.push(
799            <Button key={`cfg-use:${state.id}`} plain onPress={actions.ask('use', state.id)}>
800              <Text color={LINK}>{W.use}</Text>
801            </Button>,
802          )
803        }
804      }
805      const missing = state.missing.length > 0
806      return (
807        <Box
808          key={`cfg-wf:${state.id}`}
809          flexDirection="column"
810          rowGap={1}
811          borderStyle="round"
812          borderColor={missing ? AMBER_RULE : RULE}
813          backgroundColor={missing ? AMBER_BAR : undefined}
814          paddingX={1}
815          minWidth={0}
816        >
817          <Text wrap="wrap">
818            <Text weight="semibold">{name}</Text>
819            {rest}
820          </Text>
821          {actions$}
822        </Box>
823      )
824    })
825
826  if (cfg?.draft != null) {
827    const c = cfg.draft
828    const E = P.edit
829    const changes = configChanges(c, t)
830    const merge = effectiveMerge(c.merge)
831    const deploy = effectiveDeploy(c.deploy)
832    const set = (change: ConfigChange) => actions.cfgSet(change)
833    const langOptions = Object.entries(E.langOption).map(([value, label]) => ({ value, label }))
834    const langSelect = (axis: 'ui' | 'content', label$: string, about: string) =>
835      Select === undefined
836        ? [noFields]
837        : [
838            <Select
839              key={`cfg-${axis}`}
840              label={label$}
841              options={langOptions}
842              value={c.languages[axis]}
843              onSelect={v => set({ kind: axis, value: v as Lang })()}
844            />,
845            help(about),
846          ]
847    const commands = (list: string[]) => set({ kind: 'deploy', value: { commands: list } })()
848    const block = (key: string, title$: string, children: RenderElement[]) => (
849      <Box key={key} flexDirection="column" rowGap={1} marginTop={1} minWidth={0}>
850        {rule(`${key}-rule`)}
851        {label(title$)}
852        {children}
853      </Box>
854    )
855    return (
856      <Box flexDirection="column" minWidth={0}>
857        {notice$(view.notice)}
858        <Box flexDirection="column" borderStyle="round" borderColor={AMBER_RULE} backgroundColor={AMBER_BAR} paddingX={1} minWidth={0}>
859          <Text weight="semibold">{E.title}</Text>
860          <Text size="caption" color="#6B4A12">{E.draftHelp}</Text>
861          {buttons(
862            <Button key="cfg-discard" onPress={actions.cfgDiscard}>
863              {E.discard}
864            </Button>,
865            <Button key="cfg-save" variant="primary" onPress={actions.cfgSave}>
866              {E.save}
867            </Button>,
868          )}
869          <Text size="caption" color="#6B4A12" wrap="wrap">
870            {changes.length === 0 ? E.noChanges : t.edit.changes(changes)}
871          </Text>
872        </Box>
873        {c.error === undefined ? [] : box([line(E.notSaved(c.error), ERROR)], ERROR)}
874        <Box marginTop={1} minWidth={0}>
875          {help(E.about)}
876        </Box>
877        <Box flexDirection="column" rowGap={1} marginTop={1} minWidth={0}>
878          {label(E.language)}
879          {langSelect('ui', E.uiLabel, E.uiHelp)}
880          {langSelect('content', E.contentLabel, E.contentHelp)}
881        </Box>
882        {block('cfg-merge', E.merge, [
883          stateButton('cfg-merge-auto', E.mergeAuto(yes(merge.auto)), merge.auto, set({ kind: 'merge', value: { auto: !merge.auto } })),
884          help(E.mergeAutoHelp),
885          ...(fields
886            ? [
887                text('cfg-merge-branch', E.branchLabel, merge.branch, v => set({ kind: 'merge', value: { branch: v.trim() } })()),
888                help(E.branchHelp),
889                <Select
890                  key="cfg-merge-method"
891                  label={E.methodLabel}
892                  options={Object.entries(t.methods).map(([value, label$]) => ({ value, label: label$ }))}
893                  value={merge.method}
894                  onSelect={v => set({ kind: 'merge', value: { method: v as FlowMerge['method'] } })()}
895                />,
896              ]
897            : []),
898        ])}
899        {block('cfg-deploy', E.deploy, [
900          stateButton('cfg-deploy-auto', E.deployAuto(yes(deploy.auto)), deploy.auto, set({ kind: 'deploy', value: { auto: !deploy.auto } })),
901          help(E.deployAutoHelp),
902          stateButton('cfg-deploy-ci', E.ci(yes(deploy.ci)), deploy.ci, set({ kind: 'deploy', value: { ci: !deploy.ci } })),
903          help(E.ciHelp),
904          <Text key="cfg-routines" weight="medium">{E.routines}</Text>,
905          ...(fields
906            ? deploy.commands.flatMap((command, i) => [
907                text(
908                  `cfg-routine:${i}`,
909                  E.routine(i + 1),
910                  command,
911                  v => {
912                    if (v.trim() !== '') commands(deploy.commands.map((x, j) => (j === i ? v.trim() : x)))
913                  },
914                  v => commands(v.trim() === '' ? deploy.commands.filter((_, j) => j !== i) : deploy.commands.map((x, j) => (j === i ? v.trim() : x))),
915                ),
916                buttons(
917                  <Button key={`cfg-routine-del:${i}`} onPress={() => commands(deploy.commands.filter((_, j) => j !== i))}>
918                    {E.remove}
919                  </Button>,
920                ),
921              ])
922            : deploy.commands.map((command, i) => line(`${i + 1}. ${command}`))),
923          ...(fields && view.forms.routineFor === CFG_ROUTINE
924            ? [
925                text('cfg-routine-new', E.newRoutine, undefined, () => {}, v => {
926                  if (v.trim() !== '') commands([...deploy.commands, v.trim()])
927                  actions.form('routineFor')('')
928                }),
929              ]
930            : []),
931          ...(fields
932            ? [
933                <Button key="cfg-routine-add" plain onPress={() => actions.form('routineFor')(CFG_ROUTINE)}>
934                  <Text color={LINK}>{E.addRoutine}</Text>
935                </Button>,
936              ]
937            : []),
938          help(E.routinesHelp),
939        ])}
940        {block('cfg-workflows', E.inWorkflows, workflowCards(cfg))}
941      </Box>
942    )
943  }
944
945  if (view.draft !== null) {
946    const d = view.draft
947    const onSteps = d.steps.filter(s => s.on).map(s => s.step as unknown as StepLike)
948    const offSteps = d.steps.filter(s => !s.on).map(s => s.step as unknown as StepLike)
949    const changes = changesOf(d, t)
950    // the one "+ passo aqui": where it is open, else after the open step, else at the end
951    const slot =
952      view.insert !== null && (view.insert === INSERT_END || onSteps.some(s => s.id === view.insert))
953        ? view.insert
954        : onSteps.some(s => s.id === view.focus)
955          ? String(view.focus)
956          : INSERT_END
957    const insertAt = (id: string, step: StepLike | undefined) => (
958      <Box key={`wf-insert-box:${id}`} flexDirection="column" marginTop={1} minWidth={0}>
959        {view.insert === id ? insertForm(d, step) : (
960          <Button key={`wf-insert:${id}`} plain onPress={actions.insert(id)}>
961            <Text color={LINK}>{t.insert.here}</Text>
962          </Button>
963        )}
964      </Box>
965    )
966    return (
967      <Box flexDirection="column" minWidth={0}>
968        <Box flexDirection="column" borderStyle="round" borderColor={RULE} paddingX={1} minWidth={0}>
969          {heading(t.edit.editing(d.title))}
970          {help(t.edit.draftHelp)}
971          {buttons(
972            <Button key="wf-save" variant="primary" onPress={actions.save}>
973              {t.edit.save}
974            </Button>,
975            <Button key="wf-discard" onPress={actions.discard}>
976              {t.edit.discard}
977            </Button>,
978          )}
979          {line(changes.length === 0 ? t.edit.noChanges : t.edit.changes(changes), undefined, changes.length === 0)}
980        </Box>
981        {d.error === undefined ? [] : box([line(t.edit.notSaved(d.error), ERROR)], ERROR)}
982        {d.base === undefined ? [] : help(t.edit.derived(d.base))}
983        {d.replacesDefault
984          ? box([line(t.edit.replacesDefault(d.id), WARN)], WARN)
985          : []}
986        {help(t.edit.runningKeep)}
987        {fields
988          ? [
989              <Box key="wf-head-block" flexDirection="column" marginTop={1} minWidth={0}>
990                <Button key="wf-head-toggle" plain onPress={actions.focus(HEAD_FOCUS)}>
991                  <Text weight="semibold">{`${view.focus === HEAD_FOCUS ? '▾' : '›'} ${t.edit.nameAndDescription}`}</Text>
992                </Button>
993                {view.focus === HEAD_FOCUS
994                  ? [
995                      <Input key="wf-title" label={t.edit.nameLabel} submitLabel={t.apply} value={d.title} onInput={actions.head('title')} onSubmit={actions.head('title')} />,
996                      <Input
997                        key="wf-description"
998                        label={t.edit.descriptionLabel}
999                        submitLabel={t.apply}
1000                        {...(d.description === '' ? {} : { value: d.description })}
1001                        onInput={actions.head('description')}
1002                        onSubmit={actions.head('description')}
1003                      />,
1004                      help(t.edit.headHelp),
1005                    ]
1006                  : []}
1007              </Box>,
1008            ]
1009          : [line(d.title, undefined, false)]}
1010        <Box flexDirection="column" marginTop={1} minWidth={0}>
1011          {label(t.edit.steps)}
1012          {help(t.edit.stepsHelp)}
1013        </Box>
1014        {onSteps.length === 0 ? [help(t.edit.noSteps), insertAt(INSERT_END, undefined)] : []}
1015        {onSteps.map((s, i) => {
1016          const open = view.focus === s.id
1017          return (
1018            <Box key={`wf-row:${s.id}`} flexDirection="column" minWidth={0} marginTop={1}>
1019              {open ? (
1020                editCard(s, i + 1, { first: i === 0, last: i === onSteps.length - 1 })
1021              ) : (
1022                <Box flexDirection="row" minWidth={0}>
1023                  {stepNumber(s, i + 1)}
1024                  <Box flexDirection="row" justifyContent="space-between" flexGrow={1} flexShrink={1} columnGap={1} minWidth={0}>
1025                    <Button key={`wf-step:${s.id}`} plain onPress={actions.focus(s.id)}>
1026                      <Text weight="semibold">{title(s)}</Text>
1027                    </Button>
1028                    {pill(whoShort(s), WHO_PILL[s.kind])}
1029                  </Box>
1030                </Box>
1031              )}
1032              {slot === s.id ? insertAt(s.id, s) : []}
1033            </Box>
1034          )
1035        })}
1036        {onSteps.length > 0 && slot === INSERT_END ? insertAt(INSERT_END, onSteps[onSteps.length - 1]) : []}
1037        {offSteps.map(s => (
1038          <Box key={`wf-off:${s.id}`} flexDirection="row" justifyContent="space-between" columnGap={1} marginTop={1} minWidth={0}>
1039            <Box flexDirection="row" minWidth={0}>
1040              {stepNumber(s, '—', true)}
1041              <Text strikethrough dimColor wrap="wrap">{title(s)}</Text>
1042            </Box>
1043            <Button key={`wf-toggle:${s.id}`} plain onPress={actions.toggle(s.id)}>
1044              <Text color={LINK}>{t.edit.switchOn}</Text>
1045            </Button>
1046          </Box>
1047        ))}
1048      </Box>
1049    )
1050  }
1051
1052  /* ---------- um workflow aberto ---------- */
1053
1054  const notice = view.notice === null ? [] : [box([line(view.notice)])]
1055  const chosen = view.selected === null ? undefined : view.entries.find(e => e.flow.id === view.selected)
1056  if (chosen !== undefined) {
1057    const steps = chosen.flow.steps as unknown as StepLike[]
1058    const legend = (color: string, label: string) => (
1059      <Text key={label} dimColor wrap="wrap">
1060        <Text color={color}>●</Text>
1061        {` ${label}`}
1062      </Text>
1063    )
1064    return (
1065      <Box flexDirection="column" minWidth={0}>
1066        {back}
1067        {notice}
1068        {heading(
1069          flowTitle(chosen.flow, ui),
1070          <Button key="wf-edit" variant="primary" onPress={actions.edit(chosen.flow.id)}>
1071            {t.view.edit}
1072          </Button>,
1073        )}
1074        <Box flexDirection="row" flexWrap="wrap" columnGap={1} marginTop={1} minWidth={0}>
1075          {pill(chosen.origin, chosen.flow.base !== undefined ? TAG_BLUE : TAG_GRAY)}
1076        </Box>
1077        {flowDescription(chosen.flow, content) === '' ? [] : [<Text key="wf-desc" wrap="wrap" color={MUTED}>{flowDescription(chosen.flow, content)}</Text>]}
1078        <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginTop={1} minWidth={0}>
1079          {legend(LINK, t.view.legendSession)}
1080          {legend(OWNER, t.view.legendOwner)}
1081          {legend(MOD, t.view.legendMod)}
1082        </Box>
1083        {steps.map((s, i) => viewStep(s, i + 1, steps))}
1084      </Box>
1085    )
1086  }
1087
1088  /* ---------- a lista ---------- */
1089
1090  const card = ({ flow, origin, project, replaces }: WorkflowEntry) => {
1091    const steps = flow.steps as unknown as StepLike[]
1092    const tags = [
1093      flow.base !== undefined ? { label: t.origin.derived(flow.base), tone: TAG_BLUE } : undefined,
1094      steps.some(s => s.merge?.auto === true) ? { label: t.list.mergeAuto, tone: TAG_GRAY } : undefined,
1095      steps.some(s => s.deploy?.auto === true) ? { label: t.list.deployAuto, tone: TAG_GRAY } : undefined,
1096      project && replaces ? { label: t.list.replaces(flow.id), tone: TAG_AMBER } : undefined,
1097      view.config?.states.find(x => x.id === flow.id)?.missing.includes('merge') ? { label: P.noMergeStep, tone: TAG_AMBER } : undefined,
1098    ].filter((x): x is { label: string; tone: { bg: string; fg: string } } => x !== undefined)
1099    return (
1100      <Box key={`wf-entry:${flow.id}`} flexDirection="column" borderStyle="round" borderColor={RULE} paddingX={1} minWidth={0}>
1101        <Box flexDirection="row" justifyContent="space-between" columnGap={1} minWidth={0}>
1102          <Button key={`wf-open:${flow.id}`} plain onPress={actions.open(flow.id)}>
1103            <Text weight="semibold">{`${flowTitle(flow, ui)} ›`}</Text>
1104          </Button>
1105          <Text color={MUTED} size="footnote">{t.list.steps(steps.length)}</Text>
1106        </Box>
1107        {flowDescription(flow, content) === '' ? [] : [<Text key="wf-desc" wrap="wrap" color={MUTED}>{flowDescription(flow, content)}</Text>]}
1108        {tags.length === 0 ? [] : [<Box key="wf-tags" flexDirection="row" flexWrap="wrap" columnGap={1} minWidth={0}>{tags.map(t => pill(t.label, t.tone))}</Box>]}
1109      </Box>
1110    )
1111  }
1112  /** "Este projeto": the clone's activation, the settings in three lines, and the buttons of the state it is in. */
1113  const projectCard = (c: ConfigView) => {
1114    const merge = effectiveMerge(c.project.merge ?? {})
1115    const deploy = effectiveDeploy(c.project.deploy ?? {})
1116    const A = P.activation
1117    const { level, invalid, tampered, ask } = c.activation
1118    const name = (l: Lang) => P.langName[l] ?? l
1119    const line$ = (key: string, value: string, who?: string) => (
1120      <Box key={key} flexDirection={view.narrow ? 'column' : 'row'} columnGap={1} minWidth={0}>
1121        <Box width={view.narrow ? undefined : 10} flexShrink={0}>
1122          <Text color={MUTED} size="footnote">{P.rows[key as 'language' | 'merge' | 'deploy']}</Text>
1123        </Box>
1124        <Box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={1} minWidth={0}>
1125          <Text wrap="wrap" size="footnote">{value}</Text>
1126          {who === undefined ? [] : pill(who, TAG_GRAY)}
1127        </Box>
1128      </Box>
1129    )
1130    /** "Seguir o flow sem clique": shown only with the clone active, off until the owner turns it on. */
1131    const autowakeRow = (on: boolean) => {
1132      const W = A.autowake
1133      return (
1134        <Box key="autowake" flexDirection="column" minWidth={0}>
1135          <Box flexDirection="row" alignItems="center" columnGap={1} flexWrap="wrap" minWidth={0}>
1136            <Text size="footnote" weight="semibold">{W.label}</Text>
1137            {pill(on ? W.on : W.off, on ? TAG_BLUE : TAG_GRAY)}
1138            <Button key="autowake-toggle" onPress={actions.autowake(!on)}>{on ? W.turnOff : W.turnOn}</Button>
1139          </Box>
1140          <Text key="autowake-help" size="caption" color={MUTED} wrap="wrap">{W.help}</Text>
1141        </Box>
1142      )
1143    }
1144    const other: ActivationLevel = level === 'lembrar' ? 'barrar' : 'lembrar'
1145    const levelOptions = LEVELS.map(l => ({ value: l, label: A.options[l] ?? l }))
1146    /** The confirmation of "Ativar neste clone": the level, and what will be written. */
1147    const confirm = (a: ActivationAsk) => (
1148      <Box key="act-confirm" flexDirection="column" rowGap={1} borderStyle="round" borderColor={LINK} paddingX={1} marginTop={1} minWidth={0}>
1149        <Text weight="semibold">{A.confirmTitle}</Text>
1150        <Box flexDirection="column" minWidth={0}>
1151          {Select === undefined ? <Text size="footnote" weight="semibold">{A.howMuch}</Text> : []}
1152          {Select === undefined
1153            ? LEVELS.map(l => (
1154                <Button key={`act-level:${l}`} variant={a.level === l ? 'primary' : undefined} onPress={() => actions.actLevel(l)}>
1155                  {A.options[l] ?? l}
1156                </Button>
1157              ))
1158            : <Select key="act-level" label={A.howMuch} options={levelOptions} value={a.level} onSelect={v => actions.actLevel(v as ActivationLevel)} />}
1159          <Text size="caption" color={MUTED} wrap="wrap">{A.levelHelp}</Text>
1160          <Text size="caption" color={MUTED} wrap="wrap">{A.brake}</Text>
1161        </Box>
1162        <Box flexDirection="column" backgroundColor="#F7F6F2" paddingX={1} minWidth={0}>
1163          <Text size="footnote" weight="semibold">{A.written}</Text>
1164          <Text size="footnote" wrap="wrap">{A.writtenWhere}</Text>
1165          <Text size="footnote" wrap="wrap">{`· ${A.writtenMark}`}</Text>
1166          <Text size="footnote" wrap="wrap">{`· ${A.writtenHook}`}</Text>
1167          <Text size="caption" color={MUTED} wrap="wrap">{A.writtenNothing}</Text>
1168        </Box>
1169        {buttons(
1170          <Button key="act-confirm-go" variant="primary" onPress={actions.actConfirm}>{A.confirm}</Button>,
1171          <Button key="act-confirm-cancel" onPress={actions.actCancel}>{A.cancel}</Button>,
1172        )}
1173      </Box>
1174    )
1175    return (
1176      <Box key="cfg-card" flexDirection="column" minWidth={0}>
1177        <Box flexDirection="column" rowGap={1} borderStyle="round" borderColor={RULE} paddingX={1} marginTop={1} minWidth={0}>
1178          <Box flexDirection="row" alignItems="center" columnGap={1} flexWrap="wrap" minWidth={0}>
1179            <Text weight="semibold">{P.title}</Text>
1180            {level === undefined ? pill(A.off, TAG_GRAY) : pill(A.on(A.level[level] ?? level), TAG_BLUE)}
1181          </Box>
1182          {level === undefined ? <Text key="act-quiet" size="footnote" color={MUTED} wrap="wrap">{A.quiet}</Text> : []}
1183          {tampered ? <Text key="act-tampered" size="footnote" color={ERROR} wrap="wrap">{A.tampered}</Text> : []}
1184          {invalid ? <Text key="act-invalid" size="footnote" color={ERROR} wrap="wrap">{A.invalid}</Text> : []}
1185          {line$('language', P.languageSummary(name(languages.ui), name(languages.content)))}
1186          {line$('merge', P.mergeSummary(merge.branch, merge.method), merge.auto ? P.mergeWho.auto : P.mergeWho.owner)}
1187          {line$('deploy', P.deploySummary(deploy.ci, deploy.commands), deploy.auto ? P.deployWho.auto : P.deployWho.owner)}
1188          <Text size="caption" color={MUTED} wrap="wrap">{P.applies}</Text>
1189          {c.problems.length === 0 ? [] : box(c.problems.map(p => line(p, ERROR)), ERROR)}
1190          {buttons(
1191            ...(level === undefined && ask === null && !invalid
1192              ? [<Button key="act-open" variant="primary" onPress={actions.actOpen}>{A.activate}</Button>]
1193              : []),
1194            <Button key="cfg-open" onPress={actions.configure}>
1195              {P.configure}
1196            </Button>,
1197            ...(level === undefined
1198              ? []
1199              : [
1200                  ...(tampered ? [<Button key="act-confirm-level" variant="primary" onPress={actions.actSwitch(level)}>{A.confirmLevel(A.level[level] ?? level)}</Button>] : []),
hooks/flow-files.ts 127 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { FlowDef, Languages, ProjectSettings } from '../types'
4import { mergeFlows, resolveProjectFlows } from './flow'
5import type { AgentFound, FlowSource } from './flow'
6import { DEFAULT_FLOWS, defaultFlows } from './flows/index'
7import { isAgentName } from './gates'
8import { CONFIG_PATH, parseConfig } from './i18n'
9
10// Function declarations: the engine follows `$` past an import only into one of these.
11
12/** Every flow file of one folder as read, the ones that are not JSON named in `problems`. */
13export async function readFlowDir($: EngineInterface, dir: string): Promise<{ files: FlowSource[]; problems: string[] }> {
14  if (!(await $.fs.exists(dir))) return { files: [], problems: [] }
15  const entries = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.json'))
16  const files: FlowSource[] = []
17  const problems: string[] = []
18  for (const file of entries) {
19    try {
20      files.push({ source: `${dir}/${file.name}`, raw: JSON.parse(await $.fs.read(`${dir}/${file.name}`)) })
21    } catch {
22      problems.push(`${dir}/${file.name}: not valid JSON.`)
23    }
24  }
25  return { files, problems }
26}
27
28export type LoadedConfig = {
29  languages: Languages
30  project: ProjectSettings
31  problems: string[]
32  /** The file's text as read, so a save can change only its own keys. */
33  text: string | undefined
34}
35
36/** The project's settings from `config.json`, read fresh; a file that cannot be read counts as absent. */
37export async function loadConfig($: EngineInterface): Promise<LoadedConfig> {
38  const root = await $.session.root()
39  const read = async (path: string): Promise<string | undefined> => {
40    try {
41      return (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
42    } catch {
43      return undefined
44    }
45  }
46  const text = await read(`${root}/${CONFIG_PATH}`)
47  return { ...parseConfig(text), text }
48}
49
50export type LoadedFlows = {
51  /** The project's merge and deploy settings the flows inherited. */
52  config: LoadedConfig
53  flows: Record<string, FlowDef>
54  problems: string[]
55  projectIds: Set<string>
56  /** The project's flow files as read, and their folder. */
57  files: FlowSource[]
58  dir: string
59}
60
61/**
62 * The mod's default flows, then the project's own in `<repo>/.orquestrador/flows`, which win by id;
63 * a project flow derived from another is resolved, and one that does not resolve is named in `problems`.
64 */
65export async function loadFlows($: EngineInterface): Promise<LoadedFlows> {
66  const dir = `${await $.session.root()}/.orquestrador/flows`
67  const read = await readFlowDir($, dir)
68  const config = await loadConfig($)
69  const project = resolveProjectFlows(DEFAULT_FLOWS, read.files, config.project)
70  return {
71    config,
72    files: read.files,
73    dir,
74    flows: mergeFlows(defaultFlows(), project.flows),
75    problems: [...read.problems, ...project.problems],
76    projectIds: new Set(project.flows.map(f => f.id)),
77  }
78}
79
80/**
81 * A step's agent: the project's `.orquestrador/agents/<name>.md` wins over the plugin's `agents/<name>.md`.
82 * A name that is not one (`../x`) builds no path: no agent.
83 */
84export async function findAgent($: EngineInterface, name: string): Promise<AgentFound> {
85  if (!isAgentName(name)) return undefined
86  const project = `${await $.session.root()}/.orquestrador/agents/${name}.md`
87  if (await $.fs.exists(project)) return { source: 'project', path: project }
88  const plugin = `${$.plugin.root}/agents/${name}.md`
89  return (await $.fs.exists(plugin)) ? { source: 'plugin', path: plugin } : undefined
90}
91
92/** An agent the owner can pick for a step, as its file's frontmatter says. */
93export type AgentInfo = { name: string; description: string; model: string | undefined; source: 'project' | 'plugin' }
94
95const frontmatter = (text: string): Record<string, string> => {
96  const head = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? ''
97  return Object.fromEntries(
98    head.split(/\r?\n/).flatMap(line => {
99      const at = line.indexOf(':')
100      return at <= 0 ? [] : [[line.slice(0, at).trim(), line.slice(at + 1).trim()] as const]
101    }),
102  )
103}
104
105/**
106 * The agents on offer: the plugin's `agents/*.md` and the project's `.orquestrador/agents/*.md`, by name;
107 * a project agent of the same name replaces the plugin's, as `findAgent` has it.
108 */
109export async function listAgents($: EngineInterface): Promise<AgentInfo[]> {
110  const found = new Map<string, AgentInfo>()
111  const dirs = [
112    ['plugin', `${$.plugin.root}/agents`],
113    ['project', `${await $.session.root()}/.orquestrador/agents`],
114  ] as const
115  for (const [source, dir] of dirs) {
116    if (!(await $.fs.exists(dir))) continue
117    for (const file of await $.fs.list(dir)) {
118      if (file.kind !== 'file' || !file.name.endsWith('.md')) continue
119      const name = file.name.slice(0, -3)
120      if (!isAgentName(name)) continue
121      const head = frontmatter(await $.fs.read(`${dir}/${file.name}`))
122      found.set(name, { name, source, description: head.description ?? '', model: head.model === undefined || head.model === '' ? undefined : head.model })
123    }
124  }
125  return [...found.values()].sort((a, b) => a.name.localeCompare(b.name))
126}
127