SLOPSHOPPER

hero-journey

HUD de RPG aconchegante para o Claude Code, com os caranguejos Clawd multiclasse (pt-BR e English)

panebandspinnerrowsguardcommand
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · hero-journey
│ ┃ Hero Journey ✕ › fix the failing auth test and add an audit log call │ ┃ ‹ Back │ ┃ ▄▀ 📖 Grimoire ⏺ Read(src/auth.ts) │ ┃ ▄▀▀▀ Sage ⎿ Read 6 lines │ ┃ ▄▀▀▀▀▀▄ ⟨Claude Code's own drawing⟩ 💠 Rune Caster ✓ │ ┃ ▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀ ⏺ Bash(bun test) │ ┃ ▀▀▀▀▀▄▄▀▀▀▀▀▀▀▀▀▀▄▄ ⎿ 3 pass, 1 fail │ ┃ ▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ │ ┃ ▀ ▀ ▀ ▀ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ Nothing to keep right now. 🔮 Mage · 9 actions · ✗ 1 failed · 42s │ ┃ │ ┃ vault — · AGENTS.md ✓ · ai-memory — ⚙ Me › /hero │ ┃ │ ┃ 🎒 Backpack ▰▰▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱ 49 │ ┃ 💧 Mana ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱ 69 │ ┃ 💚 Vigor ▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ │ ┃ 📖 Grimoire ⚙ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ✻ 🌱 Apprentice thinking… (0s) 🔥 Your turn Panel › ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
🔥 Your turn Panel › ⟨Claude Code's own drawing⟩
Pane · Hero Journey
‹ Back ▄▀ 📖 Grimoire ▄▀▀▀ Sage ▄▀▀▀▀▀▄ ▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▄▄▀▀▀▀▀▀▀▀▀▀▄▄ ▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ Nothing to keep right now. vault — · AGENTS.md ✓ · ai-memory — ⚙ Memory 🎒 Backpack ▰▰▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱ 49% Light 💧 Mana ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱ 69% 💚 Vigor ▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ — 📖 Grimoire ⚙
Spinner
✻ 🌱 Apprentice thinking… (0s)
Turn line
🔮 Mage · 9 actions · ✗ 1 failed · 42s
Tool row
⟨Claude Code's own drawing⟩ 💠 Rune Caster ✓
README

hero-journey 🦀

Português · English

Uma HUD de RPG aconchegante para o Claude Code desktop, com os caranguejos Clawd multiclasse. A saída do Claude não muda: a HUD só acrescenta os mascotes, o painel, a faixa e os cartões.

1.0, estável. Funciona no app desktop e no Claude Code CLI (terminal). No terminal, os Clawds são pixel art própria e cada classe tem um ícone; veja No terminal.

Instalar

Com o Claude Code (testado no motor 2.1.295):

/plugin install hero-journey --marketplace soulrocha/Claude-code-hero-journey

O mod instalado pelo terminal no escopo de usuário também carrega nas sessões do app desktop. Depois, digite /hero.

As opções da tabela de Configurações podem ficar vazias. Para respondê-las, use /plugin configure hero-journey@claude-code-hero-journey dentro do Claude Code, ou --config chave=valor no claude plugin install. A instalação pelo terminal só avisa quais opções ficaram sem valor. Na primeira vez que o painel abre, a página Primeiros passos pergunta de novo a língua, se você usa um vault (onde ele fica e qual a pasta de entrada, digitando ou pelo 📁 Escolher pasta, que abre o seletor de pastas do sistema; as pastas são conferidas antes de salvar). Com o vault salvo, 📂 Abrir a pasta das decisões abre a pasta onde o grimório deixa as decisões. O ai-memory não pede pasta: o grimório grava nele pelo MCP, quando o MCP está conectado. Sem vault, a tela recomenda o Obsidian; sem o MCP do ai-memory, recomenda o ai-memory, e com ele conectado convida a apoiar o autor. Para voltar a ela, use ⚙ → ✦ Primeiros passos.

Módulos

Cada módulo liga e desliga no ⚙ do painel → Recursos. Todos nascem ligados.

MóduloO que fazGasta tokens?
Diário de bordoEm cada ferramenta, uma linha do mod no lugar da do app (sem o trilho): o Clawd da classe com 44 px (na falha, com a pose de falha), quem agiu e o quê, e o resultado à direita em texto nativo, sem borda ("novo", +/−, tempo, "falhou"), com o ✓/✗ sempre na mesma coluna; rodando, um anel gira. Vale durante o turno: no fim, o próprio app recolhe as linhas em "Executado N ações".Não
Faixa acima do promptUma linha. Durante o turno: o Clawd da classe, quem age e o arquivo em uso, na cor da raridade (ou o resumo da ferramenta); com plano, a trilha dos passos. Parado: Sua vez, ou os subagentes "em expedição". Nunca repete a frase do chat. O spinner do turno também diz a classe ("Mago lendo art.ts"). Em alerta, o selo do recurso (🎒 Mochila 92%, 💧 Mana 8%). O Painel › abre e fecha o painel.Não
Painel (/hero)O palco no topo (a classe em ação no seu cenário, o Aprendiz pensando ou o acampamento, acordado na sua vez e dormindo depois de 5 min parado) → quem age e o arquivo → o objetivo (o título que o app dá à sessão; sem ele, ✦ Recalibrar) → só quando existem: o plano, o grupo em expedição e o inventário → presos no fim: os recursos, 📖 Grimório, 🎒 Compactar (só com a mochila pesada) e ⚙. Heróis e itens que não cabem viram "+N".Só no ✦ Recalibrar (Haiku)
CampanhaA sessão é a campanha: a 1ª mensagem dá o título e o objetivo, cada mensagem abre um capítulo, e o capítulo fecha no fim do turno com a missão (lida do formato briefing-de-bordo), os números e as falhas. Alimenta a barra do objetivo e o recibo.Não
Recibo do turnoUma linha embaixo da resposta: a classe que mais agiu, as ações, +/−, arquivos novos, falhas, bloqueios do guarda e o tempo. Com a missão cumprida sem falha, "🦀 ✦ Missão cumprida: …" abre a linha.Não
Guarda dos protegidosAntes de editar um arquivo crítico (a lista abaixo), um dragão vermelho barra o Claude: o cartão mostra o arquivo, o caminho e a mudança, e o diálogo do Claude pergunta (Aprovar, Editar no chat, Recusar). Também pergunta antes de um comando de terminal que escreveria neles (>>, sed -i, rm, Set-Content…). Dois modos no ⚙: Perguntar (padrão, vale até no modo automático) e Só avisar (uma nota no diálogo de permissão, quando ele aparece). Se algo falhar, bloqueia.Não
Mochila (e os recursos)No rodapé, uma linha por recurso. A Mochila mede o contexto até o ponto da compactação automática (estado em palavras e, no tooltip, o peso do último turno e o que ocupa espaço). Mana e Vigor mostram o que resta, a contagem até renovar a cada minuto, o ritmo e um aviso por período a 10%. A partir de 85% da mochila, ou ao clicar na Mochila do rodapé, o cartão oferece salvar o progresso e compactar: com o Claude trabalhando, leva o /compact ao prompt; parado, compacta na hora.Só ao compactar
GrimórioO Sábio guarda o progresso (a tarefa num arquivo e o handoff no ai-memory, para Continuar no acampamento), a crônica (decisões e conquistas) e as regras (AGENTS.md). Acha sem chamar o modelo; um destino por inscrição; grava só no ✦ Selar no grimório, e desfaz. Avisa no palco; acima do prompt só no fim de um marco e antes de compactar. O ⚙ Memória liga e desliga cada recurso e aviso.Só no botão opcional ✦ Resumir com Haiku

As 19 classes

Cada tipo de tarefa do Claude veste uma classe; o mapa completo, com as famílias de ferramentas, está em docs/classes.md. Cada Clawd tem a pose de trabalho e a de falha, e um cenário.

ClasseFazCenário
AprendizPensa e responde (o principal)Campo de treino; parado, o acampamento
MagoLê e busca no projeto, inclusive comandos só de leituraBiblioteca
CaçadorPesquisa na webFloresta da lua
LadinoNavega em sitesBeco
RúnicoEscreve códigoCírculo de runas
IlusionistaTelas e estiloTeatro das ilusões
SábioDocs e textos; guarda o grimórioTorre do sábio
EngenheiroComandos de terminalOficina
BruxoTestes, lint e tiposPântano
ReiCommit, PR e merge; mensagens e avisosSala do trono
ArtíficePipeline, deploy e infraForja
OráculoLogs e monitoramentoSantuário
GeomanteBanco de dados e migraçõesMuralha de pedra
AlquimistaAPIs e integrações (MCP, HTTP)Laboratório
CartomantePlanos e tarefasTenda das cartas
InvocadorChama subagentesSalão arcano
CronomanteAgenda e automatizaCâmara do tempo
PaladinoSegurança e revisãoPortal
PintorDesign visualAteliê

O que a guarda protege

Só o que, mal configurado, derruba a aplicação, o banco ou a API e quase nunca se edita à mão. A lista é curta de propósito: se tudo for protegido, o aviso perde o peso.

ProtegeGlobs
Segredos e ambientes.env, .env.*, appsettings.Production.json, appsettings.Prod.json, appsettings.Homolog*.json, appsettings.Staging.json
Pipelines e workflowsazure-pipelines*.yml, *pipeline*.yml, .github/workflows/*.yml (e .yaml)
Chaves e certificados*.pem, *.key, *.pfx, *.p12
Estado do Terraform*.tfstate, *.tfstate.backup

Nunca perguntam: os modelos .env.example, .env.sample e .env.template. Ficam de fora de propósito migrações de banco, docker-compose, package.json e configs de build, que o Claude mexe o tempo todo. Para acrescentar ou liberar, use protect e allow no /config.

Inventário: raridade pelo impacto

RaridadeArquivo
LendárioProtegido (segue a lista do guarda)
RaroCriado
IncomumModificado
PobreExcluído

O topo mostra o branch, ↑commits à frente e ● arquivos sem commit.

Configurações

Em /config (linhas do mod):

OpçãoPara quê
languageauto (padrão) segue a língua do Claude: a configuração language do Claude Code, depois o LANG do sistema, depois a sua primeira mensagem. pt-BR ou en fixam a língua.
protectGlobs extras protegidos, separados por vírgula (ex.: **/secrets.json).
allowGlobs que o guarda nunca bloqueia, além dos modelos de .env, que já vêm liberados.
vaultPathPasta do vault (ex.: C:\Notas). Vazia, o grimório não oferece os destinos do vault e da carreira.
vaultInboxSubpasta do vault onde o grimório deixa as notas novas. Escolhendo o vault pelo painel, ela vem sozinha: 00-Inbox se existir, senão Inbox (o padrão).

No ⚙ do painel (guardado entre as sessões), em duas categorias:

  • Geral: língua e estilo (Épico ou Sóbrio);
  • Recursos: cada módulo, por onde aparece (no chat, no painel, memória, proteção). Embaixo do Grimório, o ⚙ Memória › (cada recurso e aviso do grimório, os destinos, as integrações e o botão do Haiku); embaixo da Guarda, o modo.

No pé ficam Primeiros passos (a língua e o que foi detectado para a memória, sem perguntar caminho de pasta) e Sobre (os recursos, as 19 classes com o que cada uma faz ao passar o mouse, e os créditos).

Onde o grimório grava

O queDestino sugeridoOnde grava
Salvar progressoTarefa (+ ai-memory)Com vault: <vault>/.tarefas/<projeto>/<ID>.md. Sem vault: <projeto>/.hero/tarefas/<ID>.md, fora do git. Com o MCP do ai-memory, também memory_handoff_begin.
Decisão técnicaVault · decisões<vault>/<vaultInbox>/decisao-pendente-<data>-<tema>.md; sem vault, docs/decisoes/<data>-<tema>.md (a primeira pergunta antes)
Conquista com númeroVault · carreira<vault>/<vaultInbox>/resultado-pendente-<data>-<tema>.md; sem vault, docs/decisoes
Regra que você estabeleceuAGENTS.mdUma linha sob ## Regras no AGENTS.md do projeto: uma linha só, sem crase nem tag, até 280 caracteres
  • Um destino por inscrição: o clique no destino troca entre os disponíveis (vault, projeto, ai-memory).
  • Nota nunca sobrescreve nota: se o nome já existe, a nova ganha -2, -3…
  • Só sai da lista o que gravou; o resto continua pendente, com o motivo no aviso. O Desfazer tira a linha do AGENTS.md, apaga a nota nova ou a página do ai-memory, e devolve a inscrição.
  • O vault e a pasta de entrada são conferidos antes de gravar, inclusive quando vêm do /config ou do instalador: a pasta de entrada precisa ser uma subpasta do vault.
  • O ai-memory só entra com o MCP dele conectado. O servidor é achado pelo nome da ferramenta (mcp__<servidor>__memory_write_page), então funciona mesmo com o servidor renomeado.

Privacidade: se o texto cita o vault, o ai-memory ou qualquer caminho pessoal (C:\…, /home/…, /Users/…, ~/), ele não vai para o repositório (nem AGENTS.md, nem docs/decisoes).

No terminal

O terminal não desenha Svg, então a HUD usa o que ele tem:

OndeNo terminal
PalcoOs Clawds em pixel art própria (Raster de meio-bloco ▀), sem fundo; o acampamento com a fogueira. Grande (48×13 células) com o painel livre, 24×7 com plano, grupo ou inventário. Anima em dois quadros. Só no painel encaixado (tela cheia, 110+ colunas).
Faixa, diário, spinner, reciboO ícone da classe e o nome na cor dela. O diário mantém a linha do motor (o ctrl+o continua abrindo o resultado). O recibo entra no lugar do "Baked for 3s".
RecursosUma linha por recurso com barra em texto; em alerta, também no fim da linha de dicas do prompt.
Guarda🐉, o arquivo e até 4 linhas da mudança (o motor só aceita 12 linhas em volta do diálogo).
Grimório, Primeiros passos, SobreO Sábio, o acampamento e dois Clawds em pixel art; as 19 classes em lista com ícone.

Limites conhecidos

  • Guarda e terminal: o guarda pergunta sempre que um comando cita um caminho protegido, salvo leituras conhecidas (cat, Get-Content, grep…). Por isso git add .env também pergunta. Um script que monta o caminho por dentro, sem citá-lo, passa. O modo Só o diálogo nativo apenas avisa no diálogo de permissão do Claude; se as edições estiverem liberadas automaticamente, nada pergunta.
  • Terminal: sem o painel encaixado (tela cheia) não há palco. O spinner é desenhado pelo mod, que conta o tempo, e não mostra os tokens. Os ícones das classes são emoji: num terminal sem emoji coloridos, aparecem como símbolos.
  • Mobile: o app móvel não tem campo de texto para mods. Lá, os Primeiros passos só mostram o que foi detectado; para escolher a pasta do vault, use o desktop.
  • Seletor de pasta: a API de mods não tem diálogo de pasta. O mod abre o do sistema (PowerShell no Windows, osascript no macOS, zenity ou kdialog no Linux); onde nenhum abre, a tela avisa e mostra um campo para digitar o caminho.
  • Recibo do turno: o motor desenha embaixo da resposta o texto que o hook do fim do turno devolve; a aparência dessa linha no app desktop ainda precisa ser conferida.
  • Barra lateral nativa: a API de mods não a alcança (não é um componente que o mod redesenha, e não há chamada para renomear ou agrupar sessões).
  • Diário no fim do turno: o app desktop recolhe as linhas de ferramenta em "Executado N ações" quando o turno termina, e nenhum grupo dele chega ao mod. O diário só aparece durante o turno; o recibo fica.
  • Linha do diário: para tirar o trilho do app, o mod desenha a linha inteira da ferramenta. Ainda falta confirmar no app que o clique para abrir o resultado continua funcionando.
  • Tema automático: com o tema do Claude em automático, o mod não sabe se o app está claro ou escuro. Os Svgs usam a paleta escura e o painel fica sem o tom quente.
  • Ainda não verificado no app real (depende do spike, mods/clawd-hud-spike):
  • a animação do Svg no desktop;
  • se um grupo recolhido não deixa linha vazia;
  • o rodapé fixo;
  • o prompt.fill no desktop;
  • a leitura do tema;
  • o dragão acima do diálogo;
  • a descrição das opções do diálogo.

Agradecimentos

O código desta HUD é próprio. Alguns padrões vieram dos mods do claude-code-templates, de Daniel (San) Ávila, sob licença MIT (aviso em THIRD_PARTY_NOTICES.md). Cada módulo cita de onde veio o padrão.

Mod de origemO que veio deleOnde está aqui
protected-paths-guardGlobs, o globToRegExp e o .catch que falha fechadomodules/guarda
large-edit-confirmationO $.ui.ask dentro do tool.call, o "Outro" não aprovar e negar sem ninguémmodules/guarda
tool-timing-badgeEmbrulhar o ToolUse e medir o tempomodules/diario
agent-flowAcompanhar subagentes pelo agent.spawnmodules/painel (Grupo)
git-sidebarGit por argv, sem shellmodules/painel (Inventário)
session-time-machineA linha do tempo da sessãomodules/campanha

O recibo do turno se baseia no recibo do Flightdeck, de scasella, e os recursos, no token-weather (Anthropic) e nos usage-meter e context-bar, de hamzafer.

Mods de outros autores que combinam com a HUD

Estes não fazem parte da HUD: instale direto do repositório de quem fez, depois de ler o código.

ModPara quêComo instalar
secret-redactorEsconde segredosnpx claude-code-templates --mod security/secret-redactor
prompt-cache-controlMede o cachenpx claude-code-templates --mod observability/prompt-cache-control
rulebook-guard, blast-radius / Launch Codes, session-saver, md-previewAdotados no handoffLinks a confirmar

Não instale o protected-paths-guard junto com o guarda da HUD: ele nega direto, e a HUD pergunta.

Desenvolvimento

claude plugin validate mods/hero-journey
claude plugin test mods/hero-journey
# ou tudo de uma vez: scripts/verificar.ps1 (Windows) / scripts/verificar.sh

Estrutura:

CaminhoConteúdo
hooks/register.tsxLiga os módulos aos eventos. Todo o código que usa $ fica aqui: o motor recusa o $ passado para uma função importada (conferido no 2.1.295).
hooks/core/A arte em Svg (os Clawds das 19 classes em sprites.ts, os cenários do palco em cenarios.ts e o resto em art.ts), textos pt/en, classes, preferências, pastas do sistema e o que todas as telas usam
hooks/modules/<módulo>/A lógica (<módulo>.ts, pura) e a tela (view.tsx) de cada módulo
tests/145 testes no motor, em desktop e terminal, incluindo as regressões dos QAs e da revisão do PR

English

A cozy RPG HUD for the Claude Code desktop app, with the multiclass Clawd crabs. Claude's output stays the same.

1.0, stable. Works in the desktop app and in the Claude Code CLI (terminal). In the terminal the Clawds are purpose-made pixel art (no background, animated stage in the docked pane), each class has an icon in the band, logbook, spinner and receipt, and the guard shows 🐉 within the 12 rows the engine allows around the dialog.

Install (tested on engine 2.1.295): /plugin install hero-journey --marketplace soulrocha/Claude-code-hero-journey, then type /hero.

Modules (each one toggles in the pane's ⚙ → Features):

ModuleWhat it doesSpends tokens?
LogbookOn every tool row, during the turn: the class Clawd up front (failure pose when something fails), who acted and on what, and the result on the right as plain text, with the ✓/✗ always in the same columnNo
Band above the promptOne line: the class Clawd, who acts and the file in use, and the plan trail; Your turn when idle; never the chat sentence. The turn spinner names the class too. Panel › opens the paneNo
PaneThe stage on top (the class at work in its scene, the Apprentice thinking or the camp), the objective, and only when they exist the plan, party and inventory; resources and buttons pinned to the bottomOnly on ✦ Recalibrate (Haiku)
CampaignObjective and chapters that feed the objective bar and the receiptNo
Turn receiptOne line under the answer: who acted, actions, +/−, new files, failures and timeNo
Protected-file guardA red dragon stops Claude before it edits a critical file (.env, pipelines and workflows, production and staging appsettings, keys, certificates, Terraform state) or runs a command that writes one, shows the change and asks. Ask or Only warn mode. The .env templates are never blocked. Fails closed.No
Backpack (and resources)Backpack against the auto-compaction point, its state, and (in the tooltip) last-turn weight and what fills it; Mana and Vigor with what is left, a live countdown, pace and a warning at 10%; the compaction card, also opened by clicking the Backpack, offers to save progress firstOnly when compacting
GrimoireSave progress (task file plus ai-memory handoff) and Continue at camp; decisions and achievements to the chronicle; rules to AGENTS.md. One destination each, written only on Seal, undoable; ⚙ Memory toggles each feature and promptOnly through the optional Summarize with Haiku button

Classes: 19, one per kind of Claude task (Apprentice, Mage, Hunter, Rogue, Rune Caster, Illusionist, Sage, Engineer, Witcher, King, Artificer, Oracle, Geomancer, Alchemist, Cartomancer, Summoner, Chronomancer, Paladin, Painter), each with a work pose, a failure pose and its own scene.

Language: auto follows Claude's language. Pin pt-BR or en in /config or in the pane's ⚙.

Credits: some code patterns come from Daniel (San) Ávila's claude-code-templates mods (MIT). The details are in the Agradecimentos section above and in each module's header.

Licença / License

MIT © 2026 Saulo Rocha. Os trechos adaptados mantêm o aviso em THIRD_PARTY_NOTICES.md.

Source 30 files
hooks/register.tsx 1996 lines
1// hero-journey: a HUD de RPG do Claude Code.
2//
3// Liga os módulos de hooks/modules/ aos eventos do motor. Cada módulo tem a sua
4// seção aqui e liga ou desliga no ⚙ (prefs.modules); a lógica e as telas ficam
5// na pasta do módulo. Tudo o que usa `$` mora neste arquivo, porque o motor não
6// segue o `$` através de um import.
7//
8// Gasto de tokens: só o "Compactar agora" da mochila, o ✦ Recalibrar objetivo e
9// o Haiku do grimório (desligado por padrão), e os três só com o clique da pessoa.
10//
11// Créditos dos padrões de código: Daniel Ávila (claude-code-templates, MIT),
12// citado em cada módulo e no README.
13
14import { atom, read, update } from 'claude-code'
15import type { EngineInterface, Register, RenderElement, RenderInput } from 'claude-code'
16
17import type { Campaign, Card, Cls, DiaryEntry, GuardFile, Inscription, Item, Lang, Member, ModuleId, Palette, Prefs, Progress, Written } from '../types'
18import { agentClass, baseName, classOf, delivers, patchStats, summaryOf } from './core/classes'
19import { classColor, TONE } from './core/art'
20import { DICT, looksPortuguese, resolveLang } from './core/i18n'
21import { isWindows, joinPath, openArgv, pickArgvs, pickedOf } from './core/pasta'
22import { DEFAULT_MEMORY, DEFAULT_PREFS, isOn, migratePrefs, toggleMemory, toggleModule } from './core/prefs'
23import type { Ctx } from './core/ui'
24import { assignTurn, buildReport, chapterOf, closeChapter, cutAtWord, goalOf, onPrompt, prune, storeKey } from './modules/campanha/campanha'
25import { rowView } from './modules/diario/view'
26import { bandView } from './modules/faixa/view'
27import { appendDecision, available, continuePrompt, cycleDest, detect, haikuPrompt, isPending, isSubfolder, kindOn, memoryTool, merge, nextTaskId, parseMarker, parseTask, pending, progressHome, projectFromRemote, projectName, removeLine, safeName, sameNote, saveTask, shareablePath, suggest, taskPrefix, taskText, withSuffix, withTimeout, writesFor, writtenOf } from './modules/grimorio/grimorio'
28import type { Dests, Memory, MemoryScope, Write } from './modules/grimorio/grimorio'
29import { grimPage, marcoCard } from './modules/grimorio/view'
30import { diffOf, LABELS, listOption, makeGuard, shellTargets, verdictOf } from './modules/guarda/guarda'
31import { guardView } from './modules/guarda/view'
32import { COMPACT_AT, compactInstruction, shouldWarn } from './modules/mochila/mochila'
33import { alertOf, bagOf, countdown, readingOf, warningsOf } from './modules/mochila/recursos'
34import type { UsageReading } from './modules/mochila/recursos'
35import { compactCard } from './modules/mochila/view'
36import { EMPTY_INVENTORY, LOG_ARGV, NUMSTAT_ARGV, parseInventory, parseLog, questsFromTodos, STATUS_ARGV, upsertMember } from './modules/painel/painel'
37import { setupView } from './modules/painel/primeiros-passos'
38import { aboutView, configView, footer, mainView, memoryView, stageLook } from './modules/painel/view'
39import { DIFF_MAX_BYTES, DIFF_MAX_READ, DIFF_MAX_SHOWN, diffArgv, parseDiff, untrackedDiff } from './modules/painel/diff'
40import type { ParsedDiff } from './modules/painel/diff'
41import { diffView } from './modules/painel/diff-view'
42import { rasterOfPixels } from './core/raster'
43import { TH, TW, tsprite } from './core/tsprites'
44import { layoutOf, NAP_MS, sceneOf } from './modules/painel/palco'
45import { leadOf, receiptOf, receiptParts } from './modules/recibo/recibo'
46import { CLASS_ICON } from './core/tsprites'
47
48const PANE = 'hero-journey'
49const PANE_TITLE = 'Hero Journey'
50// `Task` é o nome antigo da ferramenta Agent.
51const AGENT = /^(Agent|Task)$/
52const WRITES = /^(Edit|Write|NotebookEdit)$/
53const CARD_ORDER: readonly Card[] = ['marco', 'compactar']
54const AI_MEMORY_URL = 'https://github.com/akitaonrails/ai-memory'
55
56const lang = atom({ plugin: 'hero-journey', key: 'lang' } as const, 'en')
57const theme = atom({ plugin: 'hero-journey', key: 'theme' } as const, 'dark')
58const turnId = atom({ plugin: 'hero-journey', key: 'turnId' } as const, '')
59const diary = atom({ plugin: 'hero-journey', key: 'diary' } as const, [])
60const quests = atom({ plugin: 'hero-journey', key: 'quests' } as const, [])
61const party = atom({ plugin: 'hero-journey', key: 'party' } as const, [])
62const inventory = atom({ plugin: 'hero-journey', key: 'inventory' } as const, EMPTY_INVENTORY)
63const prefs = atom({ plugin: 'hero-journey', key: 'prefs' } as const, DEFAULT_PREFS)
64const working = atom({ plugin: 'hero-journey', key: 'working' } as const, null)
65const cards = atom({ plugin: 'hero-journey', key: 'cards' } as const, [])
66const view = atom({ plugin: 'hero-journey', key: 'view' } as const, 'main')
67const campaign = atom({ plugin: 'hero-journey', key: 'campaign' } as const, null)
68const guard = atom({ plugin: 'hero-journey', key: 'guard' } as const, [])
69const refusals = atom({ plugin: 'hero-journey', key: 'refusals' } as const, [])
70const inscriptions = atom({ plugin: 'hero-journey', key: 'inscriptions' } as const, [])
71const turn = atom({ plugin: 'hero-journey', key: 'turn' } as const, { busy: false })
72const progress = atom({ plugin: 'hero-journey', key: 'progress' } as const, { list: [] })
73const remembered = atom({ plugin: 'hero-journey', key: 'remembered' } as const, [])
74const setup = atom({ plugin: 'hero-journey', key: 'setup' } as const, {})
75const resources = atom({ plugin: 'hero-journey', key: 'resources' } as const, null)
76const tick = atom({ plugin: 'hero-journey', key: 'tick' } as const, 0)
77const warned = atom({ plugin: 'hero-journey', key: 'warned' } as const, {})
78
79const paletteOf = (value: string): Palette => (/light/i.test(value) ? 'claro' : 'escuro')
80
81/** A língua fixada na opção vale na hora; em `auto`, a que o session.start resolveu. */
82const pinned = (option: string): Lang | undefined => (option === 'pt-BR' ? 'pt' : option === 'en' ? 'en' : undefined)
83
84// As opções do mod (lidas a cada carga do módulo) e o que a sessão já disse.
85let langOption = 'auto'
86let isGuarded = makeGuard()
87let paths = { vault: '', inbox: 'Inbox' }
88// A língua da primeira mensagem só decide quando nada mais disse qual é.
89let langFromPrompt = false
90// Sem ninguém para responder (claude -p), o guarda nega.
91let interactive = true
92// O texto que abriu cada turno, para o grimório achar as preferências da pessoa.
93const turnPrompts = new Map<string, string>()
94// O cartão de compactar entra uma vez por subida da mochila acima do limite.
95let bagWarned = false
96// O relógio da contagem do reset: um só, mesmo que o session.start rode de novo.
97let clock: { cancel: () => void } | undefined
98/** O palco do terminal desenhado agora (o relógio da animação repinta só ele), e o quadro. */
99let stageNow: ReturnType<typeof stageLook>
100let stageFrame: 0 | 1 = 0
101let anim: { cancel: () => void } | undefined
102/** O spinner do terminal é do mod: com o turno rodando, o relógio o redesenha a cada segundo. */
103let spinOnTerminal = false
104// Um Selar por vez: o segundo clique avisa que está gravando; destrava após 60s se algo pendurou.
105// O Selar inteiro tem prazo menor que a trava, para nunca haver duas execuções ao mesmo tempo.
106const SEAL_TIMEOUT_MS = 15_000
107const SEAL_TOTAL_MS = 45_000
108const SEAL_LOCK_MS = 60_000
109let sealingAt = 0
110/** Só mensagem da pessoa abre campanha: subagente, gatilho agendado ou outra sessão não. */
111const isFromPerson = (e: unknown): boolean => {
112  const { origin, agentId } = e as { origin?: { kind?: string }; agentId?: string }
113  const kind = origin?.kind
114  return agentId === undefined && (kind === undefined || kind === 'composer' || kind === 'bridge' || kind === 'user')
115}
116// Por que o último "Salvar e compactar" não salvou; o cartão mostra e oferece compactar assim mesmo.
117let saveFailed: string | undefined
118// O "Verificar" que a pessoa digita no cartão de compactar, até salvar o progresso.
119let verifyDraft = ''
120// Os avisos do Sábio que a pessoa dispensou: o do turno (pelo turnId) e o de antes de dormir (pela hora).
121let notedDismissed = ''
122let saveDismissedAt = 0
123// O marco do último fim de turno (nome e detalhe do cartão) e o plano já celebrado (para não repetir).
124let marcoInfo = { name: '', sub: '' }
125/** O último recibo, que o terminal desenha no lugar da linha de duração do turno: a classe que mais agiu e as peças. */
126let lastReceipt: { lead?: Cls; head: string; parts: string[] } | undefined
127/** O giro do spinner do terminal, um passo por redesenho. */
128const SPIN = ['✻', '✳', '✢', '·', '✢', '✳']
129/** Quando o turno começou, para o tempo do spinner desenhado pelo mod no terminal. */
130let turnStartedAt = 0
131let planCelebrated = ''
132// O texto da tarefa antes do último salvar, para o Desfazer voltar a ele.
133// Quantas notas a memória automática do Claude tem neste projeto (sem ai-memory), e onde.
134let autoNotes: { n: number; dir: string } | undefined
135// O item do inventário e o diff lido para a página de diff do painel.
136let diffPath: string | undefined
137let diffCached: { path: string; diff: ParsedDiff | string } | undefined
138
139// ---------- Ajudantes (usam `$`: o validador quer funções no topo do arquivo) ----------
140
141async function langNow($: EngineInterface): Promise<Lang> {
142  return pinned(langOption) ?? (await read($, lang))
143}
144
145async function prefsNow($: EngineInterface): Promise<Prefs> {
146  return read($, prefs)
147}
148
149async function moduleOn($: EngineInterface, id: ModuleId) {
150  return isOn(await prefsNow($), id)
151}
152
153async function ctxOf($: EngineInterface, surface: string, width: number, inline = false): Promise<Omit<Ctx, 'ui'>> {
154  const p = await prefsNow($)
155  const themeValue = await read($, theme)
156  const palette = paletteOf(themeValue)
157  return {
158    desktop: surface === 'desktop',
159    inline,
160    t: DICT[await langNow($)],
161    palette,
162    skin: p.skin,
163    width,
164    bg: /dark|light/i.test(themeValue) ? TONE[palette].pane : undefined,
165  }
166}
167
168async function refreshTheme($: EngineInterface) {
169  const row = (await $.config.list().catch(() => [])).find(r => r.key === 'theme')
170  await update($, theme, () => (row === undefined ? 'dark' : String(row.value)))
171}
172
173async function refreshInventory($: EngineInterface) {
174  try {
175    const status = await $.process.run([...STATUS_ARGV], { timeoutMs: 5000 })
176    if (status.exitCode !== 0) {
177      await update($, inventory, () => EMPTY_INVENTORY)
178      return
179    }
180    const numstat = await $.process.run([...NUMSTAT_ARGV], { timeoutMs: 5000 })
181    const log = await $.process.run([...LOG_ARGV], { timeoutMs: 5000 }).catch(() => undefined)
182    const inv = parseInventory(status.stdout, numstat.exitCode === 0 ? numstat.stdout : '', isGuarded)
183    await update($, inventory, () => ({ ...inv, recent: log?.exitCode === 0 ? parseLog(log.stdout) : [] }))
184    // O diff aberto fica velho quando o inventário muda: relê no próximo desenho, ou volta se o item saiu.
185    diffCached = undefined
186    if (diffPath !== undefined && !inv.items.some(i => i.path === diffPath) && (await read($, view)) === 'diff') {
187      await update($, view, () => 'main' as const)
188    }
189  } catch {
190    await update($, inventory, () => EMPTY_INVENTORY)
191  }
192}
193
194async function loadDiff($: EngineInterface, item: Item): Promise<ParsedDiff | string> {
195  const t = DICT[await langNow($)]
196  // O git status dá o caminho a partir da raiz do repositório, não da pasta da sessão.
197  const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 5000 }).catch(() => undefined)
198  const root = top?.exitCode === 0 && top.stdout.trim() !== '' ? top.stdout.trim() : undefined
199  const full = root === undefined ? item.path : joinPath(root, item.path)
200  if (item.code === '??') {
201    const stat = await $.fs.stat(full).catch(() => undefined)
202    const isDir = item.path.endsWith('/') || item.path.endsWith('\\') || stat?.kind === 'dir'
203    if (isDir) {
204      return {
205        lines: [],
206        added: 0,
207        removed: 0,
208        binary: false,
209        isNew: false,
210        isDeleted: false,
211        more: 0,
212        directory: true,
213      }
214    }
215    const size = (stat as { size?: number } | undefined)?.size
216    if (size !== undefined && size > DIFF_MAX_BYTES) return t.diffTooBig(Math.round(size / 1024))
217    try {
218      const content = await $.fs.read(full)
219      return untrackedDiff(content, DIFF_MAX_SHOWN, DIFF_MAX_READ)
220    } catch (err) {
221      return t.diffReadError(err instanceof Error ? err.message : String(err))
222    }
223  }
224
225  try {
226    const res = await $.process.run([...diffArgv(item.path, root)], { timeoutMs: 5000 })
227    if (res.exitCode !== 0) {
228      return t.diffReadError(res.stderr.trim() || `exit ${res.exitCode}`)
229    }
230    return parseDiff(res.stdout, DIFF_MAX_SHOWN, DIFF_MAX_READ)
231  } catch (err) {
232    return t.diffReadError(err instanceof Error ? err.message : String(err))
233  }
234}
235
236async function openDiff($: EngineInterface, path: string) {
237  diffPath = path
238  const inv = await read($, inventory)
239  const item = inv.items.find(i => i.path === path) ?? { path, rarity: 'comum' as const, code: ' M' }
240  const diff = await loadDiff($, item)
241  diffCached = { path, diff }
242  await update($, view, () => 'diff' as const)
243}
244
245/** Lê o $.store na hora de gravar: outra sessão aberta pode ter mudado as preferências. */
246async function savePrefs($: EngineInterface, change: (p: Prefs) => Prefs) {
247  const stored = await $.store.get('prefs')
248  const next = change(stored === undefined ? await read($, prefs) : migratePrefs(stored))
249  await update($, prefs, () => next)
250  await $.store.set('prefs', next)
251}
252
253async function pushCard($: EngineInterface, card: Card) {
254  if (card === 'compactar') saveFailed = undefined
255  await update($, cards, list =>
256    list.includes(card) ? list : [...list, card].sort((a, b) => CARD_ORDER.indexOf(a) - CARD_ORDER.indexOf(b)),
257  )
258}
259
260async function dropCard($: EngineInterface, card: Card) {
261  if (card === 'compactar') saveFailed = undefined
262  await update($, cards, list => list.filter(c => c !== card))
263}
264
265/** Leva o texto ao prompt; onde não há caixa, copia. */
266async function fillOrCopy($: EngineInterface, text: string) {
267  const t = DICT[await langNow($)]
268  const r = await $.prompt.fill({ text })
269  if (r.isFilled) {
270    $.ui.toast(t.filled)
271    return true
272  }
273  await $.ui.copy({ text })
274  $.ui.toast(t.noComposer)
275  return false
276}
277
278/**
279 * Lê os recursos do motor. Com `detailed`, pede também o detalhamento (estimado
280 * localmente, sem tokens), que traz o ponto de compactação e o que ocupa a mochila.
281 */
282async function readResources($: EngineInterface, detailed: boolean, turnEnded: boolean) {
283  try {
284    const u = detailed ? await $.session.usage({ breakdown: 'summary' }) : await $.session.usage()
285    await takeReading($, u as unknown as UsageReading, turnEnded)
286  } catch {
287    // Sem leitura agora: o rodapé fica com a última.
288  }
289}
290
291/** Guarda a leitura, avisa a janela que ficou crítica e põe o cartão de compactar quando a mochila pesa. */
292async function takeReading($: EngineInterface, u: UsageReading, turnEnded: boolean) {
293  const prev = await read($, resources)
294  const next = readingOf(u, prev, turnEnded)
295  await update($, resources, () => next)
296  // Uma queda brusca da mochila é uma compactação (a automática também): o cartão
297  // que pedia para compactar sai, se ela ficou abaixo do limite.
298  const emptied = prev?.tokens !== undefined && next.tokens !== undefined && next.tokens < prev.tokens * 0.6
299  if (emptied && (bagOf(next).percent ?? 0) < COMPACT_AT) await dropCard($, 'compactar')
300  const t = DICT[await langNow($)]
301  const before = await read($, warned)
302  const w = warningsOf(next.windows, before, Date.now())
303  if (JSON.stringify(w.warned) !== JSON.stringify(before)) await update($, warned, () => w.warned)
304  for (const f of w.fire) {
305    const name = f.kind === 'seven_day' ? t.footer.vigor : t.footer.mana
306    $.ui.toast(t.windowWarn(name, Math.round(f.left), f.resetIn === undefined ? '' : countdown(f.resetIn)))
307  }
308  if (await moduleOn($, 'mochila')) {
309    const step = shouldWarn(bagOf(next).percent ?? 0, bagWarned)
310    if (step === 'warn') {
311      bagWarned = true
312      await pushCard($, 'compactar')
313    } else if (step === 'reset') bagWarned = false
314  }
315}
316
317/**
318 * A campanha é acompanhada sempre (a faixa e o recibo leem dela); o módulo
319 * campanha decide se ela fica guardada no $.store.
320 */
321async function saveCampaign($: EngineInterface, c: Campaign) {
322  await update($, campaign, () => c)
323  if (await moduleOn($, 'campanha')) await $.store.set(storeKey(c.id), c)
324}
325
326async function compactNow($: EngineInterface) {
327  const t = DICT[await langNow($)]
328  const w = await read($, working)
329  const tr = await read($, turn)
330  if (w !== null) {
331    if (tr.busy && (w.at === undefined || Date.now() - w.at <= 600_000)) {
332      $.ui.toast(t.compactBusy)
333      return
334    }
335    await update($, working, () => null)
336  }
337  try {
338    const r = await $.session.compact({ instructions: compactInstruction(await langNow($), await read($, campaign), await read($, quests)) })
339    if ('skip' in r) {
340      $.ui.toast(t.compactSkipped)
341      return
342    }
343    await dropCard($, 'compactar')
344    const k = (n: number | undefined) => (n === undefined ? '—' : `${Math.round(n / 1000)}k`)
345    $.ui.toast(t.compactDone(k(r.tokensBefore), k(r.tokensAfter)))
346    await readResources($, true, false)
347  } catch (err) {
348    $.ui.toast(t.compactFailed(err instanceof Error ? err.message : String(err)))
349  }
350}
351
352/**
353 * Para onde o grimório pode gravar agora: a pasta do vault e o ai-memory, se o MCP dele estiver conectado.
354 * Se a lista de ferramentas falhar, o ai-memory fica fora; `warn` (só nas ações da pessoa, nunca no
355 * desenho) diz o motivo num toast em vez de calar.
356 */
357async function grimDests($: EngineInterface, warn = false): Promise<Dests> {
358  const tools = await withTimeout($.tool.list(), SEAL_TIMEOUT_MS, 'tool.list').catch(async err => {
359    if (warn) $.ui.toast(DICT[await langNow($)].toolsFailed(err instanceof Error ? err.message : String(err)))
360    return []
361  })
362  return { vault: paths.vault, inbox: paths.inbox, memory: memoryTool(tools) }
363}
364
365let scopeCache: { cwd: string; scope: MemoryScope } | undefined
366
367/**
368 * O workspace e o projeto do ai-memory, como os clientes sem hooks devem achar:
369 * o `.ai-memory.toml` mais próximo (subindo da pasta da sessão), depois o da pasta
370 * do usuário; o projeto, sem marcador, sai do remoto (upstream, senão origin) e, sem
371 * remoto, do nome da pasta. Lido uma vez por pasta.
372 */
373async function memoryScope($: EngineInterface): Promise<MemoryScope> {
374  const cwd = await $.session.cwd()
375  if (scopeCache?.cwd === cwd) return scopeCache.scope
376  const readMarker = async (dir: string) => {
377    const file = joinPath(dir, '.ai-memory.toml')
378    return (await $.fs.exists(file).catch(() => false)) ? parseMarker(await $.fs.read(file).catch(() => '')) : undefined
379  }
380  let near: Partial<MemoryScope> | undefined
381  for (let dir = cwd, i = 0; i < 12 && near === undefined; i++) {
382    near = await readMarker(dir)
383    const up = dir.replace(/[\\/][^\\/]+[\\/]?$/, '')
384    if (up === dir || up === '' || /^[A-Za-z]:$/.test(up)) break
385    dir = up
386  }
387  const home = (await $.env.get('USERPROFILE').catch(() => undefined)) ?? (await $.env.get('HOME').catch(() => undefined))
388  const user = home === undefined ? undefined : await readMarker(home)
389  let project = near?.project
390  for (const remote of ['upstream', 'origin']) {
391    if (project !== undefined) break
392    const r = await $.process.run(['git', 'remote', 'get-url', remote], { timeoutMs: 5000 }).catch(() => undefined)
393    const name = r?.exitCode === 0 ? projectFromRemote(r.stdout) : ''
394    if (name !== '') project = name
395  }
396  const scope = { workspace: near?.workspace ?? user?.workspace ?? 'default', project: project ?? (safeName(projectName(cwd)) || 'default') }
397  scopeCache = { cwd, scope }
398  return scope
399}
400
401/** Uma chamada ao ai-memory com o escopo desta pasta: sem ele, as leituras falham e as escritas vão para o projeto padrão. */
402async function memoryCall($: EngineInterface, memory: { server: string }, tool: string, args: Record<string, unknown>) {
403  return withTimeout($.mcp.call(memory.server, tool, { ...(await memoryScope($)), ...args }), SEAL_TIMEOUT_MS, tool)
404}
405
406/** Grava o arquivo e, se a pasta-pai ainda não existir, cria a pasta e tenta de novo. */
407async function writeFileEnsuringDir($: EngineInterface, filePath: string, content: string) {
408  try {
409    await $.fs.write(filePath, content)
410  } catch {
411    const dir = filePath.replace(/[\\/][^\\/]+$/, '')
412    if (dir !== '' && dir !== filePath) {
413      const argv = (await onWindows($))
414        ? ['powershell', '-NoProfile', '-NonInteractive', '-Command', 'New-Item -ItemType Directory -Force -Path $env:HJ_DIR | Out-Null']
415        : ['mkdir', '-p', dir]
416      await $.process.run(argv, { timeoutMs: 10_000, env: { HJ_DIR: dir } }).catch(() => undefined)
417    }
418    await $.fs.write(filePath, content)
419  }
420}
421
422/**
423 * Grava uma inscrição num destino e devolve onde, ou `undefined` quando não havia
424 * nada a gravar (a regra já estava no AGENTS.md): aí o Desfazer não tem o que tirar,
425 * e tirar apagaria a linha que já existia. Nota nova nunca sobrescreve outra: ganha -2, -3…
426 */
427async function writeOne($: EngineInterface, w: Write, memory: Memory | undefined, used: Set<string>, heading: string): Promise<string | undefined> {
428  if (w.dest === 'aiMemory') {
429    let p = w.path
430    for (let n = 2; used.has(p); n++) p = withSuffix(w.path, n)
431    used.add(p)
432    const r = await memoryCall($, memory!, 'memory_write_page', { path: p, body: w.text })
433    if (r.isError) throw new Error(r.content.map(c => ('text' in c ? String(c.text) : '')).join(' ').slice(0, 200))
434    return p
435  }
436  if (w.append) {
437    const current = (await $.fs.exists(w.path)) ? await $.fs.read(w.path) : ''
438    const next = appendDecision(current, w.text, heading)
439    if (next === current) return undefined
440    await writeFileEnsuringDir($, w.path, next)
441    return w.path
442  }
443  // ponytail: exists→write não é atômico; duas sessões selando no mesmo instante podem colidir.
444  let p = w.path
445  for (let n = 2; used.has(p) || (await $.fs.exists(p)); n++) {
446    if (!used.has(p) && sameNote(await $.fs.read(p).catch(() => undefined), w.text)) {
447      used.add(p)
448      return p
449    }
450    p = withSuffix(w.path, n)
451  }
452  used.add(p)
453  await writeFileEnsuringDir($, p, w.text)
454  return p
455}
456
457/**
458 * Grava as inscrições pendentes no destino de cada uma. Nada sai daqui sem o
459 * clique em Selar. Uma inscrição só sai da lista quando gravou; se o destino
460 * falhou ou sumiu, ela continua pendente para o próximo Selar tentar de novo.
461 */
462async function seal($: EngineInterface) {
463  // Dois cliques seguidos não gravam duas vezes; destrava após 60s se algo pendurou.
464  const startedAt = Date.now()
465  if (sealingAt > 0 && startedAt - sealingAt < SEAL_LOCK_MS) {
466    $.ui.toast(DICT[await langNow($)].grimBusy)
467    return
468  }
469  sealingAt = startedAt
470  // Limite conhecido: o prazo não cancela uma gravação já em voo; ela pode concluir depois dele
471  // (a inscrição é marcada uma vez só e o Selar seguinte não duplica no vault).
472  const run = { aborted: false, done: 0 }
473  try {
474    // O prazo corre no relógio do motor ($.clock), que o teste avança sem esperar.
475    const job = sealRun($, run)
476    job.catch(() => undefined)
477    const late = Symbol('prazo')
478    const deadline = $.clock.sleep(SEAL_TOTAL_MS).then(
479      () => late,
480      () => new Promise<never>(() => {}),
481    )
482    if ((await Promise.race([job, deadline])) === late) throw new Error(`seal: timeout (${SEAL_TOTAL_MS / 1000}s)`)
483  } catch (err) {
484    run.aborted = true
485    const t = DICT[await langNow($)]
486    // O que já foi gravado até aqui vale: mostra a contagem real, depois a falha.
487    if (run.done > 0) $.ui.toast(t.sealed(run.done))
488    $.ui.toast(t.notSealed(0, err instanceof Error ? err.message : String(err)))
489  } finally {
490    // Só solta a trava se ela ainda é desta execução.
491    if (sealingAt === startedAt) sealingAt = 0
492  }
493}
494
495async function sealRun($: EngineInterface, run: { aborted: boolean; done: number }) {
496  const t = DICT[await langNow($)]
497  // Inscrição sem destino fica onde está, sem aviso de falha: falta a pessoa dizer onde guardar.
498  const list = pending(await read($, inscriptions)).filter(i => i.destinations.length > 0)
499  if (list.length === 0) {
500    if (pending(await read($, inscriptions)).length > 0) $.ui.toast(t.grimNoneMarked)
501    return
502  }
503  const repo = await $.session.cwd()
504  const found = await grimDests($, true)
505  // O vault e a pasta de entrada podem vir do /config sem passar pelos Primeiros passos:
506  // confere antes de gravar. Uma pasta de entrada que sai do vault desliga o destino.
507  const inbox = found.inbox ?? 'Inbox'
508  let vault = ''
509  if (found.vault !== '' && !isSubfolder(inbox)) $.ui.toast(t.inboxInvalid(inbox))
510  else if (found.vault !== '') vault = (await checkedFolder($, found.vault)) ?? ''
511  const dests = { ...found, vault }
512  const used = new Set<string>()
513  const missed: string[] = []
514  const sealed: Record<string, { ok: Inscription['destinations']; written: Written[]; full: boolean }> = {}
515  for (const i of list) {
516    const writes = writesFor(i, { repo, ...dests }, Date.now())
517    const rem = i.destinations.filter(d => !(i.sealed ?? []).includes(d))
518    // A regra de privacidade barrou (o texto cita o vault ou um caminho pessoal): avisa, e a inscrição fica.
519    if (writes.length === 0 && rem.length > 0 && rem.every(d => available(d, dests))) $.ui.toast(t.privacyBlocked)
520    const written: Written[] = []
521    const ok: Inscription['destinations'] = []
522    for (const w of writes) {
523      try {
524        if (run.aborted) throw new Error('prazo esgotado')
525        const at = await writeOne($, w, dests.memory, used, t.rulesHeading)
526        ok.push(w.dest)
527        if (at !== undefined) written.push(writtenOf(w, at))
528      } catch (err) {
529        missed.push(`${t.dest[w.dest]}: ${err instanceof Error ? err.message : String(err)}`)
530      }
531    }
532    if (ok.length > 0) {
533      const full = ok.length === writes.length && writes.length === rem.length
534      sealed[i.id] = { ok, written, full }
535      // Marca já, inscrição a inscrição: o que foi gravado não depende de o Selar chegar ao fim.
536      await update($, inscriptions, all =>
537        all.map((x): Inscription => {
538          if (x.id !== i.id) return x
539          const had = x.written ?? []
540          return {
541            ...x,
542            sealed: [...new Set([...(x.sealed ?? []), ...ok])],
543            written: [...had, ...written.filter(n => !had.some(h => h.dest === n.dest && h.path === n.path))],
544          }
545        }),
546      )
547      if (full) run.done += 1
548    }
549  }
550  const done = Object.values(sealed).filter(s => s.full).length
551  if (!run.aborted) {
552    if (done > 0) $.ui.toast(t.sealed(done))
553    if (done < list.length || missed.length > 0) $.ui.toast(t.notSealed(list.length - done, missed.join('; ')))
554  }
555  if (pending(await read($, inscriptions)).length === 0) await dropCard($, 'marco')
556}
557
558async function discard($: EngineInterface) {
559  await update($, inscriptions, all => all.filter(i => !isPending(i)))
560  await dropCard($, 'marco')
561}
562
563/** Apaga um arquivo que o grimório criou (o $.fs não apaga): Remove-Item no Windows, rm no resto. */
564async function deleteFile($: EngineInterface, path: string) {
565  const argv = (await onWindows($))
566    ? ['powershell', '-NoProfile', '-NonInteractive', '-Command', 'Remove-Item -LiteralPath $env:HJ_PATH -Force']
567    : ['rm', '-f', path]
568  const r = await $.process.run(argv, { timeoutMs: 10_000, env: { HJ_PATH: path } })
569  if (r.exitCode !== 0) throw new Error(r.stderr.trim().slice(0, 160) || `exit ${r.exitCode}`)
570}
571
572/** Desfaz o que um Selar gravou e devolve a inscrição para "Para guardar". */
573async function undoSeal($: EngineInterface, id: string) {
574  const t = DICT[await langNow($)]
575  const i = (await read($, inscriptions)).find(x => x.id === id)
576  if (i?.written === undefined) return
577  const memory = (await grimDests($, true)).memory
578  try {
579    for (const w of i.written) {
580      if (w.mode === 'linha' && w.line !== undefined) {
581        if (await $.fs.exists(w.path)) await $.fs.write(w.path, removeLine(await $.fs.read(w.path), w.line))
582      } else if (w.mode === 'pagina') {
583        if (memory !== undefined) await memoryCall($, memory, 'memory_delete_page', { path: w.path })
584      } else await deleteFile($, w.path)
585    }
586    await update($, inscriptions, all => all.map((x): Inscription => (x.id === id ? { ...x, sealed: undefined, written: undefined } : x)))
587    $.ui.toast(t.undone)
588  } catch (err) {
589    $.ui.toast(t.notSealed(0, err instanceof Error ? err.message : String(err)))
590  }
591}
592
593/** O vault de verdade (conferido) e os destinos do grimório agora. */
594async function liveDests($: EngineInterface): Promise<Dests> {
595  const found = await grimDests($)
596  const stat = found.vault === '' ? undefined : await withTimeout($.fs.stat(found.vault), SEAL_TIMEOUT_MS, 'fs.stat').catch(() => undefined)
597  return { ...found, vault: stat?.kind === 'dir' ? found.vault : '' }
598}
599
600/** Para onde o progresso vai, em palavras: "Tarefa + ai-memory", "Tarefa no vault" ou "Tarefa no projeto". */
601async function progressLabel($: EngineInterface) {
602  const t = DICT[await langNow($)]
603  const d = await grimDests($)
604  return d.vault !== '' ? (d.memory !== undefined ? t.progressDest.vaultMemory : t.progressDest.vault) : t.progressDest.project
605}
606
607/** O próximo passo: a tarefa atual do plano, a primeira pendente ou o **Próximo:** da última resposta. */
608async function nextStepNow($: EngineInterface) {
609  const list = await read($, quests)
610  const now = list.find(q => q.status === 'in_progress') ?? list.find(q => q.status === 'pending')
611  if (now !== undefined) return now.title
612  const c = await read($, campaign)
613  return [...(c?.chapters ?? [])].reverse().find(ch => ch.report?.next !== undefined)?.report?.next ?? ''
614}
615
616/** Lista a pasta de tarefas: se ela ainda não existe (ENOENT), devolve vazio; qualquer outro erro sobe. */
617async function listTaskDir($: EngineInterface, home: string) {
618  try {
619    return await $.fs.list(home)
620  } catch (err) {
621    const msg = err instanceof Error ? err.message : String(err)
622    if (/ENOENT|not found|no such file|does not exist/i.test(msg)) return []
623    throw err
624  }
625}
626
627/**
628 * Salvar progresso: grava a tarefa (nova, ou a desta campanha atualizada) e,
629 * com o ai-memory conectado, abre o handoff para continuar em outro agente ou PC.
630 */
631async function saveProgress($: EngineInterface): Promise<boolean> {
632  const l = await langNow($)
633  const t = DICT[l]
634  const c = await read($, campaign)
635  saveFailed = undefined
636  if (c === null) {
637    saveFailed = t.nothingToSave
638    $.ui.toast(t.nothingToSave)
639    return false
640  }
641  try {
642    const repo = await $.session.cwd()
643    const d = await liveDests($)
644    const home = progressHome(repo, d.vault, (await memoryScope($)).project)
645    const name = projectName(repo)
646    const known = (await $.store.get(`tarefa:${c.id}`).catch(() => undefined)) as string | undefined
647    const files = (await listTaskDir($, home)).map(x => x.name)
648    const path = known !== undefined && (await $.fs.exists(known)) ? known : joinPath(home, `${nextTaskId(files, taskPrefix(name))}.md`)
649    const before = (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
650    const id = /([A-Z0-9]+-\d{3})\.md$/.exec(path)?.[1] ?? nextTaskId(files, taskPrefix(name))
651    const entries = await read($, diary)
652    const inv = await read($, inventory)
653    const host = (await $.env.get('COMPUTERNAME').catch(() => undefined)) ?? (await $.env.get('HOSTNAME').catch(() => undefined)) ?? 'pc'
654    const failed = entries.filter(x => x.status === 'err').slice(-5).map(x => x.summary)
655    const task = saveTask(before === undefined ? undefined : parseTask(before), {
656      id,
657      project: name,
658      at: Date.now(),
659      title: goalOf(c),
660      objective: cutAtWord(c.objective.replace(/\s+/g, ' '), 240),
661      next: await nextStepNow($),
662      verify: verifyDraft,
663      failed,
664      logLine: [host, 'Claude Code', t.actions(entries.length), inv.recent?.[0]?.hash ?? ''].filter(Boolean).join(' | '),
665    })
666    // Sem vault, as tarefas moram no projeto: o .gitignore próprio vem antes da tarefa,
667    // para ela nunca ficar visível ao git se a gravação dele falhar.
668    const ignorePath = joinPath(joinPath(repo, '.hero'), '.gitignore')
669    if (d.vault === '' && !(await $.fs.exists(ignorePath))) await writeFileEnsuringDir($, ignorePath, '*\n')
670    await writeFileEnsuringDir($, path, taskText(task))
671    await $.store.set(`tarefa:${c.id}`, path)
672    let handoffId: string | undefined
673    if (d.memory !== undefined) {
674      try {
675        // O ID e o caminho da tarefa vão no resumo ("pegue a tarefa X" acha o arquivo em qualquer agente),
676        // relativo ao vault ou ao repositório: nome de usuário e pasta pessoal não saem da máquina.
677        const r = await memoryCall($, d.memory, 'memory_handoff_begin', {
678          summary: `${task.id} ${task.title}: ${task.next || task.objective} (${t.taskFile}: ${shareablePath(path, [d.vault, repo])})`.slice(0, 400),
679          next_steps: (await read($, quests)).filter(q => q.status !== 'completed').map(q => q.title).slice(0, 8),
680          open_questions: task.verify === '' ? [] : [`${t.verify}: ${task.verify}`],
681        })
682        if (r.isError) throw new Error(r.content.map(x => ('text' in x ? String(x.text) : '')).join(' ').slice(0, 160))
683        const text = r.content.map(x => ('text' in x ? String(x.text) : '')).join('')
684        handoffId = /"handoff_id"\s*:\s*"([^"]+)"/.exec(text)?.[1]
685      } catch (err) {
686        $.ui.toast(t.handoffFailed(err instanceof Error ? err.message : String(err)))
687      }
688    }
689    await update($, progress, s => ({ ...s, saved: { at: Date.now(), path, id: task.id, handoffId, created: before === undefined, before } }))
690    verifyDraft = ''
691    $.ui.toast(t.progressDone(task.id))
692    await refreshProgress($)
693    return true
694  } catch (err) {
695    saveFailed = err instanceof Error ? err.message : String(err)
696    $.ui.toast(t.progressFailed(saveFailed))
697    return false
698  }
699}
700
701/** Desfaz o último salvar progresso: a tarefa volta ao texto de antes (ou some, se era nova) e o handoff é cancelado. */
702async function undoProgress($: EngineInterface) {
703  const t = DICT[await langNow($)]
704  const s = (await read($, progress)).saved
705  if (s === undefined) return
706  try {
707    if (s.created) await deleteFile($, s.path)
708    else if (s.before !== undefined) await $.fs.write(s.path, s.before)
709    const memory = (await grimDests($)).memory
710    if (s.handoffId !== undefined && memory !== undefined) await memoryCall($, memory, 'memory_handoff_cancel', { handoff_id: s.handoffId })
711    await update($, progress, x => ({ ...x, saved: undefined }))
712    $.ui.toast(t.undone)
713    await refreshProgress($)
714  } catch (err) {
715    $.ui.toast(t.progressFailed(err instanceof Error ? err.message : String(err)))
716  }
717}
718
719/** "ontem 18:40 · Claude Code" a partir da tarefa: a última linha do log diz quando e quem. */
720const byOf = (log: readonly string[]) => {
721  const last = log[log.length - 1] ?? ''
722  const parts = last.split('|').map(x => x.trim())
723  return { updated: parts[0] ?? '', by: parts[2] ?? '' }
724}
725
726/** O que dá para continuar: as tarefas abertas deste projeto e, com o ai-memory, os handoffs pendentes. */
727async function refreshProgress($: EngineInterface) {
728  try {
729    const repo = await $.session.cwd()
730    const d = await liveDests($)
731    const home = progressHome(repo, d.vault, (await memoryScope($)).project)
732    const list: Progress[] = []
733    try {
734      for (const e of await listTaskDir($, home)) {
735        if (e.kind !== 'file' || !/\.md$/.test(e.name) || e.name.startsWith('_')) continue
736        const filePath = joinPath(home, e.name)
737        const task = parseTask(await $.fs.read(filePath))
738        if (task === undefined || task.status === 'concluida') continue
739        const b = byOf(task.log)
740        list.push({ id: task.id, title: task.title, next: task.next, updated: b.updated || task.updated, by: b.by, path: filePath })
741      }
742    } catch (err) {
743      $.ui.toast(DICT[await langNow($)].readFailed(err instanceof Error ? err.message : String(err)))
744    }
745    if (d.memory !== undefined) {
746      const r = await memoryCall($, d.memory, 'memory_handoff_list', {}).catch(() => undefined)
747      const text = r === undefined || r.isError ? '' : r.content.map(x => ('text' in x ? String(x.text) : '')).join('')
748      const parsed = (() => {
749        try {
750          return JSON.parse(text) as { handoffs?: { handoff_id?: string; id?: string; summary?: string; next_steps?: string[]; agent?: string; created_at?: string }[] }
751        } catch {
752          return {}
753        }
754      })()
755      for (const h of parsed.handoffs ?? []) {
756        const hid = h.handoff_id ?? h.id
757        if (hid === undefined) continue
758        // O handoff de uma tarefa já listada vira o dela (o Continuar também o aceita), não uma segunda linha.
759        const mine = list.find(x => x.handoffId === undefined && (h.summary ?? '').startsWith(`${x.id} `))
760        if (mine !== undefined) {
761          mine.handoffId = hid
762          continue
763        }
764        list.push({ id: hid, title: (h.summary ?? hid).split(':')[0]?.slice(0, 80) ?? hid, next: h.next_steps?.[0] ?? '', updated: (h.created_at ?? '').slice(0, 16).replace('T', ' '), by: h.agent ?? 'ai-memory', handoffId: hid })
765      }
766    }
767    list.sort((x, y) => y.updated.localeCompare(x.updated))
768    await update($, progress, s => ({ ...s, list }))
769  } catch {
770    // Sem pasta ou sem MCP agora: o Continuar fica com o que já tinha.
771  }
772}
773
774/** Continuar: pega o handoff (se for do ai-memory) e leva ao prompt o pedido de ler a tarefa e conferir antes de mexer. */
775async function continueTask($: EngineInterface, p: Progress) {
776  const l = await langNow($)
777  const memory = (await grimDests($)).memory
778  if (p.handoffId !== undefined && memory !== undefined) await memoryCall($, memory, 'memory_handoff_accept', { handoff_id: p.handoffId }).catch(() => undefined)
779  await fillOrCopy($, continuePrompt(l, p.title, p.path ?? (l === 'pt' ? 'o handoff que o ai-memory entregou' : 'the handoff ai-memory delivered')))
780}
781
782/**
783 * O que o Sábio lembra: com o ai-memory, as páginas recentes do projeto; sem ele,
784 * quantas notas a memória automática do Claude tem para esta pasta.
785 */
786async function refreshRemembered($: EngineInterface) {
787  const d = await grimDests($)
788  if (d.memory !== undefined) {
789    const r = await memoryCall($, d.memory, 'memory_recent', { limit: 4 }).catch(() => undefined)
790    const text = r === undefined || r.isError ? '' : r.content.map(x => ('text' in x ? String(x.text) : '')).join('')
791    try {
792      const parsed = JSON.parse(text) as { pages?: { path?: string; title?: string; kind?: string }[]; hits?: { path?: string; title?: string; kind?: string }[] }
793      const pages = parsed.pages ?? parsed.hits ?? []
794      await update($, remembered, () =>
795        pages.filter(p => typeof p.path === 'string').slice(0, 4).map(p => ({ kind: p.kind ?? (p.path ?? '').split('/')[0] ?? '', text: p.title ?? p.path ?? '', path: p.path ?? '' })),
796      )
797    } catch {
798      await update($, remembered, () => [])
799    }
800    autoNotes = undefined
801    return
802  }
803  await update($, remembered, () => [])
804  const homeDir = (await $.env.get('USERPROFILE').catch(() => undefined)) ?? (await $.env.get('HOME').catch(() => undefined))
805  if (homeDir === undefined) return
806  const dir = `${homeDir}/.claude/projects/${(await $.session.cwd()).replace(/[:\\/]/g, '-')}/memory`
807  const files = await $.fs.list(dir).catch(() => [])
808  const n = files.filter(f => f.kind === 'file' && /\.md$/i.test(f.name) && f.name !== 'MEMORY.md').length
809  autoNotes = files.length === 0 ? undefined : { n, dir }
810}
811
812/** "esquecer": marca a página como velha no ai-memory (sai da busca com o tempo) e some da lista. */
813async function forget($: EngineInterface, path: string) {
814  const t = DICT[await langNow($)]
815  const memory = (await grimDests($)).memory
816  if (memory !== undefined) await memoryCall($, memory, 'memory_feedback', { path, feedback: 'stale' }).catch(() => undefined)
817  await update($, remembered, list => list.filter(x => x.path !== path))
818  $.ui.toast(t.forgotten)
819}
820
821/** Sugere de novo o destino das inscrições pendentes (depois de trocar onde as decisões caem ou de ligar o vault). */
822async function resuggest($: EngineInterface) {
823  const p = await prefsNow($)
824  const d = await grimDests($)
825  await update($, inscriptions, all =>
826    all.map((i): Inscription => {
827      if (!isPending(i) || (i.sealed !== undefined && i.sealed.length > 0)) return i
828      const keep = i.destinations[0] !== undefined && available(i.destinations[0], d) && p.memory.decisoesEm === 'auto'
829      const s = suggest(i.kind, d, p.memory.decisoesEm)
830      return keep ? i : { ...i, destinations: s === undefined ? [] : [s] }
831    }),
832  )
833}
834
835/**
836 * Grava o vault e acha a pasta de entrada sozinha: a do jeito PARA (00-Inbox), se
837 * existir; senão, a padrão (Inbox). Assim os Primeiros passos não perguntam por ela.
838 */
839async function setVault($: EngineInterface, folder: string) {
840  await $.config.set({ key: 'hero-journey.vaultPath', value: folder })
841  let inbox = 'Inbox'
842  for (const sub of ['00-Inbox', 'Inbox']) {
843    if ((await withTimeout($.fs.stat(joinPath(folder, sub)), SEAL_TIMEOUT_MS, 'fs.stat').catch(() => undefined))?.kind === 'dir') {
844      await $.config.set({ key: 'hero-journey.vaultInbox', value: sub })
845      inbox = sub
846      break
847    }
848  }
849  // As opções só chegam ao mod na próxima carga: a sessão passa a usar o vault já.
850  paths = { vault: folder, inbox }
851}
852
853/** Escolhe (ou troca) a pasta do vault pelo seletor do sistema. Devolve se gravou. */
854async function changeVault($: EngineInterface): Promise<boolean> {
855  const t = DICT[await langNow($)]
856  const picked = await pickFolder($, t.pickVaultTitle, paths.vault)
857  if (picked === null) $.ui.toast(t.pickUnavailable)
858  if (picked === null || picked === undefined) return false
859  const folder = await checkedFolder($, picked)
860  if (folder === undefined) return false
861  await setVault($, folder)
862  await resuggest($)
863  return true
864}
865
866/** Onde as decisões caem: no projeto, ou no vault (sem vault, abre o seletor de pasta para escolher). */
867async function chooseHome($: EngineInterface, home: 'projeto' | 'vault' | 'auto') {
868  if (home === 'vault' && paths.vault === '' && !(await changeVault($))) return
869  await savePrefs($, x => ({ ...x, memory: { ...x.memory, decisoesEm: home } }))
870  await resuggest($)
871}
872
873/** O ⚙ Memória → Testar: o ai-memory responde ao memory_status? */
874async function testMemory($: EngineInterface) {
875  const t = DICT[await langNow($)]
876  const memory = (await grimDests($, true)).memory
877  if (memory === undefined) return
878  try {
879    const r = await withTimeout($.mcp.call(memory.server, 'memory_status', {}), SEAL_TIMEOUT_MS, 'memory_status')
880    if (r.isError) throw new Error(r.content.map(x => ('text' in x ? String(x.text) : '')).join(' ').slice(0, 160))
881    $.ui.toast(t.memTestOk)
882  } catch (err) {
883    $.ui.toast(t.memTestFail(err instanceof Error ? err.message : String(err)))
884  }
885}
886
887/** Haiku: só no clique em "Resumir com Haiku" (o botão aparece com o ⚙ ligado). Gasta tokens. */
888async function rewriteWithHaiku($: EngineInterface) {
889  const l = await langNow($)
890  const out: Inscription[] = []
891  for (const i of pending(await read($, inscriptions))) {
892    try {
893      const r = await $.model.complete({ model: 'haiku', prompt: haikuPrompt(i, l), maxTokens: 120 })
894      out.push(r.isAnswered && r.text.trim() !== '' ? { ...i, text: r.text.trim().replace(/^"|"$/g, '') } : i)
895    } catch {
896      out.push(i)
897    }
898  }
899  const byId = new Map(out.map(i => [i.id, i]))
900  await update($, inscriptions, all => all.map(i => byId.get(i.id) ?? i))
901  $.ui.toast(DICT[l].haikuDone(out.length))
902}
903
904/**
905 * ✦ Recalibrar objetivo: o Haiku lê os pedidos da pessoa nesta sessão (o 1º e os
906 * capítulos) e devolve o objetivo atual em poucas palavras. Só roda no clique.
907 */
908async function recalibrateGoal($: EngineInterface) {
909  const l = await langNow($)
910  const t = DICT[l]
911  const c = await read($, campaign)
912  if (c === null) return
913  const asks = [c.objective, ...c.chapters.slice(1).map(ch => ch.prompt)].slice(-10)
914  try {
915    const r = await $.model.complete({ model: 'haiku', prompt: t.recalibratePrompt(asks), maxTokens: 60 })
916    const text = r.isAnswered ? (r.text.trim().replace(/^["“']|["”'.]$/g, '').split(/\r?\n/)[0]?.trim() ?? '') : ''
917    if (text === '') {
918      $.ui.toast(t.recalibrateFail)
919      return
920    }
921    const cur = await read($, campaign)
922    if (cur !== null) await saveCampaign($, { ...cur, short: cutAtWord(text, 70), shortFrom: 'haiku' })
923    $.ui.toast(t.recalibrateDone(cutAtWord(text, 70)))
924  } catch {
925    $.ui.toast(t.recalibrateFail)
926  }
927}
928
929/** O Paladino pergunta: põe os arquivos no estado (o desenho lê), pergunta e limpa. */
930async function askGuard($: EngineInterface, files: GuardFile[]) {
931  const l = await langNow($)
932  const t = DICT[l]
933  const labels = LABELS[l]
934  const names = files.map(f => f.name).join(', ')
935  await update($, guard, () => files)
936  try {
937    const answer = await $.ui.ask(t.guardQuestion(names), {
938      header: t.guardHeader,
939      options: labels,
940    })
941    return verdictOf(answer, labels)
942  } catch {
943    // Dispensado, ou ninguém para responder (claude -p): nos dois casos, não libera.
944    return 'sem-resposta' as const
945  } finally {
946    await update($, guard, () => [])
947  }
948}
949
950/**
951 * Decide uma escrita em arquivo protegido. Sempre pergunta (o `$.ui.ask` rejeita
952 * sozinho onde não há ninguém); `interactive` só escolhe a mensagem da recusa.
953 */
954async function guardCall($: EngineInterface, tool: string, toolUseId: string, files: GuardFile[]) {
955  const t = DICT[await langNow($)]
956  const names = files.map(f => f.name).join(', ')
957  const mode = (await prefsNow($)).guardMode
958  if (mode === 'nativo') {
959    $.ui.notice(toolUseId, t.guardNotice(names))
960    return undefined
961  }
962  const verdict = await askGuard($, files)
963  if (verdict === 'liberar') return undefined
964  if (verdict === 'sem-resposta' && !interactive) return { deny: t.denyHeadless(names) }
965  if (verdict === 'negociar') {
966    await fillOrCopy($, t.negotiateDraft(names))
967    return { deny: t.denyNegotiate(names) }
968  }
969  const turn = await read($, turnId)
970  await update($, refusals, list => [...list, { turnId: turn, text: `${names} (${tool})` }])
971  return { deny: t.denyRefuse(names) }
972}
973
974/**
975 * Uma pasta digitada: só entra se for uma pasta que existe, e entra pelo caminho
976 * absoluto (um relativo mudaria de sentido em outra sessão). Caminho de rede o
977 * $.fs não alcança: a pessoa recebe o aviso em vez de nada.
978 */
979async function checkedFolder($: EngineInterface, raw: string) {
980  const t = DICT[await langNow($)]
981  const folder = raw.trim().replace(/^"|"$/g, '')
982  if (folder === '') return undefined
983  if (/^[\\/]{2}/.test(folder)) {
984    $.ui.toast(t.folderNetwork(folder))
985    return undefined
986  }
987  const stat = await withTimeout($.fs.stat(folder, { resolve: true }), SEAL_TIMEOUT_MS, 'fs.stat').catch(() => undefined)
988  if (stat?.kind === 'dir') return stat.realPath ?? folder
989  $.ui.toast(t.folderMissing(folder))
990  return undefined
991}
992
993async function onWindows($: EngineInterface) {
994  return isWindows(await $.env.get('OS').catch(() => undefined))
995}
996
997/**
998 * O seletor de pasta do sistema. Devolve o caminho escolhido, undefined se a
999 * pessoa cancelou, ou null se nenhum seletor abriu (Linux sem zenity, por exemplo).
1000 * A espera pela pessoa fica dentro do `$.process.run`, que não conta no tempo do hook.
1001 */
1002async function pickFolder($: EngineInterface, title: string, start: string): Promise<string | undefined | null> {
1003  const win = await onWindows($)
1004  const tries = win ? pickArgvs('windows') : [...pickArgvs('mac'), ...pickArgvs('linux')]
1005  for (const argv of tries) {
1006    try {
1007      const r = await $.process.run(argv, { timeoutMs: 600_000, env: { HJ_TITLE: title, HJ_START: start } })
1008      if (r.exitCode === 0) return pickedOf(r.stdout)
1009      // osascript, zenity e kdialog saem com 1 no Cancelar; o PowerShell sai com 0 e nada escrito.
1010      if (!win && r.exitCode === 1) return undefined
1011    } catch {
1012      // Sem esse programa aqui: tenta o próximo.
1013    }
1014  }
1015  return null
1016}
1017
1018/** Abre a pasta no Explorer, no Finder ou no gerenciador de arquivos do Linux. */
1019async function openFolder($: EngineInterface, path: string) {
1020  const win = await onWindows($)
1021  // xdg-open antes do open: no Linux, `open` pode ser outro programa (openvt).
1022  const tries = win ? [openArgv('windows', path)] : [openArgv('linux', path), openArgv('mac', path)]
1023  for (const argv of tries) {
1024    try {
1025      const r = await $.process.run(argv, { timeoutMs: 15_000 })
1026      // O explorer.exe sai com 1 mesmo quando abre a pasta.
1027      if (win || r.exitCode === 0) return
1028    } catch {
1029      // Sem esse programa aqui: tenta o próximo.
1030    }
1031  }
1032  $.ui.toast(DICT[await langNow($)].openFailed(path))
1033}
1034
1035/** O 📖 do rodapé, o "Ver e guardar" do Sábio e o /grimorio: abrem a página do grimório no painel. */
1036async function openGrimoire($: EngineInterface) {
1037  await refreshRemembered($)
1038  await update($, view, () => 'grimorio' as const)
1039}
1040
1041let readingTasks = false
1042
1043/**
1044 * As quests vêm da lista de tarefas do Claude. Lê o TaskList (de graça, sem o
1045 * modelo) ao iniciar e no fim de cada turno: uma sessão retomada ou um mod
1046 * recarregado não perde as tarefas abertas. Só roda se o motor liberar sem perguntar.
1047 */
1048async function refreshTasks($: EngineInterface) {
1049  try {
1050    if (!(await $.tool.list()).some(t => t.name === 'TaskList')) return
1051    const check = await $.tool.check({ tool: 'TaskList' } as never)
1052    if ((check as { decision?: string }).decision !== 'allow') return
1053    readingTasks = true
1054    const ran = (await $.tool.call({ tool: 'TaskList' } as never)) as { result?: { tasks?: { id?: unknown; subject?: unknown; status?: unknown }[] } }
1055    const tasks = ran.result?.tasks ?? []
1056    // Lista vazia: as tarefas foram concluídas e apagadas. Saem as quests que vieram
1057    // dela; as do TodoWrite (id "todo-N") ficam, porque o TaskList não as conhece.
1058    if (tasks.length === 0) {
1059      await update($, quests, list => list.filter(q => q.id.startsWith('todo-')))
1060      return
1061    }
1062    await update($, quests, () =>
1063      tasks
1064        .filter(t => typeof t.id === 'string' && typeof t.subject === 'string')
1065        .map(t => ({
1066          id: String(t.id),
1067          title: String(t.subject),
1068          status: t.status === 'completed' || t.status === 'in_progress' ? t.status : ('pending' as const),
1069        })),
1070    )
1071  } catch {
1072    // Sem TaskList (versão antiga) ou sem permissão: as quests seguem pelo TaskCreate/TodoWrite.
1073  } finally {
1074    readingTasks = false
1075  }
1076}
1077
1078/**
1079 * No Windows não há LANG: a língua do sistema vem do Get-Culture ("pt-BR").
1080 * Sem o PowerShell (Mac, Linux), devolve undefined e a língua sai do 1º pedido.
1081 */
1082async function windowsCulture($: EngineInterface): Promise<string | undefined> {
1083  try {
1084    const r = await $.process.run(['powershell', '-NoProfile', '-NonInteractive', '-Command', '(Get-Culture).Name'], { timeoutMs: 3000 })
1085    const name = r.stdout.trim()
1086    return r.exitCode === 0 && /^[a-z]{2}(-[A-Za-z]{2,})?$/.test(name) ? name : undefined
1087  } catch {
1088    return undefined
1089  }
1090}
1091
1092/**
1093 * O que cabe no painel para o rodapé ficar preso no fim: a altura do palco e
1094 * quantos heróis e itens entram (o layoutOf do palco). Se nem o mínimo couber,
1095 * o painel solta o rodapé e rola inteiro.
1096 */
1097async function paneFit($: EngineInterface, bodyRows: number) {
1098  const c = await read($, campaign)
1099  const goalLong = c === null ? 0 : goalOf(c).length
1100  return layoutOf(bodyRows - (goalLong > 40 ? 1 : 0), {
1101    goal: c !== null,
1102    steps: (await read($, quests)).length,
1103    party: (await read($, party)).filter(m => m.status === 'run').length,
1104    items: (await read($, inventory)).items.length,
1105  })
1106}
1107
1108/** A cena do palco: a ferramenta em curso e o diário do turno, ou o acampamento (com o Sábio, quando ele tem o que dizer). */
1109async function sceneNow($: EngineInterface) {
1110  const id = await read($, turnId)
1111  const entries = (await read($, diary)).filter(x => x.turnId === id)
1112  const scene = sceneOf(await read($, turn), await read($, working), entries, Date.now())
1113  if (scene.place !== 'acampamento') return scene
1114  const g = await grimOnStage($)
1115  const sage = scene.mode === 'wait' ? g.noted > 0 && notedDismissed !== id : scene.mode === 'sleep' ? g.saveNext !== undefined : false
1116  return { ...scene, sage }
1117}
1118
1119/** O ◈ da faixa: abre o painel se estiver fechado, fecha se estiver aberto. */
1120async function togglePane($: EngineInterface) {
1121  // Fecha só o que está à vista: um painel atrás de outra aba, ou aberto sem lugar, é trazido para frente.
1122  const mine = (await $.ui.panes()).find(pane => pane.id === PANE)
1123  if (mine !== undefined && mine.isShown && mine.isPlaced) {
1124    await $.ui.close({ id: PANE })
1125    return
1126  }
1127  if (!(await moduleOn($, 'painel'))) await savePrefs($, x => ({ ...x, modules: { ...x.modules, painel: true } }))
1128  await refreshTheme($)
1129  // Como o /hero: enquanto os Primeiros passos não forem concluídos, abre neles.
1130  if ((await $.store.get('setupDone')) !== true) await update($, view, () => 'boasVindas' as const)
1131  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true })
1132}
1133
1134async function renderPane($: EngineInterface, e: RenderInput<'Pane'>): Promise<RenderElement> {
1135  const ui = $.ui.resolve(e)
1136  const c: Ctx = { ...(await ctxOf($, e.surface, e.props.bodyColumns, e.props.placement === 'inline')), ui }
1137  const v = await read($, view)
1138  stageNow = undefined
1139  const p = await prefsNow($)
1140  const toMain = () => update($, view, () => 'main' as const)
1141
1142  if (v === 'sobre') return aboutView(c, toMain)
1143  if (v === 'boasVindas') {
1144    const say = (msg: string | undefined) => update($, setup, s => ({ ...s, msg }))
1145    const saveVault = async (value: string) => {
1146      const folder = await checkedFolder($, value)
1147      if (folder === undefined) {
1148        await say(c.t.folderMissing(value))
1149        return
1150      }
1151      await say(undefined)
1152      await setVault($, folder)
1153    }
1154    return setupView(c, await read($, setup), langOption, await grimDests($), {
1155      lang: async value => {
1156        await $.config.set({ key: 'hero-journey.language', value })
1157      },
1158      path: saveVault,
1159      // O seletor do sistema cai no mesmo caminho do campo: a pasta é conferida antes de salvar.
1160      pickVault: async () => {
1161        const picked = await pickFolder($, c.t.pickVaultTitle, paths.vault)
1162        if (picked === null) await say(c.t.pickUnavailable)
1163        else if (picked !== undefined) await saveVault(picked)
1164      },
1165      done: async () => {
1166        await $.store.set('setupDone', true)
1167        await update($, view, () => 'main' as const)
1168      },
1169    })
1170  }
1171  if (v === 'config') {
1172    return configView(c, p, langOption, {
1173      back: toMain,
1174      lang: async value => {
1175        const t = DICT[await langNow($)]
1176        const r = await $.config.set({ key: 'hero-journey.language', value })
1177        $.ui.toast('deny' in r && r.deny !== undefined ? t.langDenied(r.deny) : t.langChanged)
1178      },
1179      skin: skin => savePrefs($, x => ({ ...x, skin })),
1180      module: async id => {
1181        await savePrefs($, x => toggleModule(x, id))
1182        // Desligar o painel no ⚙ fecha o painel aberto.
1183        if (id === 'painel' && !(await moduleOn($, 'painel'))) await $.ui.close({ id: PANE })
1184      },
1185      guard: mode => savePrefs($, x => ({ ...x, guardMode: mode })),
1186      haiku: () => savePrefs($, x => ({ ...x, grimorioHaiku: !x.grimorioHaiku })),
1187      setup: () => update($, view, () => 'boasVindas' as const),
1188      about: () => update($, view, () => 'sobre' as const),
1189      memory: () => update($, view, () => 'memoria' as const),
1190    })
1191  }
1192  if (v === 'memoria') {
1193    return memoryView(c, p, {
1194      dests: await liveDests($),
1195      progressLabel: await progressLabel($),
1196      act: {
1197        toggle: k => savePrefs($, x => toggleMemory(x, k)),
1198        home: where => chooseHome($, where),
1199        pickVault: () => changeVault($),
1200        testMemory: () => testMemory($),
hooks/core/classes.ts 196 lines
1// Que classe faz cada coisa e como resumir uma chamada. Regras puras, sem `$`.
2
3import type { Cls } from '../../types'
4
5const has = (re: RegExp, text: unknown) => typeof text === 'string' && re.test(text)
6
7const TEST = /\b(test|tests|jest|vitest|karma|pytest|xunit|nunit|lint|eslint|tsc\b|prettier|ng test|dotnet test|playwright|cypress)\b/i
8// "logs" (docker logs, kubectl logs), arquivo .log ou acompanhar ao vivo; "git log" é leitura do Mago.
9const LOGS = /\blogs\b|\.log\b|tail -f|journalctl|Get-EventLog|Get-WinEvent/i
10const PIPELINE = /\b(az pipelines|az devops|gh run|gh workflow|docker|podman|kubectl|helm|terraform|deploy\w*|vercel|netlify|fly)\b/i
11const DB = /\b(psql|sqlcmd|mysql|sqlite3?|mongo(sh)?|redis-cli|dotnet ef|prisma|migrat\w*|flyway|liquibase)\b/i
12const PR = /\b(git (commit|push|merge|rebase|tag|cherry-pick)|gh pr|gh release|az repos pr)\b/i
13const HTTP = /\b(curl|wget|http(ie)?|grpcurl|az rest|Invoke-RestMethod|Invoke-WebRequest)\b/i
14// Comandos que só leem: cada pedaço da linha começa com um deles e nada é gravado com `>`.
15const READS = /^(ls|dir|cat|type|head|tail|less|more|wc|grep|rg|find|fd|tree|pwd|echo|which|where|file|stat|du|df|sort|uniq|cut|awk|sed -n|jq|git (status|log|diff|show|branch|blame|remote|rev-parse|ls-files)|gh (pr|issue|run) (view|list|status|diff|checks)|Get-ChildItem|Get-Content|Get-Item|Select-String|Test-Path|Resolve-Path|Get-Location|Measure-Object|Select-Object|Where-Object|Sort-Object|Format-\w+)\b/i
16const UI_FILE = /\.(html|css|scss|sass|less|svg)$|\.component\.(ts|html|scss)$|\.(tsx|jsx|vue|svelte)$/i
17const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$|[\\/]docs?[\\/]/i
18const DB_FILE = /\.(sql|prisma)$|[\\/]migrations?[\\/]/i
19const PIPE_FILE = /pipelines?.*\.ya?ml$|[\\/]\.github[\\/]workflows[\\/]|dockerfile$|\.tf$/i
20const TEST_FILE = /\.(spec|test)\.\w+$|[\\/](tests?|__tests__)[\\/]/i
21
22/** Um comando de terminal que só lê (ls, cat, git status, Get-Content...). */
23export const readsOnly = (command: string) => {
24  const c = command.trim()
25  if (c === '' || /(^|[^2&])>/.test(c) || /\s-(delete|exec|execdir)\b|\bsed\b.*\s-i\b/.test(c)) return false
26  return c.split(/\s*(?:&&|\|\||;|\|)\s*/).every(part => READS.test(part.replace(/^(cd\s+\S+\s*$)/, 'pwd')))
27}
28
29/**
30 * Entrega de verdade, o que conta como marco do grimório: commit, push, merge, tag
31 * ou PR (pelo terminal ou pelo MCP). O Rei também manda mensagens e arquivos, e
32 * isso não é marco.
33 */
34export const delivers = (tool: string, input: Record<string, unknown>) =>
35  tool === 'Bash' || tool === 'PowerShell' ? PR.test(String(input.command ?? '')) : /pull_request_(create|merge)|create_pull_request|merge_pull_request/i.test(tool)
36
37/** Os MCPs pela ferramenta: navegador, design, PR, mensagem, agenda, banco, memória e docs; o resto é integração. */
38const mcpClass = (tool: string): Cls => {
39  if (/browser|chrome|playwright|puppeteer|reticle/i.test(tool)) return 'ladino'
40  if (/figma|design|visualize|show_widget|canva|shader/i.test(tool)) return 'pintor'
41  if (/pull_request|merge|review|repo_create_branch/i.test(tool)) return 'rei'
42  if (/gmail|send_message|reply|forward|draft|slack|notify|calendar|event/i.test(tool)) return 'rei'
43  if (/schedul|cron|trigger/i.test(tool)) return 'cronomante'
44  if (/sql|postgres|supabase|database|mongo|redis/i.test(tool)) return 'geomante'
45  if (/memory_|docs?_|wiki|notion|obsidian/i.test(tool)) return 'sabio'
46  if (/context7|search_documentation|query-docs|web_search|fetch/i.test(tool)) return 'cacador'
47  if (/pipeline|build|deploy/i.test(tool)) return 'artifice'
48  return 'alquimista'
49}
50
51/**
52 * A classe de uma chamada de ferramenta, pelo mapa de docs/classes.md: Mago lê
53 * o projeto, Caçador pesquisa na web, Ladino navega, Rúnico escreve código,
54 * Ilusionista monta telas, Sábio escreve textos e guarda o saber, Engenheiro
55 * roda comandos, Bruxo testa, Rei cuida de commit e PR e fala com o mundo,
56 * Artífice publica, Oráculo lê os logs, Geomante cuida do banco, Alquimista
57 * integra, Cartomante planeja, Invocador chama ajudantes, Cronomante agenda,
58 * Paladino revisa a segurança e Pintor cuida do design. O resto fica com o
59 * Aprendiz.
60 */
61export const classOf = (tool: string, input: Record<string, unknown>): Cls => {
62  if (/^mcp__/.test(tool)) return mcpClass(tool)
63  if (/^(Read|Grep|Glob|LS|LSP|ToolSearch|NotebookRead)$/.test(tool)) return 'mago'
64  if (/^(WebFetch|WebSearch)$/.test(tool)) return 'cacador'
65  if (/^(Agent|Task|SendMessage|ListAgents|Workflow)$/.test(tool)) return 'invocador'
66  if (/^(TodoWrite|TaskCreate|TaskUpdate|TaskList|TaskGet|EnterPlanMode|ExitPlanMode|ProposeGoal)$/.test(tool)) return 'cartomante'
67  if (/^(CronCreate|CronDelete|CronList|ScheduleWakeup|RemoteTrigger)$/.test(tool)) return 'cronomante'
68  if (/^(Monitor|TaskStop|TaskOutput)$/.test(tool)) return 'oraculo'
69  if (/^(SendUserFile|PushNotification)$/.test(tool)) return 'rei'
70  if (/^(Skill|ListSkills|SearchSkills|Artifact|ArtifactComments|ArtifactData)$/.test(tool)) return 'sabio'
71  if (/^(ReportFindings)$/.test(tool)) return 'paladino'
72  if (/^(DesignSync)$/.test(tool)) return 'pintor'
73  if (tool === 'Bash' || tool === 'PowerShell') {
74    const command = String(input.command ?? '')
75    const cmd = `${command} ${String(input.description ?? '')}`
76    if (TEST.test(cmd)) return 'bruxo'
77    if (PR.test(cmd)) return 'rei'
78    if (DB.test(cmd)) return 'geomante'
79    if (LOGS.test(command)) return 'oraculo'
80    if (PIPELINE.test(cmd)) return 'artifice'
81    if (HTTP.test(cmd)) return 'alquimista'
82    if (readsOnly(command)) return 'mago'
83    return 'engenheiro'
84  }
85  if (/^(Edit|Write|MultiEdit|NotebookEdit)$/.test(tool)) {
86    const path = String(input.file_path ?? input.notebook_path ?? '')
87    if (has(PIPE_FILE, path)) return 'artifice'
88    if (has(DB_FILE, path)) return 'geomante'
89    if (has(TEST_FILE, path)) return 'bruxo'
90    if (has(UI_FILE, path)) return 'ilusionista'
91    if (has(DOC_FILE, path)) return 'sabio'
92    return 'runico'
93  }
94  return 'aprendiz'
95}
96
97/** A classe de um subagente pelo tipo e pela descrição; sem pista, ele escreve código (Rúnico). */
98export const agentClass = (type: string, description: string): Cls => {
99  const text = `${type} ${description}`
100  if (/security|segura|guard|protec/i.test(text)) return 'paladino'
101  if (/\bweb\b|internet|online|docs? (oficial|official)/i.test(text)) return 'cacador'
102  if (/explore|research|pesquis|context|search|busca|investig/i.test(text)) return 'mago'
103  // Tela e design vencem o tipo "Plan": desenhar o fluxo de uma tela é trabalho do Ilusionista.
104  if (/figma|design visual|visual design|ilustra|arte\b/i.test(text)) return 'pintor'
105  if (/design|\bui\b|\bux\b|prototip|protot|layout|tela/i.test(text)) return 'ilusionista'
106  if (/plan|architect|arquitet|roadmap/i.test(text)) return 'cartomante'
107  if (/\bqa\b|test|lint|bug|adversar/i.test(text)) return 'bruxo'
108  if (/review|revis|audit/i.test(text)) return 'paladino'
109  if (/\blogs?\b|monitor|observ/i.test(text)) return 'oraculo'
110  if (/pipeline|deploy|\bci\b|\bbuild\b|infra/i.test(text)) return 'artifice'
111  if (/database|banco|sql|migra/i.test(text)) return 'geomante'
112  if (/\bpr\b|pull request|merge|release|commit/i.test(text)) return 'rei'
113  if (/integra|\bapi\b|\bmcp\b|webhook/i.test(text)) return 'alquimista'
114  if (/\bdocs?\b|readme|escrev|write-?up|changelog|memór|memory/i.test(text)) return 'sabio'
115  if (/agend|schedul|cron/i.test(text)) return 'cronomante'
116  if (/\bcomand|shell|terminal|install/i.test(text)) return 'engenheiro'
117  return 'runico'
118}
119
120/** Uma linha humana do que a chamada faz, para o diário e a faixa. */
121export const summaryOf = (tool: string, input: Record<string, unknown>) => {
122  for (const field of ['description', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'subject', 'command']) {
123    const value = input[field]
124    if (typeof value === 'string' && value.trim() !== '') {
125      const text = field === 'file_path' || field === 'notebook_path' ? baseName(value) : value.trim()
126      return text.length > 90 ? `${text.slice(0, 89)}…` : text
127    }
128  }
129  return tool
130}
131
132export const baseName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
133
134/** +/− de um patch estruturado (Edit/Write). */
135export const patchStats = (patch: unknown) => {
136  let added = 0
137  let removed = 0
138  if (!Array.isArray(patch)) return undefined
139  for (const hunk of patch) {
140    const lines = (hunk as { lines?: unknown }).lines
141    if (!Array.isArray(lines)) continue
142    for (const line of lines) {
143      if (typeof line !== 'string') continue
144      if (line.startsWith('+')) added += 1
145      else if (line.startsWith('-')) removed += 1
146    }
147  }
148  return { added, removed }
149}
150
151/** Porcentagem legível, sem casa decimal. */
152export const pct = (value: number | undefined) => (value === undefined ? '—' : `${Math.round(value)}%`)
153
154/** Hora local de um ISO (HH:MM), ou vazio. */
155export const clockOf = (iso: string | undefined) => {
156  if (iso === undefined) return ''
157  const at = new Date(iso)
158  if (Number.isNaN(at.getTime())) return ''
159  return `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
160}
161
162/** Quanto falta para um ISO, em "2h14" ou "38min"; vazio quando já passou ou não há. */
163export const untilOf = (iso: string | undefined, now: number) => {
164  if (iso === undefined) return ''
165  const ms = new Date(iso).getTime() - now
166  if (Number.isNaN(ms) || ms <= 0) return ''
167  const min = Math.round(ms / 60000)
168  if (min < 60) return `${min}min`
169  const h = Math.floor(min / 60)
170  return h >= 48 ? `${Math.round(h / 24)}d` : `${h}h${String(min % 60).padStart(2, '0')}`
171}
172
173const KNOWN_TYPES: Record<string, string> = {
174  explore: 'Explorador',
175  plan: 'Arquiteto',
176  'claude-code-guide': 'Guia do Claude Code',
177  'statusline-setup': 'Status line',
178}
179const ACRONYM = /^(qa|ui|ux|api|pr|db|sql|ci|cd|mcp|hud)$/i
180
181/**
182 * O nome de um subagente para a tela: "acme-qa-reviewer" vira "QA reviewer",
183 * "claude-council:council-advisor" vira "Council advisor". Vazio quando o tipo
184 * não diz nada (general-purpose): aí quem chama mostra a classe.
185 */
186export const humanType = (type: string, known: Readonly<Record<string, string>> = KNOWN_TYPES) => {
187  const t = (type.split(':').pop() ?? type).trim()
188  if (t === '' || /^general(-purpose)?$/i.test(t)) return ''
189  const named = known[t.toLowerCase()]
190  if (named !== undefined) return named
191  let parts = t.split(/[-_\s]+/).filter(Boolean)
192  // Três palavras ou mais: a primeira costuma ser o prefixo da organização (acme-, org-).
193  if (parts.length >= 3) parts = parts.slice(1)
194  return parts.map((w, i) => (ACRONYM.test(w) ? w.toUpperCase() : i === 0 ? w.charAt(0).toUpperCase() + w.slice(1).toLowerCase() : w.toLowerCase())).join(' ')
195}
196
hooks/core/art.ts 568 lines
1// A arte da HUD que não é o Clawd nem o cenário: as cores das 19 classes e das
2// raridades, o Clawd recortado (dos sprites aprovados) para o chat, a faixa e o
3// grupo, os títulos do quest log, a barra do objetivo, a trilha e as barras dos
4// recursos, os ícones do ⚙ e do "Sobre", o desfile, a galeria das classes e o dragão da guarda. Tudo
5// é texto de SVG sem script: a animação vem de CSS e de SMIL, que o `Svg`
6// interativo do desktop toca; o `svg()` de core/ui põe o color-scheme.
7
8import type { Cls, Palette, Rarity } from '../../types'
9import type { Art } from './doc'
10import { doc, esc } from './doc'
11import type { Pose } from './sprites'
12import { spriteInner } from './sprites'
13
14export type { Art } from './doc'
15export { doc, esc } from './doc'
16
17const COLORS: Record<Palette, Record<Cls, string>> = {
18  escuro: {
19    aprendiz: '#f0a272',
20    mago: '#6c9ff0',
21    cacador: '#6fcf8e',
22    ladino: '#a9adc4',
23    runico: '#5fe3cf',
24    ilusionista: '#b49cf0',
25    sabio: '#8b8ff5',
26    engenheiro: '#d98a6a',
27    bruxo: '#c9ccd6',
28    rei: '#ee7a8e',
29    artifice: '#e9b75c',
30    oraculo: '#8fd3ff',
31    geomante: '#c8a57a',
32    alquimista: '#a8d07a',
33    cartomante: '#e3a8f0',
34    invocador: '#a78bfa',
35    cronomante: '#d7954a',
36    paladino: '#f2c14e',
37    pintor: '#f2715f',
38  },
39  claro: {
40    aprendiz: '#a84e1a',
41    mago: '#2a5bb0',
42    cacador: '#22784a',
43    ladino: '#4d5470',
44    runico: '#137a6b',
45    ilusionista: '#6845bd',
46    sabio: '#3f45b8',
47    engenheiro: '#8a4630',
48    bruxo: '#535866',
49    rei: '#b0324c',
50    artifice: '#855a06',
51    oraculo: '#1b6aa0',
52    geomante: '#7a5a2a',
53    alquimista: '#427a17',
54    cartomante: '#8a3a9e',
55    invocador: '#5b3fc4',
56    cronomante: '#8a5418',
57    paladino: '#8a6400',
58    pintor: '#b23a28',
59  },
60}
61
62/** Tons da pele e da raridade, nas duas paletas do protótipo. */
63// `card` é translúcido (hex de 8 dígitos): destaca a linha sobre qualquer fundo do app.
64export const TONE: Record<Palette, Record<'text' | 'muted' | 'gild' | 'gildDim' | 'ok' | 'bad' | 'warn' | 'pane' | 'card', string>> = {
65  escuro: { text: '#ece9df', muted: '#b3b0a6', gild: '#d9b26a', gildDim: '#8a7346', ok: '#8fc46a', bad: '#ee7a8e', warn: '#e6b450', pane: '#2b2a27', card: '#d9b26a17' },
66  claro: { text: '#1f1e1d', muted: '#57554f', gild: '#7a5310', gildDim: '#c9b48a', ok: '#3d7a1a', bad: '#b23450', warn: '#8a5e00', pane: '#f3f1ea', card: '#7a531014' },
67}
68
69const RARITY: Record<Palette, Record<Rarity, string>> = {
70  escuro: { lendario: '#f0a272', raro: '#6cb6ec', incomum: '#8fc46a', comum: '#d8d5cc', pobre: '#9a988f' },
71  claro: { lendario: '#a84e1a', raro: '#1b6aa0', incomum: '#3d7a1a', comum: '#4a4842', pobre: '#66645d' },
72}
73
74export const classColor = (cls: Cls, palette: Palette) => COLORS[palette][cls]
75export const rarityColor = (rarity: Rarity, palette: Palette) => RARITY[palette][rarity]
76
77type Tone = { text: string; muted: string; dim: string; gild: string; line: string; track: string; ok: string; bad: string; warn: string; hole: string }
78
79const TONES: Record<Palette, Tone> = {
80  escuro: {
81    text: '#ece9df',
82    muted: '#a9a69c',
83    dim: '#7d7a72',
84    gild: '#d9b26a',
85    line: 'rgba(217,178,106,.26)',
86    track: 'rgba(255,255,255,.08)',
87    ok: '#8fc46a',
88    bad: '#ee7a8e',
89    warn: '#e6b450',
90    hole: 'rgba(0,0,0,.35)',
91  },
92  claro: {
93    text: '#1f1e1d',
94    muted: '#57554f',
95    dim: '#7a776f',
96    gild: '#8a6216',
97    line: 'rgba(138,98,22,.32)',
98    track: 'rgba(0,0,0,.08)',
99    ok: '#3d7a1a',
100    bad: '#b23450',
101    warn: '#8a5e00',
102    hole: 'rgba(255,255,255,.7)',
103  },
104}
105
106export const toneOf = (p: Palette) => TONES[p]
107
108const RAR: Record<Palette, Record<Rarity, string>> = {
109  escuro: { lendario: '#f0a272', raro: '#6cb6ec', incomum: '#8fc46a', comum: '#d8d5cc', pobre: '#9a988f' },
110  claro: { lendario: '#a84e1a', raro: '#1b6aa0', incomum: '#3d7a1a', comum: '#4a4842', pobre: '#7a776f' },
111}
112export const rarityTone = (r: Rarity, p: Palette) => RAR[p][r]
113
114/** Corta pelo tamanho aproximado do texto em px (sem DOM para medir). */
115export const fit = (s: string, px: number, size = 11) => {
116  const max = Math.max(3, Math.floor(px / (size * 0.56)))
117  return s.length <= max ? s : `${s.slice(0, max - 1)}…`
118}
119
120// ---------- Clawd ----------
121
122/** O recorte do sprite com o corpo, o que ele veste e o acessório da mão, sem a caixa vazia em volta. */
123const CROP = { x: 14, y: 10, w: 112, h: 80 }
124
125/** O Clawd da classe dentro de outro desenho, recortado, na altura pedida. */
126export const crabAt = (cls: Cls, x: number, y: number, h: number, pose: Pose = 'work') => {
127  const w = (h * CROP.w) / CROP.h
128  return `<svg x="${x}" y="${y}" width="${w.toFixed(1)}" height="${h}" viewBox="${CROP.x} ${CROP.y} ${CROP.w} ${CROP.h}" overflow="visible">${spriteInner(cls, pose)}</svg>`
129}
130
131/** A largura do Clawd recortado numa altura. */
132export const crabWidth = (h: number) => Math.round((h * CROP.w) / CROP.h)
133
134/** O Clawd sozinho, recortado: o pet do chat, da faixa e das linhas do grupo. */
135export const petArt = (cls: Cls, pose: Pose, h: number, tip: string): Art => doc(crabWidth(h), h, crabAt(cls, 0, 0, h, pose), tip, tip)
136
137// ---------- títulos ----------
138
139/** Título do quest log, leve: fio fino, losangos pequenos; `right` é um contador à direita. */
140export const heroTitle = (w: number, label: string, p: Palette, mark?: '!' | '?', right?: string): Art => {
141  const k = TONES[p]
142  const h = 20
143  const text = (mark ? `${mark}  ` : '') + label.toUpperCase()
144  const tw = text.length * 7.4
145  const rightW = right ? right.length * 6.4 + 10 : 0
146  const cx = (w - rightW) / 2
147  const l1 = Math.max(10, cx - tw / 2 - 12)
148  const r1 = Math.min(w - rightW - 10, cx + tw / 2 + 12)
149  const dia = (x: number) => `<rect x="${x - 2.5}" y="${h / 2 - 2.5}" width="5" height="5" fill="${k.gild}" opacity=".7" transform="rotate(45 ${x} ${h / 2})"/>`
150  const inner =
151    (l1 > 16 ? `<line x1="6" y1="${h / 2}" x2="${l1 - 6}" y2="${h / 2}" stroke="${k.line}"/>` : '') +
152    dia(l1) +
153    `<text x="${cx}" y="${h / 2 + 3.6}" text-anchor="middle" font-size="10.5" letter-spacing="2" font-weight="600" fill="${k.gild}">${esc(text)}</text>` +
154    dia(r1) +
155    (w - rightW - 6 > r1 + 12 ? `<line x1="${r1 + 6}" y1="${h / 2}" x2="${w - rightW - 6}" y2="${h / 2}" stroke="${k.line}"/>` : '') +
156    (right ? `<text x="${w}" y="${h / 2 + 3.6}" text-anchor="end" font-size="10.5" fill="${k.muted}">${esc(right)}</text>` : '')
157  return doc(w, h, inner, label)
158}
159
160// ---------- progresso do objetivo ----------
161
162export type Step = { name: string; state: 'done' | 'now' | 'next' }
163
164const pctOf = (steps: readonly Step[]) => {
165  if (steps.length === 0) return 0
166  const done = steps.filter(s => s.state === 'done').length
167  return Math.round(((done + (steps.some(s => s.state === 'now') ? 0.5 : 0)) / steps.length) * 100)
168}
169
170export type StepWords = { step: (n: number, name: string, state: Step['state']) => string; steps: (done: number, total: number) => string; chapter: (n: number) => string }
171
172/** A barra do objetivo: fina, de canto a canto, um losango por passo (ToxiUI). */
173/** Losangos desenhados no máximo: os mais recentes. Contagem e % usam sempre todas as etapas. */
174const MAX_MARKS = 12
175
176export const objectiveBar = (w: number, steps: readonly Step[], chapter: number, p: Palette, words: StepWords): Art => {
177  const k = TONES[p]
178  const h = 36
179  const done = steps.filter(s => s.state === 'done').length
180  const pct = pctOf(steps)
181  const pad = 5
182  const inner0 = w - pad * 2
183  let marks = ''
184  // Só os últimos MAX_MARKS losangos, espaçados pela barra; o número no tooltip é o da etapa real.
185  const skip = Math.max(0, steps.length - MAX_MARKS)
186  const shown = steps.slice(skip)
187  shown.forEach((s, i) => {
188    const x = pad + (inner0 * (i + 1)) / shown.length
189    const lit = s.state === 'done'
190    marks += `<g><title>${esc(words.step(skip + i + 1, s.name, s.state))}</title><rect class="${s.state === 'now' ? 'breath' : ''}" x="${x - 3.5}" y="6.5" width="7" height="7" transform="rotate(45 ${x} 10)" fill="${lit || s.state === 'now' ? k.gild : k.hole}" stroke="${k.gild}" stroke-opacity="${lit ? 1 : 0.55}" stroke-width="1.2"/></g>`
191  })
192  const inner =
193    `<defs><linearGradient id="gl" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#b8904a"/><stop offset="1" stop-color="#ecc985"/></linearGradient></defs>` +
194    `<rect x="${pad}" y="8.5" width="${inner0}" height="3" rx="1.5" fill="${k.track}"/>` +
195    `<rect x="${pad}" y="8.5" width="${(inner0 * pct) / 100}" height="3" rx="1.5" fill="url(#gl)"/>` +
196    marks +
197    `<text x="0" y="31" font-size="10.5" fill="${k.muted}"><tspan fill="${k.gild}" font-weight="700">${done}/${steps.length}</tspan> ${esc(words.steps(done, steps.length))} · ${esc(words.chapter(chapter))}</text>` +
198    `<text x="${w}" y="31" text-anchor="end" font-size="10" fill="${k.dim}">${pct}%</text>`
199  return doc(w, h, inner, `${done}/${steps.length}`)
200}
201
202// ---------- inventário ----------
203
204// ---------- diário no chat ----------
205
206/** Só o pet, de 36 px de altura: ele é o destaque da linha; na falha, a pose de falha. */
207export const diaryPet = (cls: Cls, state: 'run' | 'ok' | 'err', tip: string): Art => petArt(cls, state === 'err' ? 'fail' : 'work', 44, tip)
208
209/** O anel girando do diário, sem contorno: a ferramenta ainda em curso. */
210export const spinRing = (color: string, tip: string): Art =>
211  doc(
212    14,
213    14,
214    `<circle cx="7" cy="7" r="5" fill="none" stroke="${color}" stroke-opacity=".3" stroke-width="1.6"/><path d="M7 2 A5 5 0 0 1 12 7" fill="none" stroke="${color}" stroke-width="1.6" stroke-linecap="round"><animateTransform attributeName="transform" type="rotate" from="0 7 7" to="360 7 7" dur="1s" repeatCount="indefinite"/></path>`,
215    tip,
216    tip,
217  )
218
219export const statusColor = (state: 'run' | 'ok' | 'err', p: Palette) =>
220  state === 'run' ? classColor('aprendiz', p) : state === 'err' ? TONES[p].bad : TONES[p].ok
221
222// ---------- faixa compacta ----------
223
224/** A trilha do plano em miniatura, para a faixa: um losango por passo. */
225export const trailArt = (total: number, done: number, p: Palette, tip: string): Art => {
226  const k = TONES[p]
227  const shown = Math.min(total, MAX_MARKS)
228  const lit = Math.max(0, done - (total - shown))
229  const gap = 12
230  const w = Math.max(24, (shown - 1) * gap + 10)
231  let inner = `<line x1="5" y1="7" x2="${w - 5}" y2="7" stroke="${k.gild}" stroke-opacity=".3"/><line x1="5" y1="7" x2="${5 + Math.min(lit, shown - 1) * gap}" y2="7" stroke="${k.gild}"/>`
232  for (let i = 0; i < shown; i++) {
233    const x = 5 + i * gap
234    const on = i < lit
235    const cur = i === lit
236    inner += `<rect x="${x - 3}" y="4" width="6" height="6" transform="rotate(45 ${x} 7)" fill="${on ? k.gild : 'none'}" ${on ? '' : `stroke="${k.gild}" stroke-opacity=".6"`} ${cur ? 'class="breath"' : ''}/>`
237  }
238  return doc(w, 14, inner, tip, tip)
239}
240
241/** Barra fina de recurso, entre dois `Text` nativos do rodapé. */
242export const barArt = (w: number, pct: number, color: string, tip: string, alert = false, p: Palette = 'escuro'): Art => {
243  const fill = Math.max(0, Math.min(100, pct)) / 100
244  return doc(
245    w,
246    12,
247    `<rect x="0" y="4" width="${w}" height="4" rx="2" fill="${TONES[p].track}"/><rect ${alert ? 'class="breath" ' : ''}x="0" y="4" width="${(w * fill).toFixed(1)}" height="4" rx="2" fill="${color}"/>`,
248    tip,
249    tip,
250  )
251}
252
253// ---------- polimento: ícones, cabeçalhos, desfile, grimório e recursos ----------
254
255const PARADE: Cls[] = ['mago', 'runico', 'bruxo', 'rei', 'aprendiz', 'engenheiro', 'sabio', 'cartomante', 'pintor']
256
257/** Losango de ornamento. */
258const dia = (x: number, y: number, r: number, fill: string, op = 0.75) =>
259  `<rect x="${x - r}" y="${y - r}" width="${r * 2}" height="${r * 2}" fill="${fill}" opacity="${op}" transform="rotate(45 ${x} ${y})"/>`
260
261/**
262 * O desfile do README: os 9 Clawds em fila, saltitando em ondas, e o título
263 * embaixo com ornamentos. `subtitle` é opcional (o Sobre põe a versão).
264 */
265export const parade = (w: number, title: string, p: Palette, subtitle?: string): Art => {
266  const k = toneOf(p)
267  const size = Math.min(40, Math.floor((w - 16) / PARADE.length))
268  const rowW = size * PARADE.length
269  const x0 = (w - rowW) / 2
270  // .parade-hop, não .hop: os sprites têm uma classe .hop própria, que esconderia o desfile.
271  let inner = '<style>.parade-hop{animation:phop 2.4s ease-in-out infinite}@keyframes phop{0%,100%{transform:none}50%{transform:translateY(-4px)}}</style>'
272  const { lean, css } = sharedStyles()
273  PARADE.forEach((cls, i) => {
274    inner += `<g class="parade-hop" style="animation-delay:${(i * 0.18).toFixed(2)}s">${lean(crabAt(cls, x0 + i * size + 1, 6, Math.round(((size - 2) * 80) / 112)))}</g>`
275  })
276  const ty = size + 26
277  const tw = title.length * 10
278  inner +=
279    `<line x1="${w / 2 - tw / 2 - 70}" y1="${ty - 4}" x2="${w / 2 - tw / 2 - 14}" y2="${ty - 4}" stroke="${k.line}"/>` +
280    dia(w / 2 - tw / 2 - 8, ty - 4, 3, k.gild) +
281    `<text x="${w / 2}" y="${ty}" text-anchor="middle" font-size="12" letter-spacing="2.6" font-weight="700" fill="${k.gild}">${esc(title.toUpperCase())}</text>` +
282    dia(w / 2 + tw / 2 + 8, ty - 4, 3, k.gild) +
283    `<line x1="${w / 2 + tw / 2 + 14}" y1="${ty - 4}" x2="${w / 2 + tw / 2 + 70}" y2="${ty - 4}" stroke="${k.line}"/>`
284  let h = ty + 8
285  if (subtitle) {
286    inner += `<text x="${w / 2}" y="${ty + 18}" text-anchor="middle" font-size="10.5" fill="${k.muted}">${esc(subtitle)}</text>`
287    h = ty + 26
288  }
289  return doc(w, h, css() + inner, title)
290}
291
292/**
293 * Cada sprite traz o próprio <style>, igual em todos; vários num Svg só passariam do
294 * limite do motor (128 KB). `lean` tira o estilo de cada um e `css` devolve um de cada.
295 */
296const sharedStyles = () => {
297  const styles = new Set<string>()
298  const lean = (svg: string) =>
299    svg.replace(/<style>([\s\S]*?)<\/style>/g, (_, rule: string) => {
300      styles.add(rule)
301      return ''
302    })
303  return { lean, css: () => `<style>${[...styles].join('')}</style>` }
304}
305
306/**
307 * A galeria do Sobre: as 19 classes em grade, cada Clawd na pose de trabalho com o
308 * nome embaixo; o tooltip de cada um diz o que ele faz. Em blocos de duas fileiras:
309 * cada sprite tem uns 6 KB, e 19 num Svg só passariam do limite do motor (128 KB).
310 */
311export const classGallery = (w: number, classes: readonly Cls[], name: (cls: Cls) => string, role: (cls: Cls) => string, p: Palette): Art[] => {
312  const per = 10
313  const blocks: Art[] = []
314  for (let i = 0; i < classes.length; i += per) blocks.push(galleryBlock(w, classes.slice(i, i + per), name, role, p))
315  return blocks
316}
317
318const galleryBlock = (w: number, classes: readonly Cls[], name: (cls: Cls) => string, role: (cls: Cls) => string, p: Palette): Art => {
319  const cols = 5
320  const slot = Math.floor(w / cols)
321  const h = Math.min(36, Math.round((slot - 8) / 1.4))
322  const rowH = h + 22
323  const { lean, css } = sharedStyles()
324  let inner = ''
325  classes.forEach((cls, i) => {
326    const col = i % cols
327    const row = Math.floor(i / cols)
328    const cx = col * slot + slot / 2
329    const y = row * rowH + 2
330    inner +=
331      `<g><title>${esc(`${name(cls)} · ${role(cls)}`)}</title><rect x="${col * slot}" y="${y - 2}" width="${slot}" height="${rowH}" fill="transparent"/>` +
332      lean(crabAt(cls, cx - crabWidth(h) / 2, y, h)) +
333      `<text x="${cx}" y="${y + h + 14}" text-anchor="middle" font-size="10.5" fill="${classColor(cls, p)}">${esc(name(cls))}</text></g>`
334  })
335  return doc(w, Math.ceil(classes.length / cols) * rowH, css() + inner, classes.map(name).join(', '))
336}
337
338// Ícones pequenos, desenhados (16 px), para cabeçalhos e listas.
339const ICON: Record<string, (c: string) => string> = {
340  geral: c => `<circle cx="8" cy="8" r="6" fill="none" stroke="${c}" stroke-width="1.4"/><path d="M2 8h12M8 2c2.5 2.6 2.5 9.4 0 12M8 2c-2.5 2.6-2.5 9.4 0 12" fill="none" stroke="${c}" stroke-width="1.1"/>`,
341  modulos: c => `<rect x="2" y="2" width="5" height="5" rx="1" fill="${c}"/><rect x="9" y="2" width="5" height="5" rx="1" fill="${c}" opacity=".6"/><rect x="2" y="9" width="5" height="5" rx="1" fill="${c}" opacity=".6"/><rect x="9" y="9" width="5" height="5" rx="1" fill="${c}"/>`,
342  painel: c => `<rect x="2" y="2" width="12" height="12" rx="2" fill="none" stroke="${c}" stroke-width="1.4"/><path d="M9 2v12" stroke="${c}" stroke-width="1.4"/><path d="M10.5 5h2M10.5 8h2M10.5 11h2" stroke="${c}"/>`,
343  diario: c => `<path d="M3 2h8l2 2v10H3z" fill="none" stroke="${c}" stroke-width="1.4"/><path d="M5 6h6M5 9h6M5 12h4" stroke="${c}"/>`,
344  protecao: c => `<path d="M8 1.5 13.5 4v4c0 3.2-2.4 5.6-5.5 6.5C4.9 13.6 2.5 11.2 2.5 8V4z" fill="${c}" fill-opacity=".2" stroke="${c}" stroke-width="1.4"/><path d="M5.5 8l2 2 3-3.5" fill="none" stroke="${c}" stroke-width="1.4"/>`,
345  memoria: c => `<path d="M2 3.5C4.5 2.5 6.5 2.8 8 4c1.5-1.2 3.5-1.5 6-.5v9c-2.5-1-4.5-.7-6 .5-1.5-1.2-3.5-1.5-6-.5z" fill="${c}" fill-opacity=".2" stroke="${c}" stroke-width="1.3"/><path d="M8 4v9" stroke="${c}"/>`,
346  objetivo: c => `<circle cx="8" cy="8" r="6" fill="none" stroke="${c}" stroke-width="1.3"/><circle cx="8" cy="8" r="3" fill="none" stroke="${c}" stroke-width="1.3"/><circle cx="8" cy="8" r="1" fill="${c}"/>`,
347  grupo: c => `<path d="M3 13 13 3M3 3l10 10" stroke="${c}" stroke-width="1.6" stroke-linecap="round"/><path d="M2 11.5 4.5 14M11.5 14 14 11.5" stroke="${c}" stroke-width="1.6"/>`,
348  inventario: c => `<rect x="3" y="5" width="10" height="9" rx="2" fill="${c}" fill-opacity=".25" stroke="${c}" stroke-width="1.3"/><path d="M6 5V3.5h4V5" fill="none" stroke="${c}" stroke-width="1.3"/>`,
349  grimorio: c => `<rect x="3" y="2" width="10" height="12" rx="1.5" fill="${c}" fill-opacity=".25" stroke="${c}" stroke-width="1.3"/><path d="M8 5l.9 1.8 2 .3-1.4 1.4.3 2L8 9.6 6.2 10.5l.3-2L5.1 7.1l2-.3z" fill="${c}"/>`,
350  projeto: c => `<path d="M2 5h12v8H2z" fill="none" stroke="${c}" stroke-width="1.3"/><path d="M2 5l2-2.5h4L9 5" fill="none" stroke="${c}" stroke-width="1.3"/><path d="M6 9h4M8 7v4" stroke="${c}" stroke-width="1.3"/>`,
351}
352
353export type IconName = keyof typeof ICON
354
355const iconSvg = (name: IconName, color: string, x = 0, y = 0) => `<g transform="translate(${x} ${y})">${ICON[name]?.(color) ?? ''}</g>`
356
357/** Ícone sozinho (16 px), com tooltip. */
358export const icon = (name: IconName, p: Palette, tip: string, tone: 'gild' | 'muted' = 'gild'): Art => {
359  const k = toneOf(p)
360  return doc(16, 16, iconSvg(name, tone === 'gild' ? k.gild : k.muted), tip, tip)
361}
362
363/** Cabeçalho de categoria do ⚙: ícone, rótulo em versalete e um fio fino até a borda. */
364export const categoryHeader = (w: number, name: IconName, label: string, p: Palette, tip?: string): Art => {
365  const k = toneOf(p)
366  const text = label.toUpperCase()
367  const tw = text.length * 7.6
368  const inner =
369    iconSvg(name, k.gild, 0, 2) +
370    `<text x="24" y="14.5" font-size="11" letter-spacing="1.8" font-weight="700" fill="${k.gild}">${esc(text)}</text>` +
371    `<line x1="${24 + tw + 10}" y1="10" x2="${w - (tip ? 22 : 0)}" y2="10" stroke="${k.line}"/>` +
372    (tip ? `<circle cx="${w - 8}" cy="10" r="7" fill="none" stroke="${k.gild}" stroke-opacity=".6"/><text x="${w - 8}" y="14" text-anchor="middle" font-size="10" font-weight="700" fill="${k.gild}">?</text>` : '')
373  return doc(w, 20, inner, label, tip)
374}
375
376export type ResRow = {
377  key: 'mochila' | 'mana' | 'vigor'
378  label: string
379  /** 0 a 100: quanto a barra enche; undefined antes da primeira leitura. */
380  value?: number
381  color: string
382  /** O número em destaque ("37%"). */
383  text: string
384  /** O resto da linha, em tom fraco ("Leve", "↻ 3h56", "recarregada"). */
385  sub: string
386  tip: string
387  /** Recurso em alerta: a barra pulsa devagar. */
388  pulse?: boolean
389}
390
391export type Feature = { icon: IconName; title: string; text: string }
392
393/** A lista do Sobre: ícone, título curto e uma linha. */
394export const featureList = (w: number, items: readonly Feature[], p: Palette): Art => {
395  const k = toneOf(p)
396  let inner = ''
397  items.forEach((f, i) => {
398    const y = i * 36
399    inner +=
400      `<rect x=".5" y="${y + 2.5}" width="27" height="27" rx="6" fill="${k.gild}" fill-opacity=".08" stroke="${k.line}"/>` +
401      iconSvg(f.icon, k.gild, 6, y + 8) +
402      `<text x="38" y="${y + 14}" font-size="12" font-weight="700" fill="${k.text}">${esc(f.title)}</text>` +
403      `<text x="38" y="${y + 28}" font-size="10.5" fill="${k.muted}">${esc(fit(f.text, w - 40, 10.5))}</text>`
404  })
405  return doc(w, items.length * 36, inner, items.map(f => f.title).join(', '))
406}
407
408// ---------- proteção e "Sobre" ----------
409
410const FILE_ICON = {
411  env: (c: string) =>
412    `<rect x="1" y="1" width="14" height="18" rx="2" fill="none" stroke="${c}" stroke-width="1.6"/><circle cx="6.5" cy="12" r="2.6" fill="none" stroke="${c}" stroke-width="1.6"/><line x1="9" y1="12" x2="13" y2="12" stroke="${c}" stroke-width="1.6"/><line x1="11.5" y1="12" x2="11.5" y2="14.5" stroke="${c}" stroke-width="1.6"/>`,
413  pipeline: (c: string) =>
414    `<circle cx="3.5" cy="4" r="2.5" fill="${c}"/><circle cx="12.5" cy="10" r="2.5" fill="${c}"/><circle cx="3.5" cy="16" r="2.5" fill="${c}"/><path d="M3.5 6.5 V13.5 M5.5 5 L10.5 9 M5.5 15 L10.5 11" stroke="${c}" stroke-width="1.4" fill="none"/>`,
415  file: (c: string) =>
416    `<path d="M2 1 H10 L14 5 V19 H2 Z" fill="none" stroke="${c}" stroke-width="1.6"/><path d="M10 1 V5 H14" fill="none" stroke="${c}" stroke-width="1.4"/>`,
417}
418
419export const fileKind = (name: string): keyof typeof FILE_ICON =>
420  /pipelines?.*\.ya?ml$/i.test(name) ? 'pipeline' : /(^|[\\/])\.env/i.test(name) ? 'env' : 'file'
421
422/** Um item do inventário: ícone na cor da raridade, com o nome e a raridade no tooltip. */
423export const itemIcon = (name: string, rarity: Rarity, palette: Palette, tip: string): Art => {
424  const c = rarityColor(rarity, palette)
425  const source =
426    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="-2 -1 20 22" width="18" height="20"><title>${esc(tip)}</title>` +
427    `<rect x="-1" y="0" width="18" height="20" rx="3" fill="${c}" fill-opacity=".14"/>${FILE_ICON[fileKind(name)](c)}</svg>`
428  return { source, width: 18, height: 20, alt: tip }
429}
430
431/** Ícones do "Sobre". Paths simples, desenhados aqui, sem copiar logotipo. */
432export const linkIcon = (kind: 'linkedin' | 'github', palette: Palette, tip: string): Art => {
433  const c = TONE[palette].text
434  const glyph =
435    kind === 'linkedin'
436      ? `<rect x="1" y="1" width="18" height="18" rx="3.5" fill="none" stroke="${c}" stroke-width="1.6"/><rect x="5" y="8.5" width="2.4" height="7" fill="${c}"/><circle cx="6.2" cy="5.8" r="1.5" fill="${c}"/><path d="M10 15.5 V8.5 H12.3 V9.6 Q13.2 8.3 14.8 8.4 Q16.6 8.6 16.6 11 V15.5 H14.3 V11.6 Q14.3 10.3 13.3 10.3 Q12.3 10.3 12.3 11.6 V15.5 Z" fill="${c}"/>`
437      : `<circle cx="10" cy="10" r="8.6" fill="none" stroke="${c}" stroke-width="1.6"/><path d="M7.4 17.6 V14.6 Q6.9 13.6 7.8 12.9 Q5.2 12.4 5.2 9.6 Q5.2 8.4 6 7.6 Q5.7 6.6 6.1 5.6 Q7.2 5.6 8.1 6.4 Q10 5.8 11.9 6.4 Q12.8 5.6 13.9 5.6 Q14.3 6.6 14 7.6 Q14.8 8.4 14.8 9.6 Q14.8 12.4 12.2 12.9 Q13.1 13.6 12.6 14.6 V17.6" fill="none" stroke="${c}" stroke-width="1.4" stroke-linejoin="round"/>`
438  return {
439    source: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20"><title>${esc(tip)}</title>${glyph}</svg>`,
440    width: 20,
441    height: 20,
442    alt: tip,
443  }
444}
445
446// ---------- guarda ----------
447
448/**
449 * A cabeça do dragão vermelho da guarda, de perfil para a direita, a partir da
450 * referência que o Saulo escolheu: amostrada em grade de 34×38, sem o céu, e
451 * reduzida à paleta chapada dos Clawds. K contorno, M/r/R/L do vermelho escuro ao
452 * claro, O/o papo, H/h chifre, E olho, T dente.
453 */
454const DRAGON = [
455  '..................................',
456  '.KK...........K...................',
457  '.KHH..........HHH.................',
458  '.KHH..........HHHK................',
459  '.KHHK..........KHHKK..............',
460  '.KHHHHH....HHH..KHHHHKK...........',
461  '..KHHHHK....MMH..HHHHHH...........',
462  '..KHHHHHKH..KMM..KKKHHHH..........',
463  '...KHHHHhHHHKKMMMKKHHHHHHK........',
464  '...KHHHHHHHHHKKMMKKKHHHHHK........',
465  '....HHHHHHHhHHHKMMKKKKHHHHK.......',
466  '.....KHHHHHHHhHrMMMKrrKKHHH.......',
467  '.....KKHHHHHHMRRRMMKMRKKHHH.......',
468  '....HMMHHHHHHMMrRrMMMRRMKHKK......',
469  '...MMMMKKKHHKMMrrrRRMrRMrKrMH.....',
470  '.KMMMKKKKKKKKKMMrRRRRMrrMRMRRK....',
471  '.KKKMKMrMKKKMMMMMrRRRrrRMRrrRRK...',
472  '...HKKKMrrrrMMMMMrrRRRrRRMRrrRRK..',
473  '...HMKKKMMrMrMMKKKKMRRRRMRrRMRRK..',
474  '..KMKMKKKKMMMMMMKMrrMRRRMRMrMrrK..',
475  '.KMKMKKKKKKMMMrMMEEKHMMRMMMMMMK...',
476  'HMKKMKKKKKMMMrrrMoEKKKKMrrrrMK....',
477  'KKKMMKMKRRrMMMrrrMKKKKMMMrRRRrK...',
478  'K.KMMKKMMrrrMMMMrrrMMMMrMMrRRRM.KH',
479  '.KMMMKKKKKMMMMMMMrrrrrrrrrMMRRRKMr',
480  '.MMMMMKKKKMMrrMMMMMMMrrrrrMRMRRRRr',
481  '.MMMMMMKKKMrMrrMMMMMMMrrrrKMRMRRRM',
482  '.MMMMMMKKMMMMrrRRMMMMMMrrrrKRMRRRK',
483  'KKKMMMKKKMMMMrrRRRrrHKMMMrrrMMrRrM',
484  'KKKMMMMKKKKKMrrrRRRRrrKMMMrrrrrRrM',
485  'K.KMMKMKKKKKMMrrRRRRoorMOTrrrrrRrM',
486  '..KMKMMMKMKKMMKMMrrRRooMOorrMMrrMH',
487  '.HMMKMMMKMMKKKMMMKKKMRRRRooOLKrMK.',
488  '.HMMMMMMMKMMMMMMMMMMKKRRRRLLORMK..',
489  '.HMKMMMMMKMMMMMMMMMK..KKrrLOOOM...',
490  '.HK.MMMMMMMMMrrrMMMM.....KROOoH...',
491  '.H..MMKKMMMMrMMrrrrr......MLLK....',
492  '....MMKKMMMMMrrMrrrrr.....MLK.....',
493]
494const DRAGON_INK: Record<string, string> = {
495  K: '#1c1012',
496  M: '#5c1814',
497  r: '#8f2a16',
498  R: '#c03c1a',
499  L: '#e2602a',
500  O: '#e8902e',
501  o: '#b5642a',
502  H: '#2f343f',
503  h: '#6b717e',
504  E: '#ffb020',
505  T: '#f4efe2',
506}
507
508/** Onde a fumaça sai: a frente da boca, em células da grade. */
509const MOUTH = [31, 31] as const
510
511/**
512 * A guarda dos protegidos: a cabeça do dragão vermelho, pequena (72×57, menor que o
513 * baú da 0.5), com fumaça saindo da boca: baforadas que sobem, crescem e somem.
514 * Desenhada em células (1 célula = 1,5 px); o olho pisca. Sem animação, a fumaça fica parada.
515 */
516export const dragonArt = (tip: string): Art => {
517  const scale = 1.5
518  let head = ''
519  DRAGON.forEach((row, y) => {
520    let x = 0
521    while (x < row.length) {
522      const ch = row[x]!
523      let end = x
524      while (end + 1 < row.length && row[end + 1] === ch) end++
525      const fill = DRAGON_INK[ch]
526      if (fill !== undefined) head += `<rect x="${x}" y="${y}" width="${end - x + 1}" height="1" fill="${fill}"${ch === 'E' ? ' class="dg-eye"' : ''}/>`
527      x = end + 1
528    }
529  })
530  const [mx, my] = MOUTH
531  // Cada baforada é um tufo de pixels cinza; três em sequência, com atraso.
532  const puff = (d: number, dy: number) =>
533    `<g class="dg-smoke" style="--dy:${dy}px;animation-delay:${d}s">` +
534    `<rect x="${mx + 1}" y="${my - 2}" width="3" height="1" fill="#b3ada4"/><rect x="${mx}" y="${my - 1}" width="5" height="1" fill="#9a948b"/>` +
535    `<rect x="${mx}" y="${my}" width="5" height="1" fill="#8a847c"/><rect x="${mx + 1}" y="${my + 1}" width="3" height="1" fill="#9a948b"/></g>`
536  const smoke = puff(0, -5) + puff(0.7, -7) + puff(1.4, -4)
537  const gw = DRAGON[0]!.length + 14
538  const gh = DRAGON.length
539  const css =
540    '<style>' +
541    '.dg-smoke{transform-box:fill-box;transform-origin:center;opacity:0;animation:dgs 2.1s ease-out infinite}' +
542    '@keyframes dgs{0%{opacity:.9;transform:none}100%{opacity:0;transform:translate(11px,var(--dy)) scale(2.2)}}' +
543    '.dg-eye{animation:dge 4.4s infinite}@keyframes dge{0%,94%,100%{opacity:1}96%{opacity:.2}}' +
544    '@media (prefers-reduced-motion:reduce){.dg-smoke{animation:none;opacity:.6}.dg-eye{animation:none}}' +
545    '</style>'
546  const w = Math.round(gw * scale)
547  const h = Math.round(gh * scale)
548  return {
549    source: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${gw} ${gh}" width="${w}" height="${h}" shape-rendering="crispEdges"><title>${esc(tip)}</title>${css}${head}${smoke}</svg>`,
550    width: w,
551    height: h,
552    alt: tip,
553  }
554}
555
556// ---------- grimório ----------
557
558/** As estrelinhas que piscam ao lado do Selar no grimório. */
559export const sparkleArt = (p: Palette): Art => {
560  const g = TONES[p].gild
561  return doc(
562    26,
563    20,
564    `<text class="glow" x="2" y="14" font-size="11" fill="${g}">✦</text><text class="glow" style="animation-delay:.8s" x="13" y="9" font-size="8" fill="${g}">✧</text><text class="glow" style="animation-delay:1.5s" x="16" y="18" font-size="7" fill="${g}">✦</text>`,
565    '✦',
566  )
567}
568
hooks/core/i18n.ts 865 lines
1// Textos da HUD em português do Brasil e em inglês. A língua sai da opção
2// `language` do mod (auto, pt-BR ou en); em `auto`, segue a do Claude.
3
4import type { Cls, Destination, GuardMode, InscriptionKind, Lang, ModuleId, Rarity } from '../../types'
5import type { BagState } from '../modules/mochila/recursos'
6import type { Place } from './cenarios'
7
8const PT = {
9  className: {
10    aprendiz: 'Aprendiz',
11    mago: 'Mago',
12    cacador: 'Caçador',
13    ladino: 'Ladino',
14    runico: 'Rúnico',
15    ilusionista: 'Ilusionista',
16    sabio: 'Sábio',
17    engenheiro: 'Engenheiro',
18    bruxo: 'Bruxo',
19    rei: 'Rei',
20    artifice: 'Artífice',
21    oraculo: 'Oráculo',
22    geomante: 'Geomante',
23    alquimista: 'Alquimista',
24    cartomante: 'Cartomante',
25    invocador: 'Invocador',
26    cronomante: 'Cronomante',
27    paladino: 'Paladino',
28    pintor: 'Pintor',
29  } satisfies Record<Cls, string>,
30  /** O verbo de cada classe trabalhando, antes do arquivo ou do comando ("Mago lendo art.ts"). */
31  classRole: {
32    aprendiz: 'pensa e responde',
33    mago: 'lê e busca no projeto',
34    cacador: 'pesquisa na web',
35    ladino: 'navega em sites',
36    runico: 'edita código',
37    ilusionista: 'mexe em telas e estilo',
38    sabio: 'escreve docs e guarda a memória',
39    engenheiro: 'roda comandos e builds',
40    bruxo: 'testes, lint e tipos',
41    rei: 'git, commit e PR',
42    artifice: 'pipeline, deploy e infra',
43    oraculo: 'lê logs e monitora',
44    geomante: 'banco de dados',
45    alquimista: 'APIs e integrações',
46    cartomante: 'planeja e organiza tarefas',
47    invocador: 'lidera subagentes',
48    cronomante: 'agenda e automatiza',
49    paladino: 'segurança e revisão',
50    pintor: 'design visual',
51  } satisfies Record<Cls, string>,
52  classVerb: {
53    aprendiz: 'pensando',
54    mago: 'lendo',
55    cacador: 'pesquisando',
56    ladino: 'navegando',
57    runico: 'escrevendo',
58    ilusionista: 'montando',
59    sabio: 'registrando',
60    engenheiro: 'rodando',
61    bruxo: 'caçando bugs',
62    rei: 'selando',
63    artifice: 'forjando',
64    oraculo: 'lendo os sinais',
65    geomante: 'moldando',
66    alquimista: 'misturando',
67    cartomante: 'planejando',
68    invocador: 'invocando',
69    cronomante: 'agendando',
70    paladino: 'protegendo',
71    pintor: 'pintando',
72  } satisfies Record<Cls, string>,
73  placeName: {
74    treino: 'Campo de treino',
75    biblioteca: 'Biblioteca',
76    runas: 'Círculo de runas',
77    oficina: 'Oficina',
78    pantano: 'Pântano',
79    acampamento: 'Acampamento',
80    trono: 'Sala do trono',
81    teatro: 'Teatro das ilusões',
82    torre: 'Torre do sábio',
83    floresta: 'Floresta da lua',
84    beco: 'Beco',
85    forja: 'Forja',
86    santuario: 'Santuário',
87    muralha: 'Muralha de pedra',
88    laboratorio: 'Laboratório',
89    tenda: 'Tenda das cartas',
90    salao: 'Salão arcano',
91    camara: 'Câmara do tempo',
92    portal: 'Portal',
93    atelie: 'Ateliê',
94  } satisfies Record<Place, string>,
95  // O palco: quem está em cena e o que faz.
96  yourTurn: 'Sua vez',
97  answered: (clock: string) => (clock === '' ? 'a resposta chegou' : `respondeu às ${clock}`),
98  asleep: 'descansando',
99  asleepNote: (clock: string) => (clock === '' ? 'a sessão está parada' : `sessão parada desde ${clock}`),
100  freshCamp: 'esperando a primeira mensagem',
101  stumbled: 'tropeçou',
102  failedNote: (what: string) => `${what} falhou · tentando de novo`,
103  onExpeditionTitle: 'Em expedição',
104  spinResponding: 'escrevendo a resposta',
105  startedAt: (clock: string) => (clock === '' ? '' : `começou às ${clock}`),
106  doneSteps: (n: number) => (n === 1 ? '✓ 1 passo feito' : `✓ ${n} passos feitos`),
107  section: {
108    objetivo: 'Objetivo',
109    quests: 'Quests do capítulo',
110    grupo: 'Grupo',
111    inventario: 'Inventário',
112  },
113  module: {
114    diario: ['Diário de bordo', 'O Clawd da classe e o resultado em cada linha de ferramenta, durante o turno'],
115    faixa: ['Faixa acima do prompt', 'Uma linha com quem age, o arquivo e a trilha do plano; e o spinner diz a classe'],
116    painel: ['Painel', 'O palco com a classe em ação, o objetivo e, quando há, o plano, o grupo e o inventário'],
117    campanha: ['Campanha', 'Objetivo e capítulos; ✦ Recalibrar usa o Haiku'],
118    recibo: ['Recibo do turno', 'Uma linha embaixo da resposta: quem agiu, +/−, falhas e tempo'],
119    guarda: ['Guarda dos protegidos', 'Pergunta antes de editar .env, pipelines e afins (e antes de comandos que os escrevem)'],
120    mochila: ['Mochila', 'Cartão de compactação quando a mochila pesa; Compactar agora gasta tokens'],
121    grimorio: ['Grimório', 'Salvar progresso e continuar, crônica e regras; o ⚙ Memória ajusta cada recurso'],
122  } satisfies Record<ModuleId, [string, string]>,
123  tokens: 'pode gastar tokens (só com o seu clique)',
124  paneNotPlaced: (why: string) => `O painel não abriu (${why}). Alargue a janela do Claude Code.`,
125  rarity: {
126    lendario: 'Lendário: protegidos (.env, pipelines, segredos)',
127    raro: 'Raro: críticos (API, banco, auth, build)',
128    incomum: 'Incomum: código e telas',
129    comum: 'Comum: testes, docs e config leve',
130    pobre: 'Pobre: excluídos',
131  } satisfies Record<Rarity, string>,
132  noObjective: 'O objetivo aparece com a primeira mensagem da sessão.',
133  setupTagline: 'Bem-vindo à jornada.',
134  knownTypes: { explore: 'Explorador', plan: 'Arquiteto', 'claude-code-guide': 'Guia do Claude Code', 'statusline-setup': 'Status line' } as Record<string, string>,
135  ago: (s: number) => (s < 90 ? 'agora' : s < 3600 ? `há ${Math.round(s / 60)} min` : s < 86400 ? `há ${Math.round(s / 3600)} h` : `há ${Math.round(s / 86400)} d`),
136  catGeneral: 'Geral',
137  catMemory: 'Memória',
138  rowChat: 'No chat',
139  rowPanel: 'No painel',
140  rowGuard: 'Proteção',
141  langAutoShort: 'Auto',
142  grimoireRow: 'Grimório',
143  haikuShort: 'Resumir com Haiku',
144  aboutTagline: (v: string) => `v${v} · uma HUD de RPG aconchegante para o Claude Code`,
145  aboutBy: 'Quem fez',
146  authorRole: 'desenvolvedor · Angular, .NET e Azure DevOps',
147  aboutFeatures: [
148    ['O palco', 'O Clawd da classe certa em ação; parado, o acampamento.'],
149    ['Grupo e expedições', 'Cada subagente vira um herói, com a classe do que faz.'],
150    ['Mochila e recursos', 'Contexto e janelas de uso; avisa antes de compactar.'],
151    ['Guarda dos protegidos', 'Um dragão barra o Claude antes de mexer em .env, pipelines e chaves.'],
152    ['Grimório', 'Salvar progresso, decisões e regras, só com o seu clique.'],
153  ] as [string, string][],
154  recalibrate: '✦ Recalibrar objetivo',
155  recalibrateShort: 'Recalibrar',
156  markAchievedShort: 'Alcançado?',
157  recalibrateDone: (goal: string) => `✦ Objetivo: ${goal}`,
158  recalibrateFail: 'O Haiku não respondeu; o objetivo ficou como estava.',
159  recalibratePrompt: (asks: string[]) =>
160    `Estes são os pedidos que a pessoa fez nesta sessão do Claude Code, do primeiro ao mais recente:
161${asks.map((a, n) => `${n + 1}. ${a}`).join('\n')}
162
163Escreva o objetivo ATUAL da sessão em até 8 palavras, em português do Brasil, começando por um verbo no infinitivo. Responda só com o objetivo, sem aspas nem ponto final.`,
164  chaptersTitle: 'Capítulos',
165  chaptersDone: (n: number) => (n === 1 ? '1 capítulo fechado' : `${n} capítulos fechados`),
166  waitingYou: 'esperando você',
167  atCamp: 'no acampamento · esperando você',
168  resting: 'descansando',
169  onExpedition: 'em expedição',
170  recentCommits: 'Últimos commits',
171  moreActive: (n: number) => `+${n} em ação`,
172  expedition: (n: number, first: string) => (n === 1 ? `${first} em expedição` : `${n} agentes em expedição`),
173  expeditionTip: (lines: string[]) => ['Rodando em segundo plano:', ...lines].join('\n'),
174  failedShort: 'falhou',
175  deleted: 'excluído',
176  bandStep: (n: number, total: number) => `Passo ${n} de ${total}`,
177  stepsWord: (_done: number, total: number): string => (total === 1 ? 'passo' : 'passos'),
178  chapterShort: (n: number) => `cap. ${n}`,
179  stepTip: (n: number, name: string, state: 'done' | 'now' | 'next') =>
180    `Passo ${n} · ${name} — ${state === 'done' ? 'concluído' : state === 'now' ? 'em andamento' : 'a fazer'}`,
181  rarityByImpact: 'Raridade pelo impacto',
182  rarities: 'Raridades',
183  achieved: '✓ Objetivo alcançado',
184  noQuests: 'Sem quests ainda. Elas vêm da lista de tarefas do Claude.',
185  questsMist: (n: number) => `+${n} na névoa`,
186  questsDone: (n: number) => (n === 1 ? '1 concluída' : `${n} concluídas`),
187  inProgress: 'em andamento',
188  inAction: 'em ação',
189  mainSession: (cls: string) => `sessão principal · forma de ${cls.toLowerCase()}`,
190  missionDone: 'missão cumprida',
191  doneHint: 'concluídos · passe o mouse',
192  partyDone: 'Concluídos',
193  notRepo: 'Fora de um repositório git.',
194  clean: 'Nada mexido ainda.',
195  uncommitted: (n: number) => `● ${n} sem commit`,
196  ahead: (n: number) => `↑${n}`,
197  behind: (n: number) => `↓${n}`,
198  actions: (n: number) => (n === 1 ? '1 ação' : `${n} ações`),
199  isNew: 'novo',
200  diffBack: '‹ Inventário',
201  diffEmpty: 'Sem diferenças de linha para exibir.',
202  diffBinary: 'Arquivo binário (sem prévia em texto).',
203  diffDir: 'Diretório (sem prévia em texto).',
204  diffNew: 'Arquivo novo',
205  diffDeleted: 'Arquivo excluído',
206  diffRenamed: (from: string) => `Renomeado de ${from}`,
207  diffMore: (n: number) => (n === 1 ? '… mais 1 linha' : `… mais ${n} linhas`),
208  diffReadError: (why: string) => `Não deu para ler o diff: ${why}`,
209  diffTooBig: (kb: number) => `Arquivo novo grande demais para mostrar aqui (${kb} KB).`,
210  failed: (n: number) => (n === 1 ? '1 falhou' : `${n} falharam`),
211  running: 'em execução',
212  footer: { mochila: 'Mochila', mana: 'Mana', vigor: 'Vigor' },
213  bag: { leve: 'Leve', carregada: 'Carregada', pesada: 'Pesada', transbordando: 'Transbordando' } satisfies Record<BagState, string>,
214  bagTip: (pct: string, auto: boolean, left: string, delta: string, top: string) =>
215    [
216      `Mochila (contexto): ${pct} do caminho até ${auto ? 'a compactação automática' : 'encher a janela'}${left === '' ? '' : `, faltam ${left}`}.`,
217      delta === '' ? '' : `${delta} no último turno.`,
218      top === '' ? '' : `O que pesa: ${top}.`,
219    ]
220      .filter(Boolean)
221      .join('\n'),
222  bagCategory: { messages: 'mensagens', 'system prompt': 'prompt de sistema', 'system tools': 'ferramentas do sistema', 'mcp tools': 'ferramentas MCP', 'memory files': 'arquivos de memória', skills: 'skills', 'custom agents': 'agentes' } as Record<string, string>,
223  refilled: 'recarregada',
224  windowTip: (name: string, period: string, left: string, at: string, fast: boolean, refilled: boolean) =>
225    refilled
226      ? `${name} (${period}): a janela renovou. O número volta na próxima resposta.`
227      : `${name} (${period}): ${left} restante${at === '' ? '' : `, renova ${at}`}.${fast ? ' ⚡ Gastando rápido: nesse ritmo acaba antes de renovar.' : ' No ritmo.'}`,
228  period: { mana: 'janela de 5h', vigor: 'semanal' },
229  windowWarn: (name: string, left: number, inText: string) => `${name} em ${left}%${inText === '' ? '' : `: renova em ${inText}`}.`,
230  bandAlert: { mochila: (p: number) => `🎒 Mochila ${p}%`, mana: (p: number) => `💧 Mana ${p}%`, vigor: (p: number) => `💚 Vigor ${p}%` },
231  resetAt: (clock: string) => `às ${clock}`,
232  off: (name: string) => `${name} está desligado no ⚙.`,
233  grimoire: '📖 Grimório',
234  config: '⚙',
235  about: 'ℹ',
236  back: '‹ Voltar',
237  language: 'Língua',
238  skin: 'Estilo',
239  skinEpico: 'Épico',
240  skinSobrio: 'Sóbrio',
241  modules: 'Módulos',
242  guardMode: 'Proteção',
243  guardModes: {
244    nativo: 'Só avisar',
245    dialogo: 'Perguntar',
246  } satisfies Record<GuardMode, string>,
247  guardHint: 'Perguntar: o dragão barra a mudança e mostra o que muda, até no modo automático. Só avisar: uma nota no diálogo de permissão, quando ele aparece.',
248  haiku: 'Botão “Resumir com Haiku” no grimório',
249  haikuButton: '✦ Resumir com Haiku',
250  haikuDone: (n: number) => `${n} inscrição(ões) resumida(s) pelo Haiku.`,
251  haikuFail: 'O Haiku não respondeu; as inscrições ficaram como estavam.',
252  join: '⊟ Juntar',
253  split: '⊞ Separar',
254  // Guarda
255  guardQuestion: (names: string) => `O dragão barra ${names}: um arquivo crítico. Deixa o Claude passar?`,
256  guardHeader: 'Proteção',
257  guardHints: [
258    'O Claude grava a mudança como pediu.',
259    'Bloqueia agora e leva um rascunho ao prompt para você ajustar a mudança.',
260    'Bloqueia; a resposta final e o relatório registram a recusa.',
261  ],
262  guardNotice: (names: string) => `🔒 ${names}: arquivo protegido (hero-journey)`,
263  denyRefuse: (name: string) => `${name} é protegido e a pessoa recusou a alteração. Não tente de novo; diga na resposta final que a mudança ficou de fora.`,
264  denyNegotiate: (name: string) => `${name} é protegido: a pessoa quer ajustar a mudança antes. Espere a próxima mensagem dela.`,
265  denyHeadless: (name: string) => `${name} é protegido e não há ninguém para aprovar. Peça a mudança à pessoa.`,
266  denyFailed: 'O guarda do hero-journey falhou, então a alteração foi bloqueada. Peça para a pessoa fazer a mudança.',
267  negotiateDraft: (name: string) => `Sobre a mudança em ${name}: `,
268  // Relatório
269  chapter: (n: number) => `Capítulo ${n}`,
270  result: 'Resultado',
271  risk: 'Risco',
272  next: 'Próximo',
273  waits: 'Aguarda você',
274  stats: (actions: number, files: number, added: number, removed: number, dur: string) =>
275    `${actions === 1 ? '1 ação' : `${actions} ações`} · ${files === 1 ? '1 arquivo' : `${files} arquivos`} · +${added} −${removed} · ${dur}`,
276  // Mochila
277  compactTitle: 'Mochila cheia',
278  compactBody: (p: string) =>
279    `O contexto está em ${p}. Leve a instrução ao prompt e envie quando quiser, ou compacte agora com o Claude parado.`,
280  toPrompt: 'Levar ao prompt',
281  compactNow: 'Compactar agora',
282  compactBusy: 'O Claude está trabalhando: a compactação só roda com ele parado.',
283  compactSkipped: 'Nada para compactar agora.',
284  compactFailed: (why: string) => `Não deu para compactar: ${why}`,
285  compactDone: (before: string, after: string) => `Mochila arrumada: ${before} → ${after}.`,
286  notNow: 'Agora não',
287  filled: 'Está no prompt. Envie quando quiser.',
288  noComposer: 'Não há caixa de digitação aqui: o texto foi copiado.',
289  // Grimório
290  grimTitle: 'Grimório',
291  grimEmpty: 'Nada para guardar agora.',
292  grimKind: { decisao: 'Registrar decisão', conquista: 'Conquista', regra: 'Virar regra' } satisfies Record<InscriptionKind, string>,
293  dest: {
294    agentsMd: 'AGENTS.md',
295    vaultDecisao: 'Vault · decisões',
296    carreira: 'Vault · carreira',
297    projeto: 'docs/decisoes',
298    aiMemory: 'ai-memory',
299  } satisfies Record<Destination, string>,
300  grimNoneMarked: 'Escolha onde guardar antes de selar.',
301  grimBusy: 'O grimório já está gravando; aguarde terminar.',
302  toolsFailed: (why: string) => `Não deu para ver se o ai-memory está conectado: ${why}`,
303  seal: 'Selar no grimório',
304  discard: 'Descartar',
305  sealed: (n: number) => (n === 1 ? '1 inscrição selada.' : `${n} inscrições seladas.`),
306  notSealed: (n: number, why: string) =>
307    `${n === 0 ? 'Um destino falhou.' : n === 1 ? '1 inscrição continua pendente: destino indisponível ou com falha.' : `${n} inscrições continuam pendentes: destino indisponível ou com falha.`}${why === '' ? '' : ` ${why}`}`,
308  privacyBlocked: 'Ficou fora do repositório: o texto cita o vault ou um caminho pessoal.',
309  rulesHeading: 'Regras',
310  whereDecisions: 'Onde guardo suas decisões?',
311  inProject: 'Neste projeto (docs/decisoes)',
312  myVault: '📁 Meu vault…',
313  askOnce: 'Pergunto uma vez; dá para trocar no ⚙ Memória.',
314  marcoTitle: (name: string) => `✦ Marco fechado: ${name}`,
315  marcoPlan: (done: number, total: number) => `${done} de ${total} passos · guardar na crônica?`,
316  marcoCommit: 'mudança entregue · guardar na crônica?',
317  sageNoted: (n: number) => (n === 1 ? 'O Sábio anotou 1 coisa' : `O Sábio anotou ${n} coisas`),
318  seeAndKeep: 'Ver e guardar',
319  saveBeforeStop: 'Salvar o progresso antes de parar?',
320  nextStep: (x: string) => `próximo: ${x}`,
321  saveProgress: '✦ Salvar progresso',
322  toContinue: (n: number) => (n === 1 ? '1 jogo salvo para continuar' : `${n} jogos salvos para continuar`),
323  continueTitle: 'Continuar',
324  continueBtn: 'Continuar',
325  continueHint: 'Quer continuar também no Codex, no Antigravity ou em outro PC? O ai-memory faz isso.',
326  seeHow: 'Ver como',
327  bagAt: (p: string) => `🎒 Mochila em ${p}`,
328  timeToCompact: '· hora de compactar',
329  saveFirst: 'Antes, salvar o progresso?',
330  verify: 'Verificar',
331  taskFile: 'arquivo da tarefa',
332  verifyHint: 'como saber que deu certo',
333  onlyCompact: 'Só compactar',
334  compactAnyway: 'Compactar assim mesmo',
335  saveNotDone: (why: string) => `O progresso não foi salvo: ${why}`,
336  saveAndCompact: 'Salvar e compactar',
337  toKeep: 'Para guardar',
338  keptToday: 'Guardado hoje',
339  remembers: 'O que o Sábio lembra',
340  forget: 'esquecer',
341  undo: 'Desfazer',
342  openIt: 'abrir',
343  progressSaved: 'Progresso salvo',
344  autoMemoryNotes: (n: number) => `A memória automática do Claude neste projeto: ${n === 1 ? '1 nota' : `${n} notas`}`,
345  memoryCfg: '⚙ Memória',
346  memoryOpen: '⚙ Memória ›',
347  progressDest: { vault: 'Tarefa no vault', vaultMemory: 'Tarefa + ai-memory', project: 'Tarefa no projeto' },
348  progressDone: (id: string) => `✦ Progresso salvo: ${id}`,
349  progressFailed: (why: string) => `Não deu para salvar o progresso: ${why}`,
350  readFailed: (why: string) => `Não deu para ler as tarefas: ${why}`,
351  handoffFailed: (why: string) => `A tarefa foi salva; o ai-memory não respondeu: ${why}`,
352  undone: 'Desfeito.',
353  forgotten: 'O Sábio vai esquecer isso.',
354  nothingToSave: 'Sem objetivo ainda: o progresso salva a partir da primeira mensagem.',
355  memDetected: '✓ Estrutura recomendada detectada',
356  memDetectedText: (vault: string) => `Vault em ${vault} e ai-memory conectado. O grimório já veio configurado: progresso na tarefa e no ai-memory, decisões no vault, regras no AGENTS.md.`,
357  memPartial: (what: string) => `Detectado: ${what}. O que falta usa o projeto.`,
358  memProject: 'Usando o que o projeto já tem',
359  memProjectText: 'Sem vault nem ai-memory: o progresso fica num arquivo do projeto, as decisões em docs/decisoes e as regras no AGENTS.md. Tudo funciona; as integrações abaixo só ampliam.',
360  rowFeatures: 'Recursos',
361  rowWarnings: 'Avisos',
362  rowDests: 'Destinos',
363  rowIntegrations: 'Integrações',
364  memFeature: {
365    progresso: 'Salvar progresso (onde parei)',
366    cronica: 'Registrar decisões e conquistas',
367    regras: 'Virar regra (AGENTS.md)',
368    lembra: 'Mostrar o que o Sábio lembra',
369    avisoPalco: 'No palco (fim do turno, adormecer, continuar)',
370    avisoMarco: 'No fim de um marco',
371    avisoCompactar: 'Antes de compactar',
372  },
373  decisionsIn: 'Decisões em',
374  homeAuto: 'Auto',
375  homeVault: 'Vault',
376  homeProject: 'Projeto',
377  destProgress: 'Progresso →',
378  destDecisions: 'Decisões →',
379  destRules: 'Regras →',
380  notConfigured: 'não configurado',
381  change: 'Trocar',
382  memConnected: 'conectado',
383  memMissing: 'não encontrado',
384  testIt: 'Testar',
385  whatIs: 'O que é?',
386  memTestOk: 'ai-memory respondeu.',
387  memTestFail: (why: string) => `ai-memory não respondeu: ${why}`,
388  restoreRecommended: 'Restaurar o recomendado',
389  // Pastas
390  folderMissing: (path: string) => `A pasta não existe (ou é um arquivo): ${path}`,
391  folderNetwork: (path: string) => `Caminho de rede não suportado: ${path}`,
392  // Primeiros passos
393  setupPathVault: 'Caminho do vault (ex.: C:\\Notas)',
394  inboxInvalid: (v: string) => `“${v}” precisa ser uma subpasta do vault, sem caminho absoluto nem “..”.`,
395  setupSave: 'Salvar',
396  setupPick: '📁 Escolher pasta',
397  pickVaultTitle: 'Escolha a pasta do seu vault',
398  pickUnavailable: 'O seletor de pastas do sistema não abriu aqui. Digite o caminho no campo.',
399  openFailed: (path: string) => `Não consegui abrir ${path}.`,
400  // Comemoração e geral
401  langChanged: 'Língua alterada.',
402  langDenied: (why: string) => `Não deu para mudar a língua: ${why}`,
403  credits: 'Agradecimentos: padrões de código de Daniel Ávila (claude-code-templates, MIT). Lista completa no README.',
404  linkedin: 'LinkedIn do Saulo',
405  github: 'Projeto no GitHub',
406  version: (v: string) => `versão ${v}`,
407  // Telas revisadas na 0.6
408  setupWelcome: 'Tudo já funciona: o Clawd aparece no chat, o palco mostra quem trabalha e a mochila avisa antes de encher.',
409  setupMemoryRow: 'Memória',
410  setupOptional: 'Opcional. Sem nada configurado, o progresso e as decisões ficam no próprio projeto.',
411  setupLater: 'Dá para ajustar depois em ⚙ Memória.',
412  setupStart: 'Começar a jornada',
413  setupNone: 'sem vault',
414  setupMemoryNone: 'não encontrado',
415  setupStar: '⭐ Apoiar',
416  panelToggle: 'Painel ›',
417  rowMemory: 'Memória',
418  setupLink: 'Primeiros passos ›',
419  aboutLink: 'Sobre ›',
420  modShort: { diario: 'Diário', faixa: 'Faixa', painel: 'Painel', campanha: 'Campanha', recibo: 'Recibo', guarda: 'Guarda', mochila: 'Mochila', grimorio: 'Grimório' } satisfies Record<ModuleId, string>,
421  catFeatures: 'Recursos',
422  guardAsk: 'Perguntar',
423  guardWarn: 'Só avisar',
424  guardTitle: (names: string) => `Arquivo crítico à frente: ${names}`,
425  guardSub: 'Um dragão guarda este arquivo. Mal configurado, ele derruba a aplicação, o banco ou a API. Nada passa sem a sua ordem.',
426  classesTitle: 'As 19 classes',
427  classesHint: 'Passe o mouse num Clawd para ver o que ele faz.',
428}
429
430type Dict = typeof PT
431
432const EN: Dict = {
433  className: {
434    aprendiz: 'Apprentice',
435    mago: 'Mage',
436    cacador: 'Hunter',
437    ladino: 'Rogue',
438    runico: 'Rune Caster',
439    ilusionista: 'Illusionist',
440    sabio: 'Sage',
441    engenheiro: 'Engineer',
442    bruxo: 'Witcher',
443    rei: 'King',
444    artifice: 'Artificer',
445    oraculo: 'Oracle',
446    geomante: 'Geomancer',
447    alquimista: 'Alchemist',
448    cartomante: 'Cartomancer',
449    invocador: 'Summoner',
450    cronomante: 'Chronomancer',
451    paladino: 'Paladin',
452    pintor: 'Painter',
453  },
454  classRole: {
455    aprendiz: 'thinks and answers',
456    mago: 'reads and searches the project',
457    cacador: 'searches the web',
458    ladino: 'browses sites',
459    runico: 'edits code',
460    ilusionista: 'works on screens and style',
461    sabio: 'writes docs and keeps memory',
462    engenheiro: 'runs commands and builds',
463    bruxo: 'tests, lint and types',
464    rei: 'git, commits and PRs',
465    artifice: 'pipelines, deploys and infra',
466    oraculo: 'reads logs and monitors',
467    geomante: 'databases',
468    alquimista: 'APIs and integrations',
469    cartomante: 'plans and organizes tasks',
470    invocador: 'leads subagents',
471    cronomante: 'schedules and automates',
472    paladino: 'security and review',
473    pintor: 'visual design',
474  },
475  classVerb: {
476    aprendiz: 'thinking',
477    mago: 'reading',
478    cacador: 'searching',
479    ladino: 'browsing',
480    runico: 'writing',
481    ilusionista: 'building',
482    sabio: 'recording',
483    engenheiro: 'running',
484    bruxo: 'hunting bugs',
485    rei: 'sealing',
486    artifice: 'forging',
487    oraculo: 'reading the signs',
488    geomante: 'shaping',
489    alquimista: 'mixing',
490    cartomante: 'planning',
491    invocador: 'summoning',
492    cronomante: 'scheduling',
493    paladino: 'guarding',
494    pintor: 'painting',
495  },
496  placeName: {
497    treino: 'Training ground',
498    biblioteca: 'Library',
499    runas: 'Rune circle',
500    oficina: 'Workshop',
501    pantano: 'Swamp',
502    acampamento: 'Camp',
503    trono: 'Throne room',
504    teatro: 'Theater of illusions',
505    torre: "Sage's tower",
506    floresta: 'Moon forest',
507    beco: 'Alley',
508    forja: 'Forge',
509    santuario: 'Sanctuary',
510    muralha: 'Stone wall',
511    laboratorio: 'Laboratory',
512    tenda: 'Card tent',
513    salao: 'Arcane hall',
514    camara: 'Time chamber',
515    portal: 'Portal',
516    atelie: 'Studio',
517  },
518  yourTurn: 'Your turn',
519  answered: clock => (clock === '' ? 'the answer is in' : `answered at ${clock}`),
520  asleep: 'resting',
521  asleepNote: clock => (clock === '' ? 'the session is idle' : `idle since ${clock}`),
522  freshCamp: 'waiting for the first message',
523  stumbled: 'stumbled',
524  failedNote: what => `${what} failed · trying again`,
525  onExpeditionTitle: 'On expedition',
526  spinResponding: 'writing the answer',
527  startedAt: clock => (clock === '' ? '' : `started at ${clock}`),
528  doneSteps: n => (n === 1 ? '✓ 1 step done' : `✓ ${n} steps done`),
529  section: {
530    objetivo: 'Objective',
531    quests: 'Chapter quests',
532    grupo: 'Party',
533    inventario: 'Inventory',
534  },
535  module: {
536    diario: ['Logbook', 'The class Clawd and the result on each tool row, during the turn'],
537    faixa: ['Band above the prompt', 'One line with who acts, the file and the plan trail; the spinner names the class'],
538    painel: ['Pane', 'The stage with the class at work, the objective and, when there is one, the plan, party and inventory'],
539    campanha: ['Campaign', 'Objective and chapters; ✦ Recalibrate uses Haiku'],
540    recibo: ['Turn receipt', 'One line under the answer: who acted, +/−, failures and time'],
541    guarda: ['Protected-file guard', 'Asks before editing .env, pipelines and the like (and before commands that write them)'],
542    mochila: ['Backpack', 'Compaction card when the backpack gets heavy; Compact now spends tokens'],
543    grimorio: ['Grimoire', 'Save progress and continue, chronicle and rules; ⚙ Memory tunes each feature'],
544  },
545  tokens: 'may spend tokens (only on your click)',
546  paneNotPlaced: why => `The pane did not open (${why}). Widen the Claude Code window.`,
547  rarity: {
548    lendario: 'Legendary: protected (.env, pipelines, secrets)',
549    raro: 'Rare: critical (API, database, auth, build)',
550    incomum: 'Uncommon: code and screens',
551    comum: 'Common: tests, docs and light config',
552    pobre: 'Poor: deleted',
553  },
554  noObjective: 'The objective shows up with the first message of the session.',
555  setupTagline: 'Welcome to the journey.',
556  knownTypes: { explore: 'Explorer', plan: 'Architect', 'claude-code-guide': 'Claude Code guide', 'statusline-setup': 'Status line' },
557  ago: s => (s < 90 ? 'now' : s < 3600 ? `${Math.round(s / 60)} min ago` : s < 86400 ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} d ago`),
558  catGeneral: 'General',
559  catMemory: 'Memory',
560  rowChat: 'In the chat',
561  rowPanel: 'In the pane',
562  rowGuard: 'Protection',
563  langAutoShort: 'Auto',
564  grimoireRow: 'Grimoire',
565  haikuShort: 'Summarize with Haiku',
566  aboutTagline: v => `v${v} · a cozy RPG HUD for Claude Code`,
567  aboutBy: 'Made by',
568  authorRole: 'developer · Angular, .NET and Azure DevOps',
569  aboutFeatures: [
570    ['The stage', 'The Clawd of the right class at work; idle, the camp.'],
571    ['Party and expeditions', 'Each subagent becomes a hero, with the class of its job.'],
572    ['Backpack and resources', 'Context and usage windows; warns before compacting.'],
573    ['Guard of the protected', 'A dragon stops Claude before it touches .env, pipelines and keys.'],
574    ['Grimoire', 'Save progress, decisions and rules, only on your click.'],
575  ],
576  recalibrate: '✦ Recalibrate objective',
577  recalibrateShort: 'Recalibrate',
578  markAchievedShort: 'Reached?',
579  recalibrateDone: goal => `✦ Objective: ${goal}`,
580  recalibrateFail: 'Haiku did not answer; the objective stays as it was.',
581  recalibratePrompt: asks =>
582    `These are the requests the person made in this Claude Code session, from first to latest:
583${asks.map((a, n) => `${n + 1}. ${a}`).join('\n')}
584
585Write the CURRENT objective of the session in at most 8 words, in English, starting with a verb. Reply with the objective only, no quotes or final period.`,
586  chaptersTitle: 'Chapters',
587  chaptersDone: n => (n === 1 ? '1 chapter closed' : `${n} chapters closed`),
588  waitingYou: 'waiting for you',
589  atCamp: 'at camp · waiting for you',
590  resting: 'resting',
591  onExpedition: 'on an expedition',
592  recentCommits: 'Latest commits',
593  moreActive: n => `+${n} in action`,
594  expedition: (n, first) => (n === 1 ? `${first} on an expedition` : `${n} agents on an expedition`),
595  expeditionTip: lines => ['Running in the background:', ...lines].join('\n'),
596  failedShort: 'failed',
597  deleted: 'deleted',
598  bandStep: (n, total) => `Step ${n} of ${total}`,
599  stepsWord: (_done, total) => (total === 1 ? 'step' : 'steps'),
600  chapterShort: n => `ch. ${n}`,
601  stepTip: (n, name, state) => `Step ${n} · ${name} — ${state === 'done' ? 'done' : state === 'now' ? 'in progress' : 'to do'}`,
602  rarityByImpact: 'Rarity by impact',
603  rarities: 'Rarities',
604  achieved: '✓ Objective reached',
605  noQuests: "No quests yet. They come from Claude's task list.",
606  questsMist: n => `+${n} in the mist`,
607  questsDone: n => (n === 1 ? '1 done' : `${n} done`),
608  inProgress: 'in progress',
609  inAction: 'in action',
610  mainSession: cls => `main session · ${cls.toLowerCase()} form`,
611  missionDone: 'mission complete',
612  doneHint: 'done · hover for details',
613  partyDone: 'Done',
614  notRepo: 'Not inside a git repository.',
615  clean: 'Nothing touched yet.',
616  uncommitted: n => `● ${n} uncommitted`,
617  ahead: n => `↑${n}`,
618  behind: n => `↓${n}`,
619  actions: n => (n === 1 ? '1 action' : `${n} actions`),
620  isNew: 'new',
621  diffBack: '‹ Inventory',
622  diffEmpty: 'No line differences to show.',
623  diffBinary: 'Binary file (no text preview).',
624  diffDir: 'Directory (no text preview).',
625  diffNew: 'New file',
626  diffDeleted: 'Deleted file',
627  diffRenamed: from => `Renamed from ${from}`,
628  diffMore: n => (n === 1 ? '… 1 more line' : `… ${n} more lines`),
629  diffReadError: why => `Could not read diff: ${why}`,
630  diffTooBig: kb => `New file too large to show here (${kb} KB).`,
631  failed: n => `${n} failed`,
632  running: 'running',
633  footer: { mochila: 'Backpack', mana: 'Mana', vigor: 'Vigor' },
634  bag: { leve: 'Light', carregada: 'Loaded', pesada: 'Heavy', transbordando: 'Overflowing' },
635  bagTip: (pct, auto, left, delta, top) =>
636    [
637      `Backpack (context): ${pct} of the way to ${auto ? 'auto-compaction' : 'a full window'}${left === '' ? '' : `, ${left} to go`}.`,
638      delta === '' ? '' : `${delta} last turn.`,
639      top === '' ? '' : `What weighs: ${top}.`,
640    ]
641      .filter(Boolean)
642      .join('\n'),
643  bagCategory: { messages: 'messages', 'system prompt': 'system prompt', 'system tools': 'system tools', 'mcp tools': 'MCP tools', 'memory files': 'memory files', skills: 'skills', 'custom agents': 'agents' },
644  refilled: 'refilled',
645  windowTip: (name, period, left, at, fast, refilled) =>
646    refilled
647      ? `${name} (${period}): the window reset. The number comes back with the next answer.`
648      : `${name} (${period}): ${left} left${at === '' ? '' : `, resets ${at}`}.${fast ? ' ⚡ Spending fast: at this pace it runs out before the reset.' : ' On pace.'}`,
649  period: { mana: '5-hour window', vigor: 'weekly' },
650  windowWarn: (name, left, inText) => `${name} at ${left}%${inText === '' ? '' : `: resets in ${inText}`}.`,
651  bandAlert: { mochila: p => `🎒 Backpack ${p}%`, mana: p => `💧 Mana ${p}%`, vigor: p => `💚 Vigor ${p}%` },
652  resetAt: clock => `at ${clock}`,
653  off: name => `${name} is off in ⚙.`,
654  grimoire: '📖 Grimoire',
655  config: '⚙',
656  about: 'ℹ',
657  back: '‹ Back',
658  language: 'Language',
659  skin: 'Style',
660  skinEpico: 'Epic',
661  skinSobrio: 'Sober',
662  modules: 'Modules',
663  guardMode: 'Protection',
664  guardModes: { nativo: 'Only warn', dialogo: 'Ask' },
665  guardHint: 'Ask: the dragon blocks the change and shows what changes, even in auto mode. Only warn: a note in the permission dialog, when it shows.',
666  haiku: '“Summarize with Haiku” button in the grimoire',
667  haikuButton: '✦ Summarize with Haiku',
668  haikuDone: n => `${n} inscription(s) summarized by Haiku.`,
669  haikuFail: 'Haiku did not answer; the inscriptions stay as they were.',
670  join: '⊟ Join',
671  split: '⊞ Split',
672  guardQuestion: names => `The dragon blocks ${names}: a critical file. Let Claude through?`,
673  guardHeader: 'Protection',
674  guardHints: [
675    'Claude writes the change as asked.',
676    'Blocks now and drafts a note in the prompt so you can adjust the change.',
677    'Blocks; the final answer and the report record the refusal.',
678  ],
679  guardNotice: names => `🔒 ${names}: protected file (hero-journey)`,
680  denyRefuse: name => `${name} is protected and the person refused the change. Do not retry; say in the final answer that the change was left out.`,
681  denyNegotiate: name => `${name} is protected: the person wants to adjust the change first. Wait for their next message.`,
682  denyHeadless: name => `${name} is protected and nobody can approve it. Ask the person for the change.`,
683  denyFailed: "hero-journey's guard failed, so the change was blocked. Ask the person to make it.",
684  negotiateDraft: name => `About the change in ${name}: `,
685  chapter: n => `Chapter ${n}`,
686  result: 'Result',
687  risk: 'Risk',
688  next: 'Next',
689  waits: 'Waiting on you',
690  stats: (actions, files, added, removed, dur) =>
691    `${actions === 1 ? '1 action' : `${actions} actions`} · ${files === 1 ? '1 file' : `${files} files`} · +${added} −${removed} · ${dur}`,
692  compactTitle: 'Backpack full',
693  compactBody: p => `Context is at ${p}. Send the instruction to the prompt and submit it when you like, or compact now while Claude is idle.`,
694  toPrompt: 'Send to prompt',
695  compactNow: 'Compact now',
696  compactBusy: 'Claude is working: compaction only runs while it is idle.',
697  compactSkipped: 'Nothing to compact right now.',
698  compactFailed: why => `Could not compact: ${why}`,
699  compactDone: (before, after) => `Backpack tidied: ${before} → ${after}.`,
700  notNow: 'Not now',
701  filled: 'It is in the prompt. Send it when you like.',
702  noComposer: 'There is no prompt box here: the text was copied.',
703  grimTitle: 'Grimoire',
704  grimEmpty: 'Nothing to keep right now.',
705  grimKind: { decisao: 'Record decision', conquista: 'Achievement', regra: 'Make it a rule' },
706  dest: { agentsMd: 'AGENTS.md', vaultDecisao: 'Vault · decisions', carreira: 'Vault · career', projeto: 'docs/decisoes', aiMemory: 'ai-memory' },
707  grimNoneMarked: 'Choose where to keep it before sealing.',
708  grimBusy: 'The grimoire is already writing; wait for it to finish.',
709  toolsFailed: why => `Could not check whether ai-memory is connected: ${why}`,
710  seal: 'Seal in the grimoire',
711  discard: 'Discard',
712  sealed: n => (n === 1 ? '1 inscription sealed.' : `${n} inscriptions sealed.`),
713  notSealed: (n, why) =>
714    `${n === 0 ? 'A destination failed.' : n === 1 ? '1 inscription is still pending: destination unavailable or failed.' : `${n} inscriptions are still pending: destination unavailable or failed.`}${why === '' ? '' : ` ${why}`}`,
715  privacyBlocked: 'Left out of the repository: the text mentions the vault or a personal path.',
716  rulesHeading: 'Rules',
717  whereDecisions: 'Where should I keep your decisions?',
718  inProject: 'In this project (docs/decisoes)',
719  myVault: '📁 My vault…',
720  askOnce: 'I ask once; you can change it in ⚙ Memory.',
721  marcoTitle: name => `✦ Milestone reached: ${name}`,
722  marcoPlan: (done, total) => `${done} of ${total} steps · keep it in the chronicle?`,
723  marcoCommit: 'change delivered · keep it in the chronicle?',
724  sageNoted: n => (n === 1 ? 'The Sage noted 1 thing' : `The Sage noted ${n} things`),
725  seeAndKeep: 'See and keep',
726  saveBeforeStop: 'Save your progress before stopping?',
727  nextStep: x => `next: ${x}`,
728  saveProgress: '✦ Save progress',
729  toContinue: n => (n === 1 ? '1 saved game to continue' : `${n} saved games to continue`),
730  continueTitle: 'Continue',
731  continueBtn: 'Continue',
732  continueHint: 'Want to continue in Codex, Antigravity or on another PC too? ai-memory does that.',
733  seeHow: 'See how',
734  bagAt: p => `🎒 Backpack at ${p}`,
735  timeToCompact: '· time to compact',
736  saveFirst: 'Save your progress first?',
737  verify: 'Verify',
738  taskFile: 'task file',
739  verifyHint: 'how to know it worked',
740  onlyCompact: 'Just compact',
741  compactAnyway: 'Compact anyway',
742  saveNotDone: why => `The progress was not saved: ${why}`,
743  saveAndCompact: 'Save and compact',
744  toKeep: 'To keep',
745  keptToday: 'Kept today',
746  remembers: 'What the Sage remembers',
747  forget: 'forget',
748  undo: 'Undo',
749  openIt: 'open',
750  progressSaved: 'Progress saved',
751  autoMemoryNotes: n => `Claude's auto memory for this project: ${n === 1 ? '1 note' : `${n} notes`}`,
752  memoryCfg: '⚙ Memory',
753  memoryOpen: '⚙ Memory ›',
754  progressDest: { vault: 'Task in the vault', vaultMemory: 'Task + ai-memory', project: 'Task in the project' },
755  progressDone: id => `✦ Progress saved: ${id}`,
756  progressFailed: why => `Could not save the progress: ${why}`,
757  readFailed: why => `Could not read tasks: ${why}`,
758  handoffFailed: why => `The task was saved; ai-memory did not answer: ${why}`,
759  undone: 'Undone.',
760  forgotten: 'The Sage will forget it.',
761  nothingToSave: 'No objective yet: progress saves from the first message on.',
762  memDetected: '✓ Recommended setup detected',
763  memDetectedText: vault => `Vault at ${vault} and ai-memory connected. The grimoire is already set up: progress in the task and ai-memory, decisions in the vault, rules in AGENTS.md.`,
764  memPartial: what => `Detected: ${what}. The rest uses the project.`,
765  memProject: 'Using what the project already has',
766  memProjectText: 'No vault and no ai-memory: progress goes to a file in the project, decisions to docs/decisoes and rules to AGENTS.md. It all works; the integrations below only extend it.',
767  rowFeatures: 'Features',
768  rowWarnings: 'Prompts',
769  rowDests: 'Destinations',
770  rowIntegrations: 'Integrations',
771  memFeature: {
772    progresso: 'Save progress (where I stopped)',
773    cronica: 'Record decisions and achievements',
774    regras: 'Make it a rule (AGENTS.md)',
775    lembra: 'Show what the Sage remembers',
776    avisoPalco: 'On the stage (turn end, falling asleep, continue)',
777    avisoMarco: 'At the end of a milestone',
778    avisoCompactar: 'Before compacting',
779  },
780  decisionsIn: 'Decisions in',
781  homeAuto: 'Auto',
782  homeVault: 'Vault',
783  homeProject: 'Project',
784  destProgress: 'Progress →',
785  destDecisions: 'Decisions →',
786  destRules: 'Rules →',
787  notConfigured: 'not set up',
788  change: 'Change',
789  memConnected: 'connected',
790  memMissing: 'not found',
791  testIt: 'Test',
792  whatIs: 'What is it?',
793  memTestOk: 'ai-memory answered.',
794  memTestFail: why => `ai-memory did not answer: ${why}`,
795  restoreRecommended: 'Restore the recommended',
796  folderMissing: path => `The folder does not exist (or is a file): ${path}`,
797  folderNetwork: path => `Network paths are not supported: ${path}`,
798  setupPathVault: 'Vault path (e.g. C:\\Notes)',
799  inboxInvalid: v => `“${v}” must be a subfolder of the vault, with no absolute path and no “..”.`,
800  setupSave: 'Save',
801  setupPick: '📁 Choose folder',
802  pickVaultTitle: 'Choose your vault folder',
803  pickUnavailable: 'The system folder picker did not open here. Type the path in the field.',
804  openFailed: path => `Could not open ${path}.`,
805  langChanged: 'Language changed.',
806  langDenied: why => `Could not change the language: ${why}`,
807  credits: 'Thanks: code patterns by Daniel Ávila (claude-code-templates, MIT). Full list in the README.',
808  linkedin: "Saulo's LinkedIn",
809  github: 'Project on GitHub',
810  version: v => `version ${v}`,
811  setupWelcome: 'Everything already works: Clawd shows up in the chat, the stage shows who is working and the backpack warns before it fills up.',
812  setupMemoryRow: 'Memory',
813  setupOptional: 'Optional. With nothing set up, progress and decisions stay in the project itself.',
814  setupLater: 'You can adjust it later in ⚙ Memory.',
815  setupStart: 'Start the journey',
816  setupNone: 'no vault',
817  setupMemoryNone: 'not found',
818  setupStar: '⭐ Support',
819  panelToggle: 'Panel ›',
820  rowMemory: 'Memory',
821  setupLink: 'First steps ›',
822  aboutLink: 'About ›',
823  modShort: { diario: 'Log', faixa: 'Band', painel: 'Panel', campanha: 'Campaign', recibo: 'Receipt', guarda: 'Guard', mochila: 'Backpack', grimorio: 'Grimoire' },
824  catFeatures: 'Features',
825  guardAsk: 'Ask',
826  guardWarn: 'Only warn',
827  guardTitle: names => `Critical file ahead: ${names}`,
828  guardSub: 'A dragon guards this file. Misconfigured, it takes down the app, the database or the API. Nothing passes without your word.',
829  classesTitle: 'The 19 classes',
830  classesHint: 'Hover a Clawd to see what it does.',
831}
832
833export const DICT: Record<Lang, Dict> = { pt: PT, en: EN }
834
835export type { Dict }
836
837/**
838 * A língua da HUD. A opção do mod manda; em `auto`, vale a configuração
839 * `language` do Claude Code e depois o LANG do sistema; sem nenhum dos dois,
840 * a primeira mensagem da pessoa decide; por fim, inglês.
841 */
842export const resolveLang = (
843  option: unknown,
844  claudeLanguage: unknown,
845  systemLang: string | undefined,
846  firstPrompt: string | undefined,
847): Lang => {
848  if (option === 'pt-BR') return 'pt'
849  if (option === 'en') return 'en'
850  const named = typeof claudeLanguage === 'string' ? claudeLanguage.trim().toLowerCase() : ''
851  if (/^(pt|portugu)/.test(named)) return 'pt'
852  // Outra língua do Claude (japonês, espanhol...): a HUD só fala pt e en.
853  if (named !== '') return 'en'
854  if (systemLang !== undefined && /^pt/i.test(systemLang)) return 'pt'
855  if (systemLang !== undefined && /^en/i.test(systemLang)) return 'en'
856  if (firstPrompt !== undefined && looksPortuguese(firstPrompt)) return 'pt'
857  return 'en'
858}
859
860const PT_WORDS =
861  /(?<![\p{L}])(não|você|vc|para|pra|que|com|uma|um|isso|esse|essa|está|tá|então|também|arquivo|faça|faz|leia|fale|da|dos|das|os|roda|rodar|testes|veja|projeto|quantas|quantos|tem|como|mas|aqui|agora|vamos|pode|preciso|quero|meu|minha|ele|ela|seu|sua|pelo|pela|por favor|obrigad\p{L}*)(?![\p{L}])/giu
862
863/** Acento já basta; sem acento, duas ocorrências de palavras portuguesas (repetidas valem: "para… para…"). */
864export const looksPortuguese = (text: string) => /[ãõçáéíóúâêô]/i.test(text) || (text.match(PT_WORDS) ?? []).length >= 2
865
hooks/core/pasta.ts 59 lines
1// Pastas do sistema: o seletor de pasta nativo e o "abrir no Explorer/Finder".
2// A API de mods não tem diálogo de pasta: o mod roda o do próprio sistema por
3// `$.process.run` (PowerShell no Windows, osascript no macOS, zenity ou kdialog
4// no Linux). Aqui ficam só os argv e as contas de caminho; quem roda é o register.
5
6export type Os = 'windows' | 'mac' | 'linux'
7
8/** `OS=Windows_NT` existe em todo Windows; fora dele, o register tenta o macOS e depois o Linux. */
9export const isWindows = (envOs: string | undefined) => envOs === 'Windows_NT'
10
11// O título e a pasta inicial vão por variável de ambiente, nunca no texto do
12// script: um caminho com aspas ou `$` não vira código.
13const WINDOWS_PICK = [
14  "$ErrorActionPreference='Stop'",
15  '[Console]::OutputEncoding=[Text.Encoding]::UTF8',
16  'Add-Type -AssemblyName System.Windows.Forms',
17  '[System.Windows.Forms.Application]::EnableVisualStyles()',
18  '$d=New-Object System.Windows.Forms.FolderBrowserDialog',
19  '$d.Description=$env:HJ_TITLE',
20  '$d.ShowNewFolderButton=$true',
21  'if($env:HJ_START -and (Test-Path -LiteralPath $env:HJ_START)){$d.SelectedPath=$env:HJ_START}',
22  // Um dono "sempre no topo": sem ele, o diálogo pode abrir atrás do app.
23  "$o=New-Object System.Windows.Forms.Form -Property @{TopMost=$true}",
24  'if($d.ShowDialog($o) -eq [System.Windows.Forms.DialogResult]::OK){[Console]::Out.Write($d.SelectedPath)}',
25  '$o.Dispose()',
26].join(';')
27
28/** Os comandos que abrem o seletor de pasta, na ordem de tentativa. */
29export const pickArgvs = (os: Os): string[][] =>
30  os === 'windows'
31    ? [['powershell', '-NoProfile', '-NonInteractive', '-STA', '-Command', WINDOWS_PICK]]
32    : os === 'mac'
33      ? [['osascript', '-e', 'POSIX path of (choose folder with prompt (system attribute "HJ_TITLE"))']]
34      : [
35          ['zenity', '--file-selection', '--directory', '--title=Hero Journey'],
36          ['kdialog', '--getexistingdirectory', '.'],
37        ]
38
39/** O que abre a pasta no gerenciador de arquivos do sistema. */
40export const openArgv = (os: Os, path: string): string[] =>
41  os === 'windows' ? ['explorer.exe', path.replace(/\//g, '\\')] : os === 'mac' ? ['open', path] : ['xdg-open', path]
42
43/** A saída do seletor: o caminho escolhido, ou undefined se a pessoa cancelou. */
44export const pickedOf = (stdout: string) => {
45  const path = stdout.trim()
46  if (path === '') return undefined
47  // A raiz fica com a barra: "C:" sozinho não é a raiz do disco.
48  if (/^[a-z]:[\\/]?$/i.test(path)) return `${path.slice(0, 2)}\\`
49  if (path === '/') return path
50  return path.replace(/[\\/]+$/, '')
51}
52
53/** Junta a pasta e a subpasta com a barra que a pasta já usa (C:\Vault\Inbox, /vault/Inbox). */
54export const joinPath = (root: string, sub: string) => {
55  const sep = root.includes('\\') ? '\\' : '/'
56  const clean = sub.replace(/[\\/]+/g, sep).replace(/^[\\/]+|[\\/]+$/g, '')
57  return clean === '' ? root : `${root.replace(/[\\/]+$/, '')}${sep}${clean}`
58}
59
hooks/core/prefs.ts 82 lines
1// Preferências da HUD: os módulos que ligam e desligam, a pele e o modo da guarda.
2
3import type { MemoryPrefs, ModuleId, Prefs } from '../../types'
4
5/** Ordem em que o ⚙ mostra os módulos; `tokens` marca quem pode gastar. */
6export const MODULES: readonly { id: ModuleId; tokens: boolean }[] = [
7  { id: 'diario', tokens: false },
8  { id: 'faixa', tokens: false },
9  { id: 'painel', tokens: false },
10  { id: 'campanha', tokens: true },
11  { id: 'recibo', tokens: false },
12  { id: 'mochila', tokens: true },
13  { id: 'guarda', tokens: false },
14  { id: 'grimorio', tokens: true },
15]
16
17/** Tudo ligado: com vault e ai-memory detectados, é a configuração recomendada; sem eles, cada recurso usa o projeto. */
18export const DEFAULT_MEMORY: MemoryPrefs = {
19  progresso: true,
20  cronica: true,
21  regras: true,
22  lembra: true,
23  avisoPalco: true,
24  avisoMarco: true,
25  avisoCompactar: true,
26  decisoesEm: 'auto',
27}
28
29export const DEFAULT_PREFS: Prefs = {
30  skin: 'epico',
31  modules: {},
32  guardMode: 'dialogo',
33  grimorioHaiku: false,
34  memory: DEFAULT_MEMORY,
35}
36
37/** Todo módulo nasce ligado; a pessoa desliga no ⚙. */
38export const isOn = (prefs: Prefs, id: ModuleId) => prefs.modules[id] !== false
39
40export const toggleModule = (prefs: Prefs, id: ModuleId): Prefs => ({
41  ...prefs,
42  modules: { ...prefs.modules, [id]: !isOn(prefs, id) },
43})
44
45const KNOWN = new Set<string>(MODULES.map(m => m.id))
46
47/**
48 * Preferências guardadas de uma versão antiga ganham os campos novos e perdem
49 * os que saíram (perfis, seções, modo do diário, módulos que deixaram a HUD).
50 */
51export const migratePrefs = (stored: unknown): Prefs => {
52  const s = (stored ?? {}) as Partial<Prefs> & Record<string, unknown>
53  const modules = Object.fromEntries(Object.entries(s.modules ?? {}).filter(([id]) => KNOWN.has(id)))
54  return {
55    skin: s.skin === 'sobrio' ? 'sobrio' : 'epico',
56    modules,
57    // O modo chefe saiu na 0.6: quem usava passa a ter o dragão perguntando.
58    guardMode: s.guardMode === 'nativo' ? 'nativo' : 'dialogo',
59    grimorioHaiku: s.grimorioHaiku === true,
60    memory: migrateMemory(s.memory),
61  }
62}
63
64export type MemoryToggle = Exclude<keyof MemoryPrefs, 'decisoesEm'>
65
66const migrateMemory = (stored: unknown): MemoryPrefs => {
67  const m = (stored ?? {}) as Partial<MemoryPrefs>
68  const flag = (k: MemoryToggle) => (typeof m[k] === 'boolean' ? (m[k] as boolean) : DEFAULT_MEMORY[k])
69  return {
70    progresso: flag('progresso'),
71    cronica: flag('cronica'),
72    regras: flag('regras'),
73    lembra: flag('lembra'),
74    avisoPalco: flag('avisoPalco'),
75    avisoMarco: flag('avisoMarco'),
76    avisoCompactar: flag('avisoCompactar'),
77    decisoesEm: m.decisoesEm === 'vault' || m.decisoesEm === 'projeto' ? m.decisoesEm : 'auto',
78  }
79}
80
81export const toggleMemory = (prefs: Prefs, k: MemoryToggle): Prefs => ({ ...prefs, memory: { ...prefs.memory, [k]: !prefs.memory[k] } })
82
hooks/core/ui.tsx 89 lines
1// O que toda tela usa: os elementos da superfície, o Svg só no desktop e o
2// título de seção nas duas peles. Nenhuma função aqui usa `$`.
3
4import type { EngineInterface } from 'claude-code'
5
6import type { Cls, Palette, Skin } from '../../types'
7import type { Art } from './art'
8import { heroTitle } from './art'
9import type { Dict } from './i18n'
10import { rasterOfPixels } from './raster'
11import { TH, TW, tsprite } from './tsprites'
12import type { TPose } from './tsprites'
13
14export type Ui = ReturnType<EngineInterface['ui']['resolve']>
15type DesktopUi = Extract<Ui, { Svg: unknown }>
16
17export const GITHUB_URL = 'https://github.com/soulrocha/Claude-code-hero-journey'
18/** O LinkedIn do Saulo, no "Sobre". */
19export const LINKEDIN_URL = 'https://www.linkedin.com/in/soulrocha'
20export const VERSION = '1.0.0'
21
22export type Ctx = {
23  ui: Ui
24  desktop: boolean
25  t: Dict
26  palette: Palette
27  skin: Skin
28  width: number
29  /** No terminal, o painel acima do prompt (sem o modo tela cheia): sem palco, para não comer a conversa. */
30  inline?: boolean
31  /** O tom quente do painel; ausente quando o tema do Claude é automático (não dá para saber se é claro). */
32  bg?: string
33}
34
35/**
36 * O frame isolado do `Svg` interativo pinta o fundo branco quando o esquema de
37 * cor dele difere do app. Com o tema automático, segue o do sistema, como o app.
38 */
39export const withScheme = (source: string, c: Pick<Ctx, 'palette' | 'bg'>) => {
40  const scheme = c.bg === undefined ? 'light dark' : c.palette === 'claro' ? 'light' : 'dark'
41  return source.replace(/^<svg[^>]*>/, tag => `${tag}<style>:root{color-scheme:${scheme}}</style>`)
42}
43
44/** Svg só no desktop; nas outras superfícies, nada (quem chama põe o texto). */
45export const svg = (c: Ctx, a: Art, key?: string) => {
46  if (!c.desktop) return null
47  const { Svg } = c.ui as DesktopUi
48  return <Svg key={key ?? a.alt} source={withScheme(a.source, c)} width={a.width} height={a.height} alt={a.alt} isInteractive />
49}
50
51/**
52 * A largura útil em px: as colunas menos o recuo de 1 de cada lado, a 7,6 px
53 * por coluna (medido com a régua do laboratório no app desktop).
54 */
55export const pxOf = (c: Ctx) => Math.max(160, Math.round((c.width - 2) * 7.6))
56
57/** Título do quest log; `right` é um contador à direita (ex.: "3/8"). */
58export const title = (c: Ctx, text: string, mark?: '!' | '?', right?: string) => {
59  const { Text } = c.ui
60  return c.desktop ? (
61    svg(c, heroTitle(pxOf(c), text, c.palette, mark, right), `title-${text}`)
62  ) : (
63    <Text bold color="claude">
64      {c.skin === 'epico' ? `◆ ${mark === undefined ? '' : `${mark} `}${text} ◆` : text.toUpperCase()}
65    </Text>
66  )
67}
68
69type InputUi = Extract<Ui, { Input: unknown }>
70
71/** O campo de texto, nas superfícies que têm (desktop e terminal); senão, nada. */
72export const inputOf = (ui: Ui): InputUi['Input'] | undefined => ('Input' in ui ? (ui as InputUi).Input : undefined)
73
74type TerminalUi = Extract<Ui, { Raster: unknown }>
75
76/** Uma barra em texto, para o terminal: ▰ cheio e ▱ vazio. */
77export const textBar = (pct: number, width: number) => {
78  const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
79  return { full: '▰'.repeat(full), empty: '▱'.repeat(width - full) }
80}
81
82/** Um Clawd do terminal (pixel art própria), `scale` 1 (24×7 células) ou 2 (48×13). */
83export const clawdArt = (c: Ctx, cls: Cls, pose: TPose, key: string, scale = 1, camp = false) => {
84  if (c.desktop || !('Raster' in c.ui)) return null
85  const r = rasterOfPixels(tsprite(cls, pose, camp), TW, TH, key, scale)
86  const { Raster } = c.ui as TerminalUi
87  return <Raster key={key} columns={r.columns} rows={r.rows} cells={r.cells} />
88}
89
hooks/modules/campanha/campanha.ts 137 lines
1// Campanha: a sessão é a campanha. O título e o objetivo vêm da primeira
2// mensagem, cada mensagem nova abre um capítulo, e o fim de cada turno fecha o
3// capítulo com o que aconteceu nele (a missão, os números e as falhas), que
4// alimenta a barra do objetivo e o recibo do turno. A ideia de linha do tempo
5// da sessão veio do session-time-machine, de Daniel Ávila (claude-code-templates, MIT) —
6// https://github.com/davila7/claude-code-templates/tree/main/cli-tool/components/mods/productivity/session-time-machine
7
8import type { Campaign, Chapter, DiaryEntry, Report } from '../../../types'
9
10const clean = (text: string) => text.replace(/\s+/g, ' ').trim()
11
12/** Título curto: a primeira frase da mensagem, até 60 caracteres. */
13const titleOf = (prompt: string) => {
14  const first = clean(prompt).split(/(?<=[.!?])\s/)[0] ?? ''
15  return first.length > 60 ? `${first.slice(0, 59)}…` : first
16}
17
18export const newCampaign = (id: string, prompt: string, at: number): Campaign => ({
19  id,
20  title: titleOf(prompt),
21  objective: cutAtWord(prompt, 280),
22  startedAt: at,
23  achieved: false,
24  chapters: [{ n: 1, prompt: clean(prompt).slice(0, 140) }],
25})
26
27/** Corta na palavra, com reticências: nunca "…rode os test". */
28export const cutAtWord = (text: string, max: number) => {
29  const t = clean(text)
30  if (t.length <= max) return t
31  const cut = t.slice(0, max - 1)
32  const space = cut.lastIndexOf(' ')
33  return `${(space > max * 0.5 ? cut.slice(0, space) : cut).replace(/[\s,;:.\-–—]+$/, '')}…`
34}
35
36// Aberturas que não dizem o objetivo ("Ok.", "Por favor", "Primeiro").
37const OPENERS = /^(ok|okay|beleza|certo|bom|então|entao|oi|olá|ola|e aí|e ai|por favor|please|hey|hi|primeiro|first)[\s,.!:]+/i
38
39/**
40 * O objetivo curto, sem gastar tokens: a primeira frase do pedido sem as
41 * aberturas, cortada na palavra em até 70 caracteres. O inteiro vai no tooltip.
42 */
43export const shortGoal = (prompt: string) => {
44  let t = clean(prompt)
45  for (let i = 0; i < 3 && OPENERS.test(t); i++) t = t.replace(OPENERS, '')
46  const first = t.split(/(?<=[.!?])\s/)[0] ?? t
47  const goal = first.length >= 12 ? first : t
48  return cutAtWord(goal.charAt(0).toUpperCase() + goal.slice(1), 70)
49}
50
51/** O objetivo para mostrar: o título que o app deu à sessão, a Missão da 1ª resposta ou o shortGoal. */
52export const goalOf = (c: Campaign) => c.short ?? shortGoal(c.objective)
53
54/** Uma mensagem nova: a primeira cria a campanha, as outras abrem capítulos. */
55export const onPrompt = (c: Campaign | null, id: string, prompt: string, at: number): Campaign => {
56  if (c === null) return newCampaign(id, prompt, at)
57  const n = c.chapters.length + 1
58  return { ...c, chapters: [...c.chapters, { n, prompt: clean(prompt).slice(0, 140) }] }
59}
60
61/** O capítulo de um turno. Um turno sem mensagem nova (continuação) não tem capítulo. */
62export const chapterOf = (c: Campaign | null, turnId: string): Chapter | undefined => c?.chapters.find(ch => ch.turnId === turnId)
63
64/**
65 * Liga o turno que começa ao capítulo da mensagem dele: o primeiro capítulo sem
66 * turno cujo texto bate com o do turno. Uma mensagem digitada durante outro
67 * turno espera o seu próprio; um turno de continuação não pega capítulo nenhum.
68 */
69export const assignTurn = (c: Campaign, turnId: string, text: string): Campaign => {
70  const said = clean(text)
71  const ch = c.chapters.find(x => x.turnId === undefined && said !== '' && said.startsWith(x.prompt.replace(/…$/, '')))
72  return ch === undefined ? c : { ...c, chapters: c.chapters.map(x => (x.n === ch.n ? { ...x, turnId } : x)) }
73}
74
75/** As linhas do formato briefing-de-bordo: Missão, Resultado, Risco, Próximo, Aguarda você. */
76export const briefingOf = (answer: string) => {
77  const field = (...names: string[]) => {
78    for (const name of names) {
79      const m = new RegExp(`\\*\\*${name}:\\*\\*\\s*(.+)`, 'i').exec(answer)
80      if (m?.[1] !== undefined) return clean(m[1]).slice(0, 200)
81    }
82    return undefined
83  }
84  return {
85    mission: field('Missão', 'Mission'),
86    result: field('Resultado', 'Result'),
87    risk: field('Risco', 'Risk'),
88    next: field('Próximo', 'Next'),
89    waits: field('Aguarda você', 'Waiting on you'),
90  }
91}
92
93/** O fechamento de um capítulo, montado do diário do turno e da resposta final. */
94export const buildReport = (
95  chapter: Chapter,
96  entries: readonly DiaryEntry[],
97  answer: string,
98  durationMs: number,
99  reason: string,
100  refusals: readonly string[],
101): Report => {
102  const b = briefingOf(answer)
103  const files = new Set(entries.filter(e => /^(Edit|Write|MultiEdit|NotebookEdit)$/.test(e.tool)).map(e => e.summary))
104  return {
105    chapter: chapter.n,
106    title: b.mission ?? chapter.prompt.slice(0, 80),
107    mission: b.mission,
108    result: b.result,
109    risk: b.risk,
110    next: b.next,
111    waits: b.waits,
112    durationMs,
113    reason,
114    actions: entries.length,
115    files: files.size,
116    added: entries.reduce((n, e) => n + (e.added ?? 0), 0),
117    removed: entries.reduce((n, e) => n + (e.removed ?? 0), 0),
118    created: entries.filter(e => e.isNew === true).length,
119    failed: entries.filter(e => e.status === 'err').length,
120    refusals: [...refusals],
121  }
122}
123
124/** Fecha o capítulo atual com o relatório. */
125export const closeChapter = (c: Campaign, report: Report): Campaign => ({
126  ...c,
127  chapters: c.chapters.map(ch => (ch.n === report.chapter ? { ...ch, report } : ch)),
128})
129
130/** Cada campanha numa chave própria do `$.store`, para duas sessões não sobrescreverem uma à outra. */
131export const storeKey = (id: string) => `campanha:${id}`
132
133/** As chaves de campanha a apagar para guardar só as 20 mais recentes. */
134export const prune = (stored: readonly { key: string; startedAt: number }[], keep = 20) =>
135  [...stored].sort((a, b) => b.startedAt - a.startedAt).slice(keep).map(x => x.key)
136
137
hooks/modules/diario/view.tsx 87 lines
1// Diário de bordo, enxuto: o pet da classe com 44 px de altura (na falha, a pose de falha), quem
2// age e o quê, e o resultado em texto curto + símbolo, sem contorno. Vale durante o turno: no
3// fim, o app desktop recolhe as linhas em "Executado N ações", e o recibo fica.
4// Padrão de embrulhar o ToolUse e medir o tempo: tool-timing-badge, de Daniel
5// Ávila (claude-code-templates, MIT) — https://github.com/davila7/claude-code-templates/tree/main/cli-tool/components/mods/ui/tool-timing-badge
6
7import type { RenderElement } from 'claude-code'
8
9import type { DiaryEntry } from '../../../types'
10import { classColor, diaryPet, spinRing, statusColor } from '../../core/art'
11import type { Ctx } from '../../core/ui'
12import { CLASS_ICON } from '../../core/tsprites'
13import { svg } from '../../core/ui'
14
15/** O texto curto ao lado do símbolo: "novo", "+12 −3", "falhou", "em execução" ou o tempo. */
16const resultWords = (c: Ctx, entry: Pick<DiaryEntry, 'status' | 'ms' | 'added' | 'removed' | 'isNew'>) => {
17  if (entry.status === 'run') return ''
18  if (entry.status === 'err') return c.t.failedShort
19  if (entry.isNew === true) return c.t.isNew
20  if (entry.added !== undefined && entry.added + (entry.removed ?? 0) > 0) return `+${entry.added} −${entry.removed ?? 0}`
21  if (entry.ms !== undefined && entry.ms >= 1000) return `${(entry.ms / 1000).toFixed(1)}s`
22  return ''
23}
24
25export const rowView = (
26  c: Ctx,
27  entry: Pick<DiaryEntry, 'cls' | 'status' | 'summary' | 'ms' | 'added' | 'removed' | 'isNew'>,
28  row: RenderElement,
29): RenderElement => {
30  const { Box, Text } = c.ui
31  const name = c.t.className[entry.cls]
32  const words = resultWords(c, entry)
33  const color = statusColor(entry.status, c.palette)
34  if (!c.desktop) {
35    // Terminal: a linha do motor fica (o ctrl+o continua abrindo o resultado); à direita, quem agiu
36    // na cor da classe e o resultado, com o símbolo sempre na última coluna.
37    return (
38      <Box flexDirection="row" columnGap={1}>
39        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
40          {row}
41        </Box>
42        <Box flexDirection="row" columnGap={1} flexShrink={0}>
43          <Text>{CLASS_ICON[entry.cls]}</Text>
44          <Text bold color={entry.status === 'err' ? color : classColor(entry.cls, c.palette)}>
45            {name}
46          </Text>
47          {words !== '' && (
48            <Text color={entry.status === 'err' ? color : undefined} dimColor={entry.status !== 'err'}>
49              {words}
50            </Text>
51          )}
52          <Text bold color={color}>
53            {entry.status === 'run' ? '◌' : entry.status === 'err' ? '✗' : '✓'}
54          </Text>
55        </Box>
56      </Box>
57    )
58  }
59  // A linha é do mod (sem o trilho do app): o Clawd grande, quem age e o quê, e o resultado
60  // à direita com o símbolo por último, para os símbolos ficarem alinhados na mesma coluna.
61  return (
62    <Box flexDirection="row" columnGap={1} alignItems="center">
63      {svg(c, diaryPet(entry.cls, entry.status, `${name} · ${entry.summary}`), 'mark')}
64      <Box flexDirection="row" columnGap={1} flexGrow={1} flexShrink={1}>
65        <Text bold color={entry.status === 'err' ? color : classColor(entry.cls, c.palette)}>
66          {name}
67        </Text>
68        <Text wrap="truncate-end">{entry.summary}</Text>
69      </Box>
70      <Box flexDirection="row" columnGap={1} flexShrink={0} alignItems="center">
71        {words !== '' && (
72          <Text color={entry.status === 'err' ? color : undefined} dimColor={entry.status !== 'err'}>
73            {words}
74          </Text>
75        )}
76        {entry.status === 'run' ? (
77          svg(c, spinRing(color, c.t.running), 'ring')
78        ) : (
79          <Text bold color={color}>
80            {entry.status === 'err' ? '✗' : '✓'}
81          </Text>
82        )}
83      </Box>
84    </Box>
85  )
86}
87
hooks/modules/faixa/view.tsx 126 lines
1// Faixa acima do prompt, em uma linha: o pet da classe, quem age, o arquivo em
2// uso (na cor da raridade) ou o que a ferramenta faz, e à direita o selo de
3// alerta e a trilha do plano. O "Painel ›" no canto abre e fecha o painel. Nunca repete
4// o pedido da pessoa nem a frase que o Claude escreveu no chat.
5
6import type { RenderElement } from 'claude-code'
7
8import type { Member, Quest, Working } from '../../../types'
9import { classColor, petArt, rarityTone, toneOf, trailArt } from '../../core/art'
10import type { Step } from '../../core/art'
11import type { Ctx } from '../../core/ui'
12import { CLASS_ICON } from '../../core/tsprites'
13import { svg } from '../../core/ui'
14import { humanType } from '../../core/classes'
15import { questView, rarityOf } from '../painel/painel'
16
17/** Os passos do plano: as tarefas do Claude, com a primeira em aberto como a atual. */
18export const stepsOf = (quests: readonly Quest[]): Step[] => {
19  const current = questView(quests).current
20  return quests.map(q => ({
21    name: q.title,
22    state: q.status === 'completed' ? 'done' : q === current ? 'now' : 'next',
23  }))
24}
25
26/** Os dois últimos pedaços do caminho: "painel/view.tsx". */
27const shortPath = (path: string) => path.split(/[\\/]/).filter(Boolean).slice(-2).join('/')
28
29/**
30 * `away`: subagentes rodando em segundo plano. Com o Claude parado e alguém em
31 * expedição, a faixa diz isso (nada de "Pronto" falso) e o tooltip lista cada um.
32 * `failed`: a última ferramenta do turno falhou (o pet tropeça).
33 */
34export const bandView = (
35  c: Ctx,
36  now: Working | null,
37  quests: readonly Quest[],
38  toggle: () => void,
39  away: readonly Member[] = [],
40  /** O selo de um recurso em alerta ("🎒 Mochila 92%"), ao lado do ◈; só aparece quando importa. */
41  alert?: string,
42  failed = false,
43): RenderElement => {
44  const { Box, Button, Text } = c.ui
45  const k = toneOf(c.palette)
46  const name = now ? c.t.className[now.cls] : ''
47  const awayName = (m: Member) => humanType(m.type, c.t.knownTypes) || c.t.className[m.cls]
48  const idle = away.length > 0 ? c.t.expedition(away.length, awayName(away[0] as Member)) : c.t.yourTurn
49  const idleTip = away.length > 0 ? c.t.expeditionTip(away.map(m => `${awayName(m)} (${c.t.className[m.cls]}) — ${m.description}`)) : idle
50  // Só com um plano de verdade (2 tarefas ou mais): a trilha e o placar.
51  const steps = quests.length >= 2 ? stepsOf(quests) : []
52  const done = steps.filter(s => s.state === 'done').length
53  const current = steps.find(s => s.state === 'now')
54  const file = now?.file === undefined ? undefined : shortPath(now.file)
55  if (!c.desktop) {
56    // Terminal: a mesma linha; no lugar do pet, o ◆ na cor da classe; a trilha do plano em texto.
57    const trail = steps.map(s => (s.state === 'done' ? '●' : s.state === 'now' ? '◐' : '○')).join('')
58    return (
59      <Box key="band" flexDirection="row" columnGap={1}>
60        {now ? (
61          <Text bold color={failed ? k.bad : classColor(now.cls, c.palette)}>
62            {CLASS_ICON[now.cls]} {name}
63          </Text>
64        ) : (
65          <Text color={away.length > 0 ? 'warning' : undefined} dimColor={away.length === 0}>
66            {away.length > 0 ? '🌀' : '🔥'} {idle}
67          </Text>
68        )}
69        {now && file !== undefined && (
70          <Text color={rarityTone(rarityOf(file), c.palette)} wrap="truncate-end">
71            {file}
72          </Text>
73        )}
74        {now && file === undefined && (
75          <Text dimColor wrap="truncate-end">
76            {now.summary}
77          </Text>
78        )}
79        <Box flexGrow={1} />
80        {alert !== undefined && (
81          <Button key="hero-alert" plain label={alert} onPress={toggle}>
82            <Text color="warning">{alert}</Text>
83          </Button>
84        )}
85        {steps.length > 0 && <Text color={k.gild}>{trail}</Text>}
86        {steps.length > 0 && <Text dimColor>{`${done}/${steps.length}`}</Text>}
87        <Button key="hero-toggle" plain dimColor label={c.t.panelToggle} onPress={toggle} />
88      </Box>
89    )
90  }
91  const pet = now
92    ? petArt(now.cls, failed ? 'fail' : 'work', 40, `${name} · ${now.summary}`)
93    : petArt('aprendiz', 'idle', 40, idleTip)
94  const tip = current === undefined ? `${done}/${steps.length}` : `${c.t.bandStep(Math.min(done + 1, steps.length), steps.length)}: ${current.name}`
95  return (
96    <Box key="band" flexDirection="row" columnGap={1} alignItems="center">
97      {svg(c, pet, 'band-pet')}
98      {now ? (
99        <Box flexDirection="row" columnGap={1} flexShrink={1}>
100          <Text bold color={failed ? k.bad : classColor(now.cls, c.palette)}>
101            {name}
102          </Text>
103          {file !== undefined ? (
104            <Text color={rarityTone(rarityOf(file), c.palette)} wrap="truncate-end">
105              {file}
106            </Text>
107          ) : (
108            <Text dimColor wrap="truncate-end">
109              {now.summary}
110            </Text>
111          )}
112        </Box>
113      ) : (
114        <Text color={away.length > 0 ? 'warning' : undefined} dimColor={away.length === 0} wrap="truncate-end">
115          {idle}
116        </Text>
117      )}
118      <Box flexGrow={1} />
119      {alert !== undefined && <Button key="hero-alert" plain label={alert} onPress={toggle} />}
120      {steps.length > 0 && svg(c, trailArt(steps.length, done, c.palette, tip), 'band-trail')}
121      {steps.length > 0 && <Text dimColor>{`${done}/${steps.length}`}</Text>}
122      <Button key="hero-toggle" plain dimColor label={c.t.panelToggle} onPress={toggle} />
123    </Box>
124  )
125}
126
hooks/modules/grimorio/grimorio.ts 462 lines
1// Grimório: acha, sem chamar o modelo, o que vale guardar de um turno (decisão
2// técnica, conquista com número, regra que a pessoa estabeleceu), sugere um
3// destino só para cada um e monta o salvar progresso (a tarefa num arquivo, para
4// continuar depois em qualquer agente). Nada é gravado sem o clique da pessoa.
5// O Haiku só entra, se ligado no ⚙, para reescrever um candidato numa frase.
6
7import type { Destination, Inscription, InscriptionKind, MemoryPrefs, Written } from '../../../types'
8import { joinPath } from '../../core/pasta'
9
10// Na resposta do Claude, só decisão declarada ("decidimos", "ficou decidido"):
11// a palavra "decisão" solta aparece em pendências ("aguardo sua decisão") e tabelas.
12const DECISION = /\b(decidimos|ficou decidido|optamos|adotamos|padr[ãa]o adotado|we decided|we chose|it was decided)\b/i
13// Na mensagem da pessoa, regra que ela mesma estabelece. `(?=\W|$)`: "regra:" seguido de espaço não tem fronteira.
14const RULE = /\b(a partir de agora|de agora em diante|decidi|regra:|sempre use|nunca use|from now on|always use|never use)(?=\W|$)/i
15// Frases que falam de decisão sem tomar uma.
16const NOT_DECIDED = /\b(sua decis[ãa]o|nenhuma decis[ãa]o|aguard\w*|pendente|your decision|no decision|waiting)\b/i
17// Daqui em diante a resposta do briefing é pendência, risco ou próximo passo: não é decisão nem conquista.
18const OPEN_PART = /\*\*(Aguarda você|Sua vez|Próximo|Risco|Não verificado|Waiting on you|Your turn|Next|Risk|Not verified):\*\*/i
19
20/** A parte da resposta que fala do que foi feito: sem pendências, código, tabelas nem citações. */
21const settledPart = (answer: string) => {
22  const cut = answer.search(OPEN_PART)
23  return (cut === -1 ? answer : answer.slice(0, cut))
24    .replace(/```[\s\S]*?```/g, '')
25    .split('\n')
26    .filter(line => !/^\s*(\||>)/.test(line))
27    .join('\n')
28}
29
30/** A linha **Resultado:** do briefing, quando existe: é dela que sai a conquista. */
31const resultLine = (answer: string) => /\*\*(Resultado|Result):\*\*\s*(.+)/i.exec(answer)?.[2]
32// "aumentou" sozinho não é conquista ("o contexto aumentou para 60%"); "de X para Y" é.
33const IMPROVEMENT = /\b(reduz\w*|melhor\w*|caiu|cortou|acelerou|de [\d.,]+\s?\w* para [\d.,]+|reduced|improved|faster|dropped|from [\d.,]+\s?\w* to [\d.,]+)/i
34const NUMBER = /\d+([.,]\d+)?\s?(%|ms|s\b|x\b|vezes|min|segundos|minutos|horas|times|kb|mb)/i
35
36const sentences = (text: string) =>
37  text
38    .replace(/\*\*/g, '')
39    .split(/(?<=[.!?])\s+|\n+/)
40    .map(s => s.replace(/^[-*•\d.)\s]+/, '').trim())
41    .filter(s => s.length >= 12 && s.length <= 280)
42
43export const slug = (text: string) =>
44  text
45    .normalize('NFD')
46    .replace(/[̀-ͯ]/g, '')
47    .toLowerCase()
48    .replace(/[^a-z0-9]+/g, '-')
49    .replace(/^-|-$/g, '')
50    .slice(0, 40)
51
52/** O servidor MCP do ai-memory, pelo nome da ferramenta (vale com o servidor renomeado). */
53export type Memory = { server: string }
54
55/** Para onde dá para gravar nesta sessão: a pasta do vault e o ai-memory, se o MCP estiver conectado. */
56export type Dests = { vault: string; inbox?: string; memory?: Memory }
57
58/**
59 * O escopo de toda chamada ao ai-memory. O mod é um cliente MCP sem hooks: sem
60 * `workspace` e `project`, as leituras falham e as escritas caem no projeto padrão
61 * (docs/programmatic-memory.md do ai-memory).
62 */
63export type MemoryScope = { workspace: string; project: string }
64
65/** Nome que o ai-memory aceita: minúsculas, dígitos, ponto, traço e sublinhado. */
66export const safeName = (text: string) =>
67  text
68    .toLowerCase()
69    .replace(/[^a-z0-9._-]+/g, '-')
70    .replace(/^[^a-z0-9]+|-+$/g, '')
71
72/** As chaves de escopo do `.ai-memory.toml` (só as de cima, antes da primeira seção). */
73export const parseMarker = (toml: string): Partial<MemoryScope> => {
74  const top = toml.split(/^\s*\[/m)[0] ?? ''
75  const key = (k: string) => new RegExp(`^\\s*${k}\\s*=\\s*["']([^"']+)["']`, 'm').exec(top)?.[1]?.trim()
76  const workspace = key('workspace')
77  const project = key('project')
78  return { ...(workspace ? { workspace } : {}), ...(project ? { project } : {}) }
79}
80
81/**
82 * O projeto pelo remoto do git, como o ai-memory faz: o caminho sem o host, com
83 * "/" virando "-" (`git@github.com:acme/api.git` → `acme-api`).
84 */
85export const projectFromRemote = (url: string) => {
86  const path = url
87    .trim()
88    .replace(/\.git$/i, '')
89    .replace(/^[a-z+]+:\/\/[^/]+\//i, '')
90    .replace(/^[^@/]+@[^:]+:/, '')
91  return path === '' || path === url.trim() ? '' : safeName(path.replace(/\//g, '-'))
92}
93
94/** Acha o `memory_write_page` do ai-memory entre as ferramentas da sessão. */
95export const memoryTool = (tools: readonly { name: string; description?: string }[]): Memory | undefined => {
96  for (const t of tools) {
97    const m = /^mcp__(.+)__memory_write_page$/.exec(t.name)
98    if (m?.[1] !== undefined) return { server: m[1] }
99  }
100  return undefined
101}
102
103/** Os destinos que existem nesta sessão: o AGENTS.md e o projeto sempre; o vault e o ai-memory quando há. */
104export const available = (dest: Destination, d: Dests) =>
105  dest === 'vaultDecisao' || dest === 'carreira' ? d.vault !== '' : dest === 'aiMemory' ? d.memory !== undefined : true
106
107/** Os destinos que fazem sentido para cada tipo, na ordem em que o clique troca. */
108const OPTIONS: Record<InscriptionKind, readonly Destination[]> = {
109  regra: ['agentsMd'],
110  decisao: ['vaultDecisao', 'projeto', 'aiMemory'],
111  conquista: ['carreira', 'projeto', 'aiMemory'],
112}
113
114export const optionsFor = (kind: InscriptionKind, d: Dests) => OPTIONS[kind].filter(x => available(x, d))
115
116/**
117 * O destino sugerido. Regra vai para o AGENTS.md. Decisão e conquista vão para o
118 * vault, se houver; sem vault, para o projeto quando a pessoa já escolheu isso, ou
119 * para nenhum (a primeira crônica pergunta onde guardar).
120 */
121export const suggest = (kind: InscriptionKind, d: Dests, home: MemoryPrefs['decisoesEm']): Destination | undefined => {
122  if (kind === 'regra') return 'agentsMd'
123  if (home === 'projeto') return 'projeto'
124  if (d.vault !== '') return kind === 'decisao' ? 'vaultDecisao' : 'carreira'
125  return home === 'vault' ? undefined : home === 'auto' ? undefined : 'projeto'
126}
127
128/** O clique no destino troca para o próximo que está disponível. */
129export const cycleDest = (list: readonly Inscription[], id: string, d: Dests): Inscription[] =>
130  list.map(i => {
131    if (i.id !== id) return i
132    const opts = optionsFor(i.kind, d)
133    if (opts.length === 0) return i
134    const at = opts.indexOf(i.destinations[0] as Destination)
135    return { ...i, destinations: [opts[(at + 1) % opts.length] as Destination] }
136  })
137
138/** Liga ou desliga os tipos pelo ⚙ Memória: regra com as regras, decisão e conquista com a crônica. */
139export const kindOn = (kind: InscriptionKind, m: MemoryPrefs) => (kind === 'regra' ? m.regras : m.cronica)
140
141/**
142 * A linha que vai para o AGENTS.md: uma linha só, sem crase nem tag, com no
143 * máximo 280 caracteres. A proteção é exigir o clique.
144 */
145export const oneLine = (s: string) => {
146  // `<` e `>` viram ‹ ›: `<system>` deixa de ser marcação, e `List<String>` ou `x < 10` não perdem o sentido.
147  const c = s.replace(/</g, '‹').replace(/>/g, '›').replace(/`/g, ' ').replace(/\s+/g, ' ').trim()
148  return c.length > 280 ? `${c.slice(0, 279)}…` : c
149}
150
151/**
152 * A pasta de entrada fica dentro do vault: nada de caminho absoluto, drive, caminho
153 * de rede ou `..`. Vazia vale (é o padrão, Inbox).
154 */
155export const isSubfolder = (sub: string) => !/^([a-z]:|[\\/])/i.test(sub) && !sub.split(/[\\/]/).includes('..')
156
157/** `nota.md` → `nota-2.md`: o nome livre seguinte, para nunca sobrescrever uma nota. */
158export const withSuffix = (path: string, n: number) => path.replace(/(\.md)?$/, `-${n}$1`)
159
160/** A mesma nota, ignorando a linha `data:` do frontmatter: uma nova tentativa em outro dia não duplica. */
161export const sameNote = (a: string | undefined, b: string) => {
162  // Só a linha data: do frontmatter (entre o primeiro par de ---); no corpo, data: é texto.
163  const plain = (t: string) => t.replace(/\r\n/g, '\n').replace(/^(---\n(?:(?!---\n)[^]*?\n)?)data: .*\n/, '$1')
164  return a !== undefined && plain(a) === plain(b)
165}
166
167/** Candidatos de um turno: decisões e conquistas na resposta, regras na mensagem da pessoa. */
168export const detect = (answer: string, prompt: string, turnId: string): Omit<Inscription, 'destinations'>[] => {
169  const found: Omit<Inscription, 'destinations'>[] = []
170  const add = (kind: InscriptionKind, text: string, source: string) => {
171    if (found.some(f => f.text === text)) return
172    found.push({ id: `${turnId}-${found.length}-${slug(text)}`, kind, text, source })
173  }
174  for (const s of sentences(settledPart(answer))) {
175    if (s.includes('?') || NOT_DECIDED.test(s)) continue
176    if (DECISION.test(s)) add('decisao', s, 'resposta')
177  }
178  // Conquista: um número que melhorou. Com o briefing, só da linha Resultado.
179  const result = resultLine(answer)
180  for (const s of sentences(result ?? settledPart(answer))) {
181    if (!s.includes('?') && NUMBER.test(s) && IMPROVEMENT.test(s)) add('conquista', s, 'resposta')
182  }
183  for (const s of sentences(prompt)) {
184    if (!s.includes('?') && RULE.test(s)) add('regra', s, 'mensagem')
185  }
186  return found.slice(0, 4)
187}
188
189/** Junta candidatos novos aos pendentes, sem repetir texto já visto. */
190export const merge = (current: readonly Inscription[], fresh: readonly Inscription[]) => {
191  const seen = new Set(current.map(i => i.text))
192  return [...current, ...fresh.filter(i => !seen.has(i.text))].slice(-30)
193}
194
195export const isPending = (i: Inscription) => i.sealed === undefined || i.destinations.some(d => !i.sealed!.includes(d))
196
197export const pending = (list: readonly Inscription[]) => list.filter(isPending)
198
199const today = (at: number) => new Date(at).toISOString().slice(0, 10)
200
201export type Write = { dest: Destination; path: string; text: string; append: boolean }
202
203const join = (...parts: string[]) => parts.join('/').replace(/\\/g, '/').replace(/\/+/g, '/')
204
205/**
206 * O que gravar para uma inscrição: caminho, texto e se é acréscimo. Para o
207 * AGENTS.md e o docs/decisoes do projeto (o repositório pode ser público), nada
208 * que cite o vault ou um caminho pessoal. No ai-memory o caminho é o da página,
209 * com a hora no nome, porque `memory_write_page` substitui a de mesmo caminho.
210 */
211export const writesFor = (i: Inscription, d: { repo: string } & Dests, at: number): Write[] => {
212  const date = today(at)
213  const note = (title: string) => `---\ntipo: ${title}\ndata: ${date}\norigem: hero-journey\n---\n\n${i.text}\n`
214  const already = i.sealed ?? []
215  const out: Write[] = []
216  for (const dest of i.destinations) {
217    if (already.includes(dest) || !available(dest, d)) continue
218    if (dest === 'agentsMd') {
219      if (mentionsPrivate(i.text, d) || oneLine(i.text) === '') continue
220      out.push({ dest, path: join(d.repo, 'AGENTS.md'), text: `- ${oneLine(i.text)} (${date})\n`, append: true })
221    } else if (dest === 'projeto') {
222      if (mentionsPrivate(i.text, d)) continue
223      out.push({ dest, path: join(d.repo, 'docs', 'decisoes', `${date}-${slug(i.text)}.md`), text: note(i.kind === 'conquista' ? 'resultado' : 'decisao'), append: false })
224    } else if (dest === 'vaultDecisao') {
225      out.push({ dest, path: join(d.vault, d.inbox ?? 'Inbox', `decisao-pendente-${date}-${slug(i.text)}.md`), text: note('decisao'), append: false })
226    } else if (dest === 'carreira') {
227      out.push({ dest, path: join(d.vault, d.inbox ?? 'Inbox', `resultado-pendente-${date}-${slug(i.text)}.md`), text: note('resultado'), append: false })
228    } else {
229      const hms = new Date(at).toISOString().slice(11, 19).replace(/:/g, '')
230      // Data, origem e "conferir no código": o modelo tende a confiar no que recupera (ClashEval), então a página diz de onde veio.
231      const meta = `---\ntipo: ${i.kind === 'conquista' ? 'resultado' : 'decisao'}\ndata: ${date}\norigem: hero-journey\nconferir: no código, antes de seguir\n---\n\n`
232      out.push({ dest, path: `${i.kind === 'decisao' ? 'decisions' : 'notes'}/${date}-${slug(i.text)}-${hms}.md`, text: `${meta}# ${oneLine(i.text).slice(0, 80)}\n\n${i.text}\n`, append: false })
233    }
234  }
235  return out
236}
237
238/** Regra de privacidade: nada pessoal vai para arquivos do repositório. */
239export const mentionsPrivate = (text: string, paths: { vault: string }) => {
240  const lower = text.toLowerCase().replace(/\\/g, '/')
241  const hit = (p: string) => p !== '' && lower.includes(p.toLowerCase().replace(/\\/g, '/'))
242  return (
243    hit(paths.vault) ||
244    /\b(vault|obsidian|ai-memory)\b/i.test(text) ||
245    // Qualquer caminho absoluto pessoal, em qualquer posição: C:\..., D:\..., /Users/x,
246    // /home/x, /root/, /mnt/c/..., ~/ e caminhos de rede \\servidor\pasta.
247    /\b[a-z]:[\\/]/i.test(text) ||
248    /(\/users\/|\/home\/|\/root\/|\/mnt\/[a-z]\/|(^|[\s"'`(])~\/|\\\\[\w.-]+\\)/i.test(text)
249  )
250}
251
252/** Acrescenta a linha sob "## <heading>" (ou cria a seção no fim). */
253export const appendDecision = (current: string, line: string, heading: string) => {
254  if (current.includes(line.trim())) return current
255  const marker = `## ${heading}`
256  const at = current.indexOf(marker)
257  if (at === -1) return `${current.replace(/\s*$/, '')}${current.trim() === '' ? '' : '\n\n'}${marker}\n\n${line}`
258  const end = current.indexOf('\n## ', at + marker.length)
259  const head = end === -1 ? current.replace(/\s*$/, '') : current.slice(0, end).replace(/\s*$/, '')
260  const tail = end === -1 ? '' : current.slice(end)
261  return `${head}\n${line}${tail}`
262}
263
264/** Tira uma linha que o grimório acrescentou (o Desfazer). */
265export const removeLine = (current: string, line: string) => {
266  const target = line.trim()
267  return current
268    .split('\n')
269    .filter(l => l.trim() !== target)
270    .join('\n')
271}
272
273/** O registro do que foi gravado, para o Desfazer. */
274export const writtenOf = (w: Write, path: string): Written =>
275  w.dest === 'aiMemory' ? { dest: w.dest, path, mode: 'pagina' } : w.append ? { dest: w.dest, path, mode: 'linha', line: w.text } : { dest: w.dest, path, mode: 'novo' }
276
277/** O pedido ao Haiku (só com o ⚙ ligado): uma frase, sem inventar. */
278export const haikuPrompt = (i: Inscription, lang: 'pt' | 'en') =>
279  lang === 'pt'
280    ? `Reescreva como uma única frase curta e objetiva, sem inventar nada e sem citar caminhos de arquivo pessoais. Tipo: ${i.kind}. Texto: "${i.text}". Responda só com a frase.`
281    : `Rewrite as one short, objective sentence, inventing nothing and citing no personal file paths. Kind: ${i.kind}. Text: "${i.text}". Answer with the sentence only.`
282
283// ---------- Salvar progresso: a tarefa num arquivo ----------
284
285/** O nome do projeto pela pasta do repositório: "C:\\Projetos\\claude-code-hero-journey" → "claude-code-hero-journey". */
286export const projectName = (repo: string) => repo.split(/[\\/]/).filter(Boolean).pop() ?? 'projeto'
287
288/**
289 * O caminho que pode sair da máquina (no handoff do ai-memory): relativo à
290 * primeira raiz que o contém (o vault ou o repositório), sem nome de usuário nem
291 * pasta pessoal. Fora delas, só o nome do arquivo.
292 */
293export const shareablePath = (path: string, roots: readonly string[]) => {
294  const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
295  const p = norm(path)
296  for (const root of roots.map(norm).filter(r => r !== '')) {
297    if (p.toLowerCase().startsWith(`${root.toLowerCase()}/`)) return p.slice(root.length + 1)
298  }
299  return p.split('/').pop() ?? p
300}
301
302/**
303 * Onde as tarefas moram. Com vault, em `<vault>/.tarefas/<projeto>/`, com o mesmo
304 * nome de projeto do ai-memory (do marcador ou do remoto do git): dois repositórios
305 * com a mesma pasta final não se misturam. Sem vault, em `<repo>/.hero/tarefas/`,
306 * que o grimório deixa fora do git com um `.gitignore` próprio.
307 */
308export const progressHome = (repo: string, vault: string, project: string) =>
309  vault !== '' ? joinPath(vault, `.tarefas/${project}`) : joinPath(repo, '.hero/tarefas')
310
311/** O prefixo do ID: as iniciais do projeto ("claude-code-hero-journey" → "CCHJ"). */
312export const taskPrefix = (name: string) => {
313  const initials = name
314    .split(/[-_\s.]+/)
315    .filter(Boolean)
316    .map(w => w[0]?.toUpperCase() ?? '')
317    .join('')
318    .replace(/[^A-Z0-9]/g, '')
319  return initials.slice(0, 4) || 'T'
320}
321
322/** O ID seguinte: o maior número já usado com o prefixo, mais um, com três dígitos. */
323export const nextTaskId = (files: readonly string[], prefix: string) => {
324  const used = files.map(f => new RegExp(`^${prefix}-(\\d+)\\.md$`).exec(f)?.[1]).filter((n): n is string => n !== undefined)
325  const n = used.reduce((max, x) => Math.max(max, Number(x)), 0) + 1
326  return `${prefix}-${String(n).padStart(3, '0')}`
327}
328
329export type Task = {
330  id: string
331  status: 'aberta' | 'em-andamento' | 'bloqueada' | 'concluida'
332  project: string
333  updated: string
334  title: string
335  objective: string
336  next: string
337  verify: string
338  failed: string[]
339  log: string[]
340}
341
342/** O arquivo da tarefa, no modelo do vault (`.tarefas/_modelo.md`). */
343export const taskText = (t: Task) =>
344  [
345    '---',
346    `id: ${t.id}`,
347    `status: ${t.status}`,
348    `projeto: ${t.project}`,
349    `atualizado: ${t.updated}`,
350    '---',
351    '',
352    `# ${t.id}: ${t.title}`,
353    '',
354    '## Objetivo',
355    t.objective,
356    '',
357    '## Próximo passo',
358    t.next,
359    '',
360    '## Como verificar',
361    t.verify,
362    '',
363    '## Já tentado e falhou',
364    ...(t.failed.length === 0 ? ['- (vazio)'] : t.failed.map(f => `- ${f}`)),
365    '',
366    '## Log',
367    ...t.log.map(l => `- ${l}`),
368    '',
369  ].join('\n')
370
371const section = (text: string, name: string) => {
372  const m = new RegExp(`^## ${name}\\s*\\n([\\s\\S]*?)(?=^## |$(?![\\s\\S]))`, 'm').exec(text)
373  return (m?.[1] ?? '').trim()
374}
375const listOf = (block: string) =>
376  block
377    .split('\n')
378    .map(l => l.replace(/^-\s*/, '').trim())
379    .filter(l => l !== '' && l !== '(vazio)')
380
381/** Lê um arquivo de tarefa; devolve undefined se não for uma. */
382export const parseTask = (text: string): Task | undefined => {
383  const front = /^---\n([\s\S]*?)\n---/.exec(text.replace(/\r\n/g, '\n'))?.[1]
384  if (front === undefined) return undefined
385  const field = (k: string) => new RegExp(`^${k}:\\s*(.*)$`, 'm').exec(front)?.[1]?.trim() ?? ''
386  const body = text.replace(/\r\n/g, '\n')
387  const id = field('id')
388  if (id === '') return undefined
389  const status = field('status')
390  return {
391    id,
392    status: status === 'em-andamento' || status === 'bloqueada' || status === 'concluida' ? status : 'aberta',
393    project: field('projeto'),
394    updated: field('atualizado'),
395    title: (/^# [^:\n]+:\s*(.+)$/m.exec(body)?.[1] ?? id).trim(),
396    objective: section(body, 'Objetivo'),
397    next: section(body, 'Próximo passo'),
398    verify: section(body, 'Como verificar'),
399    failed: listOf(section(body, 'Já tentado e falhou')),
400    log: listOf(section(body, 'Log')),
401  }
402}
403
404/** "2026-10-11 18:40", no fuso de quem salvou. */
405export const stamp = (at: number) => {
406  const d = new Date(at)
407  const p = (n: number) => String(n).padStart(2, '0')
408  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
409}
410
411export type ProgressInput = {
412  id: string
413  project: string
414  at: number
415  title: string
416  objective: string
417  next: string
418  verify: string
419  failed: readonly string[]
420  /** A linha do log: onde, quem e o que fez ("pc-casa | Claude Code | 4 ações, +42 −8 | a1b2c3d"). */
421  logLine: string
422}
423
424/**
425 * A tarefa salva: nova, ou a anterior atualizada. O próximo passo e o "como
426 * verificar" são os de agora (o verificar antigo fica quando a pessoa não
427 * escreveu outro); falhas e log só crescem, sem repetir.
428 */
429export const saveTask = (old: Task | undefined, p: ProgressInput): Task => ({
430  id: old?.id ?? p.id,
431  status: 'em-andamento',
432  project: p.project,
433  updated: stamp(p.at),
434  title: old?.title ?? p.title,
435  objective: old?.objective || p.objective,
436  next: p.next || old?.next || '',
437  verify: p.verify.trim() || old?.verify || '',
438  failed: [...new Set([...(old?.failed ?? []), ...p.failed])].slice(-10),
439  log: [...(old?.log ?? []), `${stamp(p.at)} | ${p.logLine}`].slice(-30),
440})
441
442/** O pedido que o Continuar leva ao prompt: ler a tarefa e conferir antes de mexer. */
443export const continuePrompt = (lang: 'pt' | 'en', title: string, where: string) =>
444  lang === 'pt'
445    ? `Continue a tarefa "${title}". Leia ${where}, confira o "Como verificar" antes de mexer e siga o próximo passo.`
446    : `Continue the task "${title}". Read ${where}, check its "Como verificar" (how to verify) before changing anything, and take the next step.`
447
448/** Limita a espera de uma operação assíncrona e limpa o timer ao concluir. */
449export async function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
450  let timer: ReturnType<typeof setTimeout> | undefined
451  try {
452    return await Promise.race([
453      promise,
454      new Promise<never>((_, reject) => {
455        timer = setTimeout(() => reject(new Error(`${label}: timeout (${Math.round(ms / 1000)}s)`)), ms)
456      }),
457    ])
458  } finally {
459    if (timer !== undefined) clearTimeout(timer)
460  }
461}
462
hooks/modules/grimorio/view.tsx 439 lines
1// Grimório na tela: a página 📖 (o Sábio na torre, o que há para guardar, o que
2// foi guardado hoje e o que ele lembra), o cartão de fim de marco, o bloco de
3// salvar progresso do cartão de compactar, o Continuar do acampamento, o aviso
4// do Sábio no palco e as linhas do ⚙ Memória. Nada aqui usa `$`.
5
6import type { RenderElement } from 'claude-code'
7
8import type { Inscription, MemoryPrefs, Progress, ProgressState } from '../../../types'
9import { classColor, petArt, sparkleArt, TONE, toneOf } from '../../core/art'
10import { stageArt } from '../../core/cenarios'
11import type { MemoryToggle } from '../../core/prefs'
12import type { Ctx } from '../../core/ui'
13import { clawdArt, inputOf, pxOf, svg, title } from '../../core/ui'
14import { optionsFor } from './grimorio'
15import type { Dests } from './grimorio'
16
17/** A cor de cada intenção: decisão em azul, conquista em rosa, regra em dourado. */
18const kindColor = (c: Ctx, kind: Inscription['kind']) =>
19  kind === 'decisao' ? classColor('mago', c.palette) : kind === 'conquista' ? classColor('rei', c.palette) : toneOf(c.palette).gild
20
21export type InscriptionActions = { cycle: (id: string) => void }
22
23/** Uma inscrição: a intenção, o destino (um só; o clique troca) e o texto. */
24export const inscriptionRow = (c: Ctx, i: Inscription, d: Dests, act?: InscriptionActions) => {
25  const { Box, Button, Text } = c.ui
26  const dest = i.destinations[0]
27  const many = optionsFor(i.kind, d).length > 1
28  const label = dest === undefined ? '→ ?' : `→ ${c.t.dest[dest]}${many && act !== undefined ? ' ▾' : ''}`
29  return (
30    <Box key={`ins-${i.id}`} flexDirection="column">
31      <Box flexDirection="row" columnGap={1}>
32        <Text bold color={kindColor(c, i.kind)}>
33          {c.t.grimKind[i.kind].toUpperCase()}
34        </Text>
35        <Box flexGrow={1} />
36        {act !== undefined && many ? (
37          <Button key={`dest-${i.id}`} plain dimColor label={label} onPress={() => act.cycle(i.id)} />
38        ) : (
39          <Text dimColor>{label}</Text>
40        )}
41      </Box>
42      <Text wrap="wrap">{i.text}</Text>
43    </Box>
44  )
45}
46
47/** O botão de selar do grimório: moldura dourada, estrelas e o verbo do Sábio. */
48export const sealButton = (c: Ctx, n: number, onPress: () => void) => {
49  const { Box, Button, Text } = c.ui
50  const gild = toneOf(c.palette).gild
51  const label = `✦ ${c.t.seal} · ${n}`
52  return (
53    <Box key="grim-seal-box" flexDirection="row" columnGap={1} alignItems="center">
54      {svg(c, sparkleArt(c.palette), 'grim-sparkle')}
55      <Box borderStyle={c.desktop ? 'round' : undefined} borderColor={gild} paddingX={c.desktop ? 1 : 0}>
56        <Button key="grim-seal" plain label={label} onPress={onPress}>
57          <Text bold color={gild}>
58            {label}
59          </Text>
60        </Button>
61      </Box>
62    </Box>
63  )
64}
65
66export type SealActions = InscriptionActions & {
67  seal: () => void
68  /** "Agora não" no cartão; "Descartar" na página. */
69  dismiss: () => void
70  /** Sem vault configurado, a primeira crônica pergunta onde guardar. */
71  chooseHome: (home: 'projeto' | 'vault') => void
72}
73
74/** "Onde guardo suas decisões?": só quando alguma crônica ainda não tem destino. */
75const whereQuestion = (c: Ctx, act: SealActions) => {
76  const { Box, Button, Text } = c.ui
77  return (
78    <Box key="grim-where" flexDirection="column">
79      <Text bold>{c.t.whereDecisions}</Text>
80      <Box flexDirection="row" columnGap={2} flexWrap="wrap">
81        <Button key="grim-home-projeto" label={c.t.inProject} onPress={() => act.chooseHome('projeto')} />
82        <Button key="grim-home-vault" plain label={c.t.myVault} onPress={() => act.chooseHome('vault')} />
83      </Box>
84      <Text dimColor>{c.t.askOnce}</Text>
85    </Box>
86  )
87}
88
89/** As inscrições pendentes, a pergunta (se precisar) e a linha de ações, com espaço entre elas. */
90const sealBlock = (c: Ctx, list: readonly Inscription[], d: Dests, act: SealActions, dismissLabel: string) => {
91  const { Box, Button } = c.ui
92  const asks = list.some(i => i.destinations.length === 0)
93  return [
94    asks ? whereQuestion(c, act) : null,
95    ...list.map(i => inscriptionRow(c, i, d, act)),
96    <Box key="grim-actions" flexDirection="row" columnGap={3} alignItems="center" flexWrap="wrap">
97      <Button key="grim-dismiss" plain dimColor label={dismissLabel} onPress={act.dismiss} />
98      <Box flexGrow={1} />
99      {sealButton(c, list.length, act.seal)}
100    </Box>,
101  ].filter((x): x is RenderElement => x !== null)
102}
103
104/** O cartão de fim de marco, acima do prompt: celebra e pergunta. */
105export const marcoCard = (c: Ctx, name: string, sub: string, list: readonly Inscription[], d: Dests, act: SealActions): RenderElement => {
106  const { Box, Text } = c.ui
107  const gild = toneOf(c.palette)
108  return (
109    <Box key="card-marco" flexDirection="column" rowGap={1} borderStyle="round" borderColor={TONE[c.palette].gildDim} paddingX={1}>
110      <Box flexDirection="row" columnGap={1} alignItems="center">
111        {svg(c, petArt('sabio', 'work', 34, c.t.className.sabio), 'marco-pet')}
112        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
113          <Text bold color={gild.gild} wrap="truncate-end">
114            {c.t.marcoTitle(name)}
115          </Text>
116          <Text dimColor wrap="truncate-end">
117            {sub}
118          </Text>
119        </Box>
120      </Box>
121      {sealBlock(c, list, d, act, c.t.notNow)}
122    </Box>
123  )
124}
125
126/** O bloco "Antes, salvar o progresso?" do cartão de compactar. */
127export const progressBlock = (c: Ctx, task: string, next: string, destLabel: string, onVerify: (value: string) => void) => {
128  const { Box, Text } = c.ui
129  const Input = inputOf(c.ui)
130  const sabio = classColor('sabio', c.palette)
131  return (
132    <Box key="save-block" flexDirection="column" borderStyle="round" borderColor={sabio} paddingX={1}>
133      <Box flexDirection="row" columnGap={1} alignItems="center">
134        {svg(c, petArt('sabio', 'work', 28, c.t.className.sabio), 'save-pet')}
135        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
136          <Text bold color={sabio} wrap="truncate-end">
137            {c.t.saveFirst}
138          </Text>
139          <Text dimColor wrap="truncate-end">
140            {next === '' ? task : `${task} · ${c.t.nextStep(next)}`}
141          </Text>
142        </Box>
143      </Box>
144      {Input !== undefined && (
145        <Box flexDirection="row" columnGap={1} alignItems="center">
146          <Text dimColor>{c.t.verify}</Text>
147          <Input key="save-verify" placeholder={c.t.verifyHint} onInput={v => onVerify(v)} onSubmit={v => onVerify(v)} />
148        </Box>
149      )}
150      <Text dimColor wrap="truncate-end">
151        → {destLabel}
152      </Text>
153    </Box>
154  )
155}
156
157/** O aviso suave do Sábio no palco: uma frase, um detalhe e as ações embaixo. */
158export const sageNudge = (c: Ctx, key: string, line: string, sub: string | undefined, action: { label: string; onPress: () => void }, secondary?: { label: string; onPress: () => void }) => {
159  const { Box, Button, Text } = c.ui
160  const k = toneOf(c.palette)
161  const sabio = classColor('sabio', c.palette)
162  return (
163    <Box key={key} flexDirection="column" marginTop={1} borderStyle={c.desktop ? 'round' : undefined} borderColor={TONE[c.palette].gildDim} paddingX={c.desktop ? 1 : 0}>
164      <Box flexDirection="row" columnGap={1} alignItems="center">
165        {svg(c, petArt('sabio', 'work', 30, c.t.className.sabio), `${key}-pet`)}
166        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
167          <Text bold color={sabio} wrap="truncate-end">
168            {line}
169          </Text>
170          {sub !== undefined && (
171            <Text dimColor wrap="truncate-end">
172              {sub}
173            </Text>
174          )}
175        </Box>
176      </Box>
177      <Box flexDirection="row" columnGap={2}>
178        <Box flexGrow={1} />
179        {secondary !== undefined && <Button key={`${key}-no`} plain dimColor label={secondary.label} onPress={secondary.onPress} />}
180        <Button key={`${key}-go`} plain label={action.label} onPress={action.onPress}>
181          <Text color={k.gild}>{action.label}</Text>
182        </Button>
183      </Box>
184    </Box>
185  )
186}
187
188/** O Continuar do acampamento: os jogos salvos, cada um com o seu botão. */
189export const continueSection = (c: Ctx, list: readonly Progress[], hint: boolean, act: { go: (p: Progress) => void; how: () => void }) => {
190  const { Box, Button, Text } = c.ui
191  return (
192    <Box key="continue" flexDirection="column" marginTop={1}>
193      {title(c, c.t.continueTitle, undefined, String(list.length))}
194      {list.slice(0, 4).map(p => (
195        <Box key={`cont-${p.id}`} flexDirection="row" columnGap={1} alignItems="center">
196          <Box flexDirection="column" flexGrow={1} flexShrink={1}>
197            <Text bold wrap="truncate-end">
198              {p.title}
199            </Text>
200            <Text dimColor wrap="truncate-end">
201              {[p.next === '' ? '' : c.t.nextStep(p.next), p.updated, p.by].filter(Boolean).join(' · ')}
202            </Text>
203          </Box>
204          <Button key={`cont-go-${p.id}`} label={c.t.continueBtn} onPress={() => act.go(p)} />
205        </Box>
206      ))}
207      {hint && (
208        <Box flexDirection="row" columnGap={1} marginTop={1}>
209          <Box flexGrow={1} flexShrink={1}>
210            <Text dimColor wrap="wrap">
211              {c.t.continueHint}
212            </Text>
213          </Box>
214          <Button key="cont-how" plain dimColor label={c.t.seeHow} onPress={act.how} />
215        </Box>
216      )}
217    </Box>
218  )
219}
220
221export type GrimData = {
222  pending: readonly Inscription[]
223  sealed: readonly Inscription[]
224  dests: Dests
225  memory: MemoryPrefs
226  progress: ProgressState
227  /** Para onde o progresso vai: "Tarefa + ai-memory", "Tarefa no projeto"... */
228  progressLabel: string
229  remembered: readonly { kind: string; text: string; path: string }[]
230  /** Sem ai-memory: quantas notas a memória automática do Claude tem neste projeto. */
231  autoNotes?: number
232}
233
234export type GrimActions = SealActions & {
235  back: () => void
236  config: () => void
237  undoSeal: (id: string) => void
238  undoProgress: () => void
239  forget: (path: string) => void
240  openNotes: () => void
241  /** Só existe com o botão do Haiku ligado no ⚙: gasta tokens, e só no clique. */
242  haiku?: () => void
243}
244
245/** A página 📖: o Sábio na torre, para guardar, guardado hoje, o que ele lembra e o estado dos destinos. */
246export const grimPage = (c: Ctx, d: GrimData, act: GrimActions): RenderElement => {
247  const { Box, Button, Text } = c.ui
248  const k = toneOf(c.palette)
249  const saved = d.progress.saved
250  const status = [
251    d.dests.vault !== '' ? 'vault ✓' : 'vault —',
252    'AGENTS.md ✓',
253    d.dests.memory !== undefined ? 'ai-memory ✓' : 'ai-memory —',
254  ].join(' · ')
255  return (
256    <Box flexDirection="column">
257      <Box key="grim-top" flexDirection="row">
258        <Button key="back" plain label={c.t.back} onPress={act.back} />
259        <Box flexGrow={1} />
260        {act.haiku !== undefined && d.pending.length > 0 && <Button key="grim-haiku" plain dimColor label={c.t.haikuButton} onPress={act.haiku} />}
261      </Box>
262      {svg(c, stageArt('sabio', 'work', 'torre', pxOf(c), 170, `${c.t.className.sabio} · ${c.t.grimTitle}`, c.t.placeName), 'grim-stage')}
263      {!c.desktop && (
264        // Terminal: o Sábio, guardião do grimório, com o pergaminho; o título ao lado.
265        <Box key="grim-sage" flexDirection="row" columnGap={1} alignItems="flex-end">
266          {clawdArt(c, 'sabio', 'work', 'grim-sabio')}
267          <Box flexDirection="column">
268            <Text bold color={TONE[c.palette].gild}>
269              📖 {c.t.grimTitle}
270            </Text>
271            <Text dimColor>{c.t.className.sabio}</Text>
272          </Box>
273        </Box>
274      )}
275      {d.pending.length > 0 ? (
276        <Box key="grim-pending" flexDirection="column" rowGap={1} marginTop={1}>
277          {title(c, c.t.toKeep, undefined, String(d.pending.length))}
278          {sealBlock(c, d.pending, d.dests, act, c.t.discard)}
279        </Box>
280      ) : (
281        <Box key="grim-empty" marginTop={1}>
282          <Text dimColor>{c.t.grimEmpty}</Text>
283        </Box>
284      )}
285      {(saved !== undefined || d.sealed.length > 0) && (
286        <Box key="grim-kept" flexDirection="column" marginTop={1}>
287          {title(c, c.t.keptToday, undefined, String(d.sealed.length + (saved === undefined ? 0 : 1)))}
288          {saved !== undefined && (
289            <Box key="kept-progress" flexDirection="column">
290              <Box flexDirection="row" columnGap={1}>
291                <Text color="success">✓</Text>
292                <Text wrap="truncate-end">
293                  {c.t.progressSaved} · {saved.id}
294                </Text>
295                <Box flexGrow={1} />
296                <Button key="undo-progress" plain dimColor label={c.t.undo} onPress={act.undoProgress} />
297              </Box>
298              <Text dimColor wrap="truncate-start">
299                {saved.path}
300              </Text>
301            </Box>
302          )}
303          {d.sealed.map(i => (
304            <Box key={`kept-${i.id}`} flexDirection="row" columnGap={1}>
305              <Text color="success">✓</Text>
306              <Text color={kindColor(c, i.kind)}>{c.t.grimKind[i.kind]}</Text>
307              <Text dimColor wrap="truncate-end">
308                {i.text}
309              </Text>
310              <Box flexGrow={1} />
311              {i.written !== undefined && i.written.length > 0 && <Button key={`undo-${i.id}`} plain dimColor label={c.t.undo} onPress={() => act.undoSeal(i.id)} />}
312            </Box>
313          ))}
314        </Box>
315      )}
316      {d.memory.lembra && (d.remembered.length > 0 || d.autoNotes !== undefined) && (
317        <Box key="grim-remembers" flexDirection="column" marginTop={1}>
318          {title(c, c.t.remembers)}
319          {d.remembered.slice(0, 4).map(r => (
320            <Box key={`mem-${r.path}`} flexDirection="row" columnGap={1}>
321              <Text color={classColor('sabio', c.palette)}>{r.kind}</Text>
322              <Text dimColor wrap="truncate-end">
323                {r.text}
324              </Text>
325              <Box flexGrow={1} />
326              <Button key={`forget-${r.path}`} plain dimColor label={c.t.forget} onPress={() => act.forget(r.path)} />
327            </Box>
328          ))}
329          {d.remembered.length === 0 && d.autoNotes !== undefined && (
330            <Box flexDirection="row" columnGap={1}>
331              <Text dimColor wrap="truncate-end">
332                {c.t.autoMemoryNotes(d.autoNotes)}
333              </Text>
334              <Box flexGrow={1} />
335              <Button key="open-notes" plain dimColor label={c.t.openIt} onPress={act.openNotes} />
336            </Box>
337          )}
338        </Box>
339      )}
340      <Box key="grim-status" flexDirection="row" columnGap={2} marginTop={1}>
341        <Text dimColor wrap="truncate-end">
342          {status}
343        </Text>
344        <Box flexGrow={1} />
345        <Button key="grim-config" plain dimColor label={c.t.memoryCfg} onPress={act.config}>
346          <Text color={k.muted}>{c.t.memoryCfg}</Text>
347        </Button>
348      </Box>
349    </Box>
350  )
351}
352
353export type MemoryConfigActions = {
354  toggle: (k: MemoryToggle) => void
355  home: (h: MemoryPrefs['decisoesEm']) => void
356  pickVault: () => void
357  testMemory: () => void
358  whatIs: () => void
359  restore: () => void
360}
361
362/** As linhas do ⚙ Memória: o que foi detectado, os recursos e avisos, os destinos e as integrações. */
363export const memoryConfig = (c: Ctx, m: MemoryPrefs, d: Dests, progressLabel: string, act: MemoryConfigActions): RenderElement[] => {
364  const { Box, Button, Text } = c.ui
365  const k = toneOf(c.palette)
366  const full = d.vault !== '' && d.memory !== undefined
367  const partial = d.vault !== '' || d.memory !== undefined
368  const check = (key: MemoryToggle) => <Button key={`mem-${key}`} plain dimColor={!m[key]} label={`${m[key] ? '☑' : '☐'} ${c.t.memFeature[key]}`} onPress={() => act.toggle(key)} />
369  const radio = (home: MemoryPrefs['decisoesEm'], label: string) => (
370    <Button key={`home-${home}`} plain dimColor={m.decisoesEm !== home} label={`${m.decisoesEm === home ? '◉' : '○'} ${label}`} onPress={() => act.home(home)} />
371  )
372  const line = (label: string, kids: (RenderElement | null)[]) => (
373    <Box key={`mline-${label}`} flexDirection="row" gap={1}>
374      <Box width={12} flexShrink={0}>
375        <Text dimColor wrap="truncate-end">
376          {label}
377        </Text>
378      </Box>
379      <Box flexDirection="column" flexGrow={1} flexShrink={1}>
380        {kids.filter((x): x is RenderElement => x !== null)}
381      </Box>
382    </Box>
383  )
384  const decisionsLabel = m.decisoesEm === 'projeto' || d.vault === '' ? c.t.dest.projeto : c.t.dest.vaultDecisao
385  return [
386    <Box key="mem-detect" flexDirection="column" borderStyle={c.desktop ? 'round' : undefined} borderColor={full ? TONE[c.palette].gildDim : undefined} paddingX={c.desktop ? 1 : 0}>
387      <Text bold color={full ? 'success' : undefined}>
388        {full ? c.t.memDetected : c.t.memProject}
389      </Text>
390      <Text dimColor wrap="wrap">
391        {full ? c.t.memDetectedText(d.vault) : partial ? c.t.memPartial(d.vault !== '' ? 'vault' : 'ai-memory') : c.t.memProjectText}
392      </Text>
393    </Box>,
394    line(c.t.rowFeatures, [check('progresso'), check('cronica'), check('regras'), check('lembra')]),
395    line(c.t.rowWarnings, [check('avisoPalco'), check('avisoMarco'), check('avisoCompactar')]),
396    line(c.t.rowDests, [
397      <Text key="d-prog" wrap="truncate-end">
398        {c.t.destProgress} <Text color={k.gild}>{progressLabel}</Text>
399      </Text>,
400      <Text key="d-dec" wrap="truncate-end">
401        {c.t.destDecisions} <Text color={k.gild}>{decisionsLabel}</Text>
402      </Text>,
403      <Box key="d-home" flexDirection="row" columnGap={1} flexWrap="wrap">
404        <Text dimColor>{c.t.decisionsIn}</Text>
405        {radio('auto', c.t.homeAuto)}
406        {radio('vault', c.t.homeVault)}
407        {radio('projeto', c.t.homeProject)}
408      </Box>,
409      <Text key="d-rule" wrap="truncate-end">
410        {c.t.destRules} <Text color={k.gild}>AGENTS.md</Text>
411      </Text>,
412    ]),
413    line(c.t.rowIntegrations, [
414      <Box key="i-vault" flexDirection="row" columnGap={1}>
415        <Text>Vault</Text>
416        <Text dimColor wrap="truncate-start">
417          {d.vault !== '' ? `${d.vault} ✓` : c.t.notConfigured}
418        </Text>
419        <Box flexGrow={1} />
420        <Button key="mem-pick" plain dimColor label={d.vault !== '' ? c.t.change : c.t.setupPick} onPress={act.pickVault} />
421      </Box>,
422      <Box key="i-mem" flexDirection="row" columnGap={1}>
423        <Text>ai-memory</Text>
424        <Text dimColor>{d.memory !== undefined ? `${c.t.memConnected} ✓` : c.t.memMissing}</Text>
425        <Box flexGrow={1} />
426        {d.memory !== undefined ? (
427          <Button key="mem-test" plain dimColor label={c.t.testIt} onPress={act.testMemory} />
428        ) : (
429          <Button key="mem-what" plain dimColor label={c.t.whatIs} onPress={act.whatIs} />
430        )}
431      </Box>,
432    ]),
433    <Box key="mem-restore" flexDirection="row">
434      <Box flexGrow={1} />
435      <Button key="mem-reset" plain dimColor label={c.t.restoreRecommended} onPress={act.restore} />
436    </Box>,
437  ]
438}
439