diff --git a/.gitconfig-aliases b/.gitconfig-aliases new file mode 100644 index 0000000..3154971 --- /dev/null +++ b/.gitconfig-aliases @@ -0,0 +1,32 @@ +[alias] + push-all = "!f() { \ + branch=${1:-$(git branch --show-current)}; \ + echo '🔄 Git RAID Push - Sincronizando origin + backup'; \ + echo '📍 Branch: '$branch; \ + echo ''; \ + echo '1️⃣ Pushing to origin...'; \ + git push origin \"$branch\" && echo '✅ origin: Push successful' || { echo '❌ origin: Push failed'; exit 1; }; \ + echo ''; \ + echo '2️⃣ Pushing to backup...'; \ + git push backup \"$branch\" && echo '✅ backup: Push successful' || { echo '⚠️ backup: Push failed (origin já foi atualizado)'; exit 1; }; \ + echo ''; \ + echo '🎉 Sincronização completa!'; \ + echo ' origin: OnoSendae/vibes-ecosystem'; \ + echo ' backup: OnoSendae/vibe-devtools-bkp'; \ + }; f" + + sync-backup = "!f() { \ + branch=${1:-$(git branch --show-current)}; \ + echo '🔄 Sincronizando backup com PRs/merges remotos'; \ + echo '📍 Branch: '$branch; \ + echo ''; \ + echo '1️⃣ Pulling from origin...'; \ + git pull origin \"$branch\" && echo '✅ Pull from origin successful' || { echo '❌ Pull from origin failed'; exit 1; }; \ + echo ''; \ + echo '2️⃣ Pushing to backup...'; \ + git push backup \"$branch\" && echo '✅ backup atualizado com mudanças de origin' || { echo '❌ backup: Push failed'; exit 1; }; \ + echo ''; \ + echo '🎉 Backup sincronizado com origin!'; \ + echo ' Mudanças remotas (PRs) agora estão no backup'; \ + }; f" + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f97d9e4..a27d95c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,6 +8,7 @@ on: jobs: build: + if: github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest steps: diff --git a/.github/workflows/publish-cli.yml b/.github/workflows/publish-cli.yml index 05fa978..25ab068 100644 --- a/.github/workflows/publish-cli.yml +++ b/.github/workflows/publish-cli.yml @@ -8,6 +8,7 @@ on: jobs: publish-cli: + if: github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml index 58c6089..1c730e9 100644 --- a/.github/workflows/publish-packages.yml +++ b/.github/workflows/publish-packages.yml @@ -20,7 +20,7 @@ on: jobs: publish-basic: - if: github.event.inputs.package == 'basic' || github.event.inputs.package == 'all' || startsWith(github.ref, 'refs/tags/packages/basic/') + if: (github.event.inputs.package == 'basic' || github.event.inputs.package == 'all' || startsWith(github.ref, 'refs/tags/packages/basic/')) && github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest permissions: contents: read @@ -44,7 +44,7 @@ jobs: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} publish-research: - if: github.event.inputs.package == 'research' || github.event.inputs.package == 'all' || startsWith(github.ref, 'refs/tags/packages/research/') + if: (github.event.inputs.package == 'research' || github.event.inputs.package == 'all' || startsWith(github.ref, 'refs/tags/packages/research/')) && github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8dabc93..af1e5b4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,6 +20,7 @@ on: jobs: publish: + if: github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ee09166..6d68b21 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,6 +14,7 @@ permissions: jobs: release: + if: github.repository == 'OnoSendae/vibe-devtools' name: Release runs-on: ubuntu-latest steps: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a9e891d..8a80923 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,7 @@ on: jobs: test-cli: + if: github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest steps: @@ -38,6 +39,7 @@ jobs: node dist/index.js --help test-packages: + if: github.repository == 'OnoSendae/vibe-devtools' runs-on: ubuntu-latest strategy: matrix: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6e8ab4f..502de86 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,11 +36,11 @@ Existem várias formas de contribuir: ### 1. Reportar Bugs 🐛 -Encontrou um bug? [Abra um issue](https://github.com/onosendae/vibe-devtools/issues/new?template=bug_report.md). +Encontrou um bug? [Abra um issue](https://github.com/OnoSendae/vibe-devtools/issues/new?template=bug_report.md). ### 2. Sugerir Features ✨ -Tem uma ideia? [Abra uma discussion](https://github.com/onosendae/vibe-devtools/discussions) ou [crie um feature request](https://github.com/onosendae/vibe-devtools/issues/new?template=feature_request.md). +Tem uma ideia? [Abra uma discussion](https://github.com/OnoSendae/vibe-devtools/discussions) ou [crie um feature request](https://github.com/OnoSendae/vibe-devtools/issues/new?template=feature_request.md). ### 3. Melhorar Documentação 📚 @@ -60,13 +60,13 @@ A maior contribuição: **crie e compartilhe vibes customizados**! ### Antes de Reportar -- Verifique a [lista de issues](https://github.com/onosendae/vibe-devtools/issues) para ver se já foi reportado +- Verifique a [lista de issues](https://github.com/OnoSendae/vibe-devtools/issues) para ver se já foi reportado - Tente reproduzir com a versão mais recente - Colete informações de debug (versões, logs, screenshots) ### Como Reportar -Use o [template de bug report](https://github.com/onosendae/vibe-devtools/issues/new?template=bug_report.md). +Use o [template de bug report](https://github.com/OnoSendae/vibe-devtools/issues/new?template=bug_report.md). **Informações essenciais**: - Versão da CLI (`vdt --version`) @@ -112,7 +112,7 @@ Error: EACCES: permission denied, mkdir '~/.vibes' ### Como Sugerir -Use o [template de feature request](https://github.com/onosendae/vibe-devtools/issues/new?template=feature_request.md). +Use o [template de feature request](https://github.com/OnoSendae/vibe-devtools/issues/new?template=feature_request.md). **Estrutura boa**: ```markdown diff --git a/OPENSOURCE-CHECKLIST.md b/OPENSOURCE-CHECKLIST.md deleted file mode 100644 index d65c042..0000000 --- a/OPENSOURCE-CHECKLIST.md +++ /dev/null @@ -1,509 +0,0 @@ -# Checklist: Tornar Vibe DevTools Opensource - -Checklist completo para disponibilizar o vibe-devtools no GitHub como projeto open source. - ---- - -## ✅ Arquivos Criados - -### Governança Essencial - -- ✅ `CONTRIBUTING.md` - Guia completo de contribuição -- ✅ `CODE_OF_CONDUCT.md` - Código de conduta (Contributor Covenant) -- ✅ `SECURITY.md` - Política de segurança -- ✅ `LICENSE` - MIT License - -### Templates GitHub - -- ✅ `.github/ISSUE_TEMPLATE/bug_report.md` - Template de bug report -- ✅ `.github/ISSUE_TEMPLATE/feature_request.md` - Template de feature request -- ✅ `.github/ISSUE_TEMPLATE/custom_vibe.md` - Template para showcase de vibes -- ✅ `.github/ISSUE_TEMPLATE/config.yml` - Configuração de issue templates -- ✅ `.github/PULL_REQUEST_TEMPLATE.md` - Template de Pull Request - -### Documentação Completa - -- ✅ `docs/getting-started/installation.md` - Guia de instalação detalhado -- ✅ `docs/getting-started/quick-start.md` - Quick start guide -- ✅ `docs/guides/creating-vibes.md` - Guia completo de criação de vibes -- ✅ `docs/github-setup.md` - Guia de configuração do GitHub - ---- - -## 🔧 Configurações do GitHub (Manuais) - -### 1. Branch Protection (`main`) - -**Settings → Branches → Add Rule** - -``` -Branch name pattern: main - -Configurações: -✅ Require a pull request before merging - ├── Require approvals: 1 - ├── Dismiss stale PR approvals - └── Require review from Code Owners - -✅ Require status checks to pass - ├── build - ├── test-cli - └── test-packages - -✅ Require conversation resolution -✅ Require linear history -✅ Include administrators -❌ Allow force pushes (disabled) -❌ Allow deletions (disabled) -``` - -### 2. CODEOWNERS - -**Criar** `.github/CODEOWNERS`: - -``` -* @cleberhensel -/apps/cli/ @cleberhensel -/packages/ @cleberhensel -/docs/ @cleberhensel -*.md @cleberhensel -/.github/workflows/ @cleberhensel -``` - -### 3. GitHub Discussions - -**Settings → General → Features** - -- ✅ Habilitar Discussions - -**Criar Categorias**: -- 💬 General (Open-ended) -- 💡 Ideas (Open-ended) -- 🙏 Q&A (Question/Answer) -- 📣 Announcements (Announcement) -- 🎨 Show and Tell (Open-ended) - -### 4. GitHub Projects - -**Projects → New Project → Board** - -**Nome**: Vibe DevTools Roadmap - -**Colunas**: -- 📋 Backlog -- 📝 Planned -- 🏗️ In Progress -- 👀 In Review -- ✅ Done - -### 5. Labels - -**Issues → Labels** - -Criar labels: - -**Priority**: -- `P0` - Crítico (#d73a4a) -- `P1` - Alto (#ff9800) -- `P2` - Médio (#ffd700) -- `P3` - Baixo (#0e8a16) - -**Type**: -- `bug` (#d73a4a) -- `enhancement` (#a2eeef) -- `documentation` (#0075ca) -- `good first issue` (#7057ff) - -**Area**: -- `cli` (#00ffff) -- `basic` (#ffff00) -- `research` (#ff00ff) - -### 6. Secrets (Actions) - -**Settings → Secrets → Actions** - -Adicionar: -- `NPM_TOKEN` - Token do npm para publicação automática - -**Como obter NPM_TOKEN**: -1. Login em npmjs.com -2. Settings → Access Tokens -3. Generate New Token → Automation -4. Copiar e adicionar ao GitHub - -### 7. Repository Settings - -**Settings → General** - -**About**: -- Description: "Ecosystem of AI-powered development tools for Cursor, Copilot & Gemini" -- Topics: `ai`, `cursor`, `github-copilot`, `automation`, `cli`, `vibe-devtools` - -**Features**: -- ❌ Wikis -- ✅ Discussions -- ✅ Projects - -**Pull Requests**: -- ✅ Allow squash merging (preferido) -- ❌ Allow merge commits -- ✅ Allow rebase merging -- ✅ Automatically delete head branches - ---- - -## 📝 Próximos Passos - -### Antes de Tornar Público - -#### 1. Revisar Arquivos Criados - -```bash -cd vibes-ecosystem - -# Revisar governança -cat CONTRIBUTING.md -cat CODE_OF_CONDUCT.md -cat SECURITY.md -cat LICENSE - -# Revisar templates -ls -la .github/ISSUE_TEMPLATE/ -cat .github/PULL_REQUEST_TEMPLATE.md - -# Revisar docs -ls -la docs/ -``` - -#### 2. Configurar GitHub (lista acima) - -- [ ] Branch protection -- [ ] CODEOWNERS -- [ ] Discussions + categorias -- [ ] Projects + roadmap -- [ ] Labels -- [ ] NPM_TOKEN secret -- [ ] Repository settings - -#### 3. Validar CI/CD - -```bash -# Verificar workflows existem -ls -la .github/workflows/ - -# Workflows esperados: -# - release.yml (changesets) ✅ já existe -# - build.yml (CI) -# - lint.yml (linting) -``` - -Se workflows estiverem faltando, criar conforme `docs/github-setup.md`. - -#### 4. Atualizar README Principal - -Adicionar badges: - -```markdown -[![npm version](https://badge.fury.io/js/vibe-devtools.svg)](https://www.npmjs.com/package/vibe-devtools) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Build](https://github.com/onosendae/vibe-devtools/actions/workflows/build.yml/badge.svg)](https://github.com/onosendae/vibe-devtools/actions) -[![Discussions](https://img.shields.io/github/discussions/onosendae/vibe-devtools)](https://github.com/onosendae/vibe-devtools/discussions) -``` - -Adicionar seção "Contributing": - -```markdown -## 🤝 Contribuindo - -Adoramos contribuições! Veja nosso [Guia de Contribuição](./CONTRIBUTING.md). - -### Como Contribuir - -1. 🐛 [Reportar bugs](./CONTRIBUTING.md#reportando-bugs) -2. ✨ [Sugerir features](./CONTRIBUTING.md#sugerindo-features) -3. 💻 [Contribuir código](./CONTRIBUTING.md#contribuindo-com-código) -4. 🎨 [Criar vibes](./CONTRIBUTING.md#criando-vibes) -5. 📚 [Melhorar docs](./CONTRIBUTING.md#melhorar-documentação) - -### Código de Conduta - -Este projeto adota o [Contributor Covenant](./CODE_OF_CONDUCT.md). -``` - -#### 5. Testar Instalação End-to-End - -```bash -# Em diretório temporário de teste -cd /tmp -mkdir test-vibe-install -cd test-vibe-install - -# Testar instalação -npx vibe-devtools install @vibe-devtools/basic -npx vibe-devtools list - -# Verificar -ls -la .cursor/commands/ - -# Limpar -cd .. -rm -rf test-vibe-install -``` - -### Ao Tornar Público - -#### 1. Mudar Visibilidade - -**Settings → General → Danger Zone → Change repository visibility** - -``` -Private → Public -``` - -⚠️ **Atenção**: Esta ação é **irreversível** se houver commits públicos depois! - -#### 2. Criar Anúncio - -**Discussions → Announcements → New** - -```markdown -# 🎉 Vibe DevTools é agora Open Source! - -Estamos muito felizes em anunciar que o **Vibe DevTools** é agora totalmente open source! - -## 🚀 O Que é Vibe DevTools? - -Vibe DevTools é um ecosystem completo de ferramentas para IA agêntica que transforma desenvolvimento com Cursor, Copilot e Gemini em uma experiência 10x mais produtiva. - -## 📦 Packages Disponíveis - -- **vibe-devtools** - CLI para gerenciar vibes -- **@vibe-devtools/basic** - Foundation kit com makers e planners -- **@vibe-devtools/research** - Pipelines de pesquisa acadêmica - -## 🤝 Como Contribuir - -Veja nosso [Guia de Contribuição](../CONTRIBUTING.md)! - -## 🎨 Crie Seus Vibes - -A maior contribuição: **criar e compartilhar vibes customizados**! - -Veja [Guia de Criação de Vibes](../docs/guides/creating-vibes.md). - -## 📢 Próximos Passos - -- ⭐ Star o repositório -- 👀 Watch para updates -- 💬 Participe das Discussions -- 🚀 Compartilhe com a comunidade - -Vamos construir juntos! 🚀✨ - ---- - -**Links**: -- npm: https://www.npmjs.com/org/vibe-devtools -- Docs: https://github.com/onosendae/vibe-devtools#readme -- Contributing: https://github.com/onosendae/vibe-devtools/blob/main/CONTRIBUTING.md -``` - -#### 3. Compartilhar - -**Twitter/X**: -``` -🎉 Vibe DevTools is now open source! - -Transform your AI-powered development with Cursor, Copilot & Gemini 🚀 - -✨ CLI tool -🏗️ Foundation kit -🔬 Research pipelines -🎨 Create custom vibes - -Star ⭐ https://github.com/onosendae/vibe-devtools - -#AI #OpenSource #DevTools #Cursor -``` - -**LinkedIn**: -``` -Estou feliz em anunciar que o Vibe DevTools é agora open source! 🎉 - -Após meses de desenvolvimento, estamos compartilhando com a comunidade um ecosystem completo de ferramentas para IA agêntica. - -O que é? -- CLI para gerenciar "vibes" (skill packs para IA) -- Foundation kit com makers e planners -- Research pipelines acadêmicas -- Framework para criar vibes customizados - -Por que open source? -- Acreditamos em desenvolvimento colaborativo -- Queremos ver a comunidade criando vibes incríveis -- Aprender com contribuições de todos - -Confira: https://github.com/onosendae/vibe-devtools - -#OpenSource #AI #DevTools #Innovation -``` - -**Dev.to**: -Criar artigo detalhado sobre: -- Motivação para criar Vibe DevTools -- Como funciona -- Exemplos de uso -- Como contribuir - -**Reddit**: -- r/javascript -- r/typescript -- r/opensource -- r/programming - -#### 4. Adicionar a Listas - -**Awesome Lists**: -- awesome-cursor -- awesome-ai-tools -- awesome-developer-tools - -**Product Hunt** (opcional): -Lançar produto quando estiver mais maduro. - ---- - -## 📊 Métricas de Sucesso - -Após lançamento, monitorar: - -- ⭐ GitHub Stars -- 🍴 Forks -- 👁️ Watchers -- 📥 Issues/PRs abertos -- 💬 Discussions ativas -- 📦 Downloads npm -- 🎨 Vibes da comunidade criados - ---- - -## 🎯 Roadmap Pós-Lançamento - -### Curto Prazo (1-2 semanas) - -- [ ] Responder a todas issues/PRs -- [ ] Engajar em Discussions -- [ ] Corrigir bugs reportados -- [ ] Melhorar docs baseado em feedback - -### Médio Prazo (1-3 meses) - -- [ ] Implementar features mais votadas -- [ ] Criar vibes adicionais (podcast, content) -- [ ] Melhorar CI/CD -- [ ] Adicionar testes automatizados - -### Longo Prazo (3-6 meses) - -- [ ] Marketplace de vibes -- [ ] GUI dashboard -- [ ] VSCode extension -- [ ] Programa de embaixadores - ---- - -## 📚 Recursos Criados - -### Documentação - -1. **Getting Started** - - Installation guide - - Quick start guide - -2. **Guides** - - Creating vibes - - Using packages (aproveitar README existente) - - Adapters (já existe: CREATING-ADAPTERS.md) - -3. **Reference** - - CLI API (aproveitar README da CLI) - - Package APIs (READMEs dos packages) - -4. **Governance** - - Contributing guide ✅ - - Code of Conduct ✅ - - Security policy ✅ - - GitHub setup guide ✅ - -### Templates - -- Bug report ✅ -- Feature request ✅ -- Custom vibe showcase ✅ -- Pull request ✅ - ---- - -## ✅ Checklist Final - -Antes de tornar público: - -### Arquivos - -- [x] CONTRIBUTING.md -- [x] CODE_OF_CONDUCT.md -- [x] SECURITY.md -- [x] LICENSE -- [x] Issue templates -- [x] PR template -- [x] Documentação completa - -### GitHub Settings - -- [ ] Branch protection configurada -- [ ] CODEOWNERS criado -- [ ] Discussions habilitado -- [ ] Projects criado -- [ ] Labels organizadas -- [ ] NPM_TOKEN configurado -- [ ] Repository settings ajustados - -### Validação - -- [ ] CI/CD funcionando -- [ ] Instalação testada end-to-end -- [ ] README atualizado com badges -- [ ] Docs acessíveis e completas - -### Lançamento - -- [ ] Repository → Public -- [ ] Anúncio em Discussions -- [ ] Posts em social media -- [ ] Artigo em dev.to -- [ ] Compartilhar em Reddit -- [ ] Adicionar em awesome lists - ---- - -## 🎉 Conclusão - -Tudo está preparado para tornar o Vibe DevTools um projeto open source de sucesso! - -**Próximo comando**: -```bash -# Revisar tudo -git status -git add . -git commit -m "docs: add opensource governance and docs" -git push - -# Configurar GitHub (manual) -# ... seguir checklist acima - -# Tornar público! 🚀 -``` - -**Boa sorte com o lançamento! 🚀✨** - diff --git a/README.md b/README.md index 2768357..2447cdd 100644 --- a/README.md +++ b/README.md @@ -1009,7 +1009,7 @@ MIT © 2025 [Ono Sendae](https://github.com/onosendae) ### GitHub - **Monorepo**: https://github.com/onosendae/vibe-devtools -- **Issues**: https://github.com/onosendae/vibe-devtools/issues +- **Issues**: https://github.com/OnoSendae/vibe-devtools/issues - **Discussions**: https://github.com/onosendae/vibe-devtools/discussions ### Docs diff --git a/RELEASE-AUTOMATION-SUMMARY.md b/RELEASE-AUTOMATION-SUMMARY.md deleted file mode 100644 index 06af1ae..0000000 --- a/RELEASE-AUTOMATION-SUMMARY.md +++ /dev/null @@ -1,399 +0,0 @@ -# Release Automation - Sumário Executivo - -**Data**: 2025-10-22 -**Sistema**: Changesets Workflow Completo -**Status**: ✅ Pronto para uso - ---- - -## 🎯 Objetivo Alcançado - -Implementar sistema de publicação **completamente automático** que: - -1. ✅ **Atualiza versão** automaticamente -2. ✅ **Cria releases** no GitHub automaticamente -3. ✅ **Publica no npm** automaticamente - -Para **CLI** e **todos os packages** de vibes. - ---- - -## 📊 Comparação: Antes vs Depois - -| Aspecto | ❌ Antes | ✅ Depois (Changesets) | -|---------|---------|----------------------| -| **Bump de versão** | Manual (`npm version`) | Automático via PR | -| **CHANGELOG** | Não existia | Gerado automaticamente | -| **GitHub Releases** | Não criava | Criadas automaticamente | -| **Publicação** | Manual ou semi-automática | Totalmente automática | -| **Coordenação** | Cada package separado | Monorepo-aware | -| **Documentação** | Nenhuma | Guia completo | - ---- - -## 🚀 Como Funciona Agora - -### Fluxo Completo - -``` -Developer GitHub Actions npm/GitHub -─────────── ────────────── ────────── - -1. Fazer mudanças - vi packages/basic/README.md - -2. Criar changeset - pnpm changeset - (descreve mudança) - -3. Commit + Push ──────→ 4. CI valida - git push (build + test) - ↓ - 5. Bot cria PR - "Version Packages" - (mostra preview) - ↓ - 6. Aguarda aprovação - ↓ -7. Mergear PR ──────→ 8. Workflow Release - • Bump versions - • Update CHANGELOGs - • npm publish ──────→ 9. Package no npm - • Create releases ────→ 10. GitHub Release - • Git tags - -11. ✅ DONE! - - Package publicado - - Release documentada - - Changelog atualizado -``` - -**Tempo total**: ~5-10 minutos do changeset ao npm - ---- - -## 📦 O Que Foi Implementado - -### 1. Changesets Setup - -**Arquivos criados:** -- `.changeset/config.json` - Configuração -- `.changeset/README.md` - Guia rápido - -**Dependências adicionadas:** -```json -{ - "@changesets/cli": "^2.27.0", - "@changesets/changelog-github": "^0.5.0" -} -``` - -**Scripts adicionados:** -```json -{ - "changeset": "changeset", - "version-packages": "changeset version", - "release": "changeset publish" -} -``` - -### 2. Workflow Principal (`release.yml`) - -**Trigger**: Push em `main` - -**Comportamento inteligente:** - -A) **Se há changesets pendentes:** - - Cria/atualiza PR "Version Packages" - - Mostra preview de bumps - - Acumula múltiplos changesets - -B) **Se PR "Version Packages" foi merged:** - - Aplica version bumps - - Atualiza CHANGELOGs - - Publica packages alterados no npm - - Cria GitHub Releases - - Cria tags git - -**Features:** -- ✅ Provenance habilitado (npm) -- ✅ GitHub Releases com notas de release -- ✅ Tags automáticas por package -- ✅ Summary no workflow run - -### 3. Documentação Completa - -**Guia CI/CD** (`docs/CI-CD-GUIDE.md`): -- Fluxo passo-a-passo -- Tipos de bump (patch/minor/major) -- Cenários comuns -- Troubleshooting -- Checklist de release - -**README atualizado**: -- Seção Publishing reescrita -- Fluxo simplificado -- Links para docs - -**Changeset README**: -- Guia rápido inline -- Exemplos práticos - -### 4. Workflows Antigos Marcados - -**Deprecated mas mantidos:** -- `publish.yml` → emergências -- `publish-cli.yml` → emergências -- `publish-packages.yml` → emergências - -**Motivo**: Backup para casos excepcionais. - ---- - -## 🎓 Como Usar (TL;DR) - -### Publicar Mudança em Package - -```bash -# 1. Fazer mudanças -vi packages/basic/README.md - -# 2. Criar changeset -pnpm changeset -# → basic -# → patch -# → "Fix typos" - -# 3. Push -git add . -git commit -m "docs: fix typos" -git push - -# 4. Aguardar PR → Mergear -# 5. ✅ Publicado automaticamente! -``` - -### Ver Status - -```bash -# Changesets pendentes -pnpm changeset status - -# Workflow runs -# https://github.com/onosendae/vibe-devtools/actions -``` - ---- - -## 🔧 Configuração Necessária - -### GitHub Secrets (Obrigatório) - -**NPM_TOKEN**: -```bash -npm login -npm token create --type=automation -# → Adicionar em GitHub Repo → Settings → Secrets -``` - -**GITHUB_TOKEN**: Já disponível automaticamente - -### Dependências (Instalar) - -```bash -pnpm install -# Instala @changesets/cli automaticamente -``` - ---- - -## 📋 Próximos Passos - -### 1. Instalar Dependências - -```bash -cd /path/to/vibes-ecosystem -pnpm install -``` - -Isso instala o `@changesets/cli`. - -### 2. Commit as Mudanças - -```bash -git add . -git commit -m "feat: implement changesets workflow for automated releases - -- Add changesets configuration -- Add release.yml workflow for automatic publishing -- Add comprehensive CI/CD documentation -- Deprecate old manual workflows -- Update README with new publishing flow - -This enables: -- Automatic version bumps -- Automatic CHANGELOG generation -- Automatic npm publishing -- Automatic GitHub Releases -- Coordinated monorepo versioning" - -git push origin main -``` - -### 3. Testar o Sistema - -**Opção A: Teste Real (Recomendado)** - -```bash -# Criar changeset de exemplo -pnpm changeset -# → Selecionar basic -# → patch -# → "Test changesets workflow" - -# Commit e push -git add . -git commit -m "test: verify changesets workflow" -git push - -# Aguardar PR "Version Packages" -# Ver em: https://github.com/onosendae/vibe-devtools/pulls - -# Verificar PR, então mergear -# → Workflow publica automaticamente! -``` - -**Opção B: Dry Run Local** - -```bash -# Ver o que aconteceria -pnpm changeset status - -# Simular version bump (NÃO commit) -pnpm changeset version -# → Ver package.json e CHANGELOG.md mudarem - -# Reverter -git reset --hard HEAD -``` - -### 4. Configurar NPM_TOKEN - -Se ainda não configurado: - -```bash -npm login -npm token create --type=automation -``` - -Então adicionar em: -- GitHub → Repo Settings → Secrets → Actions → New secret -- Name: `NPM_TOKEN` -- Value: [token] - -### 5. Validar Primeira Publicação - -Após primeiro merge de PR "Version Packages": - -1. Ver workflow run: https://github.com/onosendae/vibe-devtools/actions -2. Verificar packages no npm: - - https://www.npmjs.com/package/@vibe-devtools/basic - - https://www.npmjs.com/package/@vibe-devtools/research - - https://www.npmjs.com/package/vibe-devtools -3. Verificar GitHub Releases criadas -4. Verificar CHANGELOG.md atualizado - ---- - -## 🎉 Benefícios Conquistados - -### Para Desenvolvedores - -✅ **Sem bump manual** - changesets gerencia tudo -✅ **Sem changelog manual** - gerado automaticamente -✅ **Sem comandos de publicação** - workflow faz tudo -✅ **Coordenação de packages** - bumps coordenados -✅ **Preview antes de publicar** - PR mostra exatamente o que vai acontecer - -### Para Usuários - -✅ **Releases documentadas** - GitHub Releases com notas -✅ **Changelogs claros** - histórico completo de mudanças -✅ **Versionamento semântico** - patch/minor/major claro -✅ **Rastreabilidade** - cada mudança linkada a commit - -### Para o Projeto - -✅ **Processo padronizado** - sem ad-hoc publishing -✅ **Qualidade garantida** - CI valida antes de publicar -✅ **Histórico completo** - todas mudanças documentadas -✅ **Monorepo-aware** - gerencia múltiplos packages corretamente -✅ **Compliance** - provenance e security features habilitados - ---- - -## 🔍 Verificação de Qualidade - -### Workflows - -- [x] `release.yml` criado e configurado -- [x] Changesets integration habilitada -- [x] npm publish com provenance -- [x] GitHub Releases automation -- [x] Workflows antigos deprecated - -### Configuração - -- [x] `.changeset/config.json` configurado -- [x] Scripts npm adicionados -- [x] Dependências instaladas -- [x] README atualizado - -### Documentação - -- [x] CI/CD Guide completo -- [x] Changeset README -- [x] README principal atualizado -- [x] Exemplos práticos incluídos - -### Testing - -- [ ] Instalar dependências (`pnpm install`) -- [ ] Criar changeset de teste -- [ ] Verificar PR criado -- [ ] Verificar publicação funciona - ---- - -## 📞 Suporte - -**Documentação:** -- [CI/CD Guide](./docs/CI-CD-GUIDE.md) - Guia completo -- [Changeset README](./.changeset/README.md) - Guia rápido -- [Changesets Docs](https://github.com/changesets/changesets) - Oficial - -**Troubleshooting:** -- Ver seção troubleshooting no CI/CD Guide -- Verificar workflow runs no GitHub Actions -- Checar logs de erro nos jobs - -**Issues conhecidos:** Nenhum (sistema novo) - ---- - -## 🎯 Status Final - -✅ **Sistema implementado e pronto para uso** -✅ **Documentação completa criada** -✅ **Workflows configurados corretamente** -✅ **Compatibilidade mantida (workflows antigos)** -✅ **Testável imediatamente** - -**Próxima ação**: Instalar dependências e testar! - ---- - -**Implementado por**: Cursor AI Assistant -**Data**: 2025-10-22 -**Revisão**: Pendente (primeiro teste) - diff --git a/apps/cli/STASH-SYSTEM.md b/apps/cli/STASH-SYSTEM.md deleted file mode 100644 index 52698b6..0000000 --- a/apps/cli/STASH-SYSTEM.md +++ /dev/null @@ -1,232 +0,0 @@ -# Stash System - -Sistema de gestão de conflitos e backups para vibe-devtools, inspirado no `git stash`. - -## Overview - -O Stash System permite que você gerencie arquivos durante instalação/atualização de packages com controle total sobre o que sobrescrever, manter ou arquivar. - -### Features - -- ✅ Detecção automática de conflitos via SHA-256 hash -- ✅ Backup seguro com full copy (não patch) -- ✅ Comandos CLI familiares (inspirados no git stash) -- ✅ FILO ordering com renumeração automática -- ✅ Logging completo em JSONL -- ✅ Dry-run support -- ✅ Integration com install e update commands - -## Quick Start - -### Install com Detecção de Conflitos - -```bash -npx vibe-devtools install @vibe-devtools/basic -``` - -Se houver conflitos, você verá: - -``` -⚠️ Conflicts detected (3 files) - - 1. vibes/configs/constitution.md - Local: abc123... - Package: def456... - -How to resolve conflicts? - [1] Overwrite with package version - [2] Stash local and install package - [3] Cancel installation -``` - -Escolha opção 2 para criar backup automático. - -### Update com Stash - -```bash -npx vibe-devtools update @vibe-devtools/basic --latest -npx vibe-devtools update @vibe-devtools/basic --version 1.0.3 -npx vibe-devtools update @vibe-devtools/basic --dry-run -``` - -### Dry Run - -Preview mudanças sem instalar: - -```bash -npx vibe-devtools install @vibe-devtools/basic --dry-run -``` - -## Comandos Stash - -### List - -Lista todos os stashes: - -```bash -npx vibe-devtools stash list -``` - -Output: -``` -stash{0} - @vibe-devtools/basic - install • 2025-10-23 14:30 • 3 files - -stash{1} - manual - manual • 2025-10-23 15:45 • 2 files - -Total: 2 stashes -``` - -### Show - -Mostra detalhes de um stash: - -```bash -npx vibe-devtools stash show 0 -``` - -### Apply - -Aplica stash (mantém no histórico): - -```bash -npx vibe-devtools stash apply 0 -``` - -### Pop - -Aplica stash e remove do histórico: - -```bash -npx vibe-devtools stash pop 0 -``` - -### Remove - -Remove um stash: - -```bash -npx vibe-devtools stash remove 0 -``` - -### Diff - -Mostra diferenças entre stash e arquivos atuais: - -```bash -npx vibe-devtools stash diff 0 -npx vibe-devtools stash diff 0 --editor # abre no IDE -``` - -### Save - -Cria stash manual: - -```bash -npx vibe-devtools stash save file1.ts file2.ts -npx vibe-devtools stash save # prompt interativo -``` - -### Clear - -Remove todos os stashes: - -```bash -npx vibe-devtools stash clear -npx vibe-devtools stash clear --force # sem confirmação -``` - -## Architecture - -### Components - -- **HashCalculator**: SHA-256 hash calculation -- **StashLogger**: JSONL logging system -- **StashManager**: Core lifecycle management -- **ConflictDetector**: Hash-based conflict detection -- **ConflictResolver**: CLI prompts & diff display - -### Storage - -``` -~/.vibes/stash/ -├── index.json # Lista de stashes -├── stash-0/ -│ ├── metadata.json # Metadata do stash -│ └── files/ # Full copy dos arquivos -└── stash-1/ - ├── metadata.json - └── files/ -``` - -### Logging - -``` -~/.vibes/logs/stash.log -``` - -Format: JSONL (1 JSON per line) - -## Technical Details - -### Hash Algorithm - -SHA-256 via Node.js crypto (nativo) - -### Storage Strategy - -Full copy (não patch) para: -- Simplicidade e confiabilidade -- Suporte a qualquer tipo de arquivo -- Sempre funciona (não corrompe) - -### Ordering - -FILO (First In Last Out) com renumeração: -- `stash{0}` é sempre o mais recente -- Após `pop` ou `remove`, IDs são renumerados -- Igual ao `git stash` - -## Error Handling - -### Permission Denied - -Se erro de permissão em `~/.vibes/stash/`: - -```bash -sudo chown -R $USER ~/.vibes -``` - -### Stash Corrupted - -Sistema valida integridade via hash antes de aplicar. Se corrompido: - -```bash -npx vibe-devtools stash remove -``` - -### Disk Full - -Libere espaço ou: - -```bash -npx vibe-devtools stash clear -``` - -## Performance - -- Hash calculation: < 100ms (arquivos < 1MB) -- Stash creation: < 1s (< 100 arquivos) -- Stash apply: < 1s (< 100 arquivos) - -## Dependencies - -- `inquirer@^9.2.0` - CLI prompts -- `diff@^5.1.0` - Diff display - -## Compatibility - -- Node.js >= 18.0.0 -- Works on: macOS, Linux, Windows - diff --git a/apps/cli/TESTING.md b/apps/cli/TESTING.md deleted file mode 100644 index 3cb4f4a..0000000 --- a/apps/cli/TESTING.md +++ /dev/null @@ -1,304 +0,0 @@ -# Testing Guide: Multi-Agent Support - -**Version**: v0.4.0 -**Date**: 2025-10-22 -**Status**: Ready for Testing - ---- - -## 🎯 Test Coverage - -- ✅ TASK-014: Gemini CLI Integration -- ✅ TASK-015: Claude Code Integration -- ✅ TASK-016: Multi-Agent Coexistence - ---- - -## 📋 Test Plan - -### Test 1: Gemini CLI Detection & Installation - -**Objective**: Verify Gemini CLI is detected and vibe packages install correctly - -**Prerequisites**: -- Gemini CLI installed (`gemini --version` works) - -**Steps**: -1. Create test project: `mkdir test-gemini && cd test-gemini` -2. Detect agents: `npx vibe-devtools agents detect` -3. Verify Gemini appears in output -4. Install basic: `npx vibe-devtools install @vibe-devtools/basic` -5. Verify `.gemini/prompts/` directory created -6. Verify commands copied to `.gemini/prompts/` -7. List commands: `ls -la .gemini/prompts/` - -**Expected Result**: -``` -✓ Gemini CLI detectado -📦 Instalado para: cursor, gemini -✓ .gemini/prompts/ criado com arquivos .md -``` - -**Actual Result**: To be tested - ---- - -### Test 2: Claude Code Detection & Installation - -**Objective**: Verify Claude Code is detected and vibe packages install correctly - -**Prerequisites**: -- Claude Code installed - -**Steps**: -1. Create test project: `mkdir test-claude && cd test-claude` -2. Detect agents: `npx vibe-devtools agents detect` -3. Verify Claude appears in output -4. Install research: `npx vibe-devtools install @vibe-devtools/research` -5. Verify `.claude/commands/` directory created -6. Verify commands copied to `.claude/commands/` -7. Open Claude Code and verify commands appear - -**Expected Result**: -``` -✓ Claude Code detectado -📦 Instalado para: cursor, claude -✓ .claude/commands/ criado com arquivos .md -✓ Commands aparecem no Claude Code -``` - -**Actual Result**: To be tested - ---- - -### Test 3: Multi-Agent Coexistence - -**Objective**: Verify multiple agents can coexist in same project - -**Prerequisites**: -- Cursor, Gemini CLI, Claude Code all installed - -**Steps**: -1. Create test project: `mkdir test-multi && cd test-multi` -2. Detect all: `npx vibe-devtools agents detect` -3. Verify all 3 detected -4. Install basic: `npx vibe-devtools install @vibe-devtools/basic` -5. Verify directories created: - - `.cursor/commands/` - - `.cursor/rules/` - - `.gemini/prompts/` - - `.claude/commands/` - - `.claude/rules/` -6. Verify no file conflicts -7. Verify no over-writes -8. Count files in each: should be equal or similar -9. Open each agent and verify commands work - -**Expected Result**: -``` -🔍 Detectados: cursor, gemini, claude -📦 Instalado para: cursor, gemini, claude -✓ Todos diretórios criados -✓ Sem conflitos -✓ Commands funcionam em todos agentes -``` - -**Actual Result**: To be tested - ---- - -### Test 4: Selective Installation (--agent flag) - -**Objective**: Verify --agent flag works for selective installation - -**Steps**: -1. Create project: `mkdir test-selective && cd test-selective` -2. Install for Cursor only: `npx vibe-devtools install @vibe-devtools/basic --agent=cursor` -3. Verify only `.cursor/` created -4. Verify `.gemini/` NOT created -5. Verify `.claude/` NOT created -6. Install for Gemini only: `npx vibe-devtools install @vibe-devtools/research --agent=gemini` -7. Verify `.gemini/` NOW created -8. Verify basic NOT in `.gemini/` (only research) - -**Expected Result**: -``` ---agent=cursor → apenas .cursor/ ---agent=gemini → apenas .gemini/ -Selective installation works -``` - -**Actual Result**: To be tested - ---- - -### Test 5: Agent Not Installed (Graceful Degradation) - -**Objective**: Verify graceful handling when agent not installed - -**Prerequisites**: -- Gemini CLI NOT installed - -**Steps**: -1. Create project -2. Detect: `npx vibe-devtools agents detect` -3. Verify Gemini NOT in list -4. Install basic: `npx vibe-devtools install @vibe-devtools/basic` -5. Verify installs for detected agents only -6. Verify no error, just warning -7. Verify Cursor still works - -**Expected Result**: -``` -⚠️ Gemini not detected (expected) -✓ Installed for: cursor (fallback) -✓ No errors -``` - -**Actual Result**: To be tested - ---- - -### Test 6: Backward Compatibility - -**Objective**: Verify v1.0 packages still work - -**Steps**: -1. Use package with old vibe.json (symlinks only, no agentTargets) -2. Install: `npx vibe-devtools install ./old-package` -3. Verify installs for Cursor (fallback) -4. Verify no errors -5. Verify commands work - -**Expected Result**: -``` -⚠️ Package uses v1.0 format (Cursor only) -✓ Installed successfully -✓ Backward compatible -``` - -**Actual Result**: To be tested - ---- - -## 🔧 Manual Testing Checklist - -### Agent Detection -- [ ] `vdt agents list` shows all supported agents -- [ ] `vdt agents detect` identifies installed agents correctly -- [ ] Detection works on macOS, Linux, Windows (if applicable) -- [ ] False positives handled (dir exists but app not installed) - -### Installation -- [ ] Install for all detected agents works -- [ ] Install with --agent flag works -- [ ] Intelligent merge works (no overwrites without backup) -- [ ] Backups created when files exist -- [ ] Symlinks vs copy fallback works - -### Multi-Agent -- [ ] Multiple agents coexist without conflicts -- [ ] Each agent sees correct commands -- [ ] Commands work in each agent -- [ ] Uninstall removes from all agents - -### Error Handling -- [ ] No agent detected → graceful fallback to Cursor -- [ ] Invalid --agent → clear error message -- [ ] Agent not installed → warning but continues -- [ ] Network errors → retry or fail gracefully - ---- - -## 📊 Test Matrix - -| Test | Cursor | Gemini | Claude | Multi | Pass | -|------|--------|--------|--------|-------|------| -| Detection | ✓ | ? | ? | ? | ? | -| Installation | ✓ | ? | ? | ? | ? | -| Commands Work | ✓ | ? | ? | ? | ? | -| Coexistence | N/A | N/A | N/A | ? | ? | -| --agent Flag | ✓ | ? | ? | ? | ? | -| Graceful Fail | ✓ | ? | ? | ? | ? | - -**Legend**: ✓ Passed | ❌ Failed | ? Not tested yet - ---- - -## 🚀 How to Run Tests - -### Quick Test (Cursor Only) -```bash -mkdir test-vdt && cd test-vdt -npx vibe-devtools agents detect -npx vibe-devtools install @vibe-devtools/basic -ls -la .cursor/commands/ -``` - -### Full Multi-Agent Test -```bash -mkdir test-multi && cd test-multi -npx vibe-devtools agents detect -npx vibe-devtools install @vibe-devtools/basic -npx vibe-devtools install @vibe-devtools/research - -find . -name "*.md" -path "*/.cursor/*" | wc -l -find . -name "*.md" -path "*/.gemini/*" | wc -l -find . -name "*.md" -path "*/.claude/*" | wc -l -``` - -### Automated Test Script -```bash -#!/bin/bash -echo "Testing Vibe DevTools v0.4.0" - -echo "\n1. Detecting agents..." -npx vibe-devtools agents detect - -echo "\n2. Installing basic..." -npx vibe-devtools install @vibe-devtools/basic - -echo "\n3. Checking directories..." -for dir in .cursor .gemini .claude; do - if [ -d "$dir" ]; then - echo "✓ $dir exists" - find "$dir" -name "*.md" | wc -l | xargs echo " Commands:" - fi -done - -echo "\n4. Testing selective install..." -npx vibe-devtools install @vibe-devtools/research --agent=cursor - -echo "\nTests complete!" -``` - ---- - -## 📝 Test Results (To be filled) - -**Tester**: _______________ -**Date**: _______________ -**Version**: v0.4.0 - -### Environment -- OS: _______________ -- Node: _______________ -- Cursor: _______________ -- Gemini CLI: _______________ -- Claude Code: _______________ - -### Results -- [ ] All tests passed -- [ ] Some tests failed (see notes) -- [ ] Blocked (missing prerequisites) - -### Notes -_______________________________________________ -_______________________________________________ -_______________________________________________ - ---- - -**Status**: 📋 Ready for Testing -**Next**: Execute tests and fill results - diff --git a/packages/basic/PACKAGE-SUMMARY.md b/packages/basic/PACKAGE-SUMMARY.md deleted file mode 100644 index 679ec02..0000000 --- a/packages/basic/PACKAGE-SUMMARY.md +++ /dev/null @@ -1,333 +0,0 @@ -# @vibes/basic - Sumário do Pacote - -**Data de Criação**: 2025-10-21 -**Versão**: 1.0.0 -**Tipo**: Foundation / Meta-Vibe - ---- - -## ✅ Estrutura Completa Criada - -``` -@vibes/basic/ -├── .cursor/ -│ ├── commands/ # 8 commands fundacionais -│ │ ├── maker.command.md ✅ Cria novos commands (Framework QUEST) -│ │ ├── maker.rule.md ✅ Cria rules baseadas em best practices -│ │ ├── maker.script.md ✅ Cria scripts bash/node -│ │ ├── maker.prompt.md ✅ Cria prompts reutilizáveis -│ │ ├── planner.project.md ✅ Planeja projetos completos -│ │ ├── planner.backlog.md ✅ Gera backlogs estruturados -│ │ ├── constitution.md ✅ Cria/gerencia constituição -│ │ └── vibe.manager.md ✅ Gerencia vibes, memory, tasks -│ └── rules/ # 3 rules essenciais -│ ├── commands.mdc ✅ Padrões de estrutura de commands -│ ├── rules.mdc ✅ Padrões de criação de rules -│ └── planning.mdc ✅ Padrões de planejamento e tasks -├── templates/ # 2 templates universais -│ ├── template.commands.md ✅ Template UNIVERSAL de commands -│ └── template.task.md ✅ Template de tasks -├── scripts/ # 1 script essencial -│ └── generator.task.cjs ✅ Gera tasks a partir de JSON -├── examples/ # 3 examples educacionais -│ ├── maker-command-search.md ✅ Como criar commands (search, research, analyzer) -│ ├── maker-script-integration.md ✅ Como integrar commands + scripts -│ └── maker-rule-integration.md ✅ Como associar rules aos commands -├── constitution.md ✅ Constituição do próprio @vibes/basic -├── README.md ✅ Documentação completa -├── package.json ✅ Manifesto npm -├── vibe.json ✅ Manifesto vibe -└── PACKAGE-SUMMARY.md ✅ Este arquivo (sumário) -``` - ---- - -## 📊 Estatísticas - -### Commands (8) - -**Makers** (4): -- maker.command - Framework QUEST para criar commands -- maker.rule - Cria rules (.mdc) com best practices -- maker.script - Cria scripts bash/node auxiliares -- maker.prompt - Cria prompts reutilizáveis - -**Planners** (2): -- planner.project - Planeja projetos, gera tasks automaticamente -- planner.backlog - Gera backlogs estruturados - -**Governance** (1): -- constitution - Cria e gerencia constituição do projeto - -**Management** (1): -- vibe.manager - Gerencia vibes, memory, tasks, Trello, Slack - -### Rules (3) - -- **commands.mdc** - Estrutura universal de commands -- **rules.mdc** - Como criar rules de qualidade -- **planning.mdc** - Padrões de planejamento e tasks - -### Templates (2) - -- **template.commands.md** - Template UNIVERSAL (única referência) -- **template.task.md** - Template de tasks (usado por planner.project) - -### Scripts (1) - -- **generator.task.cjs** - Gera tasks markdown a partir de JSON estruturado - -### Examples (3) - -- **maker-command-search.md** - 3 examples completos (search.simple, research.deep, analyzer.system) -- **maker-script-integration.md** - 3 patterns de integração (args, file, stdin + JSON output) -- **maker-rule-integration.md** - 3 scenarios (code gen, research, universal) - -### Documentação (3) - -- **README.md** - Documentação completa com uso, instalação, examples -- **constitution.md** - 10 princípios fundacionais do basic -- **PACKAGE-SUMMARY.md** - Este sumário - ---- - -## 🎯 Princípios Implementados - -### I. Meta-First ✅ - -O basic é auto-referencial: -- Usa `maker.command` para criar commands -- Usa `maker.rule` para criar rules -- Usa `planner.project` para planejar features - -### II. Framework QUEST Obrigatório ✅ - -Todos os makers seguem: -- **Q**uestion: Questionar primeiro -- **U**nderstand: Entender contexto -- **E**ngineer: Engenheirar estrutura -- **S**olidify: Solidificar com templates -- **T**est: Testar e iterar - -### III. Templates Universais ✅ - -- UM template para commands: `template.commands.md` -- UM template para tasks: `template.task.md` -- Makers DEVEM usar templates como ÚNICA referência - -### IV. Examples como Educação ✅ - -Todos os 3 examples são educacionais: -- Passo-a-passo completo -- Output esperado -- Explicações inline -- Anti-patterns documentados -- Conexões entre examples - -### V. Dependências Zero ✅ - -- Standalone completo -- Apenas Node.js core -- Todos templates incluídos -- Todos scripts incluídos - ---- - -## 🚀 Como Usar - -### Instalação - -```bash -npx vibes install basic -``` - -### Cenário 1: Criar Command - -```bash -/maker.command "Command para gerar componentes React" -``` - -### Cenário 2: Criar Rule - -```bash -/maker.rule "React component patterns" -``` - -### Cenário 3: Planejar Projeto - -```bash -/planner.project "Implementar autenticação de usuário" -``` - -### Cenário 4: Criar Novo Vibe - -1. Instalar basic -2. Criar commands com `/maker.command` -3. Criar rules com `/maker.rule` -4. Criar scripts com `/maker.script` -5. Agrupar tudo em estrutura de vibe -6. Publicar via npm ou GitHub - ---- - -## 📚 Examples Incluídos - -### Example 1: maker-command-search.md - -Demonstra criação de 3 commands: -- **search.simple** - Busca simples em arquivos -- **research.deep** - Pesquisa profunda acadêmica -- **analyzer.system** - Análise completa do sistema - -Ensina: -- Quando criar scripts vs lógica inline -- Como integrar maker + scripts + templates -- Framework QUEST na prática - -### Example 2: maker-script-integration.md - -Demonstra 3 patterns de integração: -- **Input via argumentos** (simples) -- **Input via arquivo temporário** (complexo) -- **Input via stdin** (streaming) - -3 examples completos: -- analyzer.dependencies.sh -- setup.tasks-structure.sh -- scorer.references.sh - -Ensina: -- Output JSON estruturado -- Error handling em scripts -- Cleanup de temporários - -### Example 3: maker-rule-integration.md - -Demonstra 3 scenarios: -- **Rule específica** (typescript-code-generation.mdc → maker.typescript) -- **Rule para categoria** (research-academic-standards.mdc → research.*) -- **Rule universal** (commands.mdc → ALL commands) - -Ensina: -- Estrutura obrigatória de rules -- Como commands referenciam rules -- Validação de compliance - ---- - -## ✅ Validação de Qualidade - -### Completude - -- [x] 8 commands incluídos -- [x] 3 rules incluídas -- [x] 2 templates incluídos -- [x] 1 script incluído -- [x] 3 examples completos -- [x] Constitution definida -- [x] README completo -- [x] Manifestos (vibe.json, package.json) - -### Consistência - -- [x] Todos commands seguem template.commands.md -- [x] Todas rules seguem estrutura padrão -- [x] Examples referenciam uns aos outros -- [x] Constitution alinhada com implementação - -### Qualidade - -- [x] Commands com Framework QUEST -- [x] Rules com DO/DON'T/Examples -- [x] Examples educacionais (não apenas demos) -- [x] Scripts com error handling -- [x] Templates com guidance comments - -### Documentação - -- [x] README com install, uso, examples -- [x] Constitution com 10 princípios -- [x] Examples com passo-a-passo -- [x] Todos os files com propósito claro - ---- - -## 🎓 Conceitos-Chave - -### Meta-Vibe Philosophy - -O `@vibes/basic` é um **meta-vibe** porque: - -1. **Se Auto-Constrói**: Commands do basic podem criar MAIS commands -2. **É Fundacional**: Todo outro vibe pode ser construído a partir dele -3. **É Educacional**: Examples mostram como construir vibes -4. **É Completo**: Não depende de outros vibes - -### Framework QUEST - -Todos os makers seguem QUEST: - -``` -Q → U → E → S → T -↓ ↓ ↓ ↓ ↓ -Question first - Understand context - Engineer structure - Solidify with templates - Test and iterate -``` - -### Templates Universais - -Garantem: -- ✅ Consistência entre commands -- ✅ Completude de documentação -- ✅ Qualidade e padrões -- ✅ Integração perfeita - ---- - -## 📦 Próximos Passos - -### Para Usar - -1. Instalar: `npx vibes install basic` -2. Explorar: Ler examples em `examples/` -3. Criar: Usar makers para criar commands/rules -4. Planejar: Usar planners para organizar trabalho - -### Para Contribuir - -1. Fork do repositório -2. Usar `maker.command` para criar novos makers -3. Usar `maker.rule` para adicionar rules -4. Seguir constitution do basic - -### Para Criar Novo Vibe - -1. Instalar basic -2. Usar makers para criar commands -3. Organizar em estrutura de vibe -4. Publicar via npm ou GitHub - ---- - -## 🔗 Links Úteis - -- Repository: https://github.com/vibes-org/basic -- Examples: `examples/` -- Constitution: `constitution.md` -- Templates: `templates/` - ---- - -## 📄 Licença - -MIT - ---- - -**@vibes/basic** - O começo de tudo 🚀 - -_Created: 2025-10-21_ - diff --git a/shared/templates/template.assistant-architecture.md b/packages/basic/templates/template.assistant-architecture.md similarity index 100% rename from shared/templates/template.assistant-architecture.md rename to packages/basic/templates/template.assistant-architecture.md diff --git a/shared/templates/template.assistant-conversation.md b/packages/basic/templates/template.assistant-conversation.md similarity index 100% rename from shared/templates/template.assistant-conversation.md rename to packages/basic/templates/template.assistant-conversation.md diff --git a/shared/templates/template.assistant-metadata.md b/packages/basic/templates/template.assistant-metadata.md similarity index 100% rename from shared/templates/template.assistant-metadata.md rename to packages/basic/templates/template.assistant-metadata.md diff --git a/shared/templates/template.assistant-synthesis.md b/packages/basic/templates/template.assistant-synthesis.md similarity index 100% rename from shared/templates/template.assistant-synthesis.md rename to packages/basic/templates/template.assistant-synthesis.md diff --git a/shared/templates/template.character-evolution.md b/packages/basic/templates/template.character-evolution.md similarity index 100% rename from shared/templates/template.character-evolution.md rename to packages/basic/templates/template.character-evolution.md diff --git a/shared/templates/template.character-memory.md b/packages/basic/templates/template.character-memory.md similarity index 100% rename from shared/templates/template.character-memory.md rename to packages/basic/templates/template.character-memory.md diff --git a/shared/templates/template.character-personality.md b/packages/basic/templates/template.character-personality.md similarity index 100% rename from shared/templates/template.character-personality.md rename to packages/basic/templates/template.character-personality.md diff --git a/shared/templates/template.configs-command.json b/packages/basic/templates/template.configs-command.json similarity index 100% rename from shared/templates/template.configs-command.json rename to packages/basic/templates/template.configs-command.json diff --git a/shared/templates/template.manager-index.md b/packages/basic/templates/template.manager-index.md similarity index 100% rename from shared/templates/template.manager-index.md rename to packages/basic/templates/template.manager-index.md diff --git a/shared/templates/template.manager-workflow.md b/packages/basic/templates/template.manager-workflow.md similarity index 100% rename from shared/templates/template.manager-workflow.md rename to packages/basic/templates/template.manager-workflow.md diff --git a/packages/research/.cursor/commands/research.validate.md b/packages/research/.cursor/commands/research.validate.md index 56bca3c..2c930cd 100644 --- a/packages/research/.cursor/commands/research.validate.md +++ b/packages/research/.cursor/commands/research.validate.md @@ -304,13 +304,7 @@ O output é um relatório final extenso dividido em capítulos salvos em `./memo ### Fase 6: Gerar Relatório Consolidado -1. **Executar Script de Merge**: - ```bash - vibes/scripts/bash/merge-research-report.sh \ - ./memory/[RESEARCH_ID]/final-report - ``` - -2. **Validar FULL-REPORT.md**: +1. **Validar FULL-REPORT.md**: - Todos capítulos incluídos - Estrutura coerente - TOC atualizado @@ -548,21 +542,6 @@ docs(research): complete [research-name] deep research - NUNCA fazer afirmações sem referências - NUNCA deixar gaps sem documentar -## Scripts - -### merge-research-report.sh - -**Propósito**: Merge capítulos em relatório consolidado - -**Localização**: `vibes/scripts/bash/merge-research-report.sh` - -**Uso**: -```bash -vibes/scripts/bash/merge-research-report.sh [REPORT_DIR] -``` - -**Output**: `[REPORT_DIR]/FULL-REPORT.md` - ## Templates ### template.research-report.md @@ -628,9 +607,6 @@ Status: ✅ COMPLETED **Commands Obrigatórios**: Todos anteriores do pipeline -**Scripts Obrigatórios**: -- `vibes/scripts/bash/merge-research-report.sh` - **Templates Obrigatórios**: - `research/templates/template.research-report.md` diff --git a/packages/research/PUBLICACAO.md b/packages/research/PUBLICACAO.md deleted file mode 100644 index ddf39c9..0000000 --- a/packages/research/PUBLICACAO.md +++ /dev/null @@ -1,218 +0,0 @@ -# Guia de Publicação - @vibes/research - -**Versão**: 2.0.0 -**Data**: 2025-10-21 -**Status**: ✅ Pronto para publicação - ---- - -## ✅ Validações Realizadas - -### 1. npm pack -```bash -npm pack --dry-run -``` - -**Resultado**: ✅ Sucesso -- **Arquivos**: 27 files -- **Tamanho**: ~297.9 kB (unpacked), ~79.2 kB (packed) -- **Conteúdo**: .cursor/, templates/, scripts/, docs - -### 2. npm publish --dry-run -```bash -npm publish --dry-run -``` - -**Resultado**: ✅ Sucesso (sem erros críticos) -- **Package**: @vibes/research@2.0.0 -- **Registry**: npm - ---- - -## 📦 Conteúdo do Pacote - -**Commands** (12): -- research.pipeline.md -- research.initialize.md -- research.search.md -- research.score.md -- research.analyze.md -- research.synthesize.md -- research.validate.md -- research.github.md -- research.integration.md -- research.simple.pipeline.md (deprecated) -- research.deep.pipeline.md (deprecated) -- research.expert.pipeline.md (deprecated) - -**Rules** (4): -- research.mdc -- analysis.mdc -- search.mdc -- synthesis.mdc - -**Templates** (4): -- template.research-metadata.json -- template.research-synthesis.md -- template.research-reference-analysis.md -- template.research-report.md - -**Documentation**: -- README.md -- constitution.md -- CHANGELOG.md -- examples/basic-research-example.md - -**Config**: -- vibe.json -- package.json - ---- - -## 🚀 Como Publicar - -### Pré-requisitos - -1. **Conta npm verificada** - ```bash - npm whoami - ``` - -2. **Autenticado** - ```bash - npm login - ``` - -3. **Organização @vibes** (se necessário) - - Criar em npmjs.com - - Adicionar membros - -### Processo de Publicação - -#### Passo 1: Validações Finais - -```bash -cd research/ - -# Validar package.json -npm pkg get name version - -# Testar empacotamento -npm pack - -# Ver conteúdo -tar -tzf vibes-research-2.0.0.tgz | head -20 - -# Limpar tarball -rm vibes-research-2.0.0.tgz -``` - -#### Passo 2: Publicar - -```bash -# Dry-run final -npm publish --dry-run - -# Publicar (IRREVERSÍVEL) -npm publish --access public -``` - -**⚠️ ATENÇÃO**: Versões publicadas no npm são IMUTÁVEIS. Não é possível sobrescrever. - -#### Passo 3: Validar Publicação - -```bash -# Verificar no npm -npm view @vibes/research - -# Testar instalação -npm install @vibes/research - -# Ou via vibes-cli -npx vibes install @vibes/research -``` - -#### Passo 4: Criar GitHub Release - -```bash -git tag -a v2.0.0 -m "Release v2.0.0 - First distributable version" -git push origin v2.0.0 -``` - -Criar release no GitHub: -1. Ir em https://github.com/vibes-org/research/releases -2. Draft new release -3. Tag: v2.0.0 -4. Title: "v2.0.0 - First Distributable Version" -5. Description: Copiar de CHANGELOG.md -6. Publish release - ---- - -## 📋 Checklist de Publicação - -### Antes de Publicar -- [x] package.json válido -- [x] vibe.json válido -- [x] README.md completo -- [x] CHANGELOG.md atualizado -- [x] Examples incluídos -- [x] npm pack funciona -- [x] npm publish --dry-run funciona -- [ ] Repositório GitHub público criado -- [ ] npm login executado -- [ ] Organização @vibes configurada (se necessário) - -### Publicação -- [ ] npm publish --access public executado -- [ ] Package visível em npmjs.com -- [ ] npm install @vibes/research funciona -- [ ] GitHub release v2.0.0 criada - -### Pós-Publicação -- [ ] Testar instalação em projeto limpo -- [ ] Validar commands funcionando -- [ ] Atualizar documentação com link npm -- [ ] Anunciar em comunidade - ---- - -## 🎯 Comandos Resumidos - -```bash -# Validar -cd research/ -npm pack --dry-run -npm publish --dry-run - -# Publicar (CUIDADO) -npm publish --access public - -# Validar publicação -npm view @vibes/research -npm install @vibes/research - -# GitHub release -git tag -a v2.0.0 -m "Release v2.0.0" -git push origin v2.0.0 -``` - ---- - -## ⚠️ Notas Importantes - -1. **Versão é imutável**: Depois de publicar 2.0.0, não pode sobrescrever. Próxima versão seria 2.0.1 ou 2.1.0. - -2. **Organização @vibes**: Precisa existir no npm e você ter permissão. - -3. **Public package**: Usar `--access public` para pacotes scoped. - -4. **Sem bin**: Este vibe não tem executável próprio (apenas commands markdown). - -5. **Testes locais**: Sempre testar instalação antes de publicar. - ---- - -**Status**: ✅ Pronto para publicação -**Próximo passo**: Executar `npm publish --access public` quando decidir publicar - diff --git a/scripts/git-check-sync.sh b/scripts/git-check-sync.sh new file mode 100755 index 0000000..8955c35 --- /dev/null +++ b/scripts/git-check-sync.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +git fetch --all -q 2>/dev/null + +echo "📊 Status de Sincronização - Git RAID 1" +echo "========================================" +echo "" + +branches=("main" "develop" "feat/develop/multi-agent-support") + +synced=0 +divergent=0 +total=0 + +for branch in "${branches[@]}"; do + if git show-ref --verify --quiet refs/remotes/origin/$branch 2>/dev/null; then + total=$((total + 1)) + origin_hash=$(git rev-parse origin/$branch 2>/dev/null) + backup_hash=$(git rev-parse backup/$branch 2>/dev/null) + + echo "📍 Branch: $branch" + echo " origin: ${origin_hash:0:8}" + echo " backup: ${backup_hash:0:8}" + + if [ "$origin_hash" = "$backup_hash" ]; then + echo " ✅ Sincronizado" + synced=$((synced + 1)) + else + echo " ⚠️ DIVERGENTE" + divergent=$((divergent + 1)) + fi + echo "" + fi +done + +echo "========================================" +echo "📊 Resumo:" +echo " Total de branches: $total" +echo " ✅ Sincronizadas: $synced" +echo " ⚠️ Divergentes: $divergent" +echo "" + +if [ $divergent -eq 0 ]; then + echo "🎉 Sistema 100% sincronizado!" + exit 0 +else + echo "⚠️ Execute: ./scripts/git-sync-from-origin.sh" + exit 1 +fi + diff --git a/scripts/git-force-sync-backup.sh b/scripts/git-force-sync-backup.sh new file mode 100755 index 0000000..1ebfa91 --- /dev/null +++ b/scripts/git-force-sync-backup.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +set -e + +echo "⚠️ ATENÇÃO: Sincronização FORÇADA do backup" +echo " Isso irá sobrescrever TUDO no backup com o estado atual de origin" +echo "" +read -p "Tem certeza? (y/N): " -n 1 -r +echo + +if [[ ! $REPLY =~ ^[Yy]$ ]]; then + echo "❌ Operação cancelada" + exit 0 +fi + +echo "" +echo "🔄 Sincronizando TODAS as branches..." + +git fetch origin --all + +for branch in $(git branch -r | grep 'origin/' | grep -v 'HEAD' | sed 's/origin\///'); do + echo "" + echo "📍 Sincronizando branch: $branch" + + if git checkout "$branch" 2>/dev/null || git checkout -b "$branch" "origin/$branch"; then + git pull origin "$branch" + + if git push backup "$branch" --force; then + echo "✅ $branch → backup (forced)" + else + echo "⚠️ $branch → falhou" + fi + fi +done + +git checkout main 2>/dev/null || git checkout master 2>/dev/null || true + +echo "" +echo "🎉 Sincronização completa forçada!" +echo " Backup está 100% espelhado com origin" + diff --git a/scripts/git-push-all.sh b/scripts/git-push-all.sh new file mode 100755 index 0000000..ac3cc34 --- /dev/null +++ b/scripts/git-push-all.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +set -e + +BRANCH=${1:-$(git branch --show-current)} + +echo "🔄 Git RAID Push - Sincronizando origin + backup" +echo "📍 Branch: $BRANCH" +echo "" + +echo "1️⃣ Pushing to origin..." +if git push origin "$BRANCH"; then + echo "✅ origin: Push successful" +else + echo "❌ origin: Push failed" + exit 1 +fi + +echo "" +echo "2️⃣ Pushing to backup..." +if git push backup "$BRANCH"; then + echo "✅ backup: Push successful" +else + echo "⚠️ backup: Push failed (origin já foi atualizado)" + exit 1 +fi + +echo "" +echo "🎉 Sincronização completa!" +echo " origin: OnoSendae/vibe-devtools" +echo " backup: OnoSendae/vibe-devtools-bkp" + diff --git a/scripts/git-sync-from-origin.sh b/scripts/git-sync-from-origin.sh new file mode 100755 index 0000000..9c6255b --- /dev/null +++ b/scripts/git-sync-from-origin.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +set -e + +BRANCH=${1:-$(git branch --show-current)} + +echo "🔄 Sincronizando backup com PRs/merges remotos" +echo "📍 Branch: $BRANCH" +echo "" + +echo "1️⃣ Pulling from origin..." +if git pull origin "$BRANCH"; then + echo "✅ Pull from origin successful" +else + echo "❌ Pull from origin failed" + exit 1 +fi + +echo "" +echo "2️⃣ Pushing to backup..." +if git push backup "$BRANCH"; then + echo "✅ backup atualizado com mudanças de origin" +else + echo "❌ backup: Push failed" + exit 1 +fi + +echo "" +echo "🎉 Backup sincronizado com origin!" +echo " Mudanças remotas (PRs) agora estão no backup" + diff --git a/shared/scripts/generator.task.cjs b/shared/scripts/generator.task.cjs deleted file mode 100755 index 61da8f8..0000000 --- a/shared/scripts/generator.task.cjs +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -const PRIORITY_FOLDERS = { - 'P0': 'p0-bloqueador', - 'P1': 'p1-critico', - 'P2': 'p2-alto', - 'P3': 'p3-medio', - 'P4': 'p4-baixo' -}; - -function readStdin() { - return new Promise((resolve, reject) => { - let data = ''; - process.stdin.setEncoding('utf8'); - - process.stdin.on('data', chunk => { - data += chunk; - }); - - process.stdin.on('end', () => { - try { - resolve(JSON.parse(data)); - } catch (e) { - reject(new Error(`Failed to parse JSON: ${e.message}`)); - } - }); - - process.stdin.on('error', reject); - }); -} - -function loadTemplate() { - const templatePath = path.join(__dirname, '..', 'structure', 'templates', 'template.task.md'); - - if (!fs.existsSync(templatePath)) { - throw new Error(`Template not found: ${templatePath}`); - } - - return fs.readFileSync(templatePath, 'utf8'); -} - -function slugify(text) { - return text - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, '') - .substring(0, 50); -} - -function populateTemplate(template, task, metadata) { - const taskNum = String(task.number).padStart(3, '0'); - const taskId = `${metadata.featureId}-${taskNum}`; - const categorySlug = slugify(task.category); - const titleSlug = slugify(task.title); - - const replacements = { - '{{TASK_ID}}': taskId, - '{{FEATURE_ID}}': metadata.featureId, - '{{FEATURE_NAME}}': metadata.featureName, - '{{TITLE}}': task.title, - '{{PRIORITY}}': task.priority, - '{{CATEGORY}}': task.category, - '{{PHASE}}': task.phase, - '{{ESTIMATED_TIME}}': task.estimatedTime, - '{{CREATED_AT}}': metadata.timestamp, - '{{UPDATED_AT}}': metadata.timestamp, - '{{SOURCE_PLAN}}': metadata.sourcePlan, - '{{SOURCE_TYPE}}': metadata.sourceType, - '{{PLAN_OBJECTIVE}}': metadata.planObjective, - '{{CONTEXT_DESCRIPTION}}': task.contextDescription || 'N/A', - '{{FULL_DESCRIPTION}}': task.description, - '{{FILE_LIST}}': formatList(task.affectedFiles), - '{{DEPENDS_ON_LIST}}': formatList(task.dependsOn), - '{{BLOCKS_LIST}}': formatList(task.blocks), - '{{IMPLEMENTATION_STEPS}}': task.implementationSteps, - '{{IMPLEMENTATION_CHECKLIST}}': task.implementationChecklist, - '{{VALIDATION}}': task.validation, - '{{NOTES}}': task.notes || 'N/A' - }; - - let content = template; - for (const [placeholder, value] of Object.entries(replacements)) { - content = content.replace(new RegExp(placeholder, 'g'), value); - } - - return { - content, - filename: `task-${taskId}-${categorySlug}-${titleSlug}.md`, - taskNum, - categorySlug - }; -} - -function formatList(items) { - if (!items || items.length === 0) return 'N/A'; - - if (Array.isArray(items)) { - return items.map(item => `- ${item}`).join('\n'); - } - - return items; -} - -function ensureDir(dirPath) { - if (!fs.existsSync(dirPath)) { - fs.mkdirSync(dirPath, { recursive: true }); - } -} - -function generateTasks(data) { - const { metadata, tasks } = data; - const template = loadTemplate(); - - const tasksDir = path.join(__dirname, '..', 'tasks', metadata.featureId); - ensureDir(tasksDir); - - const created = []; - const errors = []; - const byPriority = {}; - const byCategory = {}; - - for (const task of tasks) { - try { - const priorityFolder = PRIORITY_FOLDERS[task.priority]; - if (!priorityFolder) { - throw new Error(`Invalid priority: ${task.priority}`); - } - - const priorityDir = path.join(tasksDir, priorityFolder); - ensureDir(priorityDir); - - const { content, filename } = populateTemplate(template, task, metadata); - - const filePath = path.join(priorityDir, filename); - fs.writeFileSync(filePath, content, 'utf8'); - - created.push({ - taskId: `${metadata.featureId}-${String(task.number).padStart(3, '0')}`, - file: path.relative(path.join(__dirname, '..', '..'), filePath), - priority: task.priority, - category: task.category - }); - - byPriority[task.priority] = (byPriority[task.priority] || 0) + 1; - byCategory[task.category] = (byCategory[task.category] || 0) + 1; - - } catch (error) { - errors.push({ - task: task.number, - error: error.message - }); - } - } - - return { - created, - errors, - summary: { - total: created.length, - byPriority, - byCategory - } - }; -} - -async function main() { - try { - const data = await readStdin(); - - if (!data.metadata || !data.tasks) { - throw new Error('Invalid input: missing metadata or tasks'); - } - - const result = generateTasks(data); - - console.log(JSON.stringify(result, null, 2)); - - process.exit(result.errors.length > 0 ? 1 : 0); - - } catch (error) { - console.error(JSON.stringify({ - error: error.message, - stack: error.stack - }, null, 2)); - process.exit(1); - } -} - -main(); diff --git a/shared/templates/analyzer-refactor.constitution.md b/shared/templates/analyzer-refactor.constitution.md deleted file mode 100644 index de401c1..0000000 --- a/shared/templates/analyzer-refactor.constitution.md +++ /dev/null @@ -1,356 +0,0 @@ -# Analyzer Refactor Constitution - -## Core Principles - -### I. Contexto Sobre Mudança - -**Entender antes de mudar** - -Refatoração DEVE ser precedida por compreensão profunda do código existente. Mudanças sem contexto levam a regressões, bugs sutis e perda de conhecimento implícito. - -**Regras**: -- SEMPRE ler e entender o propósito do código antes de sugerir mudanças -- SEMPRE identificar o domínio e caso de uso antes de refatorar -- SEMPRE considerar o histórico e razões para decisões anteriores -- SEMPRE validar que refatoração não quebra comportamento existente -- NUNCA assumir que código "feio" está errado sem investigar -- NUNCA refatorar sem entender testes existentes -- NUNCA ignorar comentários que explicam decisões de design - -**Racional**: Código legado muitas vezes contém lógica de negócio crítica e edge cases importantes. Refatoração sem contexto destroi conhecimento acumulado. - -### II. Níveis de Intensidade Progressivos - -**Refatoração em camadas incrementais** - -Mudanças DEVEM ser propostas em três níveis de intensidade crescente, permitindo escolha baseada em risco, esforço e retorno. - -**Regras**: - -**Nível Básico (Organização)**: -- APENAS mudanças que NÃO alteram lógica -- Foco em legibilidade: nomenclatura, formatação, estrutura de arquivo -- Conservador e de baixo risco -- Executável por qualquer desenvolvedor -- Exemplos: renomear variáveis, extrair constantes, reorganizar imports - -**Nível Médio (Patterns e Boas Práticas)**: -- Introdução de design patterns consolidados -- Eliminação de code smells conhecidos -- Aplicação de princípios DRY, KISS, YAGNI -- Requer conhecimento de patterns -- Risco moderado, benefício significativo -- Exemplos: Strategy Pattern, Repository Pattern, extrair métodos duplicados - -**Nível Avançado (SOLID e Excelência)**: -- Aplicação rigorosa de princípios SOLID -- Otimização algorítmica (complexidade O(n²) → O(n)) -- Arquitetura limpa e desacoplada -- Clean Code em nível avançado -- Requer expertise técnica -- Alto esforço, máximo benefício de longo prazo -- Exemplos: separar responsabilidades (SRP), inversão de dependências, algoritmos eficientes - -**Racional**: Nem todo código precisa do mesmo nível de refatoração. Níveis permitem balancear risco, esforço e retorno de forma pragmática. - -### III. Justificação Técnica Obrigatória - -**Toda sugestão DEVE ser fundamentada** - -Refatorações DEVEM incluir justificativa técnica sólida explicando POR QUÊ a mudança melhora o código, não apenas O QUÊ mudar. - -**Regras**: -- SEMPRE explicar o problema específico que a refatoração resolve -- SEMPRE citar princípios, patterns ou boas práticas aplicados -- SEMPRE documentar benefícios concretos (manutenibilidade, performance, testabilidade) -- SEMPRE incluir trade-offs (prós e contras) para níveis médio e avançado -- SEMPRE estimar esforço de implementação -- SEMPRE fornecer código antes/depois com contexto suficiente -- NUNCA sugerir mudanças "porque sim" ou "porque é melhor" -- NUNCA omitir justificativas técnicas - -**Racional**: Justificações permitem que desenvolvedores aprendam princípios, tomem decisões informadas e entendam o valor da refatoração. - -### IV. Código Antes/Depois Sempre - -**Mostrar, não apenas dizer** - -Sugestões DEVEM incluir código original e código refatorado lado a lado com contexto suficiente para compreensão. - -**Regras**: -- SEMPRE incluir snippet do código atual com linhas de contexto -- SEMPRE incluir código refatorado completo e funcional -- SEMPRE referenciar arquivo e linha específica -- SEMPRE preservar contexto (imports, dependências relacionadas) -- SEMPRE usar syntax highlighting apropriado -- NUNCA usar pseudocódigo vago -- NUNCA omitir partes críticas do código -- NUNCA assumir que leitor inferirá mudanças - -**Racional**: Desenvolvedores precisam ver exatamente o que mudar e como implementar. Abstrações vagas não são acionáveis. - -### V. Priorização por Impacto vs Esforço - -**Maximizar retorno sobre investimento** - -Sugestões DEVEM ser priorizadas usando matriz de impacto (benefício) vs esforço (custo), destacando quick wins. - -**Regras**: -- SEMPRE calcular prioridade: `priority = (severity × impact) / effort` -- SEMPRE identificar quick wins (baixo esforço, alto impacto) -- SEMPRE ordenar sugestões por prioridade calculada -- SEMPRE estimar esforço realista: LOW (<2h), MEDIUM (2-8h), HIGH (>8h) -- SEMPRE avaliar impacto em: manutenibilidade, performance, testabilidade, escalabilidade -- NUNCA priorizar arbitrariamente sem cálculo -- NUNCA omitir estimativas de esforço - -**Racional**: Tempo de desenvolvimento é limitado. Priorização permite maximizar valor entregue com recursos disponíveis. - -### VI. Princípios SOLID no Centro - -**SOLID como guia de excelência** - -Análise avançada DEVE avaliar rigorosamente os cinco princípios SOLID e propor soluções que os respeitem. - -**Regras**: - -**S - Single Responsibility Principle**: -- Classe/função DEVE ter uma única razão para mudar -- Identificar violações: classes com múltiplas responsabilidades -- Sugerir: separação em classes/módulos coesos - -**O - Open/Closed Principle**: -- Código DEVE ser aberto para extensão, fechado para modificação -- Identificar: switches/ifs que crescem com novos casos -- Sugerir: polimorfismo, strategy pattern, plugins - -**L - Liskov Substitution Principle**: -- Subtipos DEVEM ser substituíveis por tipos base sem quebrar código -- Identificar: subclasses que violam contratos da classe base -- Sugerir: redesign de hierarquia ou composição - -**I - Interface Segregation Principle**: -- Clientes NÃO DEVEM depender de interfaces que não usam -- Identificar: interfaces "gordas" com muitos métodos -- Sugerir: separação em interfaces menores e coesas - -**D - Dependency Inversion Principle**: -- Depender de abstrações, NÃO de implementações concretas -- Identificar: acoplamento direto a classes concretas -- Sugerir: injeção de dependências, interfaces, abstração - -**Racional**: SOLID representa décadas de conhecimento destilado. Código que respeita SOLID é manutenível, testável e escalável. - -### VII. Algoritmos Eficientes São Obrigatórios - -**Performance por design, não por acaso** - -Análise avançada DEVE identificar algoritmos ineficientes e propor soluções com melhor complexidade assintótica. - -**Regras**: -- SEMPRE analisar complexidade: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ) -- SEMPRE identificar loops aninhados (candidatos a O(n²)) -- SEMPRE considerar estruturas de dados mais eficientes: - * Array para acesso indexado O(1) - * Hash Map/Set para lookup O(1) - * Tree para dados ordenados O(log n) - * Heap para prioridades O(log n) -- SEMPRE sugerir algoritmos consolidados quando aplicável: - * Binary search em vez de linear search - * Hash map em vez de loops aninhados - * Memoization/DP para recursão com subproblemas repetidos - * Two pointers para problemas de arrays -- NUNCA aceitar O(n²) quando O(n) é possível -- NUNCA ignorar performance em código crítico -- NUNCA otimizar prematuramente (balancear legibilidade e performance) - -**Racional**: Algoritmos ineficientes causam problemas de escalabilidade. Complexidade importa mais que micro-otimizações. - -### VIII. Clean Code Não É Opcional - -**Código limpo é código profissional** - -Análise avançada DEVE aplicar rigorosamente princípios de Clean Code de Uncle Bob. - -**Regras**: - -**Funções**: -- Pequenas (< 20 linhas idealmente) -- Fazem uma coisa só -- Nível de abstração consistente -- Sem side effects ocultos -- Nomes revelam intenção - -**Classes**: -- Coesas (relacionadas ao mesmo propósito) -- Baixo acoplamento (poucas dependências externas) -- Encapsulamento adequado - -**Nomenclatura**: -- Nomes revelam intenção: `calculateUserAge()` não `calc()` -- Nomes pronunciáveis e buscáveis -- Sem prefixos húngaros ou codificações - -**Comentários**: -- Código DEVE ser auto-explicativo -- Comentários explicam "por que", não "o que" -- Sem código comentado (usar Git) -- Sem comentários óbvios ou redundantes - -**Error Handling**: -- Usar exceções, não códigos de erro -- Contextualizar exceções -- Não retornar null (usar Optional/Maybe) - -**Racional**: Clean Code reduz débito técnico, facilita onboarding e permite evolução sustentável do sistema. - -## Análise e Diagnóstico - -### Code Smells a Identificar - -**Long Method**: Funções > 50 linhas → Extrair métodos -**Large Class**: Classes > 500 linhas → Separar responsabilidades -**Long Parameter List**: > 5 parâmetros → Objetos de configuração -**Duplicated Code**: Blocos repetidos → DRY -**Dead Code**: Código não usado → Remover -**Speculative Generality**: Código "por precaução" → YAGNI -**Feature Envy**: Método usa mais dados de outra classe → Mover método -**Data Clumps**: Grupos de dados sempre juntos → Criar objeto -**Primitive Obsession**: Excesso de primitivos → Value objects -**Switch Statements**: Switches grandes → Polimorfismo - -### Design Patterns Aplicáveis - -Identificar oportunidades para patterns consolidados: - -- **Strategy**: Múltiplos algoritmos intercambiáveis -- **Factory**: Criação complexa de objetos -- **Observer**: Notificações de mudanças -- **Decorator**: Adicionar comportamento dinamicamente -- **Repository**: Abstração de dados -- **Dependency Injection**: Inversão de controle -- **Builder**: Construção passo-a-passo -- **Command**: Encapsular operações -- **Template Method**: Algoritmo com passos customizáveis -- **Adapter**: Integrar interfaces incompatíveis - -### Métricas de Qualidade - -Avaliar código usando métricas objetivas: - -- **Complexidade Ciclomática**: < 10 por função (idealmente < 5) -- **Profundidade de Aninhamento**: < 4 níveis -- **Acoplamento (Coupling)**: Baixo (poucas dependências) -- **Coesão (Cohesion)**: Alta (responsabilidades relacionadas) -- **Cobertura de Testes**: > 80% (crítico > 95%) -- **Duplicação**: < 5% do código - -## Boas Práticas de Sugestão - -### Estrutura de Sugestão - -Toda sugestão DEVE seguir formato consistente: - -```markdown -### [ID]: [Título Descritivo] - -**Severidade**: [Low|Medium|High] -**Categoria**: [Organization|Code Smell|Design|Architecture|Performance|SOLID] -**Localização**: [file]:[line] ou [file]:[line-range] - -**Código Atual**: -```[lang] -[código original com contexto] -``` - -**Problema**: [Descrição clara do problema] - -**Solução Proposta**: [Descrição da solução] - -**Código Refatorado**: -```[lang] -[código refatorado completo] -``` - -**Justificativa Técnica**: -- [Por que esta mudança?] -- [Que princípio/pattern aplica?] -- [Referências] - -**Benefícios**: -- [Benefício 1] -- [Benefício 2] - -**Trade-offs** (Médio/Avançado): -- Prós: [...] -- Contras: [...] - -**Esforço Estimado**: [Low|Medium|High] -``` - -### Níveis de Severidade - -- **Low**: Não afeta funcionalidade, apenas legibilidade -- **Medium**: Afeta manutenibilidade, pode causar bugs futuros -- **High**: Afeta performance, segurança ou viola princípios críticos - -### Estimativa de Esforço - -- **Low**: < 2 horas (renomear, extrair constante, reorganizar) -- **Medium**: 2-8 horas (aplicar pattern, extrair classes, refatorar módulo) -- **High**: > 8 horas (redesign arquitetural, migração algoritmos, separação camadas) - -## Restrições e Limitações - -### Quando NÃO Refatorar - -- Código que funciona em produção sem problemas e não será modificado -- Sistemas legados sem testes (criar testes primeiro) -- Código que será descontinuado em breve -- Refatoração cosmética sem benefício tangível - -### Refatoração Segura - -- SEMPRE ter testes antes de refatorar (ou criar testes primeiro) -- SEMPRE refatorar em passos pequenos e incrementais -- SEMPRE executar testes após cada passo -- SEMPRE fazer commit após cada refatoração bem-sucedida -- SEMPRE usar ferramentas de refatoração automática quando disponíveis (IDE) - -### Exceções aos Princípios - -Princípios são guias, não dogmas. Exceções justificadas são aceitáveis: - -- Performance crítica pode justificar código mais complexo -- Código temporário (prototypes) pode ser mais pragmático -- Integração com APIs legadas pode violar princípios -- Mas SEMPRE documentar exceções e justificativas - -## Governança - -Esta constitution é a **fonte autoritativa** para análise de refatoração. - -**Hierarquia de Autoridade**: -1. Constitution (este arquivo) - Mais alta -2. Language-specific rules (vibes/rules/development/languages/) -3. Project-specific conventions -4. Preferências individuais - Mais baixa - -**Processo de Emenda**: -- Constitution pode evoluir baseada em aprendizados -- Emendas devem ser documentadas com justificativa -- Mudanças devem manter espírito dos princípios core - -**Exceções**: -- Exceções aos princípios podem ser feitas quando bem justificadas -- Justificativa DEVE ser documentada em comentário de código -- Exceções recorrentes devem levar a revisão de princípios - ---- - -**Version**: 1.0.0 -**Ratified**: 2025-10-16 -**Last Amended**: 2025-10-16 -**Project**: Vibe-Driven Development Kit - Analyzer Refactor -**Maintainer**: Sistema de Commands .cursor - diff --git a/shared/templates/architecture-modular.md b/shared/templates/architecture-modular.md deleted file mode 100644 index 40ab26f..0000000 --- a/shared/templates/architecture-modular.md +++ /dev/null @@ -1,1069 +0,0 @@ -# Guia de Arquitetura Modular - -## 📋 Visão Geral - -Este documento define a arquitetura padrão para todos os módulos do sistema, baseada em **Clean Architecture**, **SOLID principles** e **Domain-Driven Design (DDD)**. Cada módulo deve seguir esta estrutura para garantir manutenibilidade, testabilidade e escalabilidade. - -## 🎯 Princípios Fundamentais - -### 1. Separação de Responsabilidades -Cada camada tem uma responsabilidade única e bem definida. - -### 2. Inversão de Dependências -Camadas externas dependem de abstrações das camadas internas, nunca o contrário. - -### 3. Testabilidade -Toda lógica de negócio deve ser testável independentemente de frameworks ou infraestrutura. - -### 4. Configurabilidade -Comportamentos devem ser configuráveis sem alterar código. - -### 5. Extensibilidade -Novas funcionalidades devem ser adicionadas sem modificar código existente (Open/Closed Principle). - ---- - -## 📁 Estrutura de Diretórios - -``` -module-name/ -├── src/ -│ ├── domain/ # Camada de Domínio (Business Rules) -│ │ ├── entities/ # Entidades de negócio -│ │ ├── value-objects/ # Objetos de valor -│ │ ├── errors/ # Erros de domínio -│ │ └── validators/ # Validadores de negócio -│ │ -│ ├── application/ # Camada de Aplicação (Use Cases) -│ │ ├── services/ # Serviços de aplicação -│ │ ├── use-cases/ # Casos de uso específicos -│ │ └── ports/ # Interfaces/Contratos -│ │ ├── repositories/ # Interfaces de repositórios -│ │ ├── formatters/ # Interfaces de formatadores -│ │ ├── providers/ # Interfaces de provedores -│ │ └── logger.js # Interface de logger -│ │ -│ ├── infrastructure/ # Camada de Infraestrutura -│ │ ├── repositories/ # Implementações de repositórios -│ │ ├── formatters/ # Implementações de formatadores -│ │ ├── providers/ # Implementações de provedores -│ │ ├── logger/ # Implementação de logger -│ │ ├── database/ # Conexões e configs de DB -│ │ ├── cache/ # Cache (Redis, Memory, etc) -│ │ ├── http/ # Clientes HTTP -│ │ └── platform/ # Utilitários específicos de plataforma -│ │ -│ ├── presentation/ # Camada de Apresentação -│ │ ├── cli/ # Interface CLI -│ │ ├── api/ # REST API (se aplicável) -│ │ ├── controllers/ # Controllers -│ │ └── middleware/ # Middlewares -│ │ -│ ├── config/ # Configurações -│ │ ├── config.js # Configuração principal -│ │ └── schemas.js # Schemas de validação (Zod) -│ │ -│ └── index.js # Entry point -│ -├── tests/ -│ ├── unit/ # Testes unitários -│ │ ├── domain/ -│ │ ├── application/ -│ │ └── infrastructure/ -│ ├── integration/ # Testes de integração -│ └── e2e/ # Testes end-to-end -│ └── fixtures/ # Dados de teste -│ └── helpers/ # Helpers de teste -│ -├── .env.example # Template de variáveis de ambiente -├── package.json -└── README.md -``` - ---- - -## 🏗️ Camadas da Arquitetura - -### 1️⃣ Domain Layer (Núcleo do Negócio) - -**Responsabilidade:** Contém as regras de negócio puras, independentes de frameworks ou infraestrutura. - -**Características:** -- ✅ Sem dependências externas -- ✅ Apenas lógica de negócio -- ✅ Altamente testável -- ✅ Reutilizável - -#### 📄 Entities (Entidades) - -Objetos que representam conceitos do domínio com identidade única. - -```javascript -export class ChatSession { - constructor({ id, workspaceId, messages, createdAt, updatedAt }) { - this.id = id; - this.workspaceId = workspaceId; - this.messages = messages || []; - this.createdAt = createdAt || new Date(); - this.updatedAt = updatedAt || new Date(); - } - - addMessage(message) { - this.messages.push(message); - this.updatedAt = new Date(); - } - - getMessageCount() { - return this.messages.length; - } - - isRecent(daysThreshold = 7) { - const daysDiff = (Date.now() - this.createdAt) / (1000 * 60 * 60 * 24); - return daysDiff <= daysThreshold; - } -} -``` - -#### 📄 Value Objects (Objetos de Valor) - -Objetos imutáveis que representam valores sem identidade única. - -```javascript -export class ChatMessage { - constructor({ role, content, timestamp }) { - this.role = role; - this.content = content; - this.timestamp = timestamp || new Date(); - Object.freeze(this); - } - - isFromUser() { - return this.role === 'user'; - } - - isFromAssistant() { - return this.role === 'assistant'; - } -} -``` - -#### 📄 Domain Errors - -Erros específicos do domínio que representam violações de regras de negócio. - -```javascript -export class DomainError extends Error { - constructor(message, metadata = {}) { - super(message); - this.name = this.constructor.name; - this.metadata = metadata; - Error.captureStackTrace(this, this.constructor); - } -} - -export class InvalidSessionError extends DomainError { - constructor(message, metadata) { - super(message, metadata); - } -} - -export class SessionNotFoundError extends DomainError { - constructor(sessionId) { - super('Session not found', { sessionId }); - } -} -``` - -#### 📄 Validators - -Validadores de regras de negócio. - -```javascript -import { z } from 'zod'; - -export const chatMessageSchema = z.object({ - role: z.enum(['user', 'assistant', 'system']), - content: z.string().min(1), - timestamp: z.date().optional() -}); - -export const chatSessionSchema = z.object({ - id: z.string().uuid(), - workspaceId: z.string(), - messages: z.array(chatMessageSchema), - createdAt: z.date(), - updatedAt: z.date() -}); - -export function validateChatMessage(data) { - return chatMessageSchema.parse(data); -} - -export function validateChatSession(data) { - return chatSessionSchema.parse(data); -} -``` - ---- - -### 2️⃣ Application Layer (Casos de Uso) - -**Responsabilidade:** Orquestra a lógica de aplicação usando as regras do domínio. - -**Características:** -- ✅ Coordena entidades do domínio -- ✅ Define interfaces (ports) -- ✅ Implementa casos de uso -- ✅ Independente de frameworks - -#### 📄 Ports (Interfaces) - -Contratos que definem como a aplicação se comunica com o mundo externo. - -```javascript -export class SessionRepository { - async findAll() { - throw new Error('Method not implemented'); - } - - async findById(id) { - throw new Error('Method not implemented'); - } - - async findByWorkspace(workspaceId) { - throw new Error('Method not implemented'); - } - - async save(session) { - throw new Error('Method not implemented'); - } -} - -export class Formatter { - format(data) { - throw new Error('Method not implemented'); - } -} - -export class Logger { - info(message, metadata) { - throw new Error('Method not implemented'); - } - - error(message, metadata) { - throw new Error('Method not implemented'); - } - - warn(message, metadata) { - throw new Error('Method not implemented'); - } - - debug(message, metadata) { - throw new Error('Method not implemented'); - } -} -``` - -#### 📄 Services - -Serviços de aplicação que implementam a lógica de negócio complexa. - -```javascript -export class SessionReaderService { - constructor({ sessionRepository, formatter, logger }) { - this.sessionRepository = sessionRepository; - this.formatter = formatter; - this.logger = logger; - } - - async readAllSessions(options = {}) { - this.logger.info('Reading all sessions', options); - - try { - const sessions = await this.sessionRepository.findAll(); - - const filtered = this.filterSessions(sessions, options); - const sorted = this.sortSessions(filtered, options); - const formatted = this.formatter.format(sorted); - - this.logger.info('Sessions read successfully', { - count: sorted.length - }); - - return formatted; - } catch (error) { - this.logger.error('Failed to read sessions', { error }); - throw error; - } - } - - async searchInSessions(keyword, options = {}) { - this.logger.info('Searching sessions', { keyword, options }); - - const sessions = await this.sessionRepository.findAll(); - const matches = sessions.filter(session => - session.messages.some(msg => - msg.content.toLowerCase().includes(keyword.toLowerCase()) - ) - ); - - return this.formatter.format(matches); - } - - filterSessions(sessions, { startDate, endDate, workspaceId } = {}) { - return sessions.filter(session => { - if (startDate && session.createdAt < startDate) return false; - if (endDate && session.createdAt > endDate) return false; - if (workspaceId && session.workspaceId !== workspaceId) return false; - return true; - }); - } - - sortSessions(sessions, { sortBy = 'createdAt', order = 'desc' } = {}) { - return sessions.sort((a, b) => { - const compareValue = order === 'asc' ? 1 : -1; - return (a[sortBy] > b[sortBy] ? 1 : -1) * compareValue; - }); - } -} -``` - -#### 📄 Use Cases - -Casos de uso específicos que representam ações do sistema. - -```javascript -export class GetSessionByIdUseCase { - constructor({ sessionRepository, logger }) { - this.sessionRepository = sessionRepository; - this.logger = logger; - } - - async execute(sessionId) { - this.logger.debug('Getting session by id', { sessionId }); - - if (!sessionId) { - throw new InvalidSessionError('Session ID is required'); - } - - const session = await this.sessionRepository.findById(sessionId); - - if (!session) { - throw new SessionNotFoundError(sessionId); - } - - this.logger.debug('Session found', { sessionId }); - return session; - } -} - -export class ExportSessionsUseCase { - constructor({ sessionRepository, formatter, fileWriter, logger }) { - this.sessionRepository = sessionRepository; - this.formatter = formatter; - this.fileWriter = fileWriter; - this.logger = logger; - } - - async execute(outputPath, options = {}) { - this.logger.info('Exporting sessions', { outputPath, options }); - - const sessions = await this.sessionRepository.findAll(); - const formatted = this.formatter.format(sessions); - - await this.fileWriter.write(outputPath, formatted); - - this.logger.info('Sessions exported successfully', { - outputPath, - count: sessions.length - }); - - return { outputPath, count: sessions.length }; - } -} -``` - ---- - -### 3️⃣ Infrastructure Layer (Implementações) - -**Responsabilidade:** Implementações concretas de ports, integração com frameworks e ferramentas. - -**Características:** -- ✅ Implementa interfaces definidas em Application -- ✅ Integra com bibliotecas externas -- ✅ Lida com I/O (file system, database, API) -- ✅ Específico de plataforma - -#### 📄 Repositories - -Implementações concretas de acesso aos dados. - -```javascript -import fs from 'node:fs/promises'; -import path from 'node:path'; -import { SessionRepository } from '../../application/ports/repositories/session-repository.js'; -import { ChatSession } from '../../domain/entities/chat-session.js'; - -export class VSCodeSessionRepository extends SessionRepository { - constructor({ pathResolver, logger }) { - super(); - this.pathResolver = pathResolver; - this.logger = logger; - } - - async findAll() { - const sessionPaths = await this.pathResolver.getAllSessionPaths(); - const sessions = []; - - for (const sessionPath of sessionPaths) { - try { - const session = await this.loadSession(sessionPath); - sessions.push(session); - } catch (error) { - this.logger.warn('Failed to load session', { sessionPath, error }); - } - } - - return sessions; - } - - async findById(id) { - const sessionPath = await this.pathResolver.getSessionPath(id); - return this.loadSession(sessionPath); - } - - async findByWorkspace(workspaceId) { - const sessions = await this.findAll(); - return sessions.filter(s => s.workspaceId === workspaceId); - } - - async loadSession(filePath) { - const content = await fs.readFile(filePath, 'utf-8'); - const data = JSON.parse(content); - return new ChatSession(data); - } - - async save(session) { - const filePath = await this.pathResolver.getSessionPath(session.id); - await fs.writeFile(filePath, JSON.stringify(session, null, 2)); - } -} -``` - -#### 📄 Formatters - -Implementações de formatação de dados. - -```javascript -import { Formatter } from '../../application/ports/formatter.js'; - -export class ConsoleFormatter extends Formatter { - format(sessions) { - const lines = []; - - for (const session of sessions) { - lines.push(this.formatSessionHeader(session)); - - for (const message of session.messages) { - lines.push(this.formatMessage(message)); - } - - lines.push(this.formatSessionFooter()); - } - - return lines.join('\n'); - } - - formatSessionHeader(session) { - return [ - '\n' + '='.repeat(80), - `📝 Session: ${session.id}`, - `📁 Workspace: ${session.workspaceId}`, - `📅 Created: ${session.createdAt.toISOString()}`, - '='.repeat(80) - ].join('\n'); - } - - formatMessage(message) { - const icon = message.isFromUser() ? '👤' : '🤖'; - const role = message.role.toUpperCase(); - return `\n${icon} ${role}:\n${message.content}`; - } - - formatSessionFooter() { - return '-'.repeat(80); - } -} - -export class JsonFormatter extends Formatter { - format(sessions) { - return JSON.stringify(sessions, null, 2); - } -} - -export class MarkdownFormatter extends Formatter { - format(sessions) { - const lines = []; - - for (const session of sessions) { - lines.push(`# Session: ${session.id}`); - lines.push(`**Workspace:** ${session.workspaceId}`); - lines.push(`**Created:** ${session.createdAt.toISOString()}`); - lines.push(''); - - for (const message of session.messages) { - const role = message.isFromUser() ? 'User' : 'Assistant'; - lines.push(`## ${role}`); - lines.push(message.content); - lines.push(''); - } - - lines.push('---'); - lines.push(''); - } - - return lines.join('\n'); - } -} -``` - -#### 📄 Platform - -Utilitários específicos de plataforma. - -```javascript -import os from 'node:os'; -import path from 'node:path'; -import fs from 'node:fs/promises'; - -export class VSCodePathResolver { - constructor({ config, logger }) { - this.config = config; - this.logger = logger; - } - - getVSCodeUserDataPath() { - switch (os.platform()) { - case 'win32': - return path.join(os.homedir(), 'AppData', 'Roaming', 'Code', 'User'); - case 'darwin': - return path.join(os.homedir(), 'Library', 'Application Support', 'Code', 'User'); - case 'linux': - return path.join(os.homedir(), '.config', 'Code', 'User'); - default: - throw new Error(`Unsupported platform: ${os.platform()}`); - } - } - - getWorkspaceStoragePath() { - return path.join(this.getVSCodeUserDataPath(), 'workspaceStorage'); - } - - getChatSessionsPath(workspaceId) { - return path.join( - this.getWorkspaceStoragePath(), - workspaceId, - 'ms-vscode.copilot-chat', - 'chatSessions' - ); - } - - async getAllSessionPaths() { - const workspaceStorage = this.getWorkspaceStoragePath(); - const workspaces = await fs.readdir(workspaceStorage); - const sessionPaths = []; - - for (const workspace of workspaces) { - const chatPath = this.getChatSessionsPath(workspace); - - try { - const files = await fs.readdir(chatPath); - const jsonFiles = files - .filter(f => f.endsWith('.json')) - .map(f => path.join(chatPath, f)); - - sessionPaths.push(...jsonFiles); - } catch (error) { - if (error.code !== 'ENOENT') { - this.logger.warn('Failed to read workspace', { workspace, error }); - } - } - } - - return sessionPaths; - } - - async getSessionPath(sessionId) { - const allPaths = await this.getAllSessionPaths(); - return allPaths.find(p => p.includes(sessionId)); - } -} -``` - -#### 📄 Logger - -Implementação de logging estruturado. - -```javascript -import pino from 'pino'; -import { Logger } from '../../application/ports/logger.js'; - -export class PinoLogger extends Logger { - constructor(options = {}) { - super(); - this.logger = pino({ - level: options.level || 'info', - transport: options.pretty ? { - target: 'pino-pretty', - options: { - colorize: true, - translateTime: 'SYS:standard', - ignore: 'pid,hostname' - } - } : undefined - }); - } - - info(message, metadata = {}) { - this.logger.info(metadata, message); - } - - error(message, metadata = {}) { - this.logger.error(metadata, message); - } - - warn(message, metadata = {}) { - this.logger.warn(metadata, message); - } - - debug(message, metadata = {}) { - this.logger.debug(metadata, message); - } -} -``` - ---- - -### 4️⃣ Presentation Layer (Interface) - -**Responsabilidade:** Interface com o usuário (CLI, API, etc). - -**Características:** -- ✅ Recebe inputs do usuário -- ✅ Valida argumentos -- ✅ Chama use cases -- ✅ Apresenta resultados - -#### 📄 CLI - -Interface de linha de comando. - -```javascript -import { Command } from 'commander'; - -export class CLI { - constructor({ sessionService, exportUseCase, logger }) { - this.sessionService = sessionService; - this.exportUseCase = exportUseCase; - this.logger = logger; - this.program = new Command(); - } - - setup() { - this.program - .name('session-reader') - .description('Read and manage VS Code chat sessions') - .version('1.0.0'); - - this.program - .command('list') - .description('List all chat sessions') - .option('-w, --workspace ', 'Filter by workspace') - .option('-s, --sort ', 'Sort by field', 'createdAt') - .option('-o, --order ', 'Sort order', 'desc') - .action(async (options) => { - try { - const result = await this.sessionService.readAllSessions(options); - console.log(result); - } catch (error) { - this.logger.error('Failed to list sessions', { error }); - process.exit(1); - } - }); - - this.program - .command('search ') - .description('Search in sessions') - .action(async (keyword, options) => { - try { - const result = await this.sessionService.searchInSessions(keyword, options); - console.log(result); - } catch (error) { - this.logger.error('Failed to search sessions', { error }); - process.exit(1); - } - }); - - this.program - .command('export ') - .description('Export sessions to file') - .option('-f, --format ', 'Output format', 'json') - .action(async (output, options) => { - try { - const result = await this.exportUseCase.execute(output, options); - console.log(`✅ Exported ${result.count} sessions to ${result.outputPath}`); - } catch (error) { - this.logger.error('Failed to export sessions', { error }); - process.exit(1); - } - }); - } - - async run(args) { - await this.program.parseAsync(args); - } -} -``` - ---- - -### 5️⃣ Config Layer (Configuração) - -**Responsabilidade:** Gerenciar configurações da aplicação. - -#### 📄 Config - -```javascript -import 'dotenv/config'; -import { z } from 'zod'; - -const configSchema = z.object({ - NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), - LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'), - LOG_PRETTY: z.coerce.boolean().default(true), - VSCODE_PATH: z.string().optional(), - OUTPUT_FORMAT: z.enum(['console', 'json', 'markdown']).default('console') -}); - -export const config = configSchema.parse(process.env); - -export function validateConfig() { - try { - configSchema.parse(process.env); - return { valid: true }; - } catch (error) { - return { - valid: false, - errors: error.errors.map(e => ({ - path: e.path.join('.'), - message: e.message - })) - }; - } -} -``` - ---- - -### 6️⃣ Entry Point (Index) - -**Responsabilidade:** Composição de dependências (Dependency Injection Container). - -```javascript -import { config } from './config/config.js'; -import { PinoLogger } from './infrastructure/logger/pino-logger.js'; -import { VSCodePathResolver } from './infrastructure/platform/vscode-path-resolver.js'; -import { VSCodeSessionRepository } from './infrastructure/repositories/vscode-session-repository.js'; -import { ConsoleFormatter } from './infrastructure/formatters/console-formatter.js'; -import { JsonFormatter } from './infrastructure/formatters/json-formatter.js'; -import { MarkdownFormatter } from './infrastructure/formatters/markdown-formatter.js'; -import { SessionReaderService } from './application/services/session-reader-service.js'; -import { GetSessionByIdUseCase } from './application/use-cases/get-session-by-id.js'; -import { ExportSessionsUseCase } from './application/use-cases/export-sessions.js'; -import { CLI } from './presentation/cli/cli.js'; - -function createContainer() { - const logger = new PinoLogger({ - level: config.LOG_LEVEL, - pretty: config.LOG_PRETTY - }); - - const pathResolver = new VSCodePathResolver({ config, logger }); - - const sessionRepository = new VSCodeSessionRepository({ - pathResolver, - logger - }); - - const formatters = { - console: new ConsoleFormatter(), - json: new JsonFormatter(), - markdown: new MarkdownFormatter() - }; - - const formatter = formatters[config.OUTPUT_FORMAT]; - - const sessionService = new SessionReaderService({ - sessionRepository, - formatter, - logger - }); - - const getSessionByIdUseCase = new GetSessionByIdUseCase({ - sessionRepository, - logger - }); - - const exportUseCase = new ExportSessionsUseCase({ - sessionRepository, - formatter, - fileWriter: { write: async (path, content) => {} }, - logger - }); - - return { - logger, - sessionService, - getSessionByIdUseCase, - exportUseCase, - cli: new CLI({ - sessionService, - exportUseCase, - logger - }) - }; -} - -export async function main(args = process.argv) { - const container = createContainer(); - - try { - await container.cli.setup(); - await container.cli.run(args); - } catch (error) { - container.logger.error('Application failed', { error }); - process.exit(1); - } -} - -if (import.meta.url === `file://${process.argv[1]}`) { - main(); -} -``` - ---- - -## 🧪 Testing Strategy - -### Unit Tests - -Testam componentes isoladamente com mocks. - -```javascript -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { SessionReaderService } from '../../../src/application/services/session-reader-service.js'; - -describe('SessionReaderService', () => { - let service; - let mockRepository; - let mockFormatter; - let mockLogger; - - beforeEach(() => { - mockRepository = { - findAll: vi.fn() - }; - mockFormatter = { - format: vi.fn(data => JSON.stringify(data)) - }; - mockLogger = { - info: vi.fn(), - error: vi.fn() - }; - - service = new SessionReaderService({ - sessionRepository: mockRepository, - formatter: mockFormatter, - logger: mockLogger - }); - }); - - it('should read all sessions', async () => { - const mockSessions = [ - { id: '1', messages: [] }, - { id: '2', messages: [] } - ]; - mockRepository.findAll.mockResolvedValue(mockSessions); - - const result = await service.readAllSessions(); - - expect(mockRepository.findAll).toHaveBeenCalled(); - expect(mockFormatter.format).toHaveBeenCalledWith(mockSessions); - expect(result).toBe(JSON.stringify(mockSessions)); - }); - - it('should filter sessions by workspace', async () => { - const sessions = [ - { id: '1', workspaceId: 'ws1', messages: [] }, - { id: '2', workspaceId: 'ws2', messages: [] } - ]; - mockRepository.findAll.mockResolvedValue(sessions); - - await service.readAllSessions({ workspaceId: 'ws1' }); - - expect(mockFormatter.format).toHaveBeenCalledWith([sessions[0]]); - }); -}); -``` - -### Integration Tests - -Testam integração entre componentes reais. - -```javascript -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { createTestContainer } from '../helpers/test-container.js'; - -describe('Session Reading Integration', () => { - let container; - - beforeAll(async () => { - container = await createTestContainer(); - }); - - afterAll(async () => { - await container.cleanup(); - }); - - it('should read sessions from file system', async () => { - const sessions = await container.sessionService.readAllSessions(); - - expect(sessions).toBeDefined(); - expect(Array.isArray(sessions)).toBe(true); - }); -}); -``` - ---- - -## 📦 Package.json Configuration - -```json -{ - "name": "module-name", - "version": "1.0.0", - "type": "module", - "description": "Module description", - "main": "src/index.js", - "scripts": { - "start": "node src/index.js", - "dev": "node --watch src/index.js", - "test": "vitest", - "test:coverage": "vitest --coverage", - "test:ui": "vitest --ui", - "lint": "eslint src/**/*.js", - "format": "prettier --write src/**/*.js" - }, - "dependencies": { - "zod": "^3.22.0", - "dotenv": "^16.3.0", - "pino": "^8.16.0", - "pino-pretty": "^10.2.0", - "commander": "^11.1.0" - }, - "devDependencies": { - "vitest": "^1.0.0", - "@vitest/ui": "^1.0.0", - "eslint": "^8.54.0", - "prettier": "^3.1.0" - } -} -``` - ---- - -## 📝 Design Patterns Aplicados - -### 1. Repository Pattern -Abstração de acesso aos dados, permitindo trocar fonte sem afetar lógica. - -### 2. Strategy Pattern -Múltiplas implementações de formatadores, loggers, etc. - -### 3. Dependency Injection -Inversão de controle através de injeção no construtor. - -### 4. Factory Pattern -Criação de objetos complexos (container de dependências). - -### 5. Use Case Pattern -Cada ação do sistema é um caso de uso isolado. - -### 6. Port & Adapter (Hexagonal Architecture) -Portas definem interfaces, adapters implementam. - ---- - -## 🎯 Checklist de Qualidade - -Antes de considerar um módulo completo, verifique: - -- [ ] Todas as camadas estão implementadas -- [ ] Dependências injetadas via construtor -- [ ] Nenhuma dependência circular -- [ ] Configurações externalizadas em .env -- [ ] Erros customizados para domínio -- [ ] Logging estruturado implementado -- [ ] Validação de inputs com Zod -- [ ] Cobertura de testes > 80% -- [ ] Testes unitários para lógica de negócio -- [ ] Testes de integração para I/O -- [ ] README com instruções claras -- [ ] JSDoc para documentação de tipos -- [ ] ESM modules (import/export) -- [ ] Async/await consistentemente -- [ ] Error handling robusto -- [ ] Multiplataforma (Windows/Mac/Linux) - ---- - -## 🚀 Benefícios desta Arquitetura - -### ✅ Manutenibilidade -Código organizado e fácil de encontrar. - -### ✅ Testabilidade -Lógica isolada e mockável. - -### ✅ Escalabilidade -Adicione features sem quebrar existentes. - -### ✅ Flexibilidade -Troque implementações sem afetar lógica. - -### ✅ Reusabilidade -Componentes podem ser reutilizados. - -### ✅ Documentação -Estrutura auto-explicativa. - -### ✅ Onboarding -Novos devs entendem rapidamente. - ---- - -## 📚 Referências - -- Clean Architecture (Robert C. Martin) -- Domain-Driven Design (Eric Evans) -- SOLID Principles -- Hexagonal Architecture (Ports & Adapters) -- Test-Driven Development (TDD) - ---- - -**Versão:** 1.0.0 -**Data:** 2025-10-11 -**Autor:** React Native Agentic Updater Team - diff --git a/shared/templates/automation/template.automation-environment.md b/shared/templates/automation/template.automation-environment.md deleted file mode 100644 index c4e76f4..0000000 --- a/shared/templates/automation/template.automation-environment.md +++ /dev/null @@ -1,314 +0,0 @@ -# Template: Configuração de Ambiente - - - -**Criado**: 2025-01-17 -**Versão**: 1.0.0 - -## Estrutura do JSON - -```json -{ - "metadata": { - "featureId": "[FEATURE_ID]", - "featureName": "[FEATURE_NAME]", - "description": "[DESCRIPTION]", - "version": "1.0.0", - "createdAt": "[ISO_8601_TIMESTAMP]", - "createdBy": "[AUTHOR]", - "tags": ["[TAG1]", "[TAG2]"], - "priority": "[LOW|MEDIUM|HIGH|CRITICAL]" - }, - "environment": { - "baseUrl": "[BASE_URL]", - "apiUrl": "[API_URL]", - "timeout": 30000, - "retries": 2, - "headless": false, - "browsers": ["chromium", "firefox", "webkit"], - "viewport": { - "width": 1920, - "height": 1080 - } - }, - "urls": { - "[PAGE_NAME]": "[FULL_URL]", - "[PAGE_NAME_2]": "[FULL_URL_2]" - }, - "endpoints": { - "[ENDPOINT_NAME]": { - "method": "[GET|POST|PUT|DELETE]", - "path": "[PATH]", - "headers": { - "[HEADER_NAME]": "[HEADER_VALUE]" - } - } - }, - "credentials": { - "[USER_TYPE]": { - "username": "[USERNAME_REFERENCE]", - "password": "[PASSWORD_REFERENCE]", - "note": "Usar variáveis de ambiente: USERNAME_[TYPE], PASSWORD_[TYPE]" - } - }, - "schemas": { - "[SCHEMA_NAME]": { - "type": "object", - "properties": { - "[PROPERTY_NAME]": { - "type": "[string|number|boolean|object|array]", - "required": true, - "description": "[DESCRIPTION]" - } - } - } - }, - "validations": { - "[VALIDATION_NAME]": { - "type": "[ELEMENT_VISIBLE|TEXT_MATCH|URL_MATCH|COUNT]", - "selector": "[SELECTOR]", - "expectedValue": "[EXPECTED_VALUE]", - "timeout": 5000 - } - } -} -``` - -## Seções do Template - -### 1. Metadados *(obrigatório)* - -```json -"metadata": { - "featureId": "[FEATURE_ID]", - "featureName": "[FEATURE_NAME]", - "description": "[DESCRIPTION]", - "version": "1.0.0", - "createdAt": "[ISO_8601_TIMESTAMP]", - "createdBy": "[AUTHOR]", - "tags": ["[TAG1]", "[TAG2]"], - "priority": "[LOW|MEDIUM|HIGH|CRITICAL]" -} -``` - -**Orientação**: -- featureId: Identificador único da feature (ex: "login-flow") -- featureName: Nome legível da feature (ex: "Login Flow") -- description: Descrição breve do que a automação faz -- version: Versão semântica (começar com 1.0.0) -- createdAt: Timestamp ISO 8601 (ex: "2025-01-17T10:30:00Z") -- createdBy: Nome do autor -- tags: Tags para categorização (ex: ["auth", "critical", "e2e"]) -- priority: Prioridade da automação - -### 2. Configuração de Ambiente *(obrigatório)* - -```json -"environment": { - "baseUrl": "[BASE_URL]", - "apiUrl": "[API_URL]", - "timeout": 30000, - "retries": 2, - "headless": false, - "browsers": ["chromium", "firefox", "webkit"], - "viewport": { - "width": 1920, - "height": 1080 - } -} -``` - -**Orientação**: -- baseUrl: URL base da aplicação (ex: "https://app.example.com") -- apiUrl: URL base da API (ex: "https://api.example.com/v1") -- timeout: Timeout padrão em ms (30000 = 30s) -- retries: Número de tentativas em caso de falha -- headless: Executar sem UI (false para debug) -- browsers: Lista de navegadores para testar -- viewport: Resolução da viewport - -### 3. URLs *(obrigatório)* - -```json -"urls": { - "[PAGE_NAME]": "[FULL_URL]", - "[PAGE_NAME_2]": "[FULL_URL_2]" -} -``` - -**Orientação**: -- Criar entrada para cada página/rota -- Usar chave descritiva (ex: "login", "dashboard", "checkout") -- URL completa ou relativa à baseUrl -- Exemplo: - ```json - "urls": { - "login": "/login", - "dashboard": "/dashboard", - "checkout": "/checkout" - } - ``` - -### 4. Endpoints *(opcional - incluir se há integração com API)* - -```json -"endpoints": { - "[ENDPOINT_NAME]": { - "method": "[GET|POST|PUT|DELETE]", - "path": "[PATH]", - "headers": { - "[HEADER_NAME]": "[HEADER_VALUE]" - } - } -} -``` - -**Orientação**: -- Documentar endpoints de API usados -- Incluir método HTTP -- Incluir path completo -- Incluir headers necessários -- Exemplo: - ```json - "endpoints": { - "login": { - "method": "POST", - "path": "/api/auth/login", - "headers": { - "Content-Type": "application/json" - } - } - } - ``` - -### 5. Credenciais *(obrigatório - referências, não valores)* - -```json -"credentials": { - "[USER_TYPE]": { - "username": "[USERNAME_REFERENCE]", - "password": "[PASSWORD_REFERENCE]", - "note": "Usar variáveis de ambiente: USERNAME_[TYPE], PASSWORD_[TYPE]" - } -} -``` - -**Orientação**: -- NUNCA incluir credenciais reais no JSON -- Usar referências a variáveis de ambiente -- Documentar como obter credenciais -- Exemplo: - ```json - "credentials": { - "admin": { - "username": "process.env.ADMIN_USERNAME", - "password": "process.env.ADMIN_PASSWORD", - "note": "Configurar variáveis ADMIN_USERNAME e ADMIN_PASSWORD" - }, - "user": { - "username": "process.env.USER_USERNAME", - "password": "process.env.USER_PASSWORD", - "note": "Configurar variáveis USER_USERNAME e USER_PASSWORD" - } - } - ``` - -### 6. Schemas *(opcional - incluir se há validação de dados)* - -```json -"schemas": { - "[SCHEMA_NAME]": { - "type": "object", - "properties": { - "[PROPERTY_NAME]": { - "type": "[string|number|boolean|object|array]", - "required": true, - "description": "[DESCRIPTION]" - } - } - } -} -``` - -**Orientação**: -- Definir schemas para validação de dados -- Usar formato JSON Schema -- Documentar tipos e validações -- Exemplo: - ```json - "schemas": { - "user": { - "type": "object", - "properties": { - "email": { - "type": "string", - "required": true, - "description": "Email do usuário" - }, - "password": { - "type": "string", - "required": true, - "minLength": 8, - "description": "Senha do usuário (mínimo 8 caracteres)" - } - } - } - } - ``` - -### 7. Validações *(opcional - incluir se há validações customizadas)* - -```json -"validations": { - "[VALIDATION_NAME]": { - "type": "[ELEMENT_VISIBLE|TEXT_MATCH|URL_MATCH|COUNT]", - "selector": "[SELECTOR]", - "expectedValue": "[EXPECTED_VALUE]", - "timeout": 5000 - } -} -``` - -**Orientação**: -- Definir validações reutilizáveis -- Tipos comuns: ELEMENT_VISIBLE, TEXT_MATCH, URL_MATCH, COUNT -- Incluir selector e valor esperado -- Configurar timeout específico -- Exemplo: - ```json - "validations": { - "loginSuccess": { - "type": "URL_MATCH", - "selector": null, - "expectedValue": "/dashboard", - "timeout": 5000 - }, - "errorMessage": { - "type": "TEXT_MATCH", - "selector": ".error-message", - "expectedValue": "Credenciais inválidas", - "timeout": 3000 - } - } - ``` - -## Checklist de Qualidade - -Antes de considerar o environment.json completo: - -- [ ] Metadados preenchidos (featureId, nome, descrição, etc) -- [ ] Configuração de ambiente definida (URLs, timeouts, browsers) -- [ ] URLs de todas as páginas documentadas -- [ ] Endpoints de API documentados (se aplicável) -- [ ] Credenciais como referências (não valores reais) -- [ ] Schemas de validação definidos (se aplicável) -- [ ] Validações customizadas documentadas (se aplicável) -- [ ] JSON válido (sem erros de sintaxe) -- [ ] Valores de exemplo substituídos por valores reais -- [ ] Documentação clara de uso -- [ ] Sem informações sensíveis expostas - diff --git a/shared/templates/automation/template.automation-index.md b/shared/templates/automation/template.automation-index.md deleted file mode 100644 index 755baeb..0000000 --- a/shared/templates/automation/template.automation-index.md +++ /dev/null @@ -1,397 +0,0 @@ -# Template: Index da Feature - - - -**Criado**: 2025-01-17 -**Versão**: 1.0.0 - -## Estrutura do JSON - -```json -{ - "metadata": { - "featureId": "[FEATURE_ID]", - "featureName": "[FEATURE_NAME]", - "description": "[DESCRIPTION]", - "version": "1.0.0", - "createdAt": "[ISO_8601_TIMESTAMP]", - "createdBy": "[AUTHOR]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "tags": ["[TAG1]", "[TAG2]"], - "priority": "[LOW|MEDIUM|HIGH|CRITICAL]", - "status": "[draft|active|deprecated]" - }, - "structure": { - "basePath": "vibes/automations/domain/[FEATURE_ID]", - "files": { - "script": "script.[nome].js", - "environment": "environment.json", - "testData": "test.data.json", - "selectors": "selectors.json", - "index": "index.json" - }, - "directories": { - "pageObjects": "page-objects/", - "fixtures": "fixtures/", - "utils": "utils/" - } - }, - "dependencies": { - "commons": { - "components": ["[COMPONENT_1]", "[COMPONENT_2]"], - "helpers": ["[HELPER_1]", "[HELPER_2]"] - }, - "external": ["[LIBRARY_1]", "[LIBRARY_2]"] - }, - "testSuites": [ - { - "id": "[SUITE_ID]", - "name": "[SUITE_NAME]", - "description": "[DESCRIPTION]", - "file": "script.[nome].js", - "scenarios": [ - { - "id": "[SCENARIO_ID]", - "name": "[SCENARIO_NAME]", - "type": "[positive|negative|edge]", - "description": "[DESCRIPTION]", - "steps": [ - { - "action": "[ACTION]", - "target": "[TARGET]", - "data": "[DATA_REFERENCE]", - "expected": "[EXPECTED_RESULT]" - } - ] - } - ] - } - ], - "pages": { - "[PAGE_NAME]": { - "url": "[PAGE_URL]", - "elements": ["[ELEMENT_1]", "[ELEMENT_2]"], - "actions": ["[ACTION_1]", "[ACTION_2]"], - "validations": ["[VALIDATION_1]", "[VALIDATION_2]"] - } - }, - "data": { - "testData": { - "file": "test.data.json", - "users": ["[USER_TYPE_1]", "[USER_TYPE_2]"], - "scenarios": ["[SCENARIO_1]", "[SCENARIO_2]"], - "products": ["[PRODUCT_1]", "[PRODUCT_2]"] - }, - "fixtures": { - "file": "fixtures/", - "items": ["[FIXTURE_1]", "[FIXTURE_2]"] - } - }, - "selectors": { - "file": "selectors.json", - "strategy": "data-testid-first", - "pages": ["[PAGE_1]", "[PAGE_2]"], - "components": ["[COMPONENT_1]", "[COMPONENT_2]"], - "common": ["[COMMON_1]", "[COMMON_2]"] - }, - "environment": { - "file": "environment.json", - "baseUrl": "[BASE_URL]", - "browsers": ["[BROWSER_1]", "[BROWSER_2]"], - "timeout": 30000, - "headless": false - }, - "execution": { - "command": "npx playwright test vibes/automations/domain/[FEATURE_ID]/script.[nome].js", - "options": { - "headed": "--headed", - "debug": "--debug", - "ui": "--ui", - "trace": "--trace on" - }, - "reporting": { - "html": true, - "json": true, - "screenshots": true, - "videos": true - } - }, - "documentation": { - "readme": "README.md", - "changelog": "CHANGELOG.md", - "examples": "examples/" - } -} -``` - -## Seções do Template - -### 1. Metadados *(obrigatório)* - -```json -"metadata": { - "featureId": "[FEATURE_ID]", - "featureName": "[FEATURE_NAME]", - "description": "[DESCRIPTION]", - "version": "1.0.0", - "createdAt": "[ISO_8601_TIMESTAMP]", - "createdBy": "[AUTHOR]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "tags": ["[TAG1]", "[TAG2]"], - "priority": "[LOW|MEDIUM|HIGH|CRITICAL]", - "status": "[draft|active|deprecated]" -} -``` - -**Orientação**: -- featureId: Identificador único (ex: "login-flow") -- featureName: Nome legível (ex: "Login Flow") -- description: Descrição breve do que a automação faz -- version: Versão semântica (começar com 1.0.0) -- createdAt: Timestamp ISO 8601 de criação -- createdBy: Nome do autor -- lastUpdated: Timestamp da última atualização -- tags: Tags para categorização (ex: ["auth", "critical", "e2e"]) -- priority: Prioridade da automação -- status: Status atual (draft, active, deprecated) - -### 2. Estrutura de Arquivos *(obrigatório)* - -```json -"structure": { - "basePath": "vibes/automations/domain/[FEATURE_ID]", - "files": { - "script": "script.[nome].js", - "environment": "environment.json", - "testData": "test.data.json", - "selectors": "selectors.json", - "index": "index.json" - }, - "directories": { - "pageObjects": "page-objects/", - "fixtures": "fixtures/", - "utils": "utils/" - } -} -``` - -**Orientação**: -- basePath: Caminho base da feature -- files: Mapeamento de arquivos principais -- directories: Diretórios adicionais (se houver) - -### 3. Dependências *(obrigatório)* - -```json -"dependencies": { - "commons": { - "components": ["[COMPONENT_1]", "[COMPONENT_2]"], - "helpers": ["[HELPER_1]", "[HELPER_2]"] - }, - "external": ["[LIBRARY_1]", "[LIBRARY_2]"] -} -``` - -**Orientação**: -- commons: Componentes e helpers reutilizados de commons/ -- external: Bibliotecas externas necessárias - -### 4. Test Suites *(obrigatório)* - -```json -"testSuites": [ - { - "id": "[SUITE_ID]", - "name": "[SUITE_NAME]", - "description": "[DESCRIPTION]", - "file": "script.[nome].js", - "scenarios": [ - { - "id": "[SCENARIO_ID]", - "name": "[SCENARIO_NAME]", - "type": "[positive|negative|edge]", - "description": "[DESCRIPTION]", - "steps": [ - { - "action": "[ACTION]", - "target": "[TARGET]", - "data": "[DATA_REFERENCE]", - "expected": "[EXPECTED_RESULT]" - } - ] - } - ] - } -] -``` - -**Orientação**: -- Documentar todas as suites de teste -- Cada suite tem cenários -- Cada cenário tem steps detalhados -- Tipos: positive (sucesso), negative (erro), edge (casos limites) - -### 5. Páginas *(obrigatório)* - -```json -"pages": { - "[PAGE_NAME]": { - "url": "[PAGE_URL]", - "elements": ["[ELEMENT_1]", "[ELEMENT_2]"], - "actions": ["[ACTION_1]", "[ACTION_2]"], - "validations": ["[VALIDATION_1]", "[VALIDATION_2]"] - } -} -``` - -**Orientação**: -- Mapear todas as páginas usadas -- Listar elementos principais -- Listar ações disponíveis -- Listar validações realizadas - -### 6. Dados *(obrigatório)* - -```json -"data": { - "testData": { - "file": "test.data.json", - "users": ["[USER_TYPE_1]", "[USER_TYPE_2]"], - "scenarios": ["[SCENARIO_1]", "[SCENARIO_2]"], - "products": ["[PRODUCT_1]", "[PRODUCT_2]"] - }, - "fixtures": { - "file": "fixtures/", - "items": ["[FIXTURE_1]", "[FIXTURE_2]"] - } -} -``` - -**Orientação**: -- Referenciar arquivo de dados de teste -- Listar tipos de usuários disponíveis -- Listar cenários de teste -- Listar produtos (se aplicável) -- Listar fixtures (se aplicável) - -### 7. Seletores *(obrigatório)* - -```json -"selectors": { - "file": "selectors.json", - "strategy": "data-testid-first", - "pages": ["[PAGE_1]", "[PAGE_2]"], - "components": ["[COMPONENT_1]", "[COMPONENT_2]"], - "common": ["[COMMON_1]", "[COMMON_2]"] -} -``` - -**Orientação**: -- Referenciar arquivo de seletores -- Documentar estratégia de seleção -- Listar páginas com seletores -- Listar componentes com seletores -- Listar elementos comuns - -### 8. Ambiente *(obrigatório)* - -```json -"environment": { - "file": "environment.json", - "baseUrl": "[BASE_URL]", - "browsers": ["[BROWSER_1]", "[BROWSER_2]"], - "timeout": 30000, - "headless": false -} -``` - -**Orientação**: -- Referenciar arquivo de ambiente -- Documentar configurações principais -- Listar navegadores suportados - -### 9. Execução *(obrigatório)* - -```json -"execution": { - "command": "npx playwright test vibes/automations/domain/[FEATURE_ID]/script.[nome].js", - "options": { - "headed": "--headed", - "debug": "--debug", - "ui": "--ui", - "trace": "--trace on" - }, - "reporting": { - "html": true, - "json": true, - "screenshots": true, - "videos": true - } -} -``` - -**Orientação**: -- Comando base de execução -- Opções de execução disponíveis -- Tipos de relatórios gerados - -### 10. Documentação *(opcional)* - -```json -"documentation": { - "readme": "README.md", - "changelog": "CHANGELOG.md", - "examples": "examples/" -} -``` - -**Orientação**: -- Referenciar arquivos de documentação -- README principal -- CHANGELOG de versões -- Exemplos de uso - -## Checklist de Qualidade - -Antes de considerar o index.json completo: - -- [ ] Metadados preenchidos (featureId, nome, descrição, etc) -- [ ] Estrutura de arquivos documentada -- [ ] Dependências listadas (commons e external) -- [ ] Test suites documentadas com cenários -- [ ] Páginas mapeadas com elementos e ações -- [ ] Dados referenciados (testData, fixtures) -- [ ] Seletores referenciados -- [ ] Ambiente configurado -- [ ] Comandos de execução documentados -- [ ] Documentação referenciada -- [ ] JSON válido (sem erros de sintaxe) -- [ ] Todas as referências de arquivos corretas -- [ ] Hierarquia completa documentada - -## Benefícios - -### Centralização -- Toda a informação da feature em um único arquivo -- Fácil de localizar e navegar -- Reduz fragmentação de documentação - -### Programabilidade -- Fácil de parsear com scripts -- Permite automação de tarefas -- Facilita geração de relatórios - -### Manutenibilidade -- Atualização em um único lugar -- Menos arquivos para manter -- Menos risco de inconsistência - -### Navegação -- Hierarquia completa visível -- Dependências claras -- Estrutura de arquivos explícita - diff --git a/shared/templates/automation/template.automation-script.md b/shared/templates/automation/template.automation-script.md deleted file mode 100644 index d84fc68..0000000 --- a/shared/templates/automation/template.automation-script.md +++ /dev/null @@ -1,263 +0,0 @@ -# Template: Script de Automação E2E - - - -**Criado**: 2025-01-17 -**Versão**: 1.0.0 - -## Estrutura do Script - -```javascript -import { test, expect } from '@playwright/test'; -import { [FEATURE_NAME]Page } from './page-objects/[feature-name].page'; -import { [HELPER_NAME] } from '../commons/helpers/[helper-name]'; -import testData from './test.data.json'; -import selectors from './selectors.json'; -import environment from './environment.json'; - -test.describe('[FEATURE_NAME]', () => { - let page; - let [featureName]Page; - - test.beforeEach(async ({ page: testPage }) => { - page = testPage; - [featureName]Page = new [FEATURE_NAME]Page(page); - await page.goto(environment.baseUrl); - }); - - test('[SCENARIO_NAME]', async () => { - // Arrange - const testDataItem = testData.[scenarioName]; - - // Act - await [featureName]Page.[action1](); - await [featureName]Page.[action2](testDataItem.[field1]); - - // Assert - await expect(page.locator(selectors.[element])).toBeVisible(); - await expect(page.locator(selectors.[element2])).toHaveText(testDataItem.[expectedValue]); - }); - - test('[SCENARIO_NAME_WITH_ERROR]', async () => { - // Arrange - const testDataItem = testData.[scenarioWithError]; - - // Act - await [featureName]Page.[action1](); - await [featureName]Page.[action2](testDataItem.[invalidField]); - - // Assert - await expect(page.locator(selectors.[errorMessage])).toBeVisible(); - await expect(page.locator(selectors.[errorMessage])).toContainText(testDataItem.[expectedError]); - }); - - test.afterEach(async () => { - await page.close(); - }); -}); -``` - -## Seções do Template - -### 1. Imports e Configuração *(obrigatório)* - -```javascript -import { test, expect } from '@playwright/test'; -import { [FEATURE_NAME]Page } from './page-objects/[feature-name].page'; -import { [HELPER_NAME] } from '../commons/helpers/[helper-name]'; -import testData from './test.data.json'; -import selectors from './selectors.json'; -import environment from './environment.json'; -``` - -**Orientação**: -- Importar test e expect do Playwright -- Importar Page Objects criados para a feature -- Importar Helpers necessários de commons -- Importar dados de teste, seletores e configuração - -### 2. Test Suite Setup *(obrigatório)* - -```javascript -test.describe('[FEATURE_NAME]', () => { - let page; - let [featureName]Page; - - test.beforeEach(async ({ page: testPage }) => { - page = testPage; - [featureName]Page = new [FEATURE_NAME]Page(page); - await page.goto(environment.baseUrl); - }); -``` - -**Orientação**: -- Criar describe block para agrupar testes relacionados -- Declarar variáveis de instância -- Configurar beforeEach para inicialização -- Navegar para URL base antes de cada teste - -### 3. Test Case - Cenário Positivo *(obrigatório)* - -```javascript -test('[SCENARIO_NAME]', async () => { - // Arrange - const testDataItem = testData.[scenarioName]; - - // Act - await [featureName]Page.[action1](); - await [featureName]Page.[action2](testDataItem.[field1]); - - // Assert - await expect(page.locator(selectors.[element])).toBeVisible(); - await expect(page.locator(selectors.[element2])).toHaveText(testDataItem.[expectedValue]); -}); -``` - -**Orientação**: -- Usar padrão AAA (Arrange-Act-Assert) -- Arrange: Preparar dados de teste -- Act: Executar ações do fluxo -- Assert: Validar resultados esperados -- Usar Page Objects para ações -- Usar seletores centralizados -- Usar dados de teste parametrizados - -### 4. Test Case - Cenário com Erro *(opcional - incluir se há casos de erro)* - -```javascript -test('[SCENARIO_NAME_WITH_ERROR]', async () => { - // Arrange - const testDataItem = testData.[scenarioWithError]; - - // Act - await [featureName]Page.[action1](); - await [featureName]Page.[action2](testDataItem.[invalidField]); - - // Assert - await expect(page.locator(selectors.[errorMessage])).toBeVisible(); - await expect(page.locator(selectors.[errorMessage])).toContainText(testDataItem.[expectedError]); -}); -``` - -**Orientação**: -- Testar casos de erro esperados -- Validar mensagens de erro -- Validar comportamento de validação -- Documentar erros esperados - -### 5. Cleanup *(obrigatório)* - -```javascript -test.afterEach(async () => { - await page.close(); -}); -``` - -**Orientação**: -- Limpar estado após cada teste -- Fechar páginas abertas -- Resetar dados se necessário -- Limpar cookies/localStorage se aplicável - -## Helpers e Utilitários *(opcional - incluir se há lógica reutilizável)* - -```javascript -// Helper para aguardar elemento -async function waitForElement(page, selector, timeout = 5000) { - await page.waitForSelector(selector, { timeout }); -} - -// Helper para fazer screenshot -async function takeScreenshot(page, name) { - await page.screenshot({ path: `screenshots/${name}.png` }); -} - -// Helper para validar URL -async function validateUrl(page, expectedUrl) { - await expect(page).toHaveURL(expectedUrl); -} -``` - -**Orientação**: -- Criar helpers para operações repetitivas -- Extrair lógica complexa em funções -- Documentar propósito de cada helper -- Reusar helpers em múltiplos testes - -## Error Handling *(obrigatório)* - -```javascript -test('[SCENARIO_NAME]', async () => { - try { - // Arrange - const testDataItem = testData.[scenarioName]; - - // Act - await [featureName]Page.[action1](); - - // Assert - await expect(page.locator(selectors.[element])).toBeVisible(); - } catch (error) { - console.error('Erro durante execução do teste:', error); - await page.screenshot({ path: 'error-screenshot.png' }); - throw error; - } -}); -``` - -**Orientação**: -- Usar try-catch para capturar erros -- Logar erros com contexto -- Tirar screenshot em caso de erro -- Re-throw para falhar o teste - -## Logging e Debugging *(opcional - incluir se necessário)* - -```javascript -test('[SCENARIO_NAME]', async () => { - console.log('Iniciando teste: [SCENARIO_NAME]'); - - // Arrange - const testDataItem = testData.[scenarioName]; - console.log('Dados de teste:', testDataItem); - - // Act - await [featureName]Page.[action1](); - console.log('Ação 1 executada'); - - // Assert - await expect(page.locator(selectors.[element])).toBeVisible(); - console.log('Teste concluído com sucesso'); -}); -``` - -**Orientação**: -- Adicionar logs em pontos estratégicos -- Logar dados de teste -- Logar progresso de ações -- Facilitar debugging - -## Checklist de Qualidade - -Antes de considerar o script completo: - -- [ ] Todos os imports necessários presentes -- [ ] Test suite configurado com beforeEach -- [ ] Cenários positivos implementados -- [ ] Cenários de erro implementados (se aplicável) -- [ ] Cleanup configurado com afterEach -- [ ] Error handling presente -- [ ] Logging adequado (se necessário) -- [ ] Helpers criados para lógica reutilizável -- [ ] Page Objects usados para abstrações -- [ ] Seletores centralizados (não hardcoded) -- [ ] Dados de teste parametrizados -- [ ] Padrão AAA seguido -- [ ] Assertions claras e específicas -- [ ] Timeouts configurados adequadamente -- [ ] Screenshots em caso de erro - diff --git a/shared/templates/automation/template.automation-selectors.md b/shared/templates/automation/template.automation-selectors.md deleted file mode 100644 index d3283af..0000000 --- a/shared/templates/automation/template.automation-selectors.md +++ /dev/null @@ -1,402 +0,0 @@ -# Template: Centralização de Seletores - - - -**Criado**: 2025-01-17 -**Versão**: 1.0.0 - -## Estrutura do JSON - -```json -{ - "metadata": { - "featureId": "[FEATURE_ID]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "strategy": "data-testid-first", - "note": "Priorizar data-testid, depois IDs, depois classes específicas" - }, - "pages": { - "[PAGE_NAME]": { - "url": "[PAGE_URL]", - "elements": { - "[ELEMENT_NAME]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]", - "alternatives": ["[ALTERNATIVE_1]", "[ALTERNATIVE_2]"] - } - } - } - }, - "components": { - "[COMPONENT_NAME]": { - "elements": { - "[ELEMENT_NAME]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]" - } - } - } - }, - "common": { - "[COMMON_ELEMENT]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]", - "usedIn": ["[PAGE_1]", "[PAGE_2]"] - } - } -} -``` - -## Seções do Template - -### 1. Metadados *(obrigatório)* - -```json -"metadata": { - "featureId": "[FEATURE_ID]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "strategy": "data-testid-first", - "note": "Priorizar data-testid, depois IDs, depois classes específicas" -} -``` - -**Orientação**: -- featureId: Identificador da feature -- lastUpdated: Timestamp da última atualização -- strategy: Estratégia de seleção (data-testid-first, id-first, etc) -- note: Notas sobre estratégia e boas práticas - -**Estratégias de Seleção**: -1. **data-testid-first** (RECOMENDADO): Priorizar atributos data-testid -2. **id-first**: Priorizar IDs de elementos -3. **semantic-first**: Priorizar roles e atributos semânticos -4. **class-first**: Priorizar classes específicas (não genéricas) - -### 2. Seletores por Página *(obrigatório)* - -```json -"pages": { - "[PAGE_NAME]": { - "url": "[PAGE_URL]", - "elements": { - "[ELEMENT_NAME]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]", - "alternatives": ["[ALTERNATIVE_1]", "[ALTERNATIVE_2]"] - } - } - } -} -``` - -**Orientação**: -- Agrupar seletores por página -- Usar chave descritiva para página (ex: "login", "dashboard") -- Incluir URL da página -- Para cada elemento: - - selector: Seletor CSS/XPath/text - - type: Tipo do seletor (css, xpath, text, role) - - priority: Prioridade (1 = preferido, 2 = alternativo, 3 = último recurso) - - description: Descrição do elemento - - alternatives: Seletores alternativos (se houver) - -**Exemplo**: -```json -"pages": { - "login": { - "url": "/login", - "elements": { - "emailInput": { - "selector": "[data-testid='email-input']", - "type": "css", - "priority": 1, - "description": "Campo de input de email", - "alternatives": ["#email", ".email-input"] - }, - "passwordInput": { - "selector": "[data-testid='password-input']", - "type": "css", - "priority": 1, - "description": "Campo de input de senha", - "alternatives": ["#password", ".password-input"] - }, - "submitButton": { - "selector": "button[type='submit']", - "type": "css", - "priority": 1, - "description": "Botão de submit do formulário", - "alternatives": ["[data-testid='submit-btn']", ".submit-button"] - }, - "errorMessage": { - "selector": ".error-message", - "type": "css", - "priority": 1, - "description": "Mensagem de erro do formulário" - } - } - } -} -``` - -### 3. Seletores por Componente *(opcional - incluir se há componentes reutilizáveis)* - -```json -"components": { - "[COMPONENT_NAME]": { - "elements": { - "[ELEMENT_NAME]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]" - } - } - } -} -``` - -**Orientação**: -- Agrupar seletores de componentes reutilizáveis -- Exemplos: header, footer, navigation, modal, dropdown -- Mesma estrutura de elementos por página -- Usar em múltiplas páginas - -**Exemplo**: -```json -"components": { - "header": { - "elements": { - "logo": { - "selector": "[data-testid='logo']", - "type": "css", - "priority": 1, - "description": "Logo do site" - }, - "userMenu": { - "selector": "[data-testid='user-menu']", - "type": "css", - "priority": 1, - "description": "Menu de usuário" - }, - "logoutButton": { - "selector": "[data-testid='logout-btn']", - "type": "css", - "priority": 1, - "description": "Botão de logout" - } - } - }, - "modal": { - "elements": { - "closeButton": { - "selector": "[data-testid='modal-close']", - "type": "css", - "priority": 1, - "description": "Botão de fechar modal" - }, - "confirmButton": { - "selector": "[data-testid='modal-confirm']", - "type": "css", - "priority": 1, - "description": "Botão de confirmar no modal" - } - } - } -} -``` - -### 4. Seletores Comuns *(opcional - incluir se há elementos usados globalmente)* - -```json -"common": { - "[COMMON_ELEMENT]": { - "selector": "[SELECTOR]", - "type": "[css|xpath|text|role]", - "priority": "[1|2|3]", - "description": "[DESCRIPTION]", - "usedIn": ["[PAGE_1]", "[PAGE_2]"] - } -} -``` - -**Orientação**: -- Elementos usados em múltiplas páginas -- Exemplos: loading spinner, toast notifications, error banners -- Incluir usedIn para documentar onde é usado - -**Exemplo**: -```json -"common": { - "loadingSpinner": { - "selector": "[data-testid='loading-spinner']", - "type": "css", - "priority": 1, - "description": "Spinner de carregamento", - "usedIn": ["dashboard", "products", "checkout"] - }, - "successToast": { - "selector": "[data-testid='success-toast']", - "type": "css", - "priority": 1, - "description": "Toast de sucesso", - "usedIn": ["login", "register", "checkout"] - }, - "errorBanner": { - "selector": "[data-testid='error-banner']", - "type": "css", - "priority": 1, - "description": "Banner de erro", - "usedIn": ["login", "register", "checkout"] - } -} -``` - -## Tipos de Seletores - -### CSS Selectors *(mais comum)* - -```json -{ - "selector": "[data-testid='email-input']", - "type": "css" -} -``` - -**Quando usar**: -- Elementos com data-testid -- IDs únicos -- Classes específicas -- Atributos customizados - -**Exemplos**: -- `[data-testid='email-input']` - Atributo data-testid -- `#email` - ID -- `.email-input` - Classe -- `input[type='email']` - Atributo type -- `form > input[type='email']` - Hierarquia - -### XPath Selectors *(último recurso)* - -```json -{ - "selector": "//input[@type='email']", - "type": "xpath" -} -``` - -**Quando usar**: -- Seletores CSS muito complexos -- Navegação por hierarquia complexa -- Seleção por texto -- Último recurso quando CSS não funciona - -**Exemplos**: -- `//input[@type='email']` - Por atributo -- `//button[contains(text(), 'Submit')]` - Por texto -- `//div[@class='container']//input` - Hierarquia - -### Text Selectors *(alternativa)* - -```json -{ - "selector": "Submit", - "type": "text" -} -``` - -**Quando usar**: -- Botões com texto único -- Links com texto específico -- Elementos identificáveis por texto -- Usar com `page.getByText()` - -**Exemplos**: -- `"Submit"` - Texto exato -- `/Submit/` - Regex - -### Role Selectors *(semântico)* - -```json -{ - "selector": "button", - "type": "role" -} -``` - -**Quando usar**: -- Elementos semânticos (button, link, heading) -- Acessibilidade -- Usar com `page.getByRole()` - -**Exemplos**: -- `"button"` - Botão -- `"link"` - Link -- `"heading"` - Heading -- `"textbox"` - Input - -## Prioridades - -### Priority 1 (Preferido) -- data-testid -- IDs únicos -- Roles semânticos -- Atributos específicos - -### Priority 2 (Alternativo) -- Classes específicas -- Seletores CSS mais complexos -- XPath simples - -### Priority 3 (Último Recurso) -- XPath complexo -- Seletores frágeis (classes genéricas) -- Seletores por posição - -## Checklist de Qualidade - -Antes de considerar o selectors.json completo: - -- [ ] Metadados preenchidos (featureId, estratégia, nota) -- [ ] Seletores organizados por página -- [ ] Seletores de componentes documentados (se aplicável) -- [ ] Seletores comuns identificados (se aplicável) -- [ ] Cada seletor tem: selector, type, priority, description -- [ ] Alternativas documentadas para seletores frágeis -- [ ] Prioridade 1 usada para seletores preferidos -- [ ] data-testid priorizado quando disponível -- [ ] JSON válido (sem erros de sintaxe) -- [ ] Seletores testados e funcionais -- [ ] Documentação clara de uso - -## Boas Práticas - -### ✅ Fazer - -- Priorizar data-testid -- Usar seletores específicos -- Documentar alternativas -- Organizar por página/componente -- Atualizar quando UI muda -- Testar seletores regularmente - -### ❌ Evitar - -- Seletores frágeis (classes genéricas como `.btn`, `.input`) -- Seletores por posição (`.container > div:nth-child(2)`) -- IDs temporários ou dinâmicos -- XPath muito complexo -- Seletores duplicados -- Seletores não testados - diff --git a/shared/templates/automation/template.automation-test-data.md b/shared/templates/automation/template.automation-test-data.md deleted file mode 100644 index 22f5458..0000000 --- a/shared/templates/automation/template.automation-test-data.md +++ /dev/null @@ -1,441 +0,0 @@ -# Template: Dados de Teste - - - -**Criado**: 2025-01-17 -**Versão**: 1.0.0 - -## Estrutura do JSON - -```json -{ - "metadata": { - "featureId": "[FEATURE_ID]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "note": "Dados de teste - NÃO usar dados reais em produção" - }, - "users": { - "[USER_TYPE]": { - "email": "[TEST_EMAIL]", - "password": "[TEST_PASSWORD]", - "firstName": "[FIRST_NAME]", - "lastName": "[LAST_NAME]", - "phone": "[PHONE]", - "address": { - "street": "[STREET]", - "city": "[CITY]", - "state": "[STATE]", - "zipCode": "[ZIP_CODE]", - "country": "[COUNTRY]" - } - } - }, - "scenarios": { - "[SCENARIO_NAME]": { - "description": "[DESCRIPTION]", - "type": "[positive|negative|edge]", - "input": { - "[FIELD_NAME]": "[VALUE]" - }, - "expected": { - "[FIELD_NAME]": "[EXPECTED_VALUE]" - } - } - }, - "products": { - "[PRODUCT_ID]": { - "name": "[PRODUCT_NAME]", - "sku": "[SKU]", - "price": "[PRICE]", - "category": "[CATEGORY]", - "inStock": true - } - }, - "forms": { - "[FORM_NAME]": { - "valid": { - "[FIELD_NAME]": "[VALID_VALUE]" - }, - "invalid": { - "[FIELD_NAME]": "[INVALID_VALUE]", - "expectedError": "[ERROR_MESSAGE]" - } - } - }, - "fixtures": { - "[FIXTURE_NAME]": { - "type": "[user|product|order|etc]", - "data": { - "[FIELD_NAME]": "[VALUE]" - } - } - } -} -``` - -## Seções do Template - -### 1. Metadados *(obrigatório)* - -```json -"metadata": { - "featureId": "[FEATURE_ID]", - "lastUpdated": "[ISO_8601_TIMESTAMP]", - "note": "Dados de teste - NÃO usar dados reais em produção" -} -``` - -**Orientação**: -- featureId: Identificador da feature -- lastUpdated: Timestamp da última atualização -- note: Aviso importante sobre uso de dados de teste - -### 2. Usuários de Teste *(obrigatório - se há autenticação)* - -```json -"users": { - "[USER_TYPE]": { - "email": "[TEST_EMAIL]", - "password": "[TEST_PASSWORD]", - "firstName": "[FIRST_NAME]", - "lastName": "[LAST_NAME]", - "phone": "[PHONE]", - "address": { - "street": "[STREET]", - "city": "[CITY]", - "state": "[STATE]", - "zipCode": "[ZIP_CODE]", - "country": "[COUNTRY]" - } - } -} -``` - -**Orientação**: -- Criar usuários para diferentes cenários -- Tipos comuns: admin, regular, premium, guest -- Incluir dados completos do perfil -- Usar emails de teste (ex: test+admin@example.com) -- Senhas devem ser válidas mas não reais - -**Exemplo**: -```json -"users": { - "admin": { - "email": "test.admin@example.com", - "password": "Test123!@#", - "firstName": "Admin", - "lastName": "User", - "phone": "+55 11 99999-9999", - "address": { - "street": "Rua Teste, 123", - "city": "São Paulo", - "state": "SP", - "zipCode": "01234-567", - "country": "Brasil" - } - }, - "regular": { - "email": "test.user@example.com", - "password": "User123!@#", - "firstName": "Regular", - "lastName": "User", - "phone": "+55 11 88888-8888", - "address": { - "street": "Av. Example, 456", - "city": "Rio de Janeiro", - "state": "RJ", - "zipCode": "20000-000", - "country": "Brasil" - } - } -} -``` - -### 3. Cenários de Teste *(obrigatório)* - -```json -"scenarios": { - "[SCENARIO_NAME]": { - "description": "[DESCRIPTION]", - "type": "[positive|negative|edge]", - "input": { - "[FIELD_NAME]": "[VALUE]" - }, - "expected": { - "[FIELD_NAME]": "[EXPECTED_VALUE]" - } - } -} -``` - -**Orientação**: -- Organizar dados por cenário de teste -- Tipos: positive (sucesso), negative (erro), edge (casos limites) -- Incluir inputs e valores esperados -- Documentar descrição de cada cenário - -**Exemplo**: -```json -"scenarios": { - "loginSuccess": { - "description": "Login com credenciais válidas", - "type": "positive", - "input": { - "email": "test.user@example.com", - "password": "User123!@#" - }, - "expected": { - "url": "/dashboard", - "welcomeMessage": "Bem-vindo" - } - }, - "loginInvalidEmail": { - "description": "Login com email inválido", - "type": "negative", - "input": { - "email": "invalid-email", - "password": "User123!@#" - }, - "expected": { - "errorMessage": "Email inválido" - } - }, - "loginWrongPassword": { - "description": "Login com senha incorreta", - "type": "negative", - "input": { - "email": "test.user@example.com", - "password": "WrongPass123!" - }, - "expected": { - "errorMessage": "Credenciais inválidas" - } - } -} -``` - -### 4. Produtos *(opcional - incluir se há e-commerce)* - -```json -"products": { - "[PRODUCT_ID]": { - "name": "[PRODUCT_NAME]", - "sku": "[SKU]", - "price": "[PRICE]", - "category": "[CATEGORY]", - "inStock": true - } -} -``` - -**Orientação**: -- Criar produtos para testes de e-commerce -- Incluir dados completos do produto -- Variar categorias, preços, disponibilidade -- Usar SKUs fictícios mas válidos - -**Exemplo**: -```json -"products": { - "laptop": { - "name": "Laptop Dell XPS 15", - "sku": "DL-XPS15-001", - "price": "8999.99", - "category": "Electronics", - "inStock": true - }, - "mouse": { - "name": "Mouse Logitech MX Master 3", - "sku": "LG-MX3-001", - "price": "599.99", - "category": "Accessories", - "inStock": true - }, - "outOfStock": { - "name": "Smartphone Samsung Galaxy S24", - "sku": "SM-GS24-001", - "price": "6999.99", - "category": "Electronics", - "inStock": false - } -} -``` - -### 5. Dados de Formulários *(opcional - incluir se há formulários)* - -```json -"forms": { - "[FORM_NAME]": { - "valid": { - "[FIELD_NAME]": "[VALID_VALUE]" - }, - "invalid": { - "[FIELD_NAME]": "[INVALID_VALUE]", - "expectedError": "[ERROR_MESSAGE]" - } - } -} -``` - -**Orientação**: -- Organizar dados por formulário -- Separar dados válidos e inválidos -- Incluir mensagens de erro esperadas -- Testar validações de campo - -**Exemplo**: -```json -"forms": { - "registration": { - "valid": { - "firstName": "João", - "lastName": "Silva", - "email": "joao.silva@example.com", - "password": "SecurePass123!", - "confirmPassword": "SecurePass123!", - "phone": "+55 11 98765-4321", - "birthDate": "1990-01-15" - }, - "invalid": { - "email": "invalid-email", - "expectedError": "Email inválido", - "password": "123", - "expectedErrorPassword": "Senha deve ter no mínimo 8 caracteres", - "phone": "123", - "expectedErrorPhone": "Telefone inválido" - } - } -} -``` - -### 6. Fixtures *(opcional - incluir se há dados reutilizáveis)* - -```json -"fixtures": { - "[FIXTURE_NAME]": { - "type": "[user|product|order|etc]", - "data": { - "[FIELD_NAME]": "[VALUE]" - } - } -} -``` - -**Orientação**: -- Criar fixtures para dados reutilizáveis -- Tipos: user, product, order, cart, etc -- Usar em múltiplos cenários -- Facilitar manutenção - -**Exemplo**: -```json -"fixtures": { - "newUser": { - "type": "user", - "data": { - "firstName": "Novo", - "lastName": "Usuário", - "email": "novo.usuario@example.com", - "password": "NewUser123!", - "phone": "+55 11 99999-9999" - } - }, - "shoppingCart": { - "type": "cart", - "data": { - "items": [ - { - "productId": "laptop", - "quantity": 1 - }, - { - "productId": "mouse", - "quantity": 2 - } - ] - } - } -} -``` - -## Tipos de Dados - -### Positive Data (Cenários de Sucesso) -- Credenciais válidas -- Dados de formulário válidos -- Produtos disponíveis -- Fluxos completos - -### Negative Data (Cenários de Erro) -- Credenciais inválidas -- Dados de formulário inválidos -- Produtos esgotados -- Erros esperados - -### Edge Cases (Casos Limites) -- Valores mínimos/máximos -- Strings vazias -- Caracteres especiais -- Limites de campos - -## Geração de Dados Dinâmicos - -Para dados que precisam ser únicos a cada execução: - -```javascript -// No script de teste -const timestamp = Date.now(); -const uniqueEmail = `test.${timestamp}@example.com`; -const uniqueUsername = `user_${timestamp}`; -``` - -**Quando usar**: -- Emails únicos -- Usernames únicos -- IDs de transação -- Timestamps - -## Checklist de Qualidade - -Antes de considerar o test.data.json completo: - -- [ ] Metadados preenchidos (featureId, timestamp, nota) -- [ ] Usuários de teste criados (se aplicável) -- [ ] Cenários positivos documentados -- [ ] Cenários negativos documentados -- [ ] Edge cases incluídos (se aplicável) -- [ ] Produtos de teste criados (se aplicável) -- [ ] Dados de formulários válidos e inválidos (se aplicável) -- [ ] Fixtures criadas para dados reutilizáveis (se aplicável) -- [ ] JSON válido (sem erros de sintaxe) -- [ ] Dados de teste (não dados reais) -- [ ] Documentação clara de cada cenário -- [ ] Valores esperados definidos - -## Boas Práticas - -### ✅ Fazer - -- Usar dados de teste claramente identificáveis -- Organizar por cenário de teste -- Incluir dados válidos e inválidos -- Documentar valores esperados -- Criar fixtures para dados reutilizáveis -- Usar emails de teste (test+*@example.com) -- Variar dados por cenário - -### ❌ Evitar - -- Dados reais de produção -- Credenciais reais -- Dados pessoais reais -- Dados duplicados -- Dados inconsistentes -- Dados sem documentação -- Dados hardcoded no script - diff --git a/shared/templates/backlog.md b/shared/templates/backlog.md deleted file mode 100644 index 970ebfc..0000000 --- a/shared/templates/backlog.md +++ /dev/null @@ -1,403 +0,0 @@ -# [PROJECT_NAME] - Especificação de Backlog Detalhada - -## Sumário Executivo - -**Projeto:** [PROJECT_NAME] -**Categoria:** [CATEGORY] -**Complexidade Estimada:** [COMPLEXITY] -**Esforço Total (MVP):** [EFFORT_HOURS] horas -**Data de Análise:** [DATE] - -### Quick Overview - -[BRIEF_DESCRIPTION] - -### Principais Decisões Técnicas - -- **Stack Principal:** [MAIN_STACK] -- **Arquitetura:** [ARCHITECTURE_PATTERN] -- **Deploy:** [DEPLOYMENT_TARGET] - ---- - -## Visão do Produto - -### Problema que Resolve - -[PROBLEM_DESCRIPTION] - -### Usuário-Alvo - -[TARGET_USER] - -### Proposta de Valor - -[VALUE_PROPOSITION] - ---- - -## Features Decompostas - -### MVP (Minimum Viable Product) - -Features essenciais para o core do produto funcionar. - -#### Feature 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor para o usuário:** [USER_VALUE] - -**Complexidade:** [COMPLEXITY] (Simple/Medium/Complex) - -**Esforço estimado:** [EFFORT] horas - -**Dependências:** [DEPENDENCIES] - -**Critérios de aceite:** -- [ ] [ACCEPTANCE_CRITERIA_1] -- [ ] [ACCEPTANCE_CRITERIA_2] -- [ ] [ACCEPTANCE_CRITERIA_3] - -**Tasks técnicas:** -1. [TASK_1] -2. [TASK_2] -3. [TASK_3] - ---- - -#### Feature 2: [FEATURE_NAME] - -[REPEAT_STRUCTURE] - ---- - -### Enhancement Features - -Features que melhoram a experiência mas não são essenciais para o core. - -#### Enhancement 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor:** [VALUE] - -**Complexidade:** [COMPLEXITY] - -**Quando implementar:** [WHEN_TO_IMPLEMENT] - ---- - -### Advanced Features - -Features avançadas para versões futuras. - -#### Advanced 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor:** [VALUE] - -**Complexidade:** [COMPLEXITY] - ---- - -## Análise de Caminhos Técnicos - -### Decisão 1: [TECHNICAL_DECISION] - -#### Opção A: [OPTION_A_NAME] - -**Tecnologias:** [TECHNOLOGIES] - -**Prós:** -- [PRO_1] -- [PRO_2] -- [PRO_3] - -**Contras:** -- [CON_1] -- [CON_2] - -**Esforço:** [EFFORT] - -**Quando escolher:** [WHEN_TO_CHOOSE] - -#### Opção B: [OPTION_B_NAME] - -**Tecnologias:** [TECHNOLOGIES] - -**Prós:** -- [PRO_1] -- [PRO_2] - -**Contras:** -- [CON_1] -- [CON_2] - -**Esforço:** [EFFORT] - -**Quando escolher:** [WHEN_TO_CHOOSE] - -#### ✅ Recomendação - -[RECOMMENDATION_WITH_JUSTIFICATION] - ---- - -### Decisão 2: [TECHNICAL_DECISION] - -[REPEAT_STRUCTURE] - ---- - -## Análise de Tradeoffs - -### Tradeoff 1: [TRADEOFF_NAME] - -**Contexto:** [CONTEXT] - -**Opção A:** [OPTION_A] -**Impacto:** [IMPACT_A] - -**Opção B:** [OPTION_B] -**Impacto:** [IMPACT_B] - -**✅ Recomendação:** [RECOMMENDATION] - -**Justificativa:** [JUSTIFICATION] - ---- - -### Tradeoff 2: [TRADEOFF_NAME] - -[REPEAT_STRUCTURE] - ---- - -## Riscos e Mitigações - -### Risco 1: [RISK_NAME] - -**Descrição:** [RISK_DESCRIPTION] - -**Probabilidade:** [LOW/MEDIUM/HIGH] - -**Impacto:** [LOW/MEDIUM/HIGH] - -**Estratégia de Mitigação:** [MITIGATION_STRATEGY] - -**Plano B:** [FALLBACK_PLAN] - ---- - -### Risco 2: [RISK_NAME] - -[REPEAT_STRUCTURE] - ---- - -## Priorização e Roadmap - -### Framework de Priorização - -| Feature | Value (1-10) | Effort (1-10) | Priority Score | Fase | -|---------|-------------|---------------|----------------|------| -| [FEATURE_1] | [VALUE] | [EFFORT] | [SCORE] | MVP | -| [FEATURE_2] | [VALUE] | [EFFORT] | [SCORE] | MVP | -| [FEATURE_3] | [VALUE] | [EFFORT] | [SCORE] | Enhancement | -| [FEATURE_4] | [VALUE] | [EFFORT] | [SCORE] | Advanced | - -### Roadmap Sugerido - -#### Fase 1: MVP (Day 1) - -**Objetivo:** Produto mínimo funcional - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] -- [FEATURE_3] - -**Esforço total:** [HOURS] horas - -**Entregável:** [DELIVERABLE] - -#### Fase 2: Enhancement (Day 2+) - -**Objetivo:** Melhorias de experiência - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] - -**Esforço total:** [HOURS] horas - -#### Fase 3: Advanced (Future) - -**Objetivo:** Features avançadas - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] - ---- - -## Backlog de Tasks (MVP) - -### Setup Inicial - -- [ ] Criar repositório e estrutura de pastas -- [ ] Inicializar package.json com dependências -- [ ] Configurar build tools -- [ ] Setup inicial de [SPECIFIC_TOOLS] - -**Estimativa:** [MINUTES] minutos - -### Implementação Core - -#### Task 1: [TASK_NAME] - -**Descrição técnica:** [TECHNICAL_DESCRIPTION] - -**Critério de conclusão:** [DONE_CRITERIA] - -**Dependências:** [DEPENDENCIES] - -**Estimativa:** [TIME] - -**Arquivos envolvidos:** -- [FILE_1] -- [FILE_2] - ---- - -#### Task 2: [TASK_NAME] - -[REPEAT_STRUCTURE] - ---- - -### UI/UX - -- [ ] [UI_TASK_1] -- [ ] [UI_TASK_2] -- [ ] [UI_TASK_3] - -**Estimativa:** [TIME] - -### Integração - -- [ ] [INTEGRATION_TASK_1] -- [ ] [INTEGRATION_TASK_2] - -**Estimativa:** [TIME] - -### Testing & Deploy - -- [ ] Testar funcionalidades principais -- [ ] Testar edge cases -- [ ] Deploy para [PLATFORM] -- [ ] Criar README com screenshots - -**Estimativa:** [TIME] - ---- - -## Stack Tecnológica Detalhada - -### Frontend - -- **Framework:** [FRAMEWORK] -- **Styling:** [STYLING_SOLUTION] -- **State Management:** [STATE_MANAGEMENT] -- **Libs auxiliares:** [LIBS] - -### Backend / BaaS - -- **Solução:** [BACKEND_SOLUTION] -- **Database:** [DATABASE] -- **Auth:** [AUTH_SOLUTION] -- **Storage:** [STORAGE_SOLUTION] - -### Deploy & DevOps - -- **Hosting:** [HOSTING] -- **CI/CD:** [CI_CD] -- **Monitoring:** [MONITORING] - -### Dependências Principais - -```json -{ - "dependencies": { - "[PACKAGE_1]": "[VERSION]", - "[PACKAGE_2]": "[VERSION]" - } -} -``` - ---- - -## Recomendações Finais - -### Ordem de Implementação Sugerida - -1. [STEP_1] -2. [STEP_2] -3. [STEP_3] -4. [STEP_4] - -### Quick Wins - -Features que entregam valor rápido com pouco esforço: -- [QUICK_WIN_1] -- [QUICK_WIN_2] - -### Armadilhas a Evitar - -- ⚠️ [PITFALL_1] -- ⚠️ [PITFALL_2] -- ⚠️ [PITFALL_3] - -### Quando Simplificar - -Se o tempo for limitado, considere: -- ❌ Remover: [FEATURE_TO_CUT] -- 📉 Simplificar: [FEATURE_TO_SIMPLIFY] -- ⏭️ Adiar: [FEATURE_TO_POSTPONE] - -### Recursos Úteis - -- [RESOURCE_1]: [LINK] -- [RESOURCE_2]: [LINK] -- [RESOURCE_3]: [LINK] - ---- - -## Definition of Done - -O projeto está completo quando: - -- [ ] Todas as features MVP implementadas -- [ ] Funcionalidades principais testadas -- [ ] Deploy realizado com sucesso -- [ ] README com descrição e screenshots -- [ ] Demo acessível (link funcionando) -- [ ] Código commitado no GitHub -- [ ] Post de showcase publicado - ---- - -## Próximos Passos - -1. **Começar implementação:** Use o backlog de tasks acima -2. **Executar command:** `exec.implement.md` ou `plan-tasks.md` -3. **Monitorar progresso:** Marque tasks completadas -4. **Ajustar escopo:** Se necessário, simplifique usando recomendações - ---- - -**Backlog gerado em:** [TIMESTAMP] -**Próxima revisão:** Após implementação do MVP - diff --git a/shared/templates/clarification.template.md b/shared/templates/clarification.template.md deleted file mode 100644 index 8ccc7f7..0000000 --- a/shared/templates/clarification.template.md +++ /dev/null @@ -1,325 +0,0 @@ ---- -type: clarification-document -version: 1.0 -feature_id: [FEATURE_ID] -feature_name: [FEATURE_NAME] -source_spec: [SPEC_PATH] -analyzed_at: [TIMESTAMP] -status: pending-review -completeness_score: [0-100]% -blocker_issues: [N] -critical_issues: [N] -important_issues: [N] ---- - -# Clarifications: [FEATURE_NAME] - -## 📊 Analysis Summary - -**Source Document**: [SPEC_PATH] -**Analysis Date**: [TIMESTAMP] -**Overall Completeness**: [X]% -**Analyzer**: AI Agent (Cursor) - -**Issue Breakdown**: -- 🚨 Blocker Issues: [N] -- 🔴 Critical Issues: [N] -- 🟡 Important Issues: [N] -- 🟢 Minor Issues: [N] -- **Total**: [N] issues identified - -**Completeness by Section**: - -| Section | Present | Complete | Clear | Score | Issues | -|---------|---------|----------|-------|-------|--------| -| Overview | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Problem Statement | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| User Stories | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Acceptance Criteria | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Functional Req | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Non-Functional Req | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Technical Considerations | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Dependencies | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Risks & Mitigation | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Success Metrics | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| **OVERALL** | - | - | - | **[%]** | **[N]** | - ---- - -## 🚨 Critical Issues (Blockers) - -_Issues that MUST be resolved before proceeding to planning/implementation_ - -### Issue #1: [Issue Title] - -**Section**: [Section Name] -**Type**: Gap / Ambiguity / Inconsistency / Missing -**Impact**: Blocks [what it blocks] -**Severity**: Blocker - -**Description**: -[Detailed description of the issue] - -**Questions to Answer**: -1. [Specific question 1] -2. [Specific question 2] -3. [Specific question 3] - -**Suggested Resolution**: -[Specific recommendation on how to resolve this] - -**Where to Update**: -[Exact section and location in spec to update] - ---- - -### Issue #2: [Issue Title] - -[Same structure as Issue #1] - ---- - -## 🔴 Critical Issues (High Priority) - -_Issues that significantly impact quality but don't block proceeding_ - -### Issue #3: [Issue Title] - -**Section**: [Section Name] -**Type**: Gap / Ambiguity / Inconsistency / Missing -**Impact**: [Description] -**Severity**: Critical - -**Description**: -[Detailed description] - -**Questions to Answer**: -1. [Question] - -**Suggested Resolution**: -[Recommendation] - ---- - -## 🟡 Important Issues (Medium Priority) - -_Issues that should be addressed for completeness_ - -### Issue #N: [Issue Title] - -[Same structure] - ---- - -## 🔍 Gaps Identified - -### Missing Information - -- [ ] **[Gap 1]**: [Description - where and what is missing] -- [ ] **[Gap 2]**: [Description] -- [ ] **[Gap 3]**: [Description] - -### Vague Statements - -- [ ] **[Vague 1]**: [Quote from spec] - Needs: [What needs to be clarified] -- [ ] **[Vague 2]**: [Quote from spec] - Needs: [What needs to be clarified] - -### Undocumented Assumptions - -- [ ] **[Assumption 1]**: [Implicit assumption that should be made explicit] -- [ ] **[Assumption 2]**: [Implicit assumption] - -### Missing Edge Cases - -- [ ] **[Edge Case 1]**: [Scenario not covered] -- [ ] **[Edge Case 2]**: [Scenario not covered] - -### Missing Error Handling - -- [ ] **[Error Scenario 1]**: [How to handle this error?] -- [ ] **[Error Scenario 2]**: [How to handle this error?] - ---- - -## ❓ Questions to Answer - -### 🚨 Blocker Questions (Must answer NOW) - -#### Q1: [Question] -- **Category**: Clarification / Decision / Technical / Validation -- **Impact**: [What happens if not answered] -- **Suggested by**: [Section that generated this question] -- **Priority**: Blocker -- **Answer**: _[To be filled]_ - ---- - -### 🔴 Critical Questions (High Priority) - -#### Q2: [Question] -- **Category**: [Category] -- **Impact**: [Impact] -- **Suggested by**: [Section] -- **Priority**: Critical -- **Answer**: _[To be filled]_ - ---- - -### 🟡 Important Questions (Medium Priority) - -#### Q3: [Question] -- **Category**: [Category] -- **Impact**: [Impact] -- **Suggested by**: [Section] -- **Priority**: Important -- **Answer**: _[To be filled]_ - ---- - -## 🎯 Ambiguities Detected - -### Ambiguity #1: [Title] - -**Location**: [Section and line] -**Statement**: "[Quote from spec]" -**Issue**: [Why this is ambiguous] -**Possible Interpretations**: -1. [Interpretation A] -2. [Interpretation B] - -**Clarification Needed**: [What exactly needs to be defined] - ---- - -## ⚠️ Inconsistencies Found - -### Inconsistency #1: [Title] - -**Locations**: [Sections involved] -**Issue**: [Description of inconsistency] -**Impact**: [What this breaks or confuses] -**Resolution**: [How to make consistent] - ---- - -## ✅ Recommendations - -### Immediate Actions (Do First) - -1. **[Action 1]**: [Specific action to take] - - **Section**: [Where to update] - - **What to add/change**: [Specific change] - - **Why**: [Rationale] - -2. **[Action 2]**: [Specific action] - - **Section**: [Where] - - **What**: [Change] - - **Why**: [Rationale] - -### Updates Needed by Section - -#### Section: [Section Name] -- **Issue**: [Problem identified] -- **Current**: [What exists now] -- **Recommended**: [What should exist] -- **Priority**: Blocker / Critical / Important - ---- - -## 📋 Checklist for Spec Update - -Use this checklist when updating the spec based on these clarifications: - -### Blockers (Must Fix) -- [ ] [Fix blocker issue 1] -- [ ] [Fix blocker issue 2] - -### Critical (Should Fix) -- [ ] [Fix critical issue 1] -- [ ] [Fix critical issue 2] - -### Important (Could Fix) -- [ ] [Fix important issue 1] -- [ ] [Fix important issue 2] - -### Validation -- [ ] All blocker questions answered -- [ ] All critical ambiguities resolved -- [ ] User stories have acceptance criteria -- [ ] Requirements are testable -- [ ] Success metrics are measurable -- [ ] Dependencies are documented -- [ ] Risks have mitigation strategies - ---- - -## 🔄 Iterative Refinement - -**Current Iteration**: 1 -**Completeness Progress**: [X]% → [Target: >90%] - -**Recommended Next Steps**: - -1. **Answer Blocker Questions**: - - [List blocker questions from above] - -2. **Update Spec**: - - Edit: `vibes/specs/[FEATURE_ID]/spec.md` - - Address blocker and critical issues - - Add missing information - - Clarify vague statements - - Resolve inconsistencies - -3. **Re-run Clarification**: - - Command: `/clarify vibes/specs/[FEATURE_ID]/spec.md` - - Validate improvements - - Check new completeness score - - Repeat until >90% - -4. **Proceed to Planning** (when ready): - - Command: `/planner.project vibes/specs/[FEATURE_ID]/spec.md` - - Planner will use clarified requirements - - Implementation will be guided by clear acceptance criteria - ---- - -## 📝 Notes & Comments - -_Use this section for additional observations, stakeholder feedback, or discussion notes_ - -[Free-form notes area] - ---- - -## 📚 References - -- **Source Spec**: [SPEC_PATH] -- **Related Specs**: [LIST if any] -- **Related Documents**: [LIST if any] - ---- - -## 🎯 Success Criteria for This Clarification - -- [ ] All blocker issues identified and documented -- [ ] Questions are specific and actionable -- [ ] Recommendations are practical -- [ ] Completeness score calculated for each section -- [ ] Next steps are clear -- [ ] Document is ready for stakeholder review - ---- - -**Clarification Version**: 1.0 -**Next Review**: After spec update -**Status**: -- [ ] Blockers resolved -- [ ] Critical questions answered -- [ ] Spec updated -- [ ] Ready for planning (>90% complete) - ---- - -**Template Version**: 1.0 -**Last Updated**: 2025-10-13 - diff --git a/shared/templates/cli-commander.template.ts b/shared/templates/cli-commander.template.ts deleted file mode 100644 index 1cf319e..0000000 --- a/shared/templates/cli-commander.template.ts +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env node -import { Command } from 'commander'; -import chalk from 'chalk'; -import pkg from './package.json'; - -const program = new Command(); - -program - .name('{{CLI_NAME}}') - .description(chalk.cyan('{{CLI_DESCRIPTION}}')) - .version(pkg.version); - -{ { COMMANDS_DEFINITION } } - -program.parse(process.argv); - -if (!process.argv.slice(2).length) { - program.outputHelp(); -} - diff --git a/shared/templates/component-flutter.template.dart b/shared/templates/component-flutter.template.dart deleted file mode 100644 index 412ce6a..0000000 --- a/shared/templates/component-flutter.template.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:flutter/material.dart'; - -class {{COMPONENT_NAME}} extends StatelessWidget { - const {{COMPONENT_NAME}}({ - super.key, - {{PROPS_DEFINITION}} - this.child, - }); - - {{PROPS_FIELDS}} - final Widget? child; - - @override - Widget build(BuildContext context) { - return {{WIDGET_TYPE}}( - {{WIDGET_PROPS}} - child: child, - ); - } -} - diff --git a/shared/templates/component-react.template.tsx b/shared/templates/component-react.template.tsx deleted file mode 100644 index 7bd7937..0000000 --- a/shared/templates/component-react.template.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { cn } from '../utils/cn'; - -export interface { { COMPONENT_NAME } }Props { - { { PROPS_DEFINITION } } - className ?: string; - children ?: React.ReactNode; -} - -export const {{ COMPONENT_NAME }}: React.FC < {{ COMPONENT_NAME }}Props > = ({ - {{ PROPS_DESTRUCTURE }} - className, - children -}) => { - return ( - < {{ ELEMENT_TYPE } -} -className = { - cn( - '{{COMPONENT_CLASS}}', - {{ VARIANT_CLASSES }} -className - )} -{ { ELEMENT_PROPS } } - > - { children } - - ); -}; - -{ { COMPONENT_NAME } }.displayName = '{{COMPONENT_NAME}}'; - diff --git a/shared/templates/constitution.md b/shared/templates/constitution.md deleted file mode 100644 index 1ed8d77..0000000 --- a/shared/templates/constitution.md +++ /dev/null @@ -1,50 +0,0 @@ -# [PROJECT_NAME] Constitution - - -## Core Principles - -### [PRINCIPLE_1_NAME] - -[PRINCIPLE_1_DESCRIPTION] - - -### [PRINCIPLE_2_NAME] - -[PRINCIPLE_2_DESCRIPTION] - - -### [PRINCIPLE_3_NAME] - -[PRINCIPLE_3_DESCRIPTION] - - -### [PRINCIPLE_4_NAME] - -[PRINCIPLE_4_DESCRIPTION] - - -### [PRINCIPLE_5_NAME] - -[PRINCIPLE_5_DESCRIPTION] - - -## [SECTION_2_NAME] - - -[SECTION_2_CONTENT] - - -## [SECTION_3_NAME] - - -[SECTION_3_CONTENT] - - -## Governance - - -[GOVERNANCE_RULES] - - -**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE] - \ No newline at end of file diff --git a/shared/templates/empathy-map.template.md b/shared/templates/empathy-map.template.md deleted file mode 100644 index 3a5d242..0000000 --- a/shared/templates/empathy-map.template.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -type: empathy-map -persona: {{PERSONA_SLUG}} -created_at: {{CREATED_AT}} -based_on: {{RESEARCH_SOURCE}} ---- - -# Empathy Map: {{PERSONA_NAME}} - -**Persona**: [{{PERSONA_NAME}}](../personas/{{PERSONA_SLUG}}.md) -**Created**: {{CREATED_AT}} -**Based on**: {{RESEARCH_SOURCE}} - -## 🗺️ Empathy Map Quadrants - -### 🗣️ SAYS (O que diz) - -Quotes literais e comentários verbais: - -{{SAYS_ITEMS}} - -### 💭 THINKS (O que pensa) - -Pensamentos internos e preocupações não verbalizadas: - -{{THINKS_ITEMS}} - -### 🏃 DOES (O que faz) - -Ações observáveis e comportamentos: - -{{DOES_ITEMS}} - -### ❤️ FEELS (O que sente) - -Emoções e estados emocionais: - -{{FEELS_ITEMS}} - -## 📊 Quadrant Visualization - -```mermaid -quadrantChart - title Empathy Map - {{PERSONA_NAME}} - x-axis Low Energy --> High Energy - y-axis Negative --> Positive - quadrant-1 Motivated - quadrant-2 Stressed - quadrant-3 Frustrated - quadrant-4 Calm -{{MERMAID_POINTS}} -``` - -## 💡 Key Insights - -{{INSIGHTS_SUMMARY}} - -## 🔗 Related - -- **Persona**: [{{PERSONA_NAME}}](../personas/{{PERSONA_SLUG}}.md) -- **Journey Maps**: {{JOURNEY_MAPS_LINKS}} -- **Research**: {{RESEARCH_LINKS}} - ---- - -**Confidence**: {{CONFIDENCE}} -**Next Steps**: {{NEXT_STEPS}} - diff --git a/shared/templates/exploration.md b/shared/templates/exploration.md deleted file mode 100644 index 680d2ac..0000000 --- a/shared/templates/exploration.md +++ /dev/null @@ -1,293 +0,0 @@ -# Relatório de Exploração: [TEMA] - -**Data**: [TIMESTAMP] -**Fonte(s)**: [CAMINHOS_DOS_ARQUIVOS] -**Gerado por**: /analyzer - ---- - -## 📋 Contexto Analisado - -### Fontes de Input -- [ARQUIVO_1] - [DESCRIÇÃO] -- [ARQUIVO_2] - [DESCRIÇÃO] - -### Resumo Executivo -[2-3 parágrafos resumindo o conteúdo analisado] - -### Conceitos Centrais Identificados -1. **[CONCEITO_1]**: [DESCRIÇÃO_BREVE] -2. **[CONCEITO_2]**: [DESCRIÇÃO_BREVE] -3. **[CONCEITO_3]**: [DESCRIÇÃO_BREVE] - ---- - -## 🔍 Gaps Identificados - -### Gaps de Conhecimento -| Gap | Descrição | Criticidade | -|-----|-----------|-------------| -| [GAP_ID] | [O_QUE_NÃO_SABEMOS] | Alta/Média/Baixa | - -### Gaps de Produto/Solução -| Gap | Oportunidade | Público Afetado | -|-----|--------------|-----------------| -| [GAP_ID] | [O_QUE_NÃO_FOI_CONSIDERADO] | [PÚBLICO] | - -### Gaps Metodológicos -| Gap | Validação Necessária | Método Sugerido | -|-----|---------------------|-----------------| -| [GAP_ID] | [O_QUE_VALIDAR] | [COMO_VALIDAR] | - ---- - -## ❓ Perguntas Exploratórias - -### Perguntas de Aprofundamento -1. [PERGUNTA_ESPECÍFICA]? -2. [PERGUNTA_ESPECÍFICA]? -3. [PERGUNTA_ESPECÍFICA]? - -### Perguntas de Expansão -1. [E_SE_PERGUNTA]? -2. [E_SE_PERGUNTA]? -3. [E_SE_PERGUNTA]? - -### Perguntas de Validação -1. [PERGUNTA_DE_TESTE]? -2. [PERGUNTA_DE_TESTE]? -3. [PERGUNTA_DE_TESTE]? - -### Perguntas de Síntese -1. [PERGUNTA_DE_CONEXÃO]? -2. [PERGUNTA_DE_CONEXÃO]? - ---- - -## 📊 Tarefas Exploratórias Priorizadas - -### Resumo de Priorização - -| Categoria | Quantidade | Tempo Total Estimado | -|-----------|------------|----------------------| -| Must (Essencial) | [N] | [X] horas | -| Should (Importante) | [N] | [X] horas | -| Could (Valioso) | [N] | [X] horas | -| Won't (Opcional) | [N] | [X] horas | - -### Matriz Impact vs Effort - -``` - Alta │ SHOULD │ MUST │ -Impact │ │ │ - Baixa│ WON'T │ COULD │ - └─────────┴─────────┘ - Baixo Alto - Effort -``` - -### Tarefas Detalhadas - -#### MUST - Essenciais (Alta Prioridade, Baixo Esforço) - -##### EXP-[ID] - [TÍTULO] -- **Tipo**: [Pesquisa Web | Análise Documental | Experimento | Command] -- **Objetivo**: [O_QUE_DESCOBRIR_OU_VALIDAR] -- **Método/Keywords**: [COMO_EXECUTAR_OU_TERMOS_DE_BUSCA] -- **Fontes/Documentos**: [ONDE_BUSCAR_OU_ARQUIVOS] -- **Output Esperado**: [O_QUE_SERÁ_GERADO] -- **Critério de Sucesso**: [COMO_SABER_QUE_ESTÁ_COMPLETO] -- **Impact**: [N]/10 - [JUSTIFICATIVA] -- **Effort**: [N]/10 - [JUSTIFICATIVA] -- **Priority Score**: [IMPACT/EFFORT] -- **Tempo Estimado**: [X] minutos/horas -- **Dependências**: [TASK_IDS] ou Nenhuma - ---- - -#### SHOULD - Importantes (Alta Prioridade, Alto Esforço) - -[REPETIR_ESTRUTURA_ACIMA_PARA_CADA_TAREFA] - ---- - -#### COULD - Valiosos (Média Prioridade, Baixo Esforço) - -[REPETIR_ESTRUTURA_ACIMA_PARA_CADA_TAREFA] - ---- - -#### WON'T - Opcionais (Baixa Prioridade ou Alto Esforço) - -[REPETIR_ESTRUTURA_ACIMA_PARA_CADA_TAREFA] - ---- - -## 👥 Análise de Públicos - -### Públicos Identificados - -#### [PÚBLICO_1] -- **Descrição**: [QUEM_SÃO] -- **Problemas**: [DORES_E_NECESSIDADES] -- **Comportamentos**: [PADRÕES_E_PREFERÊNCIAS] -- **Oportunidades**: - 1. [FEATURE_OU_ABORDAGEM_ESPECÍFICA] - 2. [MENSAGEM_OU_POSICIONAMENTO] - 3. [CASO_DE_USO_EXCLUSIVO] - -#### [PÚBLICO_2] -[REPETIR_ESTRUTURA_ACIMA] - ---- - -## 💡 Possibilidades Criativas - -### Caminhos Técnicos Alternativos - -#### Opção A: [NOME_DA_ABORDAGEM] -- **Tecnologias**: [STACK] -- **Prós**: - - [PRÓ_1] - - [PRÓ_2] -- **Contras**: - - [CONTRA_1] - - [CONTRA_2] -- **Quando Escolher**: [CONTEXTO_IDEAL] - -#### Opção B: [NOME_ALTERNATIVO] -[REPETIR_ESTRUTURA_ACIMA] - -### Ideias Não-Óbvias - -1. **[IDEIA_CRIATIVA_1]** - [DESCRIÇÃO_DA_APLICAÇÃO_ALTERNATIVA_OU_COMBINAÇÃO] - -2. **[IDEIA_CRIATIVA_2]** - [INVERSÃO_DE_PREMISSA_OU_ANALOGIA] - -3. **[IDEIA_CRIATIVA_3]** - [ADAPTAÇÃO_PARA_CONTEXTO_DIFERENTE] - -### Cenários Futuros - -#### Otimista -[O_QUE_ACONTECE_SE_TUDO_DER_CERTO] - -#### Pessimista -[PRINCIPAIS_RISCOS_E_COMO_MITIGAR] - -#### Realista -[CENÁRIO_MAIS_PROVÁVEL_COM_BALANÇO] - -#### Disruptivo -[MUDANÇA_RADICAL_QUE_PODE_ACONTECER] - ---- - -## ✨ Insights e Síntese - -### Padrões Identificados - -1. **[PADRÃO_1]**: [DESCRIÇÃO_DO_TEMA_RECORRENTE_OU_CONEXÃO] -2. **[PADRÃO_2]**: [TENSÃO_OU_TRADEOFF_FUNDAMENTAL] -3. **[PADRÃO_3]**: [PRINCÍPIO_OU_LEI_SUBJACENTE] - -### Insights-Chave - -#### 1. [INSIGHT_INESPERADO] -**Fundamentação**: [REFERÊNCIA_AO_CONTEÚDO_ANALISADO] -**Implicação**: [O_QUE_ISSO_SIGNIFICA_PARA_O_PROJETO] - -#### 2. [GAP_CRÍTICO] -**Fundamentação**: [REFERÊNCIA_AO_CONTEÚDO_ANALISADO] -**Implicação**: [O_QUE_PRECISA_SER_FEITO] - -#### 3. [OPORTUNIDADE_PROMISSORA] -**Fundamentação**: [REFERÊNCIA_AO_CONTEÚDO_ANALISADO] -**Implicação**: [COMO_EXPLORAR] - -### Recomendações Estratégicas - -#### Decisões Prontas para Serem Tomadas -1. [DECISÃO_COM_INFORMAÇÃO_SUFICIENTE] -2. [DECISÃO_COM_INFORMAÇÃO_SUFICIENTE] - -#### Decisões que Devem Ser Adiadas -1. [DECISÃO_PREMATURA] - **Razão**: [POR_QUE_ESPERAR] -2. [DECISÃO_PREMATURA] - **Razão**: [O_QUE_FALTA_SABER] - -#### Áreas que Merecem Mais Pesquisa -1. [ÁREA_TEMA] - **Priority**: Alta/Média/Baixa -2. [ÁREA_TEMA] - **Priority**: Alta/Média/Baixa - ---- - -## 🎯 Próximas Ações - -### Ações Imediatas (Próximos 3-5 passos) - -1. **[AÇÃO_1]** - **Command**: `/[COMMAND_SUGERIDO]` ou Manual - **Input**: [DADOS_DE_ENTRADA] - **Output Esperado**: [RESULTADO] - **Tempo**: [X] minutos - -2. **[AÇÃO_2]** - **Tipo**: Pesquisa Web - **Query**: `[QUERY_OTIMIZADA]` - **Fontes**: [SITES_OU_DOCS] - **Output Esperado**: [RESULTADO] - **Tempo**: [X] minutos - -3. **[AÇÃO_3]** - [CONTINUAR_PADRÃO_ACIMA] - -### Pesquisas Prioritárias - -| Query | Fontes | Output Esperado | Priority | -|-------|--------|-----------------|----------| -| [QUERY_1] | [FONTES] | [RESULTADO] | Alta | -| [QUERY_2] | [FONTES] | [RESULTADO] | Média | - -### Validações Necessárias - -| Hipótese | Método | Critério | Priority | -|----------|--------|----------|----------| -| [PREMISSA_A_TESTAR] | [COMO_TESTAR] | [MÉTRICA_DE_SUCESSO] | Alta | - ---- - -## 📝 Metadata - -**Total de Gaps Identificados**: [N] -**Total de Perguntas Formuladas**: [N] -**Total de Tarefas Geradas**: [N] -**Tarefas MUST**: [N] -**Tarefas SHOULD**: [N] -**Tarefas COULD**: [N] -**Tarefas WON'T**: [N] -**Públicos Analisados**: [N] -**Insights Principais**: [N] - -**Commands Sugeridos**: -- [COMMAND_1] -- [COMMAND_2] - -**Arquivos para Revisitar**: -- [ARQUIVO_1] -- [ARQUIVO_2] - ---- - -## 🔄 Iteração - -Este relatório pode ser re-explorado com `/analyzer` focando em: -- [ASPECTO_ESPECÍFICO_1] -- [ASPECTO_ESPECÍFICO_2] - -Ou usar como input para: -- `/backlog.planner` se features foram identificadas -- `/planner` se objetivo de implementação está claro -- Pesquisa manual seguindo queries sugeridas - diff --git a/shared/templates/feature-spec.template.md b/shared/templates/feature-spec.template.md deleted file mode 100644 index 88ab767..0000000 --- a/shared/templates/feature-spec.template.md +++ /dev/null @@ -1,302 +0,0 @@ ---- -type: feature-specification -spec_version: 1.0 -feature_id: [FEATURE_ID] -feature_name: [FEATURE_NAME] -status: draft -priority: [P0|P1|P2|P3|P4] -created_at: [TIMESTAMP] -updated_at: [TIMESTAMP] -author: [AUTHOR] -tags: [TAG1, TAG2, TAG3] -related_specs: [] -related_plans: [] -changelog: - - version: 1.0 - date: [TIMESTAMP] - changes: Initial specification created ---- - -# Feature Specification: [FEATURE_NAME] - -## 📋 Overview - -**Feature ID**: [FEATURE_ID] -**Status**: Draft -**Priority**: [PRIORITY] -**Estimated Complexity**: [LOW|MEDIUM|HIGH|VERY_HIGH] - -**One-line Summary**: -[Uma frase descrevendo o que esta feature faz] - -**Detailed Description**: -[Descrição completa da feature, incluindo contexto, motivação e visão geral da solução proposta. Explique WHAT será construído, não HOW.] - -## 🎯 Problem Statement - -**Problem**: -[Qual problema específico esta feature resolve? Por que é importante?] - -**Current State**: -[Como é hoje? O que existe atualmente? Quais são as limitações?] - -**Desired State**: -[Como será após esta feature? O que mudará?] - -**Impact**: -[Qual o impacto de NÃO resolver este problema? Quem é afetado?] - -## 👥 User Stories - -### Primary User Story - -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1 - específico e testável] -- [ ] [Critério 2 - específico e testável] -- [ ] [Critério 3 - específico e testável] - -### Additional User Stories - -#### Story 2: [Nome da história] -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1] -- [ ] [Critério 2] - -#### Story 3: [Nome da história] -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1] -- [ ] [Critério 2] - -## ✅ Acceptance Criteria (Consolidated) - -### Functional Requirements -- [ ] [Requisito funcional 1 - mensurável] -- [ ] [Requisito funcional 2 - mensurável] -- [ ] [Requisito funcional 3 - mensurável] - -### Non-Functional Requirements -- [ ] **Performance**: [Critério de performance específico] -- [ ] **Usability**: [Critério de usabilidade específico] -- [ ] **Reliability**: [Critério de confiabilidade específico] -- [ ] **Security**: [Critério de segurança específico] -- [ ] **Maintainability**: [Critério de manutenibilidade específico] - -### Edge Cases & Error Handling -- [ ] [Como lidar com caso extremo 1] -- [ ] [Como lidar com caso extremo 2] -- [ ] [Como lidar com erro 1] - -## 📦 Requirements - -### Functional Requirements - -#### FR-001: [Nome do requisito] -**Description**: [Descrição detalhada] -**Priority**: [MUST|SHOULD|COULD|WON'T] -**User Story**: [Referência à user story] - -#### FR-002: [Nome do requisito] -**Description**: [Descrição detalhada] -**Priority**: [MUST|SHOULD|COULD|WON'T] -**User Story**: [Referência à user story] - -### Non-Functional Requirements - -#### NFR-001: Performance -**Description**: [Requisito de performance específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -#### NFR-002: Security -**Description**: [Requisito de segurança específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -#### NFR-003: Usability -**Description**: [Requisito de usabilidade específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -## 🏗️ Technical Considerations - -### Architecture Impact -[Como esta feature impacta a arquitetura atual? Novos componentes? Mudanças em existentes?] - -### Technology Stack -- **Frontend**: [Tecnologias necessárias] -- **Backend**: [Tecnologias necessárias] -- **Infrastructure**: [Tecnologias necessárias] -- **Third-party**: [Serviços ou bibliotecas externas] - -### Data Model Changes -[Mudanças necessárias no modelo de dados? Novas entidades? Migrações?] - -### API Changes -[Novos endpoints? Mudanças em endpoints existentes? Breaking changes?] - -### Integration Points -[Quais sistemas/serviços esta feature integra? Como?] - -## 🔗 Dependencies - -### Internal Dependencies -- [ ] [Feature ou componente interno necessário] -- [ ] [Feature ou componente interno necessário] - -### External Dependencies -- [ ] [Serviço externo ou biblioteca necessária] -- [ ] [Serviço externo ou biblioteca necessária] - -### Blockers -- [ ] [Bloqueio que impede o início do desenvolvimento] -- [ ] [Bloqueio que impede o início do desenvolvimento] - -## 📊 Success Metrics - -### Quantitative Metrics -- **Metric 1**: [Nome da métrica] - Target: [Valor] -- **Metric 2**: [Nome da métrica] - Target: [Valor] -- **Metric 3**: [Nome da métrica] - Target: [Valor] - -### Qualitative Metrics -- [Como mediremos sucesso qualitativamente?] -- [Feedback de usuários? Surveys?] - -### OKRs (Optional) -**Objective**: [Objetivo de alto nível] - -**Key Results**: -- KR1: [Resultado-chave mensurável 1] -- KR2: [Resultado-chave mensurável 2] -- KR3: [Resultado-chave mensurável 3] - -## 🚨 Risks & Mitigation - -### Risk 1: [Nome do risco] -**Probability**: [LOW|MEDIUM|HIGH] -**Impact**: [LOW|MEDIUM|HIGH] -**Mitigation**: [Como mitigar este risco] -**Contingency**: [Plano B se risco se materializar] - -### Risk 2: [Nome do risco] -**Probability**: [LOW|MEDIUM|HIGH] -**Impact**: [LOW|MEDIUM|HIGH] -**Mitigation**: [Como mitigar este risco] -**Contingency**: [Plano B se risco se materializar] - -## 🎨 UX/UI Considerations (Optional) - -### User Flows -[Descrever fluxos principais do usuário] - -### Wireframes/Mockups -[Links para wireframes, mockups ou protótipos] - -### Design System -[Componentes do design system a serem usados ou criados] - -## 🧪 Testing Strategy - -### Unit Tests -- [ ] [Área a ser coberta por unit tests] -- [ ] [Área a ser coberta por unit tests] - -### Integration Tests -- [ ] [Integração a ser testada] -- [ ] [Integração a ser testada] - -### E2E Tests -- [ ] [Fluxo end-to-end a ser testado] -- [ ] [Fluxo end-to-end a ser testado] - -### Manual Testing Checklist -- [ ] [Cenário manual 1] -- [ ] [Cenário manual 2] - -## 📅 Timeline & Phases - -### Phase 1: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -### Phase 2: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -### Phase 3: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -## 📝 Open Questions - -1. [Questão em aberto 1 que precisa ser respondida] -2. [Questão em aberto 2 que precisa ser respondida] -3. [Questão em aberto 3 que precisa ser respondida] - -## 🔄 Changelog - -**How to version**: -1. When updating spec, increment `spec_version` in frontmatter: - - MAJOR.0 (2.0): Breaking changes, scope change - - X.MINOR (1.1): New sections, requirements added - - X.X.PATCH: Clarifications, typo fixes (optional) -2. Add entry to changelog below -3. Update `updated_at` timestamp -4. Keep all changelog history for traceability - ---- - -### [TIMESTAMP] - Version 1.0 -- Initial specification created -- Problem statement defined -- User stories documented -- Requirements specified - -### [Future versions will be added here] -- Example: Version 1.1 - Added NFR for accessibility -- Example: Version 2.0 - Scope changed to include admin panel - ---- - -## 📚 References - -- [Link 1 para documentação relevante] -- [Link 2 para pesquisa ou artigo] -- [Link 3 para spec relacionada] - -## 💬 Comments & Feedback - -_Use esta seção para adicionar comentários, feedback ou discussões sobre a spec._ - ---- - -**Next Steps**: -1. Review spec with stakeholders -2. Use `/clarify` to identify gaps and refine -3. Use `/planner.project` to create implementation plan -4. Use `/planner.task` to break down into tasks -5. Use `/exec.implement` to build the feature - ---- - -**Template Version**: 1.0 -**Last Updated**: 2025-10-13 - diff --git a/shared/templates/heuristic-evaluation.template.md b/shared/templates/heuristic-evaluation.template.md deleted file mode 100644 index d6c75fb..0000000 --- a/shared/templates/heuristic-evaluation.template.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -type: heuristic-evaluation -interface: {{INTERFACE_NAME}} -evaluator: {{EVALUATOR}} -date: {{EVALUATION_DATE}} ---- - -# Heuristic Evaluation: {{INTERFACE_NAME}} - -**Interface**: {{INTERFACE_NAME}} -**URL/Path**: {{INTERFACE_URL}} -**Evaluator**: {{EVALUATOR}} -**Date**: {{EVALUATION_DATE}} - -## 📊 Summary - -| Metric | Value | -|--------|-------| -| **Total Issues** | {{TOTAL_ISSUES}} | -| **Severity 4 (Catastrophic)** | {{SEV_4}} | -| **Severity 3 (Major)** | {{SEV_3}} | -| **Severity 2 (Minor)** | {{SEV_2}} | -| **Severity 1 (Cosmetic)** | {{SEV_1}} | - -## 🔍 Heuristic Checklist - -### 1. Visibility of System Status -{{HEURISTIC_1_EVAL}} - -### 2. Match Between System and Real World -{{HEURISTIC_2_EVAL}} - -### 3. User Control and Freedom -{{HEURISTIC_3_EVAL}} - -### 4. Consistency and Standards -{{HEURISTIC_4_EVAL}} - -### 5. Error Prevention -{{HEURISTIC_5_EVAL}} - -### 6. Recognition Rather Than Recall -{{HEURISTIC_6_EVAL}} - -### 7. Flexibility and Efficiency of Use -{{HEURISTIC_7_EVAL}} - -### 8. Aesthetic and Minimalist Design -{{HEURISTIC_8_EVAL}} - -### 9. Help Users Recognize, Diagnose, and Recover from Errors -{{HEURISTIC_9_EVAL}} - -### 10. Help and Documentation -{{HEURISTIC_10_EVAL}} - -## 🎯 Prioritized Recommendations - -### Severity 4 (Fix Immediately) -{{SEV_4_ISSUES}} - -### Severity 3 (High Priority) -{{SEV_3_ISSUES}} - -### Severity 2 (Medium Priority) -{{SEV_2_ISSUES}} - -### Severity 1 (Low Priority) -{{SEV_1_ISSUES}} - -## 📝 Notes - -{{ADDITIONAL_NOTES}} - diff --git a/shared/templates/in-review/angular-component-template.ts b/shared/templates/in-review/angular-component-template.ts deleted file mode 100644 index f07dddc..0000000 --- a/shared/templates/in-review/angular-component-template.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Component, OnInit, OnDestroy, signal } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { MatButtonModule } from '@angular/material/button'; -import { MatCardModule } from '@angular/material/card'; -import { Subject, takeUntil } from 'rxjs'; -import { [SERVICE_NAME] } from '../services/[SERVICE_FILE]'; -import { [MODEL_NAME] } from '../models/[MODEL_FILE]'; - -@Component({ - selector: 'app-[COMPONENT_NAME]', - standalone: true, - imports: [ - CommonModule, - MatButtonModule, - MatCardModule - ], - templateUrl: './[COMPONENT_NAME].component.html', - styleUrls: ['./[COMPONENT_NAME].component.scss'] -}) -export class [COMPONENT_CLASS_NAME]Component implements OnInit, OnDestroy { - private destroy$ = new Subject(); - - data = signal<[MODEL_NAME][]>([]); - loading = signal(false); - error = signal(null); - - constructor(private service: [SERVICE_NAME]) { } - - ngOnInit(): void { - this.loadData(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - loadData(): void { - this.loading.set(true); - this.error.set(null); - - this.service.getAll() - .pipe(takeUntil(this.destroy$)) - .subscribe({ - next: (data) => { - this.data.set(data); - this.loading.set(false); - }, - error: (err) => { - this.error.set(err.message); - this.loading.set(false); - } - }); - } - - onAction(item: [MODEL_NAME]): void { - } -} - diff --git a/shared/templates/in-review/angular-service-template.ts b/shared/templates/in-review/angular-service-template.ts deleted file mode 100644 index b500e3f..0000000 --- a/shared/templates/in-review/angular-service-template.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Injectable } from '@angular/core'; -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import { Observable, throwError } from 'rxjs'; -import { catchError, retry } from 'rxjs/operators'; -import { environment } from '../../../environments/environment'; -import { [MODEL_NAME] } from '../models/[MODEL_FILE]'; - -@Injectable({ - providedIn: 'root' -}) -export class [SERVICE_NAME] { - private readonly apiUrl = `${environment.apiUrl}/[RESOURCE_PATH]`; - - constructor(private http: HttpClient) { } - - getAll(): Observable < [MODEL_NAME][] > { - return this.http.get<[MODEL_NAME][]>(this.apiUrl) - .pipe( - retry(2), - catchError(this.handleError) - ); - } - - getById(id: number): Observable < [MODEL_NAME] > { - return this.http.get<[MODEL_NAME]>(`${this.apiUrl}/${id}`) - .pipe( - retry(2), - catchError(this.handleError) - ); - } - - create(data: [MODEL_NAME]): Observable < [MODEL_NAME] > { - return this.http.post<[MODEL_NAME]>(this.apiUrl, data) - .pipe( - catchError(this.handleError) - ); - } - - update(id: number, data: [MODEL_NAME]): Observable < [MODEL_NAME] > { - return this.http.put<[MODEL_NAME]>(`${this.apiUrl}/${id}`, data) - .pipe( - catchError(this.handleError) - ); - } - - delete (id: number): Observable < void> { - return this.http.delete(`${this.apiUrl}/${id}`) - .pipe( - catchError(this.handleError) - ); - } - - private handleError(error: any): Observable < never > { - let errorMessage = 'An error occurred'; - - if(error.error instanceof ErrorEvent) { - errorMessage = `Error: ${error.error.message}`; - } else { - errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; - if (error.error?.message) { - errorMessage = error.error.message; - } - } - - console.error(errorMessage); - return throwError(() => new Error(errorMessage)); -} -} - diff --git a/shared/templates/in-review/application-yml-template.yml b/shared/templates/in-review/application-yml-template.yml deleted file mode 100644 index b9f61ca..0000000 --- a/shared/templates/in-review/application-yml-template.yml +++ /dev/null @@ -1,67 +0,0 @@ -spring: - application: - name: [APPLICATION_NAME] - - datasource: - url: jdbc:postgresql://localhost:5432/[DATABASE_NAME] - username: ${DB_USERNAME:postgres} - password: ${DB_PASSWORD:postgres} - driver-class-name: org.postgresql.Driver - hikari: - maximum-pool-size: 10 - minimum-idle: 5 - connection-timeout: 30000 - idle-timeout: 600000 - max-lifetime: 1800000 - - jpa: - hibernate: - ddl-auto: validate - show-sql: false - properties: - hibernate: - dialect: org.hibernate.dialect.PostgreSQLDialect - format_sql: true - use_sql_comments: true - jdbc: - batch_size: 20 - order_inserts: true - order_updates: true - - flyway: - enabled: true - baseline-on-migrate: true - locations: classpath:db/migration - -server: - port: ${SERVER_PORT:8080} - servlet: - context-path: /api - error: - include-message: always - include-binding-errors: always - -logging: - level: - root: INFO - [PACKAGE_NAME]: DEBUG - org.hibernate.SQL: DEBUG - org.hibernate.type.descriptor.sql.BasicBinder: TRACE - -openai: - api: - key: ${OPENAI_API_KEY} - url: https://api.openai.com/v1 - model: gpt-4 - temperature: 0.7 - max-tokens: 1000 - -management: - endpoints: - web: - exposure: - include: health,info,metrics,prometheus - endpoint: - health: - show-details: always - diff --git a/shared/templates/in-review/architecture-modular.md b/shared/templates/in-review/architecture-modular.md deleted file mode 100644 index 40ab26f..0000000 --- a/shared/templates/in-review/architecture-modular.md +++ /dev/null @@ -1,1069 +0,0 @@ -# Guia de Arquitetura Modular - -## 📋 Visão Geral - -Este documento define a arquitetura padrão para todos os módulos do sistema, baseada em **Clean Architecture**, **SOLID principles** e **Domain-Driven Design (DDD)**. Cada módulo deve seguir esta estrutura para garantir manutenibilidade, testabilidade e escalabilidade. - -## 🎯 Princípios Fundamentais - -### 1. Separação de Responsabilidades -Cada camada tem uma responsabilidade única e bem definida. - -### 2. Inversão de Dependências -Camadas externas dependem de abstrações das camadas internas, nunca o contrário. - -### 3. Testabilidade -Toda lógica de negócio deve ser testável independentemente de frameworks ou infraestrutura. - -### 4. Configurabilidade -Comportamentos devem ser configuráveis sem alterar código. - -### 5. Extensibilidade -Novas funcionalidades devem ser adicionadas sem modificar código existente (Open/Closed Principle). - ---- - -## 📁 Estrutura de Diretórios - -``` -module-name/ -├── src/ -│ ├── domain/ # Camada de Domínio (Business Rules) -│ │ ├── entities/ # Entidades de negócio -│ │ ├── value-objects/ # Objetos de valor -│ │ ├── errors/ # Erros de domínio -│ │ └── validators/ # Validadores de negócio -│ │ -│ ├── application/ # Camada de Aplicação (Use Cases) -│ │ ├── services/ # Serviços de aplicação -│ │ ├── use-cases/ # Casos de uso específicos -│ │ └── ports/ # Interfaces/Contratos -│ │ ├── repositories/ # Interfaces de repositórios -│ │ ├── formatters/ # Interfaces de formatadores -│ │ ├── providers/ # Interfaces de provedores -│ │ └── logger.js # Interface de logger -│ │ -│ ├── infrastructure/ # Camada de Infraestrutura -│ │ ├── repositories/ # Implementações de repositórios -│ │ ├── formatters/ # Implementações de formatadores -│ │ ├── providers/ # Implementações de provedores -│ │ ├── logger/ # Implementação de logger -│ │ ├── database/ # Conexões e configs de DB -│ │ ├── cache/ # Cache (Redis, Memory, etc) -│ │ ├── http/ # Clientes HTTP -│ │ └── platform/ # Utilitários específicos de plataforma -│ │ -│ ├── presentation/ # Camada de Apresentação -│ │ ├── cli/ # Interface CLI -│ │ ├── api/ # REST API (se aplicável) -│ │ ├── controllers/ # Controllers -│ │ └── middleware/ # Middlewares -│ │ -│ ├── config/ # Configurações -│ │ ├── config.js # Configuração principal -│ │ └── schemas.js # Schemas de validação (Zod) -│ │ -│ └── index.js # Entry point -│ -├── tests/ -│ ├── unit/ # Testes unitários -│ │ ├── domain/ -│ │ ├── application/ -│ │ └── infrastructure/ -│ ├── integration/ # Testes de integração -│ └── e2e/ # Testes end-to-end -│ └── fixtures/ # Dados de teste -│ └── helpers/ # Helpers de teste -│ -├── .env.example # Template de variáveis de ambiente -├── package.json -└── README.md -``` - ---- - -## 🏗️ Camadas da Arquitetura - -### 1️⃣ Domain Layer (Núcleo do Negócio) - -**Responsabilidade:** Contém as regras de negócio puras, independentes de frameworks ou infraestrutura. - -**Características:** -- ✅ Sem dependências externas -- ✅ Apenas lógica de negócio -- ✅ Altamente testável -- ✅ Reutilizável - -#### 📄 Entities (Entidades) - -Objetos que representam conceitos do domínio com identidade única. - -```javascript -export class ChatSession { - constructor({ id, workspaceId, messages, createdAt, updatedAt }) { - this.id = id; - this.workspaceId = workspaceId; - this.messages = messages || []; - this.createdAt = createdAt || new Date(); - this.updatedAt = updatedAt || new Date(); - } - - addMessage(message) { - this.messages.push(message); - this.updatedAt = new Date(); - } - - getMessageCount() { - return this.messages.length; - } - - isRecent(daysThreshold = 7) { - const daysDiff = (Date.now() - this.createdAt) / (1000 * 60 * 60 * 24); - return daysDiff <= daysThreshold; - } -} -``` - -#### 📄 Value Objects (Objetos de Valor) - -Objetos imutáveis que representam valores sem identidade única. - -```javascript -export class ChatMessage { - constructor({ role, content, timestamp }) { - this.role = role; - this.content = content; - this.timestamp = timestamp || new Date(); - Object.freeze(this); - } - - isFromUser() { - return this.role === 'user'; - } - - isFromAssistant() { - return this.role === 'assistant'; - } -} -``` - -#### 📄 Domain Errors - -Erros específicos do domínio que representam violações de regras de negócio. - -```javascript -export class DomainError extends Error { - constructor(message, metadata = {}) { - super(message); - this.name = this.constructor.name; - this.metadata = metadata; - Error.captureStackTrace(this, this.constructor); - } -} - -export class InvalidSessionError extends DomainError { - constructor(message, metadata) { - super(message, metadata); - } -} - -export class SessionNotFoundError extends DomainError { - constructor(sessionId) { - super('Session not found', { sessionId }); - } -} -``` - -#### 📄 Validators - -Validadores de regras de negócio. - -```javascript -import { z } from 'zod'; - -export const chatMessageSchema = z.object({ - role: z.enum(['user', 'assistant', 'system']), - content: z.string().min(1), - timestamp: z.date().optional() -}); - -export const chatSessionSchema = z.object({ - id: z.string().uuid(), - workspaceId: z.string(), - messages: z.array(chatMessageSchema), - createdAt: z.date(), - updatedAt: z.date() -}); - -export function validateChatMessage(data) { - return chatMessageSchema.parse(data); -} - -export function validateChatSession(data) { - return chatSessionSchema.parse(data); -} -``` - ---- - -### 2️⃣ Application Layer (Casos de Uso) - -**Responsabilidade:** Orquestra a lógica de aplicação usando as regras do domínio. - -**Características:** -- ✅ Coordena entidades do domínio -- ✅ Define interfaces (ports) -- ✅ Implementa casos de uso -- ✅ Independente de frameworks - -#### 📄 Ports (Interfaces) - -Contratos que definem como a aplicação se comunica com o mundo externo. - -```javascript -export class SessionRepository { - async findAll() { - throw new Error('Method not implemented'); - } - - async findById(id) { - throw new Error('Method not implemented'); - } - - async findByWorkspace(workspaceId) { - throw new Error('Method not implemented'); - } - - async save(session) { - throw new Error('Method not implemented'); - } -} - -export class Formatter { - format(data) { - throw new Error('Method not implemented'); - } -} - -export class Logger { - info(message, metadata) { - throw new Error('Method not implemented'); - } - - error(message, metadata) { - throw new Error('Method not implemented'); - } - - warn(message, metadata) { - throw new Error('Method not implemented'); - } - - debug(message, metadata) { - throw new Error('Method not implemented'); - } -} -``` - -#### 📄 Services - -Serviços de aplicação que implementam a lógica de negócio complexa. - -```javascript -export class SessionReaderService { - constructor({ sessionRepository, formatter, logger }) { - this.sessionRepository = sessionRepository; - this.formatter = formatter; - this.logger = logger; - } - - async readAllSessions(options = {}) { - this.logger.info('Reading all sessions', options); - - try { - const sessions = await this.sessionRepository.findAll(); - - const filtered = this.filterSessions(sessions, options); - const sorted = this.sortSessions(filtered, options); - const formatted = this.formatter.format(sorted); - - this.logger.info('Sessions read successfully', { - count: sorted.length - }); - - return formatted; - } catch (error) { - this.logger.error('Failed to read sessions', { error }); - throw error; - } - } - - async searchInSessions(keyword, options = {}) { - this.logger.info('Searching sessions', { keyword, options }); - - const sessions = await this.sessionRepository.findAll(); - const matches = sessions.filter(session => - session.messages.some(msg => - msg.content.toLowerCase().includes(keyword.toLowerCase()) - ) - ); - - return this.formatter.format(matches); - } - - filterSessions(sessions, { startDate, endDate, workspaceId } = {}) { - return sessions.filter(session => { - if (startDate && session.createdAt < startDate) return false; - if (endDate && session.createdAt > endDate) return false; - if (workspaceId && session.workspaceId !== workspaceId) return false; - return true; - }); - } - - sortSessions(sessions, { sortBy = 'createdAt', order = 'desc' } = {}) { - return sessions.sort((a, b) => { - const compareValue = order === 'asc' ? 1 : -1; - return (a[sortBy] > b[sortBy] ? 1 : -1) * compareValue; - }); - } -} -``` - -#### 📄 Use Cases - -Casos de uso específicos que representam ações do sistema. - -```javascript -export class GetSessionByIdUseCase { - constructor({ sessionRepository, logger }) { - this.sessionRepository = sessionRepository; - this.logger = logger; - } - - async execute(sessionId) { - this.logger.debug('Getting session by id', { sessionId }); - - if (!sessionId) { - throw new InvalidSessionError('Session ID is required'); - } - - const session = await this.sessionRepository.findById(sessionId); - - if (!session) { - throw new SessionNotFoundError(sessionId); - } - - this.logger.debug('Session found', { sessionId }); - return session; - } -} - -export class ExportSessionsUseCase { - constructor({ sessionRepository, formatter, fileWriter, logger }) { - this.sessionRepository = sessionRepository; - this.formatter = formatter; - this.fileWriter = fileWriter; - this.logger = logger; - } - - async execute(outputPath, options = {}) { - this.logger.info('Exporting sessions', { outputPath, options }); - - const sessions = await this.sessionRepository.findAll(); - const formatted = this.formatter.format(sessions); - - await this.fileWriter.write(outputPath, formatted); - - this.logger.info('Sessions exported successfully', { - outputPath, - count: sessions.length - }); - - return { outputPath, count: sessions.length }; - } -} -``` - ---- - -### 3️⃣ Infrastructure Layer (Implementações) - -**Responsabilidade:** Implementações concretas de ports, integração com frameworks e ferramentas. - -**Características:** -- ✅ Implementa interfaces definidas em Application -- ✅ Integra com bibliotecas externas -- ✅ Lida com I/O (file system, database, API) -- ✅ Específico de plataforma - -#### 📄 Repositories - -Implementações concretas de acesso aos dados. - -```javascript -import fs from 'node:fs/promises'; -import path from 'node:path'; -import { SessionRepository } from '../../application/ports/repositories/session-repository.js'; -import { ChatSession } from '../../domain/entities/chat-session.js'; - -export class VSCodeSessionRepository extends SessionRepository { - constructor({ pathResolver, logger }) { - super(); - this.pathResolver = pathResolver; - this.logger = logger; - } - - async findAll() { - const sessionPaths = await this.pathResolver.getAllSessionPaths(); - const sessions = []; - - for (const sessionPath of sessionPaths) { - try { - const session = await this.loadSession(sessionPath); - sessions.push(session); - } catch (error) { - this.logger.warn('Failed to load session', { sessionPath, error }); - } - } - - return sessions; - } - - async findById(id) { - const sessionPath = await this.pathResolver.getSessionPath(id); - return this.loadSession(sessionPath); - } - - async findByWorkspace(workspaceId) { - const sessions = await this.findAll(); - return sessions.filter(s => s.workspaceId === workspaceId); - } - - async loadSession(filePath) { - const content = await fs.readFile(filePath, 'utf-8'); - const data = JSON.parse(content); - return new ChatSession(data); - } - - async save(session) { - const filePath = await this.pathResolver.getSessionPath(session.id); - await fs.writeFile(filePath, JSON.stringify(session, null, 2)); - } -} -``` - -#### 📄 Formatters - -Implementações de formatação de dados. - -```javascript -import { Formatter } from '../../application/ports/formatter.js'; - -export class ConsoleFormatter extends Formatter { - format(sessions) { - const lines = []; - - for (const session of sessions) { - lines.push(this.formatSessionHeader(session)); - - for (const message of session.messages) { - lines.push(this.formatMessage(message)); - } - - lines.push(this.formatSessionFooter()); - } - - return lines.join('\n'); - } - - formatSessionHeader(session) { - return [ - '\n' + '='.repeat(80), - `📝 Session: ${session.id}`, - `📁 Workspace: ${session.workspaceId}`, - `📅 Created: ${session.createdAt.toISOString()}`, - '='.repeat(80) - ].join('\n'); - } - - formatMessage(message) { - const icon = message.isFromUser() ? '👤' : '🤖'; - const role = message.role.toUpperCase(); - return `\n${icon} ${role}:\n${message.content}`; - } - - formatSessionFooter() { - return '-'.repeat(80); - } -} - -export class JsonFormatter extends Formatter { - format(sessions) { - return JSON.stringify(sessions, null, 2); - } -} - -export class MarkdownFormatter extends Formatter { - format(sessions) { - const lines = []; - - for (const session of sessions) { - lines.push(`# Session: ${session.id}`); - lines.push(`**Workspace:** ${session.workspaceId}`); - lines.push(`**Created:** ${session.createdAt.toISOString()}`); - lines.push(''); - - for (const message of session.messages) { - const role = message.isFromUser() ? 'User' : 'Assistant'; - lines.push(`## ${role}`); - lines.push(message.content); - lines.push(''); - } - - lines.push('---'); - lines.push(''); - } - - return lines.join('\n'); - } -} -``` - -#### 📄 Platform - -Utilitários específicos de plataforma. - -```javascript -import os from 'node:os'; -import path from 'node:path'; -import fs from 'node:fs/promises'; - -export class VSCodePathResolver { - constructor({ config, logger }) { - this.config = config; - this.logger = logger; - } - - getVSCodeUserDataPath() { - switch (os.platform()) { - case 'win32': - return path.join(os.homedir(), 'AppData', 'Roaming', 'Code', 'User'); - case 'darwin': - return path.join(os.homedir(), 'Library', 'Application Support', 'Code', 'User'); - case 'linux': - return path.join(os.homedir(), '.config', 'Code', 'User'); - default: - throw new Error(`Unsupported platform: ${os.platform()}`); - } - } - - getWorkspaceStoragePath() { - return path.join(this.getVSCodeUserDataPath(), 'workspaceStorage'); - } - - getChatSessionsPath(workspaceId) { - return path.join( - this.getWorkspaceStoragePath(), - workspaceId, - 'ms-vscode.copilot-chat', - 'chatSessions' - ); - } - - async getAllSessionPaths() { - const workspaceStorage = this.getWorkspaceStoragePath(); - const workspaces = await fs.readdir(workspaceStorage); - const sessionPaths = []; - - for (const workspace of workspaces) { - const chatPath = this.getChatSessionsPath(workspace); - - try { - const files = await fs.readdir(chatPath); - const jsonFiles = files - .filter(f => f.endsWith('.json')) - .map(f => path.join(chatPath, f)); - - sessionPaths.push(...jsonFiles); - } catch (error) { - if (error.code !== 'ENOENT') { - this.logger.warn('Failed to read workspace', { workspace, error }); - } - } - } - - return sessionPaths; - } - - async getSessionPath(sessionId) { - const allPaths = await this.getAllSessionPaths(); - return allPaths.find(p => p.includes(sessionId)); - } -} -``` - -#### 📄 Logger - -Implementação de logging estruturado. - -```javascript -import pino from 'pino'; -import { Logger } from '../../application/ports/logger.js'; - -export class PinoLogger extends Logger { - constructor(options = {}) { - super(); - this.logger = pino({ - level: options.level || 'info', - transport: options.pretty ? { - target: 'pino-pretty', - options: { - colorize: true, - translateTime: 'SYS:standard', - ignore: 'pid,hostname' - } - } : undefined - }); - } - - info(message, metadata = {}) { - this.logger.info(metadata, message); - } - - error(message, metadata = {}) { - this.logger.error(metadata, message); - } - - warn(message, metadata = {}) { - this.logger.warn(metadata, message); - } - - debug(message, metadata = {}) { - this.logger.debug(metadata, message); - } -} -``` - ---- - -### 4️⃣ Presentation Layer (Interface) - -**Responsabilidade:** Interface com o usuário (CLI, API, etc). - -**Características:** -- ✅ Recebe inputs do usuário -- ✅ Valida argumentos -- ✅ Chama use cases -- ✅ Apresenta resultados - -#### 📄 CLI - -Interface de linha de comando. - -```javascript -import { Command } from 'commander'; - -export class CLI { - constructor({ sessionService, exportUseCase, logger }) { - this.sessionService = sessionService; - this.exportUseCase = exportUseCase; - this.logger = logger; - this.program = new Command(); - } - - setup() { - this.program - .name('session-reader') - .description('Read and manage VS Code chat sessions') - .version('1.0.0'); - - this.program - .command('list') - .description('List all chat sessions') - .option('-w, --workspace ', 'Filter by workspace') - .option('-s, --sort ', 'Sort by field', 'createdAt') - .option('-o, --order ', 'Sort order', 'desc') - .action(async (options) => { - try { - const result = await this.sessionService.readAllSessions(options); - console.log(result); - } catch (error) { - this.logger.error('Failed to list sessions', { error }); - process.exit(1); - } - }); - - this.program - .command('search ') - .description('Search in sessions') - .action(async (keyword, options) => { - try { - const result = await this.sessionService.searchInSessions(keyword, options); - console.log(result); - } catch (error) { - this.logger.error('Failed to search sessions', { error }); - process.exit(1); - } - }); - - this.program - .command('export ') - .description('Export sessions to file') - .option('-f, --format ', 'Output format', 'json') - .action(async (output, options) => { - try { - const result = await this.exportUseCase.execute(output, options); - console.log(`✅ Exported ${result.count} sessions to ${result.outputPath}`); - } catch (error) { - this.logger.error('Failed to export sessions', { error }); - process.exit(1); - } - }); - } - - async run(args) { - await this.program.parseAsync(args); - } -} -``` - ---- - -### 5️⃣ Config Layer (Configuração) - -**Responsabilidade:** Gerenciar configurações da aplicação. - -#### 📄 Config - -```javascript -import 'dotenv/config'; -import { z } from 'zod'; - -const configSchema = z.object({ - NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), - LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'), - LOG_PRETTY: z.coerce.boolean().default(true), - VSCODE_PATH: z.string().optional(), - OUTPUT_FORMAT: z.enum(['console', 'json', 'markdown']).default('console') -}); - -export const config = configSchema.parse(process.env); - -export function validateConfig() { - try { - configSchema.parse(process.env); - return { valid: true }; - } catch (error) { - return { - valid: false, - errors: error.errors.map(e => ({ - path: e.path.join('.'), - message: e.message - })) - }; - } -} -``` - ---- - -### 6️⃣ Entry Point (Index) - -**Responsabilidade:** Composição de dependências (Dependency Injection Container). - -```javascript -import { config } from './config/config.js'; -import { PinoLogger } from './infrastructure/logger/pino-logger.js'; -import { VSCodePathResolver } from './infrastructure/platform/vscode-path-resolver.js'; -import { VSCodeSessionRepository } from './infrastructure/repositories/vscode-session-repository.js'; -import { ConsoleFormatter } from './infrastructure/formatters/console-formatter.js'; -import { JsonFormatter } from './infrastructure/formatters/json-formatter.js'; -import { MarkdownFormatter } from './infrastructure/formatters/markdown-formatter.js'; -import { SessionReaderService } from './application/services/session-reader-service.js'; -import { GetSessionByIdUseCase } from './application/use-cases/get-session-by-id.js'; -import { ExportSessionsUseCase } from './application/use-cases/export-sessions.js'; -import { CLI } from './presentation/cli/cli.js'; - -function createContainer() { - const logger = new PinoLogger({ - level: config.LOG_LEVEL, - pretty: config.LOG_PRETTY - }); - - const pathResolver = new VSCodePathResolver({ config, logger }); - - const sessionRepository = new VSCodeSessionRepository({ - pathResolver, - logger - }); - - const formatters = { - console: new ConsoleFormatter(), - json: new JsonFormatter(), - markdown: new MarkdownFormatter() - }; - - const formatter = formatters[config.OUTPUT_FORMAT]; - - const sessionService = new SessionReaderService({ - sessionRepository, - formatter, - logger - }); - - const getSessionByIdUseCase = new GetSessionByIdUseCase({ - sessionRepository, - logger - }); - - const exportUseCase = new ExportSessionsUseCase({ - sessionRepository, - formatter, - fileWriter: { write: async (path, content) => {} }, - logger - }); - - return { - logger, - sessionService, - getSessionByIdUseCase, - exportUseCase, - cli: new CLI({ - sessionService, - exportUseCase, - logger - }) - }; -} - -export async function main(args = process.argv) { - const container = createContainer(); - - try { - await container.cli.setup(); - await container.cli.run(args); - } catch (error) { - container.logger.error('Application failed', { error }); - process.exit(1); - } -} - -if (import.meta.url === `file://${process.argv[1]}`) { - main(); -} -``` - ---- - -## 🧪 Testing Strategy - -### Unit Tests - -Testam componentes isoladamente com mocks. - -```javascript -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { SessionReaderService } from '../../../src/application/services/session-reader-service.js'; - -describe('SessionReaderService', () => { - let service; - let mockRepository; - let mockFormatter; - let mockLogger; - - beforeEach(() => { - mockRepository = { - findAll: vi.fn() - }; - mockFormatter = { - format: vi.fn(data => JSON.stringify(data)) - }; - mockLogger = { - info: vi.fn(), - error: vi.fn() - }; - - service = new SessionReaderService({ - sessionRepository: mockRepository, - formatter: mockFormatter, - logger: mockLogger - }); - }); - - it('should read all sessions', async () => { - const mockSessions = [ - { id: '1', messages: [] }, - { id: '2', messages: [] } - ]; - mockRepository.findAll.mockResolvedValue(mockSessions); - - const result = await service.readAllSessions(); - - expect(mockRepository.findAll).toHaveBeenCalled(); - expect(mockFormatter.format).toHaveBeenCalledWith(mockSessions); - expect(result).toBe(JSON.stringify(mockSessions)); - }); - - it('should filter sessions by workspace', async () => { - const sessions = [ - { id: '1', workspaceId: 'ws1', messages: [] }, - { id: '2', workspaceId: 'ws2', messages: [] } - ]; - mockRepository.findAll.mockResolvedValue(sessions); - - await service.readAllSessions({ workspaceId: 'ws1' }); - - expect(mockFormatter.format).toHaveBeenCalledWith([sessions[0]]); - }); -}); -``` - -### Integration Tests - -Testam integração entre componentes reais. - -```javascript -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { createTestContainer } from '../helpers/test-container.js'; - -describe('Session Reading Integration', () => { - let container; - - beforeAll(async () => { - container = await createTestContainer(); - }); - - afterAll(async () => { - await container.cleanup(); - }); - - it('should read sessions from file system', async () => { - const sessions = await container.sessionService.readAllSessions(); - - expect(sessions).toBeDefined(); - expect(Array.isArray(sessions)).toBe(true); - }); -}); -``` - ---- - -## 📦 Package.json Configuration - -```json -{ - "name": "module-name", - "version": "1.0.0", - "type": "module", - "description": "Module description", - "main": "src/index.js", - "scripts": { - "start": "node src/index.js", - "dev": "node --watch src/index.js", - "test": "vitest", - "test:coverage": "vitest --coverage", - "test:ui": "vitest --ui", - "lint": "eslint src/**/*.js", - "format": "prettier --write src/**/*.js" - }, - "dependencies": { - "zod": "^3.22.0", - "dotenv": "^16.3.0", - "pino": "^8.16.0", - "pino-pretty": "^10.2.0", - "commander": "^11.1.0" - }, - "devDependencies": { - "vitest": "^1.0.0", - "@vitest/ui": "^1.0.0", - "eslint": "^8.54.0", - "prettier": "^3.1.0" - } -} -``` - ---- - -## 📝 Design Patterns Aplicados - -### 1. Repository Pattern -Abstração de acesso aos dados, permitindo trocar fonte sem afetar lógica. - -### 2. Strategy Pattern -Múltiplas implementações de formatadores, loggers, etc. - -### 3. Dependency Injection -Inversão de controle através de injeção no construtor. - -### 4. Factory Pattern -Criação de objetos complexos (container de dependências). - -### 5. Use Case Pattern -Cada ação do sistema é um caso de uso isolado. - -### 6. Port & Adapter (Hexagonal Architecture) -Portas definem interfaces, adapters implementam. - ---- - -## 🎯 Checklist de Qualidade - -Antes de considerar um módulo completo, verifique: - -- [ ] Todas as camadas estão implementadas -- [ ] Dependências injetadas via construtor -- [ ] Nenhuma dependência circular -- [ ] Configurações externalizadas em .env -- [ ] Erros customizados para domínio -- [ ] Logging estruturado implementado -- [ ] Validação de inputs com Zod -- [ ] Cobertura de testes > 80% -- [ ] Testes unitários para lógica de negócio -- [ ] Testes de integração para I/O -- [ ] README com instruções claras -- [ ] JSDoc para documentação de tipos -- [ ] ESM modules (import/export) -- [ ] Async/await consistentemente -- [ ] Error handling robusto -- [ ] Multiplataforma (Windows/Mac/Linux) - ---- - -## 🚀 Benefícios desta Arquitetura - -### ✅ Manutenibilidade -Código organizado e fácil de encontrar. - -### ✅ Testabilidade -Lógica isolada e mockável. - -### ✅ Escalabilidade -Adicione features sem quebrar existentes. - -### ✅ Flexibilidade -Troque implementações sem afetar lógica. - -### ✅ Reusabilidade -Componentes podem ser reutilizados. - -### ✅ Documentação -Estrutura auto-explicativa. - -### ✅ Onboarding -Novos devs entendem rapidamente. - ---- - -## 📚 Referências - -- Clean Architecture (Robert C. Martin) -- Domain-Driven Design (Eric Evans) -- SOLID Principles -- Hexagonal Architecture (Ports & Adapters) -- Test-Driven Development (TDD) - ---- - -**Versão:** 1.0.0 -**Data:** 2025-10-11 -**Autor:** React Native Agentic Updater Team - diff --git a/shared/templates/in-review/backlog.md b/shared/templates/in-review/backlog.md deleted file mode 100644 index 970ebfc..0000000 --- a/shared/templates/in-review/backlog.md +++ /dev/null @@ -1,403 +0,0 @@ -# [PROJECT_NAME] - Especificação de Backlog Detalhada - -## Sumário Executivo - -**Projeto:** [PROJECT_NAME] -**Categoria:** [CATEGORY] -**Complexidade Estimada:** [COMPLEXITY] -**Esforço Total (MVP):** [EFFORT_HOURS] horas -**Data de Análise:** [DATE] - -### Quick Overview - -[BRIEF_DESCRIPTION] - -### Principais Decisões Técnicas - -- **Stack Principal:** [MAIN_STACK] -- **Arquitetura:** [ARCHITECTURE_PATTERN] -- **Deploy:** [DEPLOYMENT_TARGET] - ---- - -## Visão do Produto - -### Problema que Resolve - -[PROBLEM_DESCRIPTION] - -### Usuário-Alvo - -[TARGET_USER] - -### Proposta de Valor - -[VALUE_PROPOSITION] - ---- - -## Features Decompostas - -### MVP (Minimum Viable Product) - -Features essenciais para o core do produto funcionar. - -#### Feature 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor para o usuário:** [USER_VALUE] - -**Complexidade:** [COMPLEXITY] (Simple/Medium/Complex) - -**Esforço estimado:** [EFFORT] horas - -**Dependências:** [DEPENDENCIES] - -**Critérios de aceite:** -- [ ] [ACCEPTANCE_CRITERIA_1] -- [ ] [ACCEPTANCE_CRITERIA_2] -- [ ] [ACCEPTANCE_CRITERIA_3] - -**Tasks técnicas:** -1. [TASK_1] -2. [TASK_2] -3. [TASK_3] - ---- - -#### Feature 2: [FEATURE_NAME] - -[REPEAT_STRUCTURE] - ---- - -### Enhancement Features - -Features que melhoram a experiência mas não são essenciais para o core. - -#### Enhancement 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor:** [VALUE] - -**Complexidade:** [COMPLEXITY] - -**Quando implementar:** [WHEN_TO_IMPLEMENT] - ---- - -### Advanced Features - -Features avançadas para versões futuras. - -#### Advanced 1: [FEATURE_NAME] - -**Descrição:** [FEATURE_DESCRIPTION] - -**Valor:** [VALUE] - -**Complexidade:** [COMPLEXITY] - ---- - -## Análise de Caminhos Técnicos - -### Decisão 1: [TECHNICAL_DECISION] - -#### Opção A: [OPTION_A_NAME] - -**Tecnologias:** [TECHNOLOGIES] - -**Prós:** -- [PRO_1] -- [PRO_2] -- [PRO_3] - -**Contras:** -- [CON_1] -- [CON_2] - -**Esforço:** [EFFORT] - -**Quando escolher:** [WHEN_TO_CHOOSE] - -#### Opção B: [OPTION_B_NAME] - -**Tecnologias:** [TECHNOLOGIES] - -**Prós:** -- [PRO_1] -- [PRO_2] - -**Contras:** -- [CON_1] -- [CON_2] - -**Esforço:** [EFFORT] - -**Quando escolher:** [WHEN_TO_CHOOSE] - -#### ✅ Recomendação - -[RECOMMENDATION_WITH_JUSTIFICATION] - ---- - -### Decisão 2: [TECHNICAL_DECISION] - -[REPEAT_STRUCTURE] - ---- - -## Análise de Tradeoffs - -### Tradeoff 1: [TRADEOFF_NAME] - -**Contexto:** [CONTEXT] - -**Opção A:** [OPTION_A] -**Impacto:** [IMPACT_A] - -**Opção B:** [OPTION_B] -**Impacto:** [IMPACT_B] - -**✅ Recomendação:** [RECOMMENDATION] - -**Justificativa:** [JUSTIFICATION] - ---- - -### Tradeoff 2: [TRADEOFF_NAME] - -[REPEAT_STRUCTURE] - ---- - -## Riscos e Mitigações - -### Risco 1: [RISK_NAME] - -**Descrição:** [RISK_DESCRIPTION] - -**Probabilidade:** [LOW/MEDIUM/HIGH] - -**Impacto:** [LOW/MEDIUM/HIGH] - -**Estratégia de Mitigação:** [MITIGATION_STRATEGY] - -**Plano B:** [FALLBACK_PLAN] - ---- - -### Risco 2: [RISK_NAME] - -[REPEAT_STRUCTURE] - ---- - -## Priorização e Roadmap - -### Framework de Priorização - -| Feature | Value (1-10) | Effort (1-10) | Priority Score | Fase | -|---------|-------------|---------------|----------------|------| -| [FEATURE_1] | [VALUE] | [EFFORT] | [SCORE] | MVP | -| [FEATURE_2] | [VALUE] | [EFFORT] | [SCORE] | MVP | -| [FEATURE_3] | [VALUE] | [EFFORT] | [SCORE] | Enhancement | -| [FEATURE_4] | [VALUE] | [EFFORT] | [SCORE] | Advanced | - -### Roadmap Sugerido - -#### Fase 1: MVP (Day 1) - -**Objetivo:** Produto mínimo funcional - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] -- [FEATURE_3] - -**Esforço total:** [HOURS] horas - -**Entregável:** [DELIVERABLE] - -#### Fase 2: Enhancement (Day 2+) - -**Objetivo:** Melhorias de experiência - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] - -**Esforço total:** [HOURS] horas - -#### Fase 3: Advanced (Future) - -**Objetivo:** Features avançadas - -**Features incluídas:** -- [FEATURE_1] -- [FEATURE_2] - ---- - -## Backlog de Tasks (MVP) - -### Setup Inicial - -- [ ] Criar repositório e estrutura de pastas -- [ ] Inicializar package.json com dependências -- [ ] Configurar build tools -- [ ] Setup inicial de [SPECIFIC_TOOLS] - -**Estimativa:** [MINUTES] minutos - -### Implementação Core - -#### Task 1: [TASK_NAME] - -**Descrição técnica:** [TECHNICAL_DESCRIPTION] - -**Critério de conclusão:** [DONE_CRITERIA] - -**Dependências:** [DEPENDENCIES] - -**Estimativa:** [TIME] - -**Arquivos envolvidos:** -- [FILE_1] -- [FILE_2] - ---- - -#### Task 2: [TASK_NAME] - -[REPEAT_STRUCTURE] - ---- - -### UI/UX - -- [ ] [UI_TASK_1] -- [ ] [UI_TASK_2] -- [ ] [UI_TASK_3] - -**Estimativa:** [TIME] - -### Integração - -- [ ] [INTEGRATION_TASK_1] -- [ ] [INTEGRATION_TASK_2] - -**Estimativa:** [TIME] - -### Testing & Deploy - -- [ ] Testar funcionalidades principais -- [ ] Testar edge cases -- [ ] Deploy para [PLATFORM] -- [ ] Criar README com screenshots - -**Estimativa:** [TIME] - ---- - -## Stack Tecnológica Detalhada - -### Frontend - -- **Framework:** [FRAMEWORK] -- **Styling:** [STYLING_SOLUTION] -- **State Management:** [STATE_MANAGEMENT] -- **Libs auxiliares:** [LIBS] - -### Backend / BaaS - -- **Solução:** [BACKEND_SOLUTION] -- **Database:** [DATABASE] -- **Auth:** [AUTH_SOLUTION] -- **Storage:** [STORAGE_SOLUTION] - -### Deploy & DevOps - -- **Hosting:** [HOSTING] -- **CI/CD:** [CI_CD] -- **Monitoring:** [MONITORING] - -### Dependências Principais - -```json -{ - "dependencies": { - "[PACKAGE_1]": "[VERSION]", - "[PACKAGE_2]": "[VERSION]" - } -} -``` - ---- - -## Recomendações Finais - -### Ordem de Implementação Sugerida - -1. [STEP_1] -2. [STEP_2] -3. [STEP_3] -4. [STEP_4] - -### Quick Wins - -Features que entregam valor rápido com pouco esforço: -- [QUICK_WIN_1] -- [QUICK_WIN_2] - -### Armadilhas a Evitar - -- ⚠️ [PITFALL_1] -- ⚠️ [PITFALL_2] -- ⚠️ [PITFALL_3] - -### Quando Simplificar - -Se o tempo for limitado, considere: -- ❌ Remover: [FEATURE_TO_CUT] -- 📉 Simplificar: [FEATURE_TO_SIMPLIFY] -- ⏭️ Adiar: [FEATURE_TO_POSTPONE] - -### Recursos Úteis - -- [RESOURCE_1]: [LINK] -- [RESOURCE_2]: [LINK] -- [RESOURCE_3]: [LINK] - ---- - -## Definition of Done - -O projeto está completo quando: - -- [ ] Todas as features MVP implementadas -- [ ] Funcionalidades principais testadas -- [ ] Deploy realizado com sucesso -- [ ] README com descrição e screenshots -- [ ] Demo acessível (link funcionando) -- [ ] Código commitado no GitHub -- [ ] Post de showcase publicado - ---- - -## Próximos Passos - -1. **Começar implementação:** Use o backlog de tasks acima -2. **Executar command:** `exec.implement.md` ou `plan-tasks.md` -3. **Monitorar progresso:** Marque tasks completadas -4. **Ajustar escopo:** Se necessário, simplifique usando recomendações - ---- - -**Backlog gerado em:** [TIMESTAMP] -**Próxima revisão:** Após implementação do MVP - diff --git a/shared/templates/in-review/clarification.template.md b/shared/templates/in-review/clarification.template.md deleted file mode 100644 index 8ccc7f7..0000000 --- a/shared/templates/in-review/clarification.template.md +++ /dev/null @@ -1,325 +0,0 @@ ---- -type: clarification-document -version: 1.0 -feature_id: [FEATURE_ID] -feature_name: [FEATURE_NAME] -source_spec: [SPEC_PATH] -analyzed_at: [TIMESTAMP] -status: pending-review -completeness_score: [0-100]% -blocker_issues: [N] -critical_issues: [N] -important_issues: [N] ---- - -# Clarifications: [FEATURE_NAME] - -## 📊 Analysis Summary - -**Source Document**: [SPEC_PATH] -**Analysis Date**: [TIMESTAMP] -**Overall Completeness**: [X]% -**Analyzer**: AI Agent (Cursor) - -**Issue Breakdown**: -- 🚨 Blocker Issues: [N] -- 🔴 Critical Issues: [N] -- 🟡 Important Issues: [N] -- 🟢 Minor Issues: [N] -- **Total**: [N] issues identified - -**Completeness by Section**: - -| Section | Present | Complete | Clear | Score | Issues | -|---------|---------|----------|-------|-------|--------| -| Overview | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Problem Statement | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| User Stories | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Acceptance Criteria | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Functional Req | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Non-Functional Req | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Technical Considerations | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Dependencies | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Risks & Mitigation | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| Success Metrics | [✅/❌] | [✅/⚠️/❌] | [✅/⚠️/❌] | [%] | [N] | -| **OVERALL** | - | - | - | **[%]** | **[N]** | - ---- - -## 🚨 Critical Issues (Blockers) - -_Issues that MUST be resolved before proceeding to planning/implementation_ - -### Issue #1: [Issue Title] - -**Section**: [Section Name] -**Type**: Gap / Ambiguity / Inconsistency / Missing -**Impact**: Blocks [what it blocks] -**Severity**: Blocker - -**Description**: -[Detailed description of the issue] - -**Questions to Answer**: -1. [Specific question 1] -2. [Specific question 2] -3. [Specific question 3] - -**Suggested Resolution**: -[Specific recommendation on how to resolve this] - -**Where to Update**: -[Exact section and location in spec to update] - ---- - -### Issue #2: [Issue Title] - -[Same structure as Issue #1] - ---- - -## 🔴 Critical Issues (High Priority) - -_Issues that significantly impact quality but don't block proceeding_ - -### Issue #3: [Issue Title] - -**Section**: [Section Name] -**Type**: Gap / Ambiguity / Inconsistency / Missing -**Impact**: [Description] -**Severity**: Critical - -**Description**: -[Detailed description] - -**Questions to Answer**: -1. [Question] - -**Suggested Resolution**: -[Recommendation] - ---- - -## 🟡 Important Issues (Medium Priority) - -_Issues that should be addressed for completeness_ - -### Issue #N: [Issue Title] - -[Same structure] - ---- - -## 🔍 Gaps Identified - -### Missing Information - -- [ ] **[Gap 1]**: [Description - where and what is missing] -- [ ] **[Gap 2]**: [Description] -- [ ] **[Gap 3]**: [Description] - -### Vague Statements - -- [ ] **[Vague 1]**: [Quote from spec] - Needs: [What needs to be clarified] -- [ ] **[Vague 2]**: [Quote from spec] - Needs: [What needs to be clarified] - -### Undocumented Assumptions - -- [ ] **[Assumption 1]**: [Implicit assumption that should be made explicit] -- [ ] **[Assumption 2]**: [Implicit assumption] - -### Missing Edge Cases - -- [ ] **[Edge Case 1]**: [Scenario not covered] -- [ ] **[Edge Case 2]**: [Scenario not covered] - -### Missing Error Handling - -- [ ] **[Error Scenario 1]**: [How to handle this error?] -- [ ] **[Error Scenario 2]**: [How to handle this error?] - ---- - -## ❓ Questions to Answer - -### 🚨 Blocker Questions (Must answer NOW) - -#### Q1: [Question] -- **Category**: Clarification / Decision / Technical / Validation -- **Impact**: [What happens if not answered] -- **Suggested by**: [Section that generated this question] -- **Priority**: Blocker -- **Answer**: _[To be filled]_ - ---- - -### 🔴 Critical Questions (High Priority) - -#### Q2: [Question] -- **Category**: [Category] -- **Impact**: [Impact] -- **Suggested by**: [Section] -- **Priority**: Critical -- **Answer**: _[To be filled]_ - ---- - -### 🟡 Important Questions (Medium Priority) - -#### Q3: [Question] -- **Category**: [Category] -- **Impact**: [Impact] -- **Suggested by**: [Section] -- **Priority**: Important -- **Answer**: _[To be filled]_ - ---- - -## 🎯 Ambiguities Detected - -### Ambiguity #1: [Title] - -**Location**: [Section and line] -**Statement**: "[Quote from spec]" -**Issue**: [Why this is ambiguous] -**Possible Interpretations**: -1. [Interpretation A] -2. [Interpretation B] - -**Clarification Needed**: [What exactly needs to be defined] - ---- - -## ⚠️ Inconsistencies Found - -### Inconsistency #1: [Title] - -**Locations**: [Sections involved] -**Issue**: [Description of inconsistency] -**Impact**: [What this breaks or confuses] -**Resolution**: [How to make consistent] - ---- - -## ✅ Recommendations - -### Immediate Actions (Do First) - -1. **[Action 1]**: [Specific action to take] - - **Section**: [Where to update] - - **What to add/change**: [Specific change] - - **Why**: [Rationale] - -2. **[Action 2]**: [Specific action] - - **Section**: [Where] - - **What**: [Change] - - **Why**: [Rationale] - -### Updates Needed by Section - -#### Section: [Section Name] -- **Issue**: [Problem identified] -- **Current**: [What exists now] -- **Recommended**: [What should exist] -- **Priority**: Blocker / Critical / Important - ---- - -## 📋 Checklist for Spec Update - -Use this checklist when updating the spec based on these clarifications: - -### Blockers (Must Fix) -- [ ] [Fix blocker issue 1] -- [ ] [Fix blocker issue 2] - -### Critical (Should Fix) -- [ ] [Fix critical issue 1] -- [ ] [Fix critical issue 2] - -### Important (Could Fix) -- [ ] [Fix important issue 1] -- [ ] [Fix important issue 2] - -### Validation -- [ ] All blocker questions answered -- [ ] All critical ambiguities resolved -- [ ] User stories have acceptance criteria -- [ ] Requirements are testable -- [ ] Success metrics are measurable -- [ ] Dependencies are documented -- [ ] Risks have mitigation strategies - ---- - -## 🔄 Iterative Refinement - -**Current Iteration**: 1 -**Completeness Progress**: [X]% → [Target: >90%] - -**Recommended Next Steps**: - -1. **Answer Blocker Questions**: - - [List blocker questions from above] - -2. **Update Spec**: - - Edit: `vibes/specs/[FEATURE_ID]/spec.md` - - Address blocker and critical issues - - Add missing information - - Clarify vague statements - - Resolve inconsistencies - -3. **Re-run Clarification**: - - Command: `/clarify vibes/specs/[FEATURE_ID]/spec.md` - - Validate improvements - - Check new completeness score - - Repeat until >90% - -4. **Proceed to Planning** (when ready): - - Command: `/planner.project vibes/specs/[FEATURE_ID]/spec.md` - - Planner will use clarified requirements - - Implementation will be guided by clear acceptance criteria - ---- - -## 📝 Notes & Comments - -_Use this section for additional observations, stakeholder feedback, or discussion notes_ - -[Free-form notes area] - ---- - -## 📚 References - -- **Source Spec**: [SPEC_PATH] -- **Related Specs**: [LIST if any] -- **Related Documents**: [LIST if any] - ---- - -## 🎯 Success Criteria for This Clarification - -- [ ] All blocker issues identified and documented -- [ ] Questions are specific and actionable -- [ ] Recommendations are practical -- [ ] Completeness score calculated for each section -- [ ] Next steps are clear -- [ ] Document is ready for stakeholder review - ---- - -**Clarification Version**: 1.0 -**Next Review**: After spec update -**Status**: -- [ ] Blockers resolved -- [ ] Critical questions answered -- [ ] Spec updated -- [ ] Ready for planning (>90% complete) - ---- - -**Template Version**: 1.0 -**Last Updated**: 2025-10-13 - diff --git a/shared/templates/in-review/constitution.md b/shared/templates/in-review/constitution.md deleted file mode 100644 index 1ed8d77..0000000 --- a/shared/templates/in-review/constitution.md +++ /dev/null @@ -1,50 +0,0 @@ -# [PROJECT_NAME] Constitution - - -## Core Principles - -### [PRINCIPLE_1_NAME] - -[PRINCIPLE_1_DESCRIPTION] - - -### [PRINCIPLE_2_NAME] - -[PRINCIPLE_2_DESCRIPTION] - - -### [PRINCIPLE_3_NAME] - -[PRINCIPLE_3_DESCRIPTION] - - -### [PRINCIPLE_4_NAME] - -[PRINCIPLE_4_DESCRIPTION] - - -### [PRINCIPLE_5_NAME] - -[PRINCIPLE_5_DESCRIPTION] - - -## [SECTION_2_NAME] - - -[SECTION_2_CONTENT] - - -## [SECTION_3_NAME] - - -[SECTION_3_CONTENT] - - -## Governance - - -[GOVERNANCE_RULES] - - -**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE] - \ No newline at end of file diff --git a/shared/templates/in-review/docker-compose-template.yml b/shared/templates/in-review/docker-compose-template.yml deleted file mode 100644 index 50733ac..0000000 --- a/shared/templates/in-review/docker-compose-template.yml +++ /dev/null @@ -1,65 +0,0 @@ -version: '3.8' - -services: - postgres: - image: postgres:15-alpine - container_name: [PROJECT_NAME]-postgres - environment: - POSTGRES_DB: [DATABASE_NAME] - POSTGRES_USER: ${DB_USERNAME:-postgres} - POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres} - ports: - - "5432:5432" - volumes: - - postgres_data:/var/lib/postgresql/data - networks: - - app-network - healthcheck: - test: ["CMD-SHELL", "pg_isready -U postgres"] - interval: 10s - timeout: 5s - retries: 5 - - backend: - build: - context: ./backend - dockerfile: Dockerfile - container_name: [PROJECT_NAME]-backend - environment: - SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/[DATABASE_NAME] - SPRING_DATASOURCE_USERNAME: ${DB_USERNAME:-postgres} - SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD:-postgres} - OPENAI_API_KEY: ${OPENAI_API_KEY} - SERVER_PORT: 8080 - ports: - - "8080:8080" - depends_on: - postgres: - condition: service_healthy - networks: - - app-network - restart: unless-stopped - - frontend: - build: - context: ./frontend - dockerfile: Dockerfile - container_name: [PROJECT_NAME]-frontend - environment: - API_URL: http://backend:8080/api - ports: - - "4200:80" - depends_on: - - backend - networks: - - app-network - restart: unless-stopped - -volumes: - postgres_data: - driver: local - -networks: - app-network: - driver: bridge - diff --git a/shared/templates/in-review/environment-ts-template.ts b/shared/templates/in-review/environment-ts-template.ts deleted file mode 100644 index 5ea5606..0000000 --- a/shared/templates/in-review/environment-ts-template.ts +++ /dev/null @@ -1,14 +0,0 @@ -export const environment = { - production: false, - apiUrl: 'http://localhost:8080/api', - features: { - enableAI: true, - enableWhisper: true, - enableDebugMode: true - }, - openai: { - maxTokens: 1000, - temperature: 0.7 - } -}; - diff --git a/shared/templates/in-review/feature-spec.template.md b/shared/templates/in-review/feature-spec.template.md deleted file mode 100644 index 88ab767..0000000 --- a/shared/templates/in-review/feature-spec.template.md +++ /dev/null @@ -1,302 +0,0 @@ ---- -type: feature-specification -spec_version: 1.0 -feature_id: [FEATURE_ID] -feature_name: [FEATURE_NAME] -status: draft -priority: [P0|P1|P2|P3|P4] -created_at: [TIMESTAMP] -updated_at: [TIMESTAMP] -author: [AUTHOR] -tags: [TAG1, TAG2, TAG3] -related_specs: [] -related_plans: [] -changelog: - - version: 1.0 - date: [TIMESTAMP] - changes: Initial specification created ---- - -# Feature Specification: [FEATURE_NAME] - -## 📋 Overview - -**Feature ID**: [FEATURE_ID] -**Status**: Draft -**Priority**: [PRIORITY] -**Estimated Complexity**: [LOW|MEDIUM|HIGH|VERY_HIGH] - -**One-line Summary**: -[Uma frase descrevendo o que esta feature faz] - -**Detailed Description**: -[Descrição completa da feature, incluindo contexto, motivação e visão geral da solução proposta. Explique WHAT será construído, não HOW.] - -## 🎯 Problem Statement - -**Problem**: -[Qual problema específico esta feature resolve? Por que é importante?] - -**Current State**: -[Como é hoje? O que existe atualmente? Quais são as limitações?] - -**Desired State**: -[Como será após esta feature? O que mudará?] - -**Impact**: -[Qual o impacto de NÃO resolver este problema? Quem é afetado?] - -## 👥 User Stories - -### Primary User Story - -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1 - específico e testável] -- [ ] [Critério 2 - específico e testável] -- [ ] [Critério 3 - específico e testável] - -### Additional User Stories - -#### Story 2: [Nome da história] -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1] -- [ ] [Critério 2] - -#### Story 3: [Nome da história] -**As a** [tipo de usuário] -**I want** [objetivo/desejo] -**So that** [benefício/valor] - -**Acceptance Criteria**: -- [ ] [Critério 1] -- [ ] [Critério 2] - -## ✅ Acceptance Criteria (Consolidated) - -### Functional Requirements -- [ ] [Requisito funcional 1 - mensurável] -- [ ] [Requisito funcional 2 - mensurável] -- [ ] [Requisito funcional 3 - mensurável] - -### Non-Functional Requirements -- [ ] **Performance**: [Critério de performance específico] -- [ ] **Usability**: [Critério de usabilidade específico] -- [ ] **Reliability**: [Critério de confiabilidade específico] -- [ ] **Security**: [Critério de segurança específico] -- [ ] **Maintainability**: [Critério de manutenibilidade específico] - -### Edge Cases & Error Handling -- [ ] [Como lidar com caso extremo 1] -- [ ] [Como lidar com caso extremo 2] -- [ ] [Como lidar com erro 1] - -## 📦 Requirements - -### Functional Requirements - -#### FR-001: [Nome do requisito] -**Description**: [Descrição detalhada] -**Priority**: [MUST|SHOULD|COULD|WON'T] -**User Story**: [Referência à user story] - -#### FR-002: [Nome do requisito] -**Description**: [Descrição detalhada] -**Priority**: [MUST|SHOULD|COULD|WON'T] -**User Story**: [Referência à user story] - -### Non-Functional Requirements - -#### NFR-001: Performance -**Description**: [Requisito de performance específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -#### NFR-002: Security -**Description**: [Requisito de segurança específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -#### NFR-003: Usability -**Description**: [Requisito de usabilidade específico] -**Metric**: [Métrica mensurável] -**Target**: [Valor alvo] - -## 🏗️ Technical Considerations - -### Architecture Impact -[Como esta feature impacta a arquitetura atual? Novos componentes? Mudanças em existentes?] - -### Technology Stack -- **Frontend**: [Tecnologias necessárias] -- **Backend**: [Tecnologias necessárias] -- **Infrastructure**: [Tecnologias necessárias] -- **Third-party**: [Serviços ou bibliotecas externas] - -### Data Model Changes -[Mudanças necessárias no modelo de dados? Novas entidades? Migrações?] - -### API Changes -[Novos endpoints? Mudanças em endpoints existentes? Breaking changes?] - -### Integration Points -[Quais sistemas/serviços esta feature integra? Como?] - -## 🔗 Dependencies - -### Internal Dependencies -- [ ] [Feature ou componente interno necessário] -- [ ] [Feature ou componente interno necessário] - -### External Dependencies -- [ ] [Serviço externo ou biblioteca necessária] -- [ ] [Serviço externo ou biblioteca necessária] - -### Blockers -- [ ] [Bloqueio que impede o início do desenvolvimento] -- [ ] [Bloqueio que impede o início do desenvolvimento] - -## 📊 Success Metrics - -### Quantitative Metrics -- **Metric 1**: [Nome da métrica] - Target: [Valor] -- **Metric 2**: [Nome da métrica] - Target: [Valor] -- **Metric 3**: [Nome da métrica] - Target: [Valor] - -### Qualitative Metrics -- [Como mediremos sucesso qualitativamente?] -- [Feedback de usuários? Surveys?] - -### OKRs (Optional) -**Objective**: [Objetivo de alto nível] - -**Key Results**: -- KR1: [Resultado-chave mensurável 1] -- KR2: [Resultado-chave mensurável 2] -- KR3: [Resultado-chave mensurável 3] - -## 🚨 Risks & Mitigation - -### Risk 1: [Nome do risco] -**Probability**: [LOW|MEDIUM|HIGH] -**Impact**: [LOW|MEDIUM|HIGH] -**Mitigation**: [Como mitigar este risco] -**Contingency**: [Plano B se risco se materializar] - -### Risk 2: [Nome do risco] -**Probability**: [LOW|MEDIUM|HIGH] -**Impact**: [LOW|MEDIUM|HIGH] -**Mitigation**: [Como mitigar este risco] -**Contingency**: [Plano B se risco se materializar] - -## 🎨 UX/UI Considerations (Optional) - -### User Flows -[Descrever fluxos principais do usuário] - -### Wireframes/Mockups -[Links para wireframes, mockups ou protótipos] - -### Design System -[Componentes do design system a serem usados ou criados] - -## 🧪 Testing Strategy - -### Unit Tests -- [ ] [Área a ser coberta por unit tests] -- [ ] [Área a ser coberta por unit tests] - -### Integration Tests -- [ ] [Integração a ser testada] -- [ ] [Integração a ser testada] - -### E2E Tests -- [ ] [Fluxo end-to-end a ser testado] -- [ ] [Fluxo end-to-end a ser testado] - -### Manual Testing Checklist -- [ ] [Cenário manual 1] -- [ ] [Cenário manual 2] - -## 📅 Timeline & Phases - -### Phase 1: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -### Phase 2: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -### Phase 3: [Nome da fase] -**Duration**: [Tempo estimado] -**Deliverables**: -- [Entregável 1] -- [Entregável 2] - -## 📝 Open Questions - -1. [Questão em aberto 1 que precisa ser respondida] -2. [Questão em aberto 2 que precisa ser respondida] -3. [Questão em aberto 3 que precisa ser respondida] - -## 🔄 Changelog - -**How to version**: -1. When updating spec, increment `spec_version` in frontmatter: - - MAJOR.0 (2.0): Breaking changes, scope change - - X.MINOR (1.1): New sections, requirements added - - X.X.PATCH: Clarifications, typo fixes (optional) -2. Add entry to changelog below -3. Update `updated_at` timestamp -4. Keep all changelog history for traceability - ---- - -### [TIMESTAMP] - Version 1.0 -- Initial specification created -- Problem statement defined -- User stories documented -- Requirements specified - -### [Future versions will be added here] -- Example: Version 1.1 - Added NFR for accessibility -- Example: Version 2.0 - Scope changed to include admin panel - ---- - -## 📚 References - -- [Link 1 para documentação relevante] -- [Link 2 para pesquisa ou artigo] -- [Link 3 para spec relacionada] - -## 💬 Comments & Feedback - -_Use esta seção para adicionar comentários, feedback ou discussões sobre a spec._ - ---- - -**Next Steps**: -1. Review spec with stakeholders -2. Use `/clarify` to identify gaps and refine -3. Use `/planner.project` to create implementation plan -4. Use `/planner.task` to break down into tasks -5. Use `/exec.implement` to build the feature - ---- - -**Template Version**: 1.0 -**Last Updated**: 2025-10-13 - diff --git a/shared/templates/in-review/openai-service-template.java b/shared/templates/in-review/openai-service-template.java deleted file mode 100644 index 7951743..0000000 --- a/shared/templates/in-review/openai-service-template.java +++ /dev/null @@ -1,89 +0,0 @@ -package [PACKAGE_NAME].infrastructure.ai; - -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.*; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import java.util.List; -import java.util.Map; - -@Service -@RequiredArgsConstructor -@Slf4j -public class OpenAIService { - - private final RestTemplate restTemplate; - - @Value("${openai.api.key}") - private String apiKey; - - @Value("${openai.api.url:https://api.openai.com/v1}") - private String apiUrl; - - @Value("${openai.model:gpt-4}") - private String model; - - public String chat(String prompt) { - return chat(prompt, 0.7, 1000); - } - - public String chat(String prompt, double temperature, int maxTokens) { - log.info("Sending chat request to OpenAI with model: {}", model); - - var headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setBearerAuth(apiKey); - - var requestBody = Map.of( - "model", model, - "messages", List.of(Map.of("role", "user", "content", prompt)), - "temperature", temperature, - "max_tokens", maxTokens - ); - - var request = new HttpEntity<>(requestBody, headers); - - try { - var response = restTemplate.postForEntity( - apiUrl + "/chat/completions", - request, - Map.class - ); - - var choices = (List>) response.getBody().get("choices"); - var message = (Map) choices.get(0).get("message"); - - return message.get("content"); - - } catch (Exception e) { - log.error("Error calling OpenAI API", e); - throw new RuntimeException("Failed to get response from OpenAI", e); - } - } - - public String transcribeAudio(byte[] audioData, String fileName) { - log.info("Sending audio transcription request to Whisper"); - - var headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - headers.setBearerAuth(apiKey); - - try { - var response = restTemplate.postForEntity( - apiUrl + "/audio/transcriptions", - null, - Map.class - ); - - return (String) response.getBody().get("text"); - - } catch (Exception e) { - log.error("Error calling Whisper API", e); - throw new RuntimeException("Failed to transcribe audio", e); - } - } -} - diff --git a/shared/templates/in-review/postgresql-migration-template.sql b/shared/templates/in-review/postgresql-migration-template.sql deleted file mode 100644 index 880caad..0000000 --- a/shared/templates/in-review/postgresql-migration-template.sql +++ /dev/null @@ -1,31 +0,0 @@ --- Migration: [MIGRATION_DESCRIPTION] --- Version: [VERSION_NUMBER] --- Date: [MIGRATION_DATE] - -CREATE TABLE IF NOT EXISTS [TABLE_NAME] ( - id BIGSERIAL PRIMARY KEY, - [COLUMN_NAME] [COLUMN_TYPE] [CONSTRAINTS], - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - created_by VARCHAR(255), - updated_by VARCHAR(255) -); - -CREATE INDEX idx_[TABLE_NAME]_[COLUMN_NAME] ON [TABLE_NAME]([COLUMN_NAME]); - -COMMENT ON TABLE [TABLE_NAME] IS '[TABLE_DESCRIPTION]'; -COMMENT ON COLUMN [TABLE_NAME].[COLUMN_NAME] IS '[COLUMN_DESCRIPTION]'; - -CREATE OR REPLACE FUNCTION update_updated_at_column() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = CURRENT_TIMESTAMP; - RETURN NEW; -END; -$$ language 'plpgsql'; - -CREATE TRIGGER update_[TABLE_NAME]_updated_at - BEFORE UPDATE ON [TABLE_NAME] - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - diff --git a/shared/templates/in-review/slack-feature-synced.template.md b/shared/templates/in-review/slack-feature-synced.template.md deleted file mode 100644 index c822cfb..0000000 --- a/shared/templates/in-review/slack-feature-synced.template.md +++ /dev/null @@ -1,24 +0,0 @@ -🔄 *Feature Sincronizada com Trello* - -*Feature:* {{FEATURE_NAME}} -*Tasks:* {{TOTAL}} - -*Distribution:* - • 🚨 P0: {{P0_COUNT}} - • 🔴 P1: {{P1_COUNT}} - • 🟡 P2: {{P2_COUNT}} - • 🟢 P3: {{P3_COUNT}} - • ⚪ P4: {{P4_COUNT}} - -*Phases:* - • MVP: {{MVP_COUNT}} tasks - • Alpha: {{ALPHA_COUNT}} tasks - • Beta: {{BETA_COUNT}} tasks - • Production: {{PROD_COUNT}} tasks - -━━━━━━━━━━━━━━━━ -🔗 <{{BOARD_URL}}|View Board> -📁 Feature Index: `{{INDEX_PATH}}` - - - diff --git a/shared/templates/in-review/slack-milestone.template.md b/shared/templates/in-review/slack-milestone.template.md deleted file mode 100644 index fc5b944..0000000 --- a/shared/templates/in-review/slack-milestone.template.md +++ /dev/null @@ -1,17 +0,0 @@ -🎉 *Milestone Atingido!* - -*Feature:* {{FEATURE_NAME}} -*Milestone:* {{MILESTONE_NAME}} - -{{MILESTONE_DETAILS}} - -*Próxima fase:* {{NEXT_PHASE}} -*Tasks pendentes:* {{PENDING_COUNT}} - -━━━━━━━━━━━━━━━━ -Progress Geral: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) - -🔗 <{{BOARD_URL}}|View Board> - - - diff --git a/shared/templates/in-review/slack-task-completed.template.md b/shared/templates/in-review/slack-task-completed.template.md deleted file mode 100644 index f5369f3..0000000 --- a/shared/templates/in-review/slack-task-completed.template.md +++ /dev/null @@ -1,21 +0,0 @@ -✅ *Task Completada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Status:* in_progress → completed - -*{{TITLE}}* -✨ Task finalizada com sucesso! - -*Next Suggested:* {{NEXT_TASK_ID}} - {{NEXT_TITLE}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> - - - diff --git a/shared/templates/in-review/slack-task-created.template.md b/shared/templates/in-review/slack-task-created.template.md deleted file mode 100644 index ac54416..0000000 --- a/shared/templates/in-review/slack-task-created.template.md +++ /dev/null @@ -1,23 +0,0 @@ -✨ *Nova Task Criada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Category:* {{CATEGORY}} -*Status:* pending - -*{{TITLE}}* -{{DESCRIPTION_SUMMARY}} - -*Estimated Time:* {{ESTIMATED_TIME}} -*Phase:* {{PHASE_NAME}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> - - - diff --git a/shared/templates/in-review/slack-task-started.template.md b/shared/templates/in-review/slack-task-started.template.md deleted file mode 100644 index 0f1af3b..0000000 --- a/shared/templates/in-review/slack-task-started.template.md +++ /dev/null @@ -1,20 +0,0 @@ -🔨 *Task Iniciada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Status:* pending → in_progress - -*{{TITLE}}* -{{DESCRIPTION_SUMMARY}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> -📁 Task File: `{{TASK_FILE_PATH}}` - - - diff --git a/shared/templates/in-review/spring-boot-controller-template.java b/shared/templates/in-review/spring-boot-controller-template.java deleted file mode 100644 index 939bec8..0000000 --- a/shared/templates/in-review/spring-boot-controller-template.java +++ /dev/null @@ -1,59 +0,0 @@ -package [PACKAGE_NAME].api.controller; - -import [PACKAGE_NAME].application.service.[SERVICE_NAME]; -import [PACKAGE_NAME].api.dto.[DTO_NAME]; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import jakarta.validation.Valid; -import java.util.List; - -@RestController -@RequestMapping("/api/[RESOURCE_PATH]") -@RequiredArgsConstructor -@Slf4j -public class [CONTROLLER_NAME] { - - private final [SERVICE_NAME] service; - - @GetMapping - public ResponseEntity> getAll() { - log.info("Fetching all [RESOURCE_NAME]"); - var result = service.findAll(); - return ResponseEntity.ok(result); - } - - @GetMapping("/{id}") - public ResponseEntity<[DTO_NAME]> getById(@PathVariable Long id) { - log.info("Fetching [RESOURCE_NAME] with id: {}", id); - var result = service.findById(id); - return ResponseEntity.ok(result); - } - - @PostMapping - public ResponseEntity<[DTO_NAME]> create(@Valid @RequestBody [DTO_NAME] dto) { - log.info("Creating new [RESOURCE_NAME]"); - var result = service.create(dto); - return ResponseEntity.status(HttpStatus.CREATED).body(result); - } - - @PutMapping("/{id}") - public ResponseEntity<[DTO_NAME]> update( - @PathVariable Long id, - @Valid @RequestBody [DTO_NAME] dto) { - log.info("Updating [RESOURCE_NAME] with id: {}", id); - var result = service.update(id, dto); - return ResponseEntity.ok(result); - } - - @DeleteMapping("/{id}") - public ResponseEntity delete(@PathVariable Long id) { - log.info("Deleting [RESOURCE_NAME] with id: {}", id); - service.delete(id); - return ResponseEntity.noContent().build(); - } -} - diff --git a/shared/templates/in-review/task.md b/shared/templates/in-review/task.md deleted file mode 100644 index d682903..0000000 --- a/shared/templates/in-review/task.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -task_id: {{TASK_ID}} -feature_id: {{FEATURE_ID}} -feature_name: {{FEATURE_NAME}} -title: {{TITLE}} -priority: {{PRIORITY}} -category: {{CATEGORY}} -status: pending -phase: {{PHASE}} -estimated_time: {{ESTIMATED_TIME}} -created_at: {{CREATED_AT}} -updated_at: {{UPDATED_AT}} -source_plan: {{SOURCE_PLAN}} -source_type: {{SOURCE_TYPE}} ---- - -# Task: {{TITLE}} - -## Metadata - -- **ID**: {{TASK_ID}} -- **Feature**: {{FEATURE_NAME}} ({{FEATURE_ID}}) -- **Priority**: {{PRIORITY_LABEL}} -- **Category**: {{CATEGORY}} -- **Status**: pending -- **Phase**: {{PHASE}} -- **Estimated Time**: {{ESTIMATED_TIME}} - -## Context - -**Feature**: {{FEATURE_NAME}} -**From Plan**: {{SOURCE_PLAN}} -**Plan Type**: {{SOURCE_TYPE}} -**Objective**: {{PLAN_OBJECTIVE}} - -{{CONTEXT_DESCRIPTION}} - -## Description - -{{FULL_DESCRIPTION}} - -## Affected Files - -{{AFFECTED_FILES}} - -## Dependencies - -**Depends On**: -{{DEPENDS_ON_LIST}} - -**Blocks**: -{{BLOCKS_LIST}} - -## Implementation Steps - -{{IMPLEMENTATION_STEPS}} - -## Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - -## Validation - -{{VALIDATION_CRITERIA}} - -## Notes - -{{ADDITIONAL_NOTES}} diff --git a/shared/templates/in-review/task.template.md b/shared/templates/in-review/task.template.md deleted file mode 100644 index 456840d..0000000 --- a/shared/templates/in-review/task.template.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -task_id: {{TASK_ID}} -feature_id: {{FEATURE_ID}} -feature_name: {{FEATURE_NAME}} -title: {{TITLE}} -priority: {{PRIORITY}} -category: {{CATEGORY}} -status: pending -phase: {{PHASE}} -estimated_time: {{ESTIMATED_TIME}} -created_at: {{CREATED_AT}} -updated_at: {{UPDATED_AT}} -source_plan: {{SOURCE_PLAN}} -source_type: {{SOURCE_TYPE}} ---- - -# Task: {{TITLE}} - -## Metadata - -- **ID**: {{TASK_ID}} -- **Feature**: {{FEATURE_NAME}} ({{FEATURE_ID}}) -- **Priority**: {{PRIORITY}} -- **Category**: {{CATEGORY}} -- **Status**: pending -- **Phase**: {{PHASE}} -- **Estimated Time**: {{ESTIMATED_TIME}} - -## Context - -**Feature**: {{FEATURE_NAME}} -**From Plan**: {{SOURCE_PLAN}} -**Plan Type**: {{SOURCE_TYPE}} -**Objective**: {{PLAN_OBJECTIVE}} - -{{CONTEXT_DESCRIPTION}} - -## Description - -{{FULL_DESCRIPTION}} - -## Affected Files - -{{FILE_LIST}} - -## Dependencies - -**Depends On**: -{{DEPENDS_ON_LIST}} - -**Blocks**: -{{BLOCKS_LIST}} - -## Implementation Steps - -{{IMPLEMENTATION_STEPS}} - -## Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - -## Validation - -{{VALIDATION}} - -## Notes - -{{NOTES}} - diff --git a/shared/templates/in-review/trello-card.template.md b/shared/templates/in-review/trello-card.template.md deleted file mode 100644 index acea047..0000000 --- a/shared/templates/in-review/trello-card.template.md +++ /dev/null @@ -1,45 +0,0 @@ -# {{TASK_ID}}: {{TITLE}} - -## 📋 Metadata - -- **Feature**: {{FEATURE_NAME}} ({{FEATURE_ID}}) -- **Priority**: {{PRIORITY}} -- **Category**: {{CATEGORY}} -- **Phase**: {{PHASE}} -- **Estimated Time**: {{ESTIMATED_TIME}} -- **Status**: {{STATUS}} - -## 📝 Description - -{{DESCRIPTION}} - -## 📂 Affected Files - -{{AFFECTED_FILES}} - -## 🔗 Dependencies - -**Depends On**: {{DEPENDS_ON}} -**Blocks**: {{BLOCKS}} - -## ✅ Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - -## 🎯 Validation - -{{VALIDATION}} - -## 📎 Links - -- Task File: `{{TASK_FILE_PATH}}` -- Feature Index: `vibes/tasks/{{FEATURE_ID}}/_INDEX.md` -- Source Plan: `{{SOURCE_PLAN}}` - ---- - -*Synced from filesystem* -*Last Sync: {{TIMESTAMP}}* - - - diff --git a/shared/templates/index.md b/shared/templates/index.md deleted file mode 100644 index be132d9..0000000 --- a/shared/templates/index.md +++ /dev/null @@ -1,41 +0,0 @@ -# [PROJECT_NAME] - Índice de Arquivos - -> Gerado automaticamente em [GENERATION_DATE] - -## Informações Gerais - -- **Diretório Raiz**: `[ROOT_DIRECTORY]` -- **Total de Arquivos**: [TOTAL_FILES] -- **Total de Diretórios**: [TOTAL_DIRECTORIES] -- **Profundidade Máxima**: [MAX_DEPTH] - -## Estrutura Hierárquica - -[TREE_STRUCTURE] - -## Arquivos por Tipo - -[FILES_BY_TYPE] - -## Arquivos Detalhados - -[DETAILED_FILE_LIST] - -## Próximos Passos - -- [ ] Revisar estrutura de diretórios -- [ ] Analisar dependências entre arquivos -- [ ] Documentar arquivos principais -- [ ] Identificar arquivos obsoletos - -## Metadados - -- **Padrões Excluídos**: [EXCLUDE_PATTERNS] -- **Arquivos Ocultos Incluídos**: [INCLUDE_HIDDEN] -- **Gerado por**: Command gerar-indices -- **Sourcemap**: Veja `_sourcemap.json` para estrutura completa em JSON - ---- - -*Este arquivo foi gerado automaticamente. Não edite manualmente.* - diff --git a/shared/templates/interview-findings.template.md b/shared/templates/interview-findings.template.md deleted file mode 100644 index b34f81c..0000000 --- a/shared/templates/interview-findings.template.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -type: interview-findings -participant_id: {{PARTICIPANT_ID}} -persona_match: {{PERSONA_MATCH}} -date: {{INTERVIEW_DATE}} -duration: {{ACTUAL_DURATION}} -interviewer: {{INTERVIEWER_NAME}} ---- - -# Interview Findings: {{PARTICIPANT_ID}} - -**Date**: {{INTERVIEW_DATE}} -**Duration**: {{ACTUAL_DURATION}} minutes -**Persona Match**: {{PERSONA_MATCH}} -**Interviewer**: {{INTERVIEWER_NAME}} - -## 👤 Participant Profile - -| Attribute | Value | -|-----------|-------| -| **Age** | {{AGE}} | -| **Occupation** | {{OCCUPATION}} | -| **Location** | {{LOCATION}} | -| **Tech Proficiency** | {{TECH_PROFICIENCY}} | -| **Product Usage** | {{USAGE_FREQUENCY}} | - -## 🗣️ Key Quotes - -> {{QUOTE_1}} - -> {{QUOTE_2}} - -> {{QUOTE_3}} - -## 📊 Findings - -### Behaviors Observed - -{{BEHAVIORS_OBSERVED}} - -### Pain Points Mentioned - -1. {{PAIN_POINT_1}} -2. {{PAIN_POINT_2}} -3. {{PAIN_POINT_3}} - -### Needs Expressed - -1. {{NEED_1}} -2. {{NEED_2}} -3. {{NEED_3}} - -### Positive Feedback - -{{POSITIVE_FEEDBACK}} - -### Negative Feedback / Frustrations - -{{NEGATIVE_FEEDBACK}} - -## 💡 Insights - -### Key Takeaways - -1. {{INSIGHT_1}} -2. {{INSIGHT_2}} -3. {{INSIGHT_3}} - -### Patterns & Themes - -{{PATTERNS_DESCRIPTION}} - -### Unexpected Discoveries - -{{UNEXPECTED_FINDINGS}} - -## 🎯 Recommendations - -Based on this interview: - -1. {{RECOMMENDATION_1}} -2. {{RECOMMENDATION_2}} -3. {{RECOMMENDATION_3}} - -## 📝 Raw Notes - -{{RAW_NOTES}} - -## 🔗 Related - -- **Research Goal**: {{RESEARCH_GOAL}} -- **Interview Script**: [{{SCRIPT_NAME}}]({{SCRIPT_PATH}}) -- **Other Interviews**: {{OTHER_INTERVIEWS_LINKS}} - ---- - -**Status**: {{STATUS}} -**Confidence**: {{CONFIDENCE_LEVEL}} -**Follow-up Needed**: {{FOLLOW_UP_NEEDED}} - diff --git a/shared/templates/interview-script.template.md b/shared/templates/interview-script.template.md deleted file mode 100644 index 2d351ef..0000000 --- a/shared/templates/interview-script.template.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -type: interview-script -research_goal: {{RESEARCH_GOAL}} -persona_target: {{PERSONA_TARGET}} -interview_type: {{INTERVIEW_TYPE}} -duration: {{DURATION}} -created_at: {{CREATED_AT}} ---- - -# Interview Script: {{RESEARCH_GOAL}} - -**Research Goal**: {{RESEARCH_GOAL}} -**Target Persona**: {{PERSONA_TARGET}} -**Type**: {{INTERVIEW_TYPE}} -**Duration**: {{DURATION}} minutes -**Date**: {{CREATED_AT}} - -## 🎯 Objectives - -{{OBJECTIVES_LIST}} - -## 👥 Participant Profile - -**Ideal participant**: -{{PARTICIPANT_CRITERIA}} - -## 📝 Interview Guide - -### Introduction (5 minutes) - -1. **Welcome & Thank**: - - Agradecer pela participação - - Explicar duração (~{{DURATION}} min) - -2. **Context**: - - Explicar objetivo: {{RESEARCH_GOAL_BRIEF}} - - Não há respostas certas ou erradas - - Feedback honesto é valioso - -3. **Consent**: - - Pedir permissão para gravar: "Posso gravar para facilitar anotações?" - - Garantir confidencialidade - ---- - -### Warm-up (5-10 minutes) - -**Tell me about** (contexto geral): - -{{WARMUP_QUESTIONS}} - ---- - -### Main Questions (20-30 minutes) - -#### Section 1: {{SECTION_1_TITLE}} - -{{SECTION_1_QUESTIONS}} - -#### Section 2: {{SECTION_2_TITLE}} - -{{SECTION_2_QUESTIONS}} - -#### Section 3: {{SECTION_3_TITLE}} - -{{SECTION_3_QUESTIONS}} - ---- - -### Closing (5 minutes) - -1. **Open floor**: "Há algo que não perguntei mas você acha importante compartilhar?" - -2. **Recommendation**: "Recomendaria [produto/serviço] para um amigo? Por quê?" - -3. **Thank & Next Steps**: - - Agradecer novamente - - Explicar próximos passos (análise, possível follow-up) - - Oferecer compensação (se aplicável) - -## 🎙️ Interview Techniques - -**During interview**: -- ✅ Listen more, talk less (80/20 rule) -- ✅ Allow silence (5-second rule antes de next question) -- ✅ Ask "why" 5 times para aprofundar -- ✅ Observe body language e hesitations -- ✅ Take notes de quotes literais -- ❌ Don't lead ("Don't you think X is bad?") -- ❌ Don't defend product (você está aprendendo) -- ❌ Don't interrupt - -## 📝 Findings Document - -**Salve findings em**: `.cursor/ux/interviews/{{SLUG}}-findings.md` - -Use template: `vibes/structure/templates/ux/interview-findings.template.md` - ---- - -**Prepared by**: Vibe DevTools UX Kit -**Based on**: research-methods.mdc (TEDW Framework) - diff --git a/shared/templates/journey-map.template.md b/shared/templates/journey-map.template.md deleted file mode 100644 index 396e73a..0000000 --- a/shared/templates/journey-map.template.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -type: journey-map -scenario: {{SCENARIO_NAME}} -persona: {{PERSONA_SLUG}} -created_at: {{CREATED_AT}} -updated_at: {{UPDATED_AT}} ---- - -# Journey Map: {{SCENARIO_NAME}} - -**Persona**: [{{PERSONA_NAME}}](../personas/{{PERSONA_SLUG}}.md) -**Scenario**: {{SCENARIO_DESCRIPTION}} -**Date**: {{CREATED_AT}} - -## 📋 Journey Overview - -| Metric | Value | -|--------|-------| -| **Total Stages** | {{TOTAL_STAGES}} | -| **Critical Pain Points** | {{CRITICAL_PAIN_POINTS}} | -| **Key Opportunities** | {{KEY_OPPORTUNITIES}} | -| **Overall Sentiment** | {{OVERALL_SENTIMENT}} | - -## 🗺️ Journey Stages - -{{STAGES_CONTENT}} - -## 📊 Journey Visualization - -```mermaid -journey - title {{SCENARIO_NAME}} - {{PERSONA_NAME}} -{{MERMAID_STAGES}} -``` - -## 📊 Insights & Analysis - -### Critical Pain Points - -{{PAIN_POINTS_SUMMARY}} - -### Top Opportunities - -{{OPPORTUNITIES_SUMMARY}} - -### Emotional Journey - -{{EMOTIONAL_ANALYSIS}} - -## 🎯 Recommendations - -{{RECOMMENDATIONS_LIST}} - -## 🔗 Related Artifacts - -- **Persona**: [{{PERSONA_NAME}}](../personas/{{PERSONA_SLUG}}.md) -- **Empathy Map**: {{EMPATHY_MAP_LINK}} -- **Usability Tests**: {{USABILITY_TESTS_LINKS}} -- **Research Source**: {{RESEARCH_SOURCE}} - -## 📝 Metadata - -- **Created**: {{CREATED_AT}} -- **Last Updated**: {{UPDATED_AT}} -- **Validated with Users**: {{VALIDATED}} -- **Confidence Level**: {{CONFIDENCE}} - ---- - -**Next Steps**: Use insights para priorizar features e design improvements. - diff --git a/shared/templates/mcp-config-template.json b/shared/templates/mcp-config-template.json deleted file mode 100644 index 663c6e2..0000000 --- a/shared/templates/mcp-config-template.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "mcpServers": { - "[SERVER_NAME]": { - "command": "[COMMAND]", - "args": [ - "[ARG1]", - "[ARG2]" - ], - "env": { - "[ENV_VAR_1]": "[VALUE_1]", - "[ENV_VAR_2]": "[VALUE_2]" - } - } - } -} \ No newline at end of file diff --git a/shared/templates/mcp-project-structure-template.md b/shared/templates/mcp-project-structure-template.md deleted file mode 100644 index 81e0861..0000000 --- a/shared/templates/mcp-project-structure-template.md +++ /dev/null @@ -1,697 +0,0 @@ -# Template de Estrutura de Projeto MCP - - - -**Criado**: 2025-01-16 -**Versão**: 1.0 - -## Estrutura de Diretórios - -``` -[PROJECT_NAME]/ -├── src/ -│ ├── index.ts # Entry point do servidor -│ ├── server.ts # Configuração e inicialização do servidor MCP -│ ├── resources/ # Resource providers -│ │ ├── index.ts # Export de todos os resources -│ │ └── example-resource.ts # Exemplo de resource provider -│ ├── tools/ # Tool providers -│ │ ├── index.ts # Export de todas as tools -│ │ └── example-tool.ts # Exemplo de tool provider -│ ├── prompts/ # Prompt templates (opcional) -│ │ ├── index.ts -│ │ └── example-prompt.ts -│ ├── types/ # Definições de tipos TypeScript -│ │ └── index.ts -│ ├── utils/ # Funções utilitárias -│ │ ├── index.ts -│ │ └── logger.ts -│ └── config/ # Configurações -│ └── index.ts -├── tests/ -│ ├── unit/ # Testes unitários -│ │ ├── resources/ -│ │ │ └── example-resource.test.ts -│ │ └── tools/ -│ │ └── example-tool.test.ts -│ └── integration/ # Testes de integração -│ └── server.test.ts -├── config/ -│ └── default.json # Configuração padrão -├── docs/ -│ ├── README.md # Documentação principal -│ ├── API.md # Documentação da API (se aplicável) -│ └── EXAMPLES.md # Exemplos de uso -├── .env.example # Template de variáveis de ambiente -├── .gitignore # Padrões de arquivos ignorados pelo Git -├── .eslintrc.json # Configuração do ESLint -├── .prettierrc # Configuração do Prettier -├── package.json # Dependências e scripts -├── tsconfig.json # Configuração do TypeScript -└── README.md # Documentação do projeto -``` - -## Arquivos de Configuração - -### package.json - -```json -{ - "name": "[PROJECT_NAME]", - "version": "0.1.0", - "description": "[PROJECT_DESCRIPTION]", - "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "dev": "tsx watch src/index.ts", - "build": "tsc", - "start": "node dist/index.js", - "test": "vitest", - "test:unit": "vitest run tests/unit", - "test:integration": "vitest run tests/integration", - "test:watch": "vitest watch", - "lint": "eslint src --ext .ts", - "format": "prettier --write \"src/**/*.ts\"", - "type-check": "tsc --noEmit" - }, - "keywords": [ - "mcp", - "model-context-protocol", - "server", - "[KEYWORDS]" - ], - "author": "[YOUR_NAME]", - "license": "MIT", - "dependencies": { - "@modelcontextprotocol/sdk": "^0.5.0" - }, - "devDependencies": { - "@types/node": "^20.10.0", - "@typescript-eslint/eslint-plugin": "^6.15.0", - "@typescript-eslint/parser": "^6.15.0", - "eslint": "^8.56.0", - "prettier": "^3.1.1", - "tsx": "^4.7.0", - "typescript": "^5.3.3", - "vitest": "^1.1.0" - }, - "engines": { - "node": ">=18.0.0" - } -} -``` - -### tsconfig.json - -```json -{ - "compilerOptions": { - "target": "ES2022", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "lib": ["ES2022"], - - "strict": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "strictBindCallApply": true, - "strictPropertyInitialization": true, - "noImplicitThis": true, - "alwaysStrict": true, - - "noUnusedLocals": true, - "noUnusedParameters": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedIndexedAccess": true, - "noImplicitOverride": true, - "noPropertyAccessFromIndexSignature": true, - - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "resolveJsonModule": true, - "isolatedModules": true, - "forceConsistentCasingInFileNames": true, - - "declaration": true, - "declarationMap": true, - "sourceMap": true, - - "outDir": "./dist", - "rootDir": "./src", - - "skipLibCheck": true - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "tests", "**/*.test.ts"] -} -``` - -### .env.example - -```bash -# MCP Server Configuration -MCP_SERVER_NAME=[PROJECT_NAME] -MCP_SERVER_VERSION=0.1.0 - -# Logging -LOG_LEVEL=info -LOG_FORMAT=json - -# [ADDITIONAL_ENV_VARIABLES] -# API_KEY=your-api-key-here -# DATABASE_URL=your-database-url-here -``` - -### .gitignore - -``` -# Dependencies -node_modules/ -package-lock.json -yarn.lock -pnpm-lock.yaml - -# Build output -dist/ -build/ -*.tsbuildinfo - -# Environment variables -.env -.env.local -.env.*.local - -# IDE -.vscode/ -.idea/ -*.swp -*.swo -*~ - -# OS -.DS_Store -Thumbs.db - -# Logs -logs/ -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Testing -coverage/ -.nyc_output/ - -# Misc -.cache/ -.temp/ -``` - -### .eslintrc.json - -```json -{ - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 2022, - "sourceType": "module", - "project": "./tsconfig.json" - }, - "plugins": ["@typescript-eslint"], - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/recommended-requiring-type-checking" - ], - "rules": { - "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], - "@typescript-eslint/explicit-function-return-type": "warn", - "@typescript-eslint/no-explicit-any": "error", - "@typescript-eslint/prefer-const": "error", - "no-console": ["warn", { "allow": ["warn", "error"] }] - }, - "env": { - "node": true, - "es2022": true - } -} -``` - -### .prettierrc - -```json -{ - "semi": true, - "trailingComma": "es5", - "singleQuote": true, - "printWidth": 100, - "tabWidth": 2, - "useTabs": false, - "arrowParens": "always", - "endOfLine": "lf" -} -``` - -## Código Base - -### src/index.ts - -```typescript -#!/usr/bin/env node - -import { Server } from '@modelcontextprotocol/sdk/server/index.js'; -import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; -import { - CallToolRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - ReadResourceRequestSchema, -} from '@modelcontextprotocol/sdk/types.js'; - -import { createLogger } from './utils/logger.js'; -import { initializeServer } from './server.js'; - -const logger = createLogger('index'); - -async function main() { - const server = new Server( - { - name: process.env.MCP_SERVER_NAME || '[PROJECT_NAME]', - version: process.env.MCP_SERVER_VERSION || '0.1.0', - }, - { - capabilities: { - resources: {}, - tools: {}, - }, - } - ); - - await initializeServer(server); - - const transport = new StdioServerTransport(); - await server.connect(transport); - - logger.info('MCP server started successfully'); -} - -main().catch((error) => { - logger.error('Failed to start MCP server', { error }); - process.exit(1); -}); -``` - -### src/server.ts - -```typescript -import { Server } from '@modelcontextprotocol/sdk/server/index.js'; -import { - CallToolRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - ReadResourceRequestSchema, -} from '@modelcontextprotocol/sdk/types.js'; - -import { createLogger } from './utils/logger.js'; -import * as resources from './resources/index.js'; -import * as tools from './tools/index.js'; - -const logger = createLogger('server'); - -export async function initializeServer(server: Server): Promise { - server.setRequestHandler(ListResourcesRequestSchema, async () => { - logger.info('Listing resources'); - return resources.listResources(); - }); - - server.setRequestHandler(ReadResourceRequestSchema, async (request) => { - logger.info('Reading resource', { uri: request.params.uri }); - return resources.readResource(request.params.uri); - }); - - server.setRequestHandler(ListToolsRequestSchema, async () => { - logger.info('Listing tools'); - return tools.listTools(); - }); - - server.setRequestHandler(CallToolRequestSchema, async (request) => { - logger.info('Calling tool', { name: request.params.name }); - return tools.callTool(request.params.name, request.params.arguments); - }); - - logger.info('Server initialized successfully'); -} -``` - -### src/types/index.ts - -```typescript -export interface ServerConfig { - name: string; - version: string; - logLevel: 'debug' | 'info' | 'warn' | 'error'; - [key: string]: unknown; -} - -export interface ResourceMetadata { - name: string; - description: string; - uri: string; - mimeType: string; -} - -export interface ToolMetadata { - name: string; - description: string; - inputSchema: { - type: 'object'; - properties: Record; - required?: string[]; - }; -} - -export type ToolArguments = Record; -``` - -### src/utils/logger.ts - -```typescript -export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; - -interface LogContext { - [key: string]: unknown; -} - -export function createLogger(module: string) { - const logLevel = (process.env.LOG_LEVEL || 'info') as LogLevel; - - const levels: Record = { - debug: 0, - info: 1, - warn: 2, - error: 3, - }; - - const currentLevel = levels[logLevel]; - - function log(level: LogLevel, message: string, context?: LogContext) { - if (levels[level] >= currentLevel) { - const timestamp = new Date().toISOString(); - const logMessage = JSON.stringify({ - timestamp, - level, - module, - message, - ...context, - }); - - console.log(logMessage); - } - } - - return { - debug: (message: string, context?: LogContext) => log('debug', message, context), - info: (message: string, context?: LogContext) => log('info', message, context), - warn: (message: string, context?: LogContext) => log('warn', message, context), - error: (message: string, context?: LogContext) => log('error', message, context), - }; -} -``` - -### src/resources/index.ts - -```typescript -import { Resource } from '@modelcontextprotocol/sdk/types.js'; -import { ResourceMetadata } from '../types/index.js'; -import { exampleResource } from './example-resource.js'; - -export async function listResources(): Promise { - return [ - { - uri: 'example://resource', - name: 'Example Resource', - description: 'An example resource', - mimeType: 'application/json', - }, - ]; -} - -export async function readResource(uri: string): Promise { - if (uri === 'example://resource') { - return exampleResource(); - } - - throw new Error(`Resource not found: ${uri}`); -} -``` - -### src/resources/example-resource.ts - -```typescript -import { Resource } from '@modelcontextprotocol/sdk/types.js'; - -export function exampleResource(): Resource { - return { - uri: 'example://resource', - name: 'Example Resource', - description: 'An example resource demonstrating the structure', - mimeType: 'application/json', - text: JSON.stringify({ - message: 'Hello from MCP server!', - timestamp: new Date().toISOString(), - data: { - example: true, - count: 42, - }, - }, null, 2), - }; -} -``` - -### src/tools/index.ts - -```typescript -import { Tool, TextContent } from '@modelcontextprotocol/sdk/types.js'; -import { ToolArguments } from '../types/index.js'; -import { exampleTool } from './example-tool.js'; - -export async function listTools(): Promise { - return [ - { - name: 'example_tool', - description: 'An example tool that demonstrates the structure', - inputSchema: { - type: 'object', - properties: { - message: { - type: 'string', - description: 'The message to process', - }, - }, - required: ['message'], - }, - }, - ]; -} - -export async function callTool( - name: string, - args: ToolArguments -): Promise { - if (name === 'example_tool') { - return exampleTool(args); - } - - throw new Error(`Tool not found: ${name}`); -} -``` - -### src/tools/example-tool.ts - -```typescript -import { TextContent } from '@modelcontextprotocol/sdk/types.js'; -import { ToolArguments } from '../types/index.js'; - -export function exampleTool(args: ToolArguments): TextContent[] { - const message = args.message as string; - - return [ - { - type: 'text', - text: JSON.stringify({ - success: true, - message: `Processed: ${message}`, - timestamp: new Date().toISOString(), - input: args, - }, null, 2), - }, - ]; -} -``` - -## Testes - -### tests/unit/resources/example-resource.test.ts - -```typescript -import { describe, it, expect } from 'vitest'; -import { exampleResource } from '../../../src/resources/example-resource.js'; - -describe('exampleResource', () => { - it('should return a valid resource', () => { - const resource = exampleResource(); - - expect(resource).toBeDefined(); - expect(resource.uri).toBe('example://resource'); - expect(resource.name).toBe('Example Resource'); - expect(resource.mimeType).toBe('application/json'); - expect(resource.text).toBeDefined(); - }); - - it('should return JSON content', () => { - const resource = exampleResource(); - const data = JSON.parse(resource.text || '{}'); - - expect(data.message).toBe('Hello from MCP server!'); - expect(data.timestamp).toBeDefined(); - expect(data.data).toBeDefined(); - }); -}); -``` - -### tests/unit/tools/example-tool.test.ts - -```typescript -import { describe, it, expect } from 'vitest'; -import { exampleTool } from '../../../src/tools/example-tool.js'; - -describe('exampleTool', () => { - it('should process a message', () => { - const result = exampleTool({ message: 'test' }); - - expect(result).toHaveLength(1); - expect(result[0].type).toBe('text'); - - const data = JSON.parse(result[0].text); - expect(data.success).toBe(true); - expect(data.message).toContain('test'); - }); - - it('should include timestamp', () => { - const result = exampleTool({ message: 'test' }); - const data = JSON.parse(result[0].text); - - expect(data.timestamp).toBeDefined(); - expect(new Date(data.timestamp).getTime()).toBeGreaterThan(0); - }); -}); -``` - -## Documentação - -### README.md - -```markdown -# [PROJECT_NAME] - -[PROJECT_DESCRIPTION] - -## Features - -- [FEATURE_1] -- [FEATURE_2] -- [FEATURE_3] - -## Installation - -\`\`\`bash -npm install -\`\`\` - -## Configuration - -Copy \`.env.example\` to \`.env\` and configure your environment variables: - -\`\`\`bash -cp .env.example .env -\`\`\` - -## Development - -\`\`\`bash -npm run dev -\`\`\` - -## Building - -\`\`\`bash -npm run build -\`\`\` - -## Testing - -\`\`\`bash -npm test -\`\`\` - -## Usage - -[USAGE_INSTRUCTIONS] - -## License - -MIT -``` - -## Checklist de Qualidade - -Antes de considerar este template completo, verifique: - -### Estrutura -- [x] Diretórios obrigatórios definidos (src/, tests/, config/, docs/) -- [x] Arquivos de configuração essenciais incluídos -- [x] Código base funcional fornecido -- [x] Exemplos de resources e tools incluídos - -### Configuração -- [x] package.json com scripts e dependências -- [x] tsconfig.json com strict mode -- [x] .env.example com variáveis de ambiente -- [x] .gitignore com padrões apropriados -- [x] .eslintrc.json e .prettierrc configurados - -### Código -- [x] Entry point (index.ts) funcional -- [x] Server initialization (server.ts) completa -- [x] Logger utility implementado -- [x] Type definitions claras -- [x] Exemplos de resources e tools funcionais - -### Testes -- [x] Estrutura de testes definida -- [x] Exemplo de teste unitário fornecido -- [x] Configuração de Vitest incluída - -### Documentação -- [x] README.md com instruções básicas -- [x] Comandos de desenvolvimento documentados -- [x] Estrutura de projeto explicada - ---- - -## Metadados do Template - -**Versão**: 1.0.0 -**Criado**: 2025-01-16 -**Mantido Por**: planner.mcp-resources.md - -**Changelog**: -- 1.0.0 (2025-01-16): Template inicial para scaffold de projetos MCP em TypeScript diff --git a/shared/templates/medical.template.anamnesis.chronic.md b/shared/templates/medical.template.anamnesis.chronic.md deleted file mode 100644 index 7176d12..0000000 --- a/shared/templates/medical.template.anamnesis.chronic.md +++ /dev/null @@ -1,303 +0,0 @@ -# Template de Anamnese de Condições Crônicas - -**Criado**: $DATE -**Versão**: 1.0 -**Usado por**: medical.anamnesis.md -**Contexto**: Anamnese de condições crônicas e acompanhamento - ---- - -## Dados Demográficos *(obrigatório)* - -**Nome**: [NOME_DO_PACIENTE] -**Idade**: [IDADE] anos -**Gênero**: [GÊNERO] -**Data da Consulta**: [DATA] -**Especialidade**: [ESPECIALIDADE] - ---- - -## Condições Crônicas Atuais *(obrigatório)* - -### Condições Crônicas - -1. **[CONDIÇÃO_1]**: - - Diagnóstico: [DIAGNÓSTICO] - - Data do diagnóstico: [DATA] - - Gravidade: [LEVE/MODERADA/SEVERA] - - Controle: [BOM/REGULAR/RUIM] - -2. **[CONDIÇÃO_2]**: - - Diagnóstico: [DIAGNÓSTICO] - - Data do diagnóstico: [DATA] - - Gravidade: [LEVE/MODERADA/SEVERA] - - Controle: [BOM/REGULAR/RUIM] - -3. **[CONDIÇÃO_3]**: - - Diagnóstico: [DIAGNÓSTICO] - - Data do diagnóstico: [DATA] - - Gravidade: [LEVE/MODERADA/SEVERA] - - Controle: [BOM/REGULAR/RUIM] - ---- - -## Evolução das Condições *(obrigatório)* - -### [CONDIÇÃO_1] - -**Evolução desde última consulta**: -- Status: [MELHORANDO/ESTÁVEL/PIORANDO] -- Mudanças: [DESCRIÇÃO_DAS_MUDANÇAS] -- Fatores relacionados: [FATORES_RELACIONADOS] - -**Sintomas Atuais**: -- [SINTOMA_1]: [FREQUÊNCIA] - [GRAVIDADE] -- [SINTOMA_2]: [FREQUÊNCIA] - [GRAVIDADE] -- [SINTOMA_3]: [FREQUÊNCIA] - [GRAVIDADE] - -**Impacto Funcional**: -- Atividades de vida diária: [IMPACTO] -- Trabalho: [IMPACTO] -- Qualidade de vida: [IMPACTO] - -### [CONDIÇÃO_2] - -**Evolução desde última consulta**: -- Status: [MELHORANDO/ESTÁVEL/PIORANDO] -- Mudanças: [DESCRIÇÃO_DAS_MUDANÇAS] -- Fatores relacionados: [FATORES_RELACIONADOS] - -**Sintomas Atuais**: -- [SINTOMA_1]: [FREQUÊNCIA] - [GRAVIDADE] -- [SINTOMA_2]: [FREQUÊNCIA] - [GRAVIDADE] -- [SINTOMA_3]: [FREQUÊNCIA] - [GRAVIDADE] - -**Impacto Funcional**: -- Atividades de vida diária: [IMPACTO] -- Trabalho: [IMPACTO] -- Qualidade de vida: [IMPACTO] - ---- - -## Medicações e Aderência *(obrigatório)* - -### Medicações Crônicas - -1. **[MEDICAÇÃO_1]**: - - Dosagem: [DOSAGEM] - - Frequência: [FREQUÊNCIA] - - Indicação: [INDICAÇÃO] - - Duração: [DURAÇÃO] - - Aderência: [EXCELENTE/BOA/REGULAR/RUIM] - - Efeitos colaterais: [SIM/NÃO] - [DESCRIÇÃO] - -2. **[MEDICAÇÃO_2]**: - - Dosagem: [DOSAGEM] - - Frequência: [FREQUÊNCIA] - - Indicação: [INDICAÇÃO] - - Duração: [DURAÇÃO] - - Aderência: [EXCELENTE/BOA/REGULAR/RUIM] - - Efeitos colaterais: [SIM/NÃO] - [DESCRIÇÃO] - -3. **[MEDICAÇÃO_3]**: - - Dosagem: [DOSAGEM] - - Frequência: [FREQUÊNCIA] - - Indicação: [INDICAÇÃO] - - Duração: [DURAÇÃO] - - Aderência: [EXCELENTE/BOA/REGULAR/RUIM] - - Efeitos colaterais: [SIM/NÃO] - [DESCRIÇÃO] - -### Aderência ao Tratamento - -**Aderência Geral**: [EXCELENTE/BOA/REGULAR/RUIM] - -**Fatores que Afetam Aderência**: -- [ ] Custo dos medicamentos -- [ ] Efeitos colaterais -- [ ] Complexidade do regime -- [ ] Esquecimento -- [ ] Crenças sobre medicação -- [ ] Outros: [DESCRIÇÃO] - -**Estratégias para Melhorar Aderência**: -- [ESTRATÉGIA_1]: [DESCRIÇÃO] -- [ESTRATÉGIA_2]: [DESCRIÇÃO] -- [ESTRATÉGIA_3]: [DESCRIÇÃO] - ---- - -## Controle da Doença *(obrigatório)* - -### Parâmetros de Controle - -**Parâmetros Clínicos**: -- [PARÂMETRO_1]: [VALOR] - [META] - [CONTROLE] -- [PARÂMETRO_2]: [VALOR] - [META] - [CONTROLE] -- [PARÂMETRO_3]: [VALOR] - [META] - [CONTROLE] - -**Exemplos**: -- Pressão arterial: [VALOR] - Meta: [META] - [BEM_CONTROLADO/NÃO_CONTROLADO] -- Glicemia: [VALOR] - Meta: [META] - [BEM_CONTROLADO/NÃO_CONTROLADO] -- Colesterol: [VALOR] - Meta: [META] - [BEM_CONTROLADO/NÃO_CONTROLADO] - -### Objetivos de Tratamento - -**Objetivos Alcançados**: -- [ ] [OBJETIVO_1]: [STATUS] -- [ ] [OBJETIVO_2]: [STATUS] -- [ ] [OBJETIVO_3]: [STATUS] - -**Objetivos Não Alcançados**: -- [ ] [OBJETIVO_1]: [RAZÃO] -- [ ] [OBJETIVO_2]: [RAZÃO] -- [ ] [OBJETIVO_3]: [RAZÃO] - ---- - -## Complicações *(obrigatório)* - -### Complicações Desenvolvidas - -- [ ] Nenhuma complicação -- [ ] [COMPLICAÇÃO_1]: [DESCRIÇÃO] - [DATA] - [TRATAMENTO] -- [ ] [COMPLICAÇÃO_2]: [DESCRIÇÃO] - [DATA] - [TRATAMENTO] -- [ ] [COMPLICAÇÃO_3]: [DESCRIÇÃO] - [DATA] - [TRATAMENTO] - -### Riscos de Complicações - -**Riscos Identificados**: -- [ ] [RISCO_1]: [PROBABILIDADE] - [ESTRATÉGIA_PREVENTIVA] -- [ ] [RISCO_2]: [PROBABILIDADE] - [ESTRATÉGIA_PREVENTIVA] -- [ ] [RISCO_3]: [PROBABILIDADE] - [ESTRATÉGIA_PREVENTIVA] - ---- - -## Fatores de Risco *(obrigatório)* - -### Fatores de Risco Modificáveis - -**Tabagismo**: -- [ ] Nunca fumou -- [ ] Ex-fumante: [QUANTIDADE] cigarros/dia por [DURAÇÃO] anos - Parou há [TEMPO] -- [ ] Fumante atual: [QUANTIDADE] cigarros/dia há [DURAÇÃO] anos - -**Álcool**: -- [ ] Não bebe -- [ ] Bebe ocasionalmente: [QUANTIDADE] drinks/semana -- [ ] Bebe regularmente: [QUANTIDADE] drinks/dia - -**Exercício Físico**: -- [ ] Sedentário -- [ ] Exercício leve: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] -- [ ] Exercício moderado: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] -- [ ] Exercício intenso: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] - -**Dieta**: -- [ ] Dieta balanceada -- [ ] Dieta específica: [TIPO] -- [ ] Restrições alimentares: [RESTRIÇÕES] - -**Peso**: -- IMC: [VALOR] - [CLASSIFICAÇÃO] -- Mudança de peso: [GANHO/PERDA/MANTIDO] - [QUANTIDADE] kg - -### Fatores de Risco Não Modificáveis - -**Idade**: [IDADE] anos - -**Gênero**: [GÊNERO] - -**Histórico Familiar**: -- [ ] Nenhum -- [ ] [DOENÇA_1]: [PARENTESCO] - [IDADE_DE_INÍCIO] -- [ ] [DOENÇA_2]: [PARENTESCO] - [IDADE_DE_INÍCIO] - ---- - -## Plano de Tratamento *(obrigatório)* - -### Medicações - -**Medicações Mantidas**: -- [ ] [MEDICAÇÃO_1]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [MEDICAÇÃO_2]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] - -**Medicações Ajustadas**: -- [ ] [MEDICAÇÃO_1]: [AJUSTE] - [JUSTIFICATIVA] -- [ ] [MEDICAÇÃO_2]: [AJUSTE] - [JUSTIFICATIVA] - -**Medicações Adicionadas**: -- [ ] [MEDICAÇÃO_1]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [MEDICAÇÃO_2]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] - -**Medicações Descontinuadas**: -- [ ] [MEDICAÇÃO_1]: [RAZÃO] -- [ ] [MEDICAÇÃO_2]: [RAZÃO] - -### Modificações de Estilo de Vida - -**Recomendações**: -1. [RECOMENDAÇÃO_1]: [DESCRIÇÃO] -2. [RECOMENDAÇÃO_2]: [DESCRIÇÃO] -3. [RECOMENDAÇÃO_3]: [DESCRIÇÃO] - -### Exames Complementares - -**Exames de Monitoramento**: -- [ ] [EXAME_1]: [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [EXAME_2]: [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [EXAME_3]: [FREQUÊNCIA] - [INDICAÇÃO] - ---- - -## Acompanhamento *(obrigatório)* - -### Próxima Consulta - -**Data**: [DATA] -**Intervalo**: [INTERVALO] -**Justificativa**: [JUSTIFICATIVA] - -### Objetivos para Próxima Consulta - -1. [OBJETIVO_1]: [DESCRIÇÃO] -2. [OBJETIVO_2]: [DESCRIÇÃO] -3. [OBJETIVO_3]: [DESCRIÇÃO] - -### Sinais de Alerta - -**Sinais que Requerem Retorno Antecipado**: -- [SINAL_1]: [DESCRIÇÃO] -- [SINAL_2]: [DESCRIÇÃO] -- [SINAL_3]: [DESCRIÇÃO] - ---- - -## Notas Adicionais *(opcional)* - -[OBSERVAÇÕES_ADICIONAIS] - ---- - -## Checklist de Qualidade - -Antes de considerar esta anamnese completa, verifique: - -- [ ] Todas as seções obrigatórias preenchidas -- [ ] Nenhum placeholder [CAPS] restante -- [ ] Condições crônicas documentadas -- [ ] Evolução desde última consulta documentada -- [ ] Medicações e aderência documentadas -- [ ] Controle da doença avaliado -- [ ] Complicações identificadas -- [ ] Fatores de risco documentados -- [ ] Plano de tratamento atualizado -- [ ] Acompanhamento definido - ---- - -**Anamnese Concluída em**: [DATA_HORA] -**Responsável**: [NOME_DO_PROFISSIONAL] -**Especialidade**: [ESPECIALIDADE] -**Contexto**: [CONDIÇÕES_CRÔNICAS] - diff --git a/shared/templates/medical.template.anamnesis.emergency.md b/shared/templates/medical.template.anamnesis.emergency.md deleted file mode 100644 index 65f774d..0000000 --- a/shared/templates/medical.template.anamnesis.emergency.md +++ /dev/null @@ -1,284 +0,0 @@ -# Template de Anamnese de Emergência - Framework OPQRST - -**Criado**: $DATE -**Versão**: 1.0 -**Usado por**: medical.anamnesis.md -**Contexto**: Anamnese de emergências agudas e urgências - ---- - -## Dados Demográficos *(obrigatório)* - -**Nome**: [NOME_DO_PACIENTE] -**Idade**: [IDADE] anos -**Gênero**: [GÊNERO] -**Data da Consulta**: [DATA] -**Hora da Consulta**: [HORA] -**Especialidade**: [ESPECIALIDADE] - ---- - -## Queixa Principal *(obrigatório)* - -**Queixa Principal**: [DESCRIÇÃO_EM_PALAVRAS_DO_PACIENTE] - -**Duração**: [DURAÇÃO_DOS_SINTOMAS] - -**Contexto**: [EMERGÊNCIA_URGENTE] - ---- - -## Anamnese da Doença Atual - OPQRST *(obrigatório)* - -### O - Onset (Início) - -**Pergunta**: "Quando os sintomas começaram exatamente?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Detalhes**: -- Início: [SUBDITA_OU_GRADUAL] -- Data e hora: [DATA_HORA] -- Fatores desencadeantes: [FATORES_DESENCADEANTES] -- Circunstâncias: [CIRCUNSTÂNCIAS_DO_INÍCIO] - ---- - -### P - Provocation (Provocação) - -**Pergunta**: "O que piora os sintomas? O que desencadeia?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Fatores Desencadeantes**: -- [FATOR_1]: [Efeito no sintoma] -- [FATOR_2]: [Efeito no sintoma] -- [FATOR_3]: [Efeito no sintoma] - -**Fatores que Pioram**: -- [FATOR_1]: [Efeito no sintoma] -- [FATOR_2]: [Efeito no sintoma] -- [FATOR_3]: [Efeito no sintoma] - ---- - -### Q - Quality (Qualidade) - -**Pergunta**: "Como você descreveria [sintoma]? É agudo, maçante, ardente?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Características**: -- Tipo: [AGUDO/MAÇANTE/ARDENTE/LATEJANTE/OUTRO] -- Qualidade: [DESCRIÇÃO_QUALITATIVA] -- Sensação: [DESCRIÇÃO_DO_PACIENTE] - ---- - -### R - Radiation (Irradiação) - -**Pergunta**: "O [sintoma] espalha para algum outro lugar?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Irradiação**: -- Localização primária: [LOCALIZAÇÃO_PRIMÁRIA] -- Irradiação: [SIM/NÃO] -- Se sim, para onde: [LOCALIZAÇÃO_DA_IRRADIAÇÃO] -- Padrão de irradiação: [PADRÃO] - ---- - -### S - Severity (Gravidade) - -**Pergunta**: "Em uma escala de 1 a 10, onde 10 é o pior possível, como você classificaria [sintoma]?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Gravidade**: -- Escala numérica: [1-10] -- Comparação: [COMPARAÇÃO_COM_OUTRAS_DORES] -- Impacto funcional: [IMPACTO_NA_CAPACIDADE_FUNCIONAL] - ---- - -### T - Time (Tempo) - -**Pergunta**: "Há quanto tempo dura? É contínuo ou vai e vem?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Tempo**: -- Duração: [DURAÇÃO] -- Padrão: [CONTÍNUO/INTERMITENTE] -- Frequência: [FREQUÊNCIA_DE_EPISÓDIOS] -- Duração de cada episódio: [DURAÇÃO_DE_CADA_EPISÓDIO] - ---- - -## Histórico Médico Crítico *(obrigatório)* - -### Condições Crônicas Relevantes - -- [ ] Nenhuma -- [ ] [CONDIÇÃO_1]: [DIAGNÓSTICO] - [ANO_DO_DIAGNÓSTICO] - [CONTROLE] -- [ ] [CONDIÇÃO_2]: [DIAGNÓSTICO] - [ANO_DO_DIAGNÓSTICO] - [CONTROLE] - -### Cirurgias Recentes - -- [ ] Nenhuma -- [ ] [CIRURGIA_1]: [TIPO] - [ANO] - [COMPLICAÇÕES] -- [ ] [CIRURGIA_2]: [TIPO] - [ANO] - [COMPLICAÇÕES] - -### Trauma - -- [ ] Nenhum -- [ ] [TRAUMA_1]: [DESCRIÇÃO] - [MECANISMO] - [ANO] -- [ ] [TRAUMA_2]: [DESCRIÇÃO] - [MECANISMO] - [ANO] - ---- - -## Medicações Atuais *(obrigatório)* - -### Medicações Críticas - -- [ ] Nenhuma -- [ ] [MEDICAÇÃO_1]: [DOSAGEM] - [FREQUÊNCIA] - [ÚLTIMA_DOSE] -- [ ] [MEDICAÇÃO_2]: [DOSAGEM] - [FREQUÊNCIA] - [ÚLTIMA_DOSE] -- [ ] [MEDICAÇÃO_3]: [DOSAGEM] - [FREQUÊNCIA] - [ÚLTIMA_DOSE] - -### Anticoagulantes - -- [ ] Não usa -- [ ] [ANTICOAGULANTE_1]: [DOSAGEM] - [FREQUÊNCIA] - [ÚLTIMA_DOSE] - -### Alergias - -- [ ] Nenhuma conhecida -- [ ] [ALERGIA_1]: [SUBSTÂNCIA] - [REAÇÃO] - ---- - -## Red Flags Identificadas *(obrigatório)* - -- [ ] Nenhum red flag identificado -- [ ] [RED_FLAG_1]: [DESCRIÇÃO] - [URGÊNCIA] -- [ ] [RED_FLAG_2]: [DESCRIÇÃO] - [URGÊNCIA] -- [ ] [RED_FLAG_3]: [DESCRIÇÃO] - [URGÊNCIA] - ---- - -## Avaliação de Urgência *(obrigatório)* - -- [ ] **Emergência**: Requer avaliação imediata (minutos a horas) -- [ ] **Urgente**: Requer avaliação em 24 horas -- [ ] **Semi-urgente**: Requer avaliação em 1 semana - -**Justificativa**: [JUSTIFICATIVA_DA_URGÊNCIA] - -**Critérios de Emergência**: -- [ ] Sinais vitais instáveis -- [ ] Red flags identificados -- [ ] Trauma de alta energia -- [ ] Alteração de estado mental -- [ ] Dor torácica severa -- [ ] Dispneia severa -- [ ] Hemorragia ativa - ---- - -## Impressão Diagnóstica Inicial *(obrigatório)* - -### Hipótese Diagnóstica Principal - -**Diagnóstico**: [DIAGNÓSTICO_PRINCIPAL] - -**Justificativa**: [JUSTIFICATIVA_CLÍNICA] - -**Probabilidade**: [ALTA/MÉDIA/BAIXA] - ---- - -### Diagnósticos Diferenciais - -1. **[DIAGNÓSTICO_DIFERENCIAL_1]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -2. **[DIAGNÓSTICO_DIFERENCIAL_2]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -3. **[DIAGNÓSTICO_DIFERENCIAL_3]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - ---- - -## Recomendações Imediatas *(obrigatório)* - -### Estabilização - -1. [MEDIDA_1]: [DESCRIÇÃO] -2. [MEDIDA_2]: [DESCRIÇÃO] -3. [MEDIDA_3]: [DESCRIÇÃO] - -### Exames Complementares Urgentes - -1. [EXAME_1]: [INDICAÇÃO] - [URGÊNCIA] -2. [EXAME_2]: [INDICAÇÃO] - [URGÊNCIA] -3. [EXAME_3]: [INDICAÇÃO] - [URGÊNCIA] - -### Medidas de Suporte - -1. [MEDIDA_1]: [DESCRIÇÃO] -2. [MEDIDA_2]: [DESCRIÇÃO] -3. [MEDIDA_3]: [DESCRIÇÃO] - ---- - -## Próximos Passos *(obrigatório)* - -### Ações Imediatas - -- [ ] Direcionar para pronto-socorro IMEDIATAMENTE -- [ ] Chamar ambulância -- [ ] Não dirigir - usar transporte médico -- [ ] Manter repouso até avaliação médica -- [ ] Monitorar sinais vitais - -### Acompanhamento - -- [ ] Retorno em [TEMPO] -- [ ] Acompanhamento com [ESPECIALISTA] -- [ ] Monitoramento de [PARÂMETRO] - ---- - -## Notas Adicionais *(opcional)* - -[OBSERVAÇÕES_ADICIONAIS] - ---- - -## Checklist de Qualidade - -Antes de considerar esta anamnese completa, verifique: - -- [ ] Todas as seções obrigatórias preenchidas -- [ ] Nenhum placeholder [CAPS] restante -- [ ] Queixa principal claramente identificada -- [ ] Framework OPQRST aplicado sistematicamente -- [ ] Red flags identificados (se houver) -- [ ] Urgência avaliada adequadamente -- [ ] Recomendações imediatas claras e acionáveis -- [ ] Próximos passos definidos -- [ ] Impressão diagnóstica inicial fundamentada - ---- - -**Anamnese Concluída em**: [DATA_HORA] -**Responsável**: [NOME_DO_PROFISSIONAL] -**Especialidade**: [ESPECIALIDADE] -**Contexto**: [EMERGÊNCIA_URGENTE] - diff --git a/shared/templates/medical.template.anamnesis.general.md b/shared/templates/medical.template.anamnesis.general.md deleted file mode 100644 index a942eba..0000000 --- a/shared/templates/medical.template.anamnesis.general.md +++ /dev/null @@ -1,363 +0,0 @@ -# Template de Anamnese Geral - Framework SOCRATES - -**Criado**: $DATE -**Versão**: 1.0 -**Usado por**: medical.anamnesis.md -**Contexto**: Anamnese de sintomas gerais e consultas de rotina - ---- - -## Dados Demográficos *(obrigatório)* - -**Nome**: [NOME_DO_PACIENTE] -**Idade**: [IDADE] anos -**Gênero**: [GÊNERO] -**Data da Consulta**: [DATA] -**Especialidade**: [ESPECIALIDADE] - ---- - -## Queixa Principal *(obrigatório)* - -**Queixa Principal**: [DESCRIÇÃO_EM_PALAVRAS_DO_PACIENTE] - -**Duração**: [DURAÇÃO_DOS_SINTOMAS] - -**Contexto**: [PRIMEIRA_CONSULTA_OU_ACOMPANHAMENTO] - ---- - -## Anamnese da Doença Atual - SOCRATES *(obrigatório)* - -### S - Site (Localização) - -**Pergunta**: "Onde exatamente você está sentindo [sintoma]?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - ---- - -### O - Onset (Início) - -**Pergunta**: "Quando isso começou?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Detalhes**: -- Início: [SUBDITA_OU_GRADUAL] -- Fatores desencadeantes: [FATORES_DESENCADEANTES] -- Circunstâncias: [CIRCUNSTÂNCIAS_DO_INÍCIO] - ---- - -### C - Character (Característica) - -**Pergunta**: "Como você descreveria [sintoma]? É agudo, maçante, ardente, latejante?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Características**: -- Tipo: [AGUDO/MAÇANTE/ARDENTE/LATEJANTE/OUTRO] -- Qualidade: [DESCRIÇÃO_QUALITATIVA] -- Intensidade: [LEVE/MODERADO/SEVERO] - ---- - -### R - Radiation (Irradiação) - -**Pergunta**: "O [sintoma] espalha para algum outro lugar?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Irradiação**: -- Localização: [LOCALIZAÇÃO_PRIMÁRIA] -- Irradiação: [SIM/NÃO] -- Se sim, para onde: [LOCALIZAÇÃO_DA_IRRADIAÇÃO] - ---- - -### A - Associations (Associações) - -**Pergunta**: "Você está experimentando algum outro sintoma junto com [queixa principal]?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Sintomas Associados**: -- [SINTOMA_1]: [DESCRIÇÃO] -- [SINTOMA_2]: [DESCRIÇÃO] -- [SINTOMA_3]: [DESCRIÇÃO] -- [OUTROS_SINTOMAS]: [DESCRIÇÃO] - ---- - -### T - Time Course (Evolução Temporal) - -**Pergunta**: "Como [sintoma] mudou desde que começou? Está melhorando, piorando ou igual?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Evolução**: -- Padrão: [MELHORANDO/PIORANDO/IGUAL/FLUTUANTE] -- Progressão: [GRADUAL/SUDITA] -- Frequência: [CONTÍNUO/INTERMITENTE] -- Duração de cada episódio: [DURAÇÃO] - ---- - -### E - Exacerbating/Relieving Factors (Fatores que Pioram/Melhoram) - -**Pergunta**: "O que piora [sintoma]? O que melhora?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Fatores que Pioram**: -- [FATOR_1]: [Efeito no sintoma] -- [FATOR_2]: [Efeito no sintoma] -- [FATOR_3]: [Efeito no sintoma] - -**Fatores que Melhoram**: -- [FATOR_1]: [Efeito no sintoma] -- [FATOR_2]: [Efeito no sintoma] -- [FATOR_3]: [Efeito no sintoma] - ---- - -### S - Severity (Gravidade) - -**Pergunta**: "Em uma escala de 1 a 10, onde 1 é muito leve e 10 é o pior possível, como você classificaria [sintoma]?" - -**Resposta**: [RESPOSTA_DO_PACIENTE] - -**Gravidade**: -- Escala numérica: [1-10] -- Impacto na qualidade de vida: [LEVE/MODERADO/SEVERO] -- Impacto nas atividades diárias: [DESCRIÇÃO] - ---- - -## Histórico Médico Relevante *(obrigatório)* - -### Condições Crônicas - -- [ ] Nenhuma -- [ ] [CONDIÇÃO_1]: [DIAGNÓSTICO] - [ANO_DO_DIAGNÓSTICO] -- [ ] [CONDIÇÃO_2]: [DIAGNÓSTICO] - [ANO_DO_DIAGNÓSTICO] -- [ ] [CONDIÇÃO_3]: [DIAGNÓSTICO] - [ANO_DO_DIAGNÓSTICO] - -### Cirurgias - -- [ ] Nenhuma -- [ ] [CIRURGIA_1]: [TIPO] - [ANO] -- [ ] [CIRURGIA_2]: [TIPO] - [ANO] -- [ ] [CIRURGIA_3]: [TIPO] - [ANO] - -### Internações - -- [ ] Nenhuma -- [ ] [INTERNAÇÃO_1]: [MOTIVO] - [ANO] -- [ ] [INTERNAÇÃO_2]: [MOTIVO] - [ANO] - -### Trauma - -- [ ] Nenhum -- [ ] [TRAUMA_1]: [DESCRIÇÃO] - [ANO] -- [ ] [TRAUMA_2]: [DESCRIÇÃO] - [ANO] - ---- - -## Medicações Atuais *(obrigatório)* - -### Medicações Prescritas - -- [ ] Nenhuma -- [ ] [MEDICAÇÃO_1]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [MEDICAÇÃO_2]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] -- [ ] [MEDICAÇÃO_3]: [DOSAGEM] - [FREQUÊNCIA] - [INDICAÇÃO] - -### Medicações Sem Prescrição - -- [ ] Nenhuma -- [ ] [MEDICAÇÃO_1]: [DOSAGEM] - [FREQUÊNCIA] -- [ ] [MEDICAÇÃO_2]: [DOSAGEM] - [FREQUÊNCIA] - -### Suplementos e Vitaminas - -- [ ] Nenhum -- [ ] [SUPLEMENTO_1]: [DOSAGEM] - [FREQUÊNCIA] -- [ ] [SUPLEMENTO_2]: [DOSAGEM] - [FREQUÊNCIA] - -### Aderência ao Tratamento - -- [ ] Excelente -- [ ] Boa -- [ ] Regular -- [ ] Ruim -- [ ] Não aderente - -**Comentários**: [COMENTÁRIOS_SOBRE_ADERÊNCIA] - ---- - -## Alergias *(obrigatório)* - -- [ ] Nenhuma conhecida -- [ ] [ALERGIA_1]: [SUBSTÂNCIA] - [REAÇÃO] -- [ ] [ALERGIA_2]: [SUBSTÂNCIA] - [REAÇÃO] -- [ ] [ALERGIA_3]: [SUBSTÂNCIA] - [REAÇÃO] - ---- - -## Histórico Familiar Relevante *(opcional)* - -### Doenças Familiares - -- [ ] Nenhuma conhecida -- [ ] [DOENÇA_1]: [PARENTESCO] - [IDADE_DE_INÍCIO] -- [ ] [DOENÇA_2]: [PARENTESCO] - [IDADE_DE_INÍCIO] -- [ ] [DOENÇA_3]: [PARENTESCO] - [IDADE_DE_INÍCIO] - -### Morte Súbita - -- [ ] Nenhuma -- [ ] [PARENTESCO] - [IDADE] - [CIRCUNSTÂNCIAS] - ---- - -## Fatores de Estilo de Vida *(obrigatório)* - -### Tabagismo - -- [ ] Nunca fumou -- [ ] Ex-fumante: [QUANTIDADE] cigarros/dia por [DURAÇÃO] anos - Parou há [TEMPO] -- [ ] Fumante atual: [QUANTIDADE] cigarros/dia há [DURAÇÃO] anos - -### Álcool - -- [ ] Não bebe -- [ ] Bebe ocasionalmente: [QUANTIDADE] drinks/semana -- [ ] Bebe regularmente: [QUANTIDADE] drinks/dia - -### Uso de Substâncias - -- [ ] Não usa -- [ ] [SUBSTÂNCIA_1]: [FREQUÊNCIA] - [QUANTIDADE] -- [ ] [SUBSTÂNCIA_2]: [FREQUÊNCIA] - [QUANTIDADE] - -### Exercício Físico - -- [ ] Sedentário -- [ ] Exercício leve: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] -- [ ] Exercício moderado: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] -- [ ] Exercício intenso: [TIPO] - [FREQUÊNCIA] - [DURAÇÃO] - -### Dieta - -- [ ] Dieta balanceada -- [ ] Dieta específica: [TIPO] -- [ ] Restrições alimentares: [RESTRIÇÕES] - -### Sono - -- [ ] Sono adequado: [HORAS] horas/noite -- [ ] Dificuldade para dormir -- [ ] Insônia -- [ ] Apneia do sono - ---- - -## Impressão Diagnóstica Inicial *(obrigatório)* - -### Hipótese Diagnóstica Principal - -**Diagnóstico**: [DIAGNÓSTICO_PRINCIPAL] - -**Justificativa**: [JUSTIFICATIVA_CLÍNICA] - ---- - -### Diagnósticos Diferenciais - -1. **[DIAGNÓSTICO_DIFERENCIAL_1]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -2. **[DIAGNÓSTICO_DIFERENCIAL_2]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -3. **[DIAGNÓSTICO_DIFERENCIAL_3]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - ---- - -## Red Flags Identificadas *(obrigatório)* - -- [ ] Nenhum red flag identificado -- [ ] [RED_FLAG_1]: [DESCRIÇÃO] -- [ ] [RED_FLAG_2]: [DESCRIÇÃO] -- [ ] [RED_FLAG_3]: [DESCRIÇÃO] - ---- - -## Avaliação de Urgência *(obrigatório)* - -- [ ] **Emergência**: Requer avaliação imediata (minutos a horas) -- [ ] **Urgente**: Requer avaliação em 24 horas -- [ ] **Semi-urgente**: Requer avaliação em 1 semana -- [ ] **Rotina**: Requer avaliação em 2-4 semanas - -**Justificativa**: [JUSTIFICATIVA_DA_URGÊNCIA] - ---- - -## Recomendações *(obrigatório)* - -### Exames Complementares - -1. [EXAME_1]: [INDICAÇÃO] -2. [EXAME_2]: [INDICAÇÃO] -3. [EXAME_3]: [INDICAÇÃO] - -### Medidas de Suporte - -1. [MEDIDA_1]: [DESCRIÇÃO] -2. [MEDIDA_2]: [DESCRIÇÃO] -3. [MEDIDA_3]: [DESCRIÇÃO] - -### Acompanhamento - -- [ ] Retorno em [TEMPO] -- [ ] Acompanhamento com [ESPECIALISTA] -- [ ] Monitoramento de [PARÂMETRO] - ---- - -## Notas Adicionais *(opcional)* - -[OBSERVAÇÕES_ADICIONAIS] - ---- - -## Checklist de Qualidade - -Antes de considerar esta anamnese completa, verifique: - -- [ ] Todas as seções obrigatórias preenchidas -- [ ] Nenhum placeholder [CAPS] restante -- [ ] Queixa principal claramente identificada -- [ ] Framework SOCRATES aplicado sistematicamente -- [ ] Histórico médico relevante documentado -- [ ] Medicações atuais documentadas -- [ ] Alergias documentadas -- [ ] Red flags identificados (se houver) -- [ ] Urgência avaliada adequadamente -- [ ] Recomendações claras e acionáveis -- [ ] Impressão diagnóstica inicial fundamentada - ---- - -**Anamnese Concluída em**: [DATA_HORA] -**Responsável**: [NOME_DO_PROFISSIONAL] -**Especialidade**: [ESPECIALIDADE] - diff --git a/shared/templates/medical.template.anamnesis.mental-health.md b/shared/templates/medical.template.anamnesis.mental-health.md deleted file mode 100644 index 972fab0..0000000 --- a/shared/templates/medical.template.anamnesis.mental-health.md +++ /dev/null @@ -1,491 +0,0 @@ -# Template de Anamnese de Saúde Mental - -**Criado**: $DATE -**Versão**: 1.0 -**Usado por**: medical.anamnesis.md -**Contexto**: Anamnese de sintomas psiquiátricos e saúde mental - ---- - -## Dados Demográficos *(obrigatório)* - -**Nome**: [NOME_DO_PACIENTE] -**Idade**: [IDADE] anos -**Gênero**: [GÊNERO] -**Data da Consulta**: [DATA] -**Especialidade**: [ESPECIALIDADE] - ---- - -## Queixa Principal *(obrigatório)* - -**Queixa Principal**: [DESCRIÇÃO_EM_PALAVRAS_DO_PACIENTE] - -**Duração**: [DURAÇÃO_DOS_SINTOMAS] - -**Contexto**: [PRIMEIRA_CONSULTA_OU_ACOMPANHAMENTO] - ---- - -## Sintomas Psiquiátricos *(obrigatório)* - -### Humor e Afeto - -**Depressão**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas: [DESCRIÇÃO_DOS_SINTOMAS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Mania/Hipomania**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas: [DESCRIÇÃO_DOS_SINTOMAS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Ansiedade**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas: [DESCRIÇÃO_DOS_SINTOMAS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Irritabilidade**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas: [DESCRIÇÃO_DOS_SINTOMAS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - ---- - -### Ansiedade e Pânico - -**Preocupação Excessiva**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Tópicos de preocupação: [TÓPICOS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Ataques de Pânico**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas durante ataques: [SINTOMAS] -- [ ] Fatores desencadeantes: [FATORES] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Fobias**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Tipo: [TIPO_DE_FOBIA] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - ---- - -### Psicose - -**Delírios**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Tipo: [TIPO_DE_DELÍRIO] -- [ ] Conteúdo: [CONTEÚDO_DO_DELÍRIO] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Alucinações**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Tipo: [VISUAL/AUDITIVA/TÁTIL/OUTRA] -- [ ] Conteúdo: [CONTEÚDO_DA_ALUCINAÇÃO] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - -**Pensamento Desorganizado**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Sintomas: [DESCRIÇÃO_DOS_SINTOMAS] -- [ ] Impacto: [IMPACTO_NA_VIDA_DIÁRIA] - ---- - -### Pensamentos Suicidas/Homicidas - -**Ideação Suicida**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Intensidade: [LEVE/MODERADA/SEVERA] -- [ ] Plano: [SIM/NÃO] - [DESCRIÇÃO_DO_PLANO] -- [ ] Intenção: [SIM/NÃO] - [DESCRIÇÃO_DA_INTENÇÃO] -- [ ] Acesso a meios: [SIM/NÃO] - [DESCRIÇÃO_DOS_MEIOS] - -**Ideação Homicida**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Intensidade: [LEVE/MODERADA/SEVERA] -- [ ] Plano: [SIM/NÃO] - [DESCRIÇÃO_DO_PLANO] -- [ ] Intenção: [SIM/NÃO] - [DESCRIÇÃO_DA_INTENÇÃO] -- [ ] Acesso a meios: [SIM/NÃO] - [DESCRIÇÃO_DOS_MEIOS] - -**Tentativas Prévia**: -- [ ] Nenhuma -- [ ] [TENTATIVA_1]: [DATA] - [MÉTODO] - [RESULTADO] -- [ ] [TENTATIVA_2]: [DATA] - [MÉTODO] - [RESULTADO] - ---- - -## Uso de Substâncias *(obrigatório)* - -### Álcool - -**Uso de Álcool**: -- [ ] Não bebe -- [ ] Bebe ocasionalmente: [QUANTIDADE] drinks/semana -- [ ] Bebe regularmente: [QUANTIDADE] drinks/dia -- [ ] Problemas relacionados: [SIM/NÃO] - [DESCRIÇÃO] - -**Histórico de Abuso/Dependência**: -- [ ] Nenhum -- [ ] Abuso: [DURAÇÃO] - [TRATAMENTO] -- [ ] Dependência: [DURAÇÃO] - [TRATAMENTO] - -### Drogas - -**Uso de Drogas**: -- [ ] Não usa -- [ ] [DROGA_1]: [FREQUÊNCIA] - [QUANTIDADE] -- [ ] [DROGA_2]: [FREQUÊNCIA] - [QUANTIDADE] -- [ ] Problemas relacionados: [SIM/NÃO] - [DESCRIÇÃO] - -**Histórico de Abuso/Dependência**: -- [ ] Nenhum -- [ ] Abuso: [DURAÇÃO] - [TRATAMENTO] -- [ ] Dependência: [DURAÇÃO] - [TRATAMENTO] - -### Medicamentos - -**Uso de Medicamentos Sem Prescrição**: -- [ ] Não usa -- [ ] [MEDICAÇÃO_1]: [FREQUÊNCIA] - [QUANTIDADE] -- [ ] [MEDICAÇÃO_2]: [FREQUÊNCIA] - [QUANTIDADE] - -**Abuso de Medicamentos Prescritos**: -- [ ] Não -- [ ] [MEDICAÇÃO_1]: [FREQUÊNCIA] - [QUANTIDADE] -- [ ] [MEDICAÇÃO_2]: [FREQUÊNCIA] - [QUANTIDADE] - ---- - -## Trauma e Estresse *(obrigatório)* - -### Eventos Traumáticos - -**Eventos Traumáticos**: -- [ ] Nenhum -- [ ] [EVENTO_1]: [DESCRIÇÃO] - [DATA] - [IMPACTO] -- [ ] [EVENTO_2]: [DESCRIÇÃO] - [DATA] - [IMPACTO] - -**Abuso**: -- [ ] Nenhum -- [ ] Físico: [DESCRIÇÃO] - [DATA] - [IMPACTO] -- [ ] Sexual: [DESCRIÇÃO] - [DATA] - [IMPACTO] -- [ ] Emocional: [DESCRIÇÃO] - [DATA] - [IMPACTO] -- [ ] Negligência: [DESCRIÇÃO] - [DATA] - [IMPACTO] - -### Sintomas de PTSD - -**Sintomas de PTSD**: -- [ ] Não presente -- [ ] Presente: [FREQUÊNCIA] - [GRAVIDADE] - -**Sintomas**: -- [ ] Flashbacks: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Pesadelos: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Evitação: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Hipervigilância: [FREQUÊNCIA] - [GRAVIDADE] -- [ ] Reatividade: [FREQUÊNCIA] - [GRAVIDADE] - -### Estressores Atuais - -**Estressores Atuais**: -- [ ] Nenhum -- [ ] [ESTRESSOR_1]: [DESCRIÇÃO] - [IMPACTO] -- [ ] [ESTRESSOR_2]: [DESCRIÇÃO] - [IMPACTO] -- [ ] [ESTRESSOR_3]: [DESCRIÇÃO] - [IMPACTO] - -**Coping**: -- [ ] Estratégias de coping: [DESCRIÇÃO] -- [ ] Efetividade: [EFETIVA/INEFETIVA] -- [ ] Necessidade de suporte: [SIM/NÃO] - ---- - -## Funcionamento Social e Ocupacional *(obrigatório)* - -### Funcionamento Social - -**Relacionamentos**: -- [ ] Relacionamentos saudáveis -- [ ] Dificuldades em relacionamentos: [DESCRIÇÃO] -- [ ] Isolamento social: [SIM/NÃO] - [GRAVIDADE] - -**Suporte Social**: -- [ ] Suporte adequado -- [ ] Suporte limitado: [DESCRIÇÃO] -- [ ] Sem suporte: [DESCRIÇÃO] - -**Atividades Sociais**: -- [ ] Atividades sociais adequadas -- [ ] Redução de atividades sociais: [DESCRIÇÃO] -- [ ] Sem atividades sociais: [DESCRIÇÃO] - -### Funcionamento Ocupacional - -**Trabalho**: -- [ ] Trabalho estável -- [ ] Dificuldades no trabalho: [DESCRIÇÃO] -- [ ] Desemprego: [DURAÇÃO] - [RAZÃO] - -**Produtividade**: -- [ ] Produtividade adequada -- [ ] Redução de produtividade: [DESCRIÇÃO] -- [ ] Incapacidade de trabalhar: [DESCRIÇÃO] - -### Funcionamento Acadêmico - -**Escola**: -- [ ] Desempenho adequado -- [ ] Dificuldades acadêmicas: [DESCRIÇÃO] -- [ ] Abandono escolar: [DATA] - [RAZÃO] - -**Concentração**: -- [ ] Concentração adequada -- [ ] Dificuldade de concentração: [DESCRIÇÃO] -- [ ] Incapacidade de concentração: [DESCRIÇÃO] - -### Funcionamento Familiar - -**Relacionamentos Familiares**: -- [ ] Relacionamentos saudáveis -- [ ] Dificuldades familiares: [DESCRIÇÃO] -- [ ] Conflitos familiares: [DESCRIÇÃO] - -**Suporte Familiar**: -- [ ] Suporte adequado -- [ ] Suporte limitado: [DESCRIÇÃO] -- [ ] Sem suporte: [DESCRIÇÃO] - ---- - -## Histórico Psiquiátrico *(obrigatório)* - -### Transtornos Mentais Prévia - -**Transtornos Prévia**: -- [ ] Nenhum -- [ ] [TRANSTORNO_1]: [DIAGNÓSTICO] - [DATA] - [TRATAMENTO] -- [ ] [TRANSTORNO_2]: [DIAGNÓSTICO] - [DATA] - [TRATAMENTO] -- [ ] [TRANSTORNO_3]: [DIAGNÓSTICO] - [DATA] - [TRATAMENTO] - -### Hospitalizações Psiquiátricas - -**Hospitalizações**: -- [ ] Nenhuma -- [ ] [HOSPITALIZAÇÃO_1]: [DATA] - [MOTIVO] - [DURAÇÃO] -- [ ] [HOSPITALIZAÇÃO_2]: [DATA] - [MOTIVO] - [DURAÇÃO] - -### Tratamentos Prévia - -**Psicoterapia**: -- [ ] Nunca -- [ ] [TIPO_DE_TERAPIA]: [DURAÇÃO] - [RESULTADO] -- [ ] [TIPO_DE_TERAPIA]: [DURAÇÃO] - [RESULTADO] - -**Medicações Psiquiátricas**: -- [ ] Nunca -- [ ] [MEDICAÇÃO_1]: [DURAÇÃO] - [RESULTADO] -- [ ] [MEDICAÇÃO_2]: [DURAÇÃO] - [RESULTADO] - ---- - -## Avaliação de Risco *(obrigatório)* - -### Risco de Suicídio - -**Risco de Suicídio**: [BAIXO/MÉDIO/ALTO] - -**Fatores de Risco**: -- [ ] Ideação suicida -- [ ] Plano suicida -- [ ] Intenção suicida -- [ ] Acesso a meios -- [ ] Tentativas prévia -- [ ] Histórico familiar de suicídio -- [ ] Transtornos mentais -- [ ] Uso de substâncias -- [ ] Isolamento social -- [ ] Estressores atuais - -**Fatores de Proteção**: -- [ ] Suporte social -- [ ] Suporte familiar -- [ ] Tratamento em andamento -- [ ] Razões para viver -- [ ] Planejamento futuro - -### Risco de Homicídio - -**Risco de Homicídio**: [BAIXO/MÉDIO/ALTO] - -**Fatores de Risco**: -- [ ] Ideação homicida -- [ ] Plano homicida -- [ ] Intenção homicida -- [ ] Acesso a meios -- [ ] Histórico de violência -- [ ] Transtornos mentais -- [ ] Uso de substâncias -- [ ] Estressores atuais - -**Fatores de Proteção**: -- [ ] Suporte social -- [ ] Suporte familiar -- [ ] Tratamento em andamento -- [ ] Controle de impulsos -- [ ] Planejamento futuro - -### Risco de Violência - -**Risco de Violência**: [BAIXO/MÉDIO/ALTO] - -**Fatores de Risco**: -- [ ] Histórico de violência -- [ ] Transtornos mentais -- [ ] Uso de substâncias -- [ ] Estressores atuais -- [ ] Agressividade - -**Fatores de Proteção**: -- [ ] Suporte social -- [ ] Suporte familiar -- [ ] Tratamento em andamento -- [ ] Controle de impulsos -- [ ] Planejamento futuro - ---- - -## Impressão Diagnóstica Inicial *(obrigatório)* - -### Hipótese Diagnóstica Principal - -**Diagnóstico**: [DIAGNÓSTICO_PRINCIPAL] - -**Justificativa**: [JUSTIFICATIVA_CLÍNICA] - -**Probabilidade**: [ALTA/MÉDIA/BAIXA] - ---- - -### Diagnósticos Diferenciais - -1. **[DIAGNÓSTICO_DIFERENCIAL_1]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -2. **[DIAGNÓSTICO_DIFERENCIAL_2]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - -3. **[DIAGNÓSTICO_DIFERENCIAL_3]** - - Probabilidade: [ALTA/MÉDIA/BAIXA] - - Justificativa: [JUSTIFICATIVA] - ---- - -## Recomendações *(obrigatório)* - -### Avaliação Psiquiátrica - -**Avaliação Psiquiátrica Presencial**: -- [ ] Recomendada: [URGÊNCIA] -- [ ] Data: [DATA] -- [ ] Especialista: [ESPECIALISTA] - -### Psicoterapia - -**Psicoterapia**: -- [ ] Recomendada: [TIPO_DE_TERAPIA] -- [ ] Frequência: [FREQUÊNCIA] -- [ ] Duração: [DURAÇÃO] - -### Medicação - -**Medicação Psiquiátrica**: -- [ ] Recomendada: [MEDICAÇÃO] -- [ ] Dosagem: [DOSAGEM] -- [ ] Frequência: [FREQUÊNCIA] -- [ ] Indicação: [INDICAÇÃO] - -### Medidas de Suporte - -**Medidas de Suporte**: -1. [MEDIDA_1]: [DESCRIÇÃO] -2. [MEDIDA_2]: [DESCRIÇÃO] -3. [MEDIDA_3]: [DESCRIÇÃO] - -### Hospitalização - -**Hospitalização Psiquiátrica**: -- [ ] Não recomendada -- [ ] Recomendada: [URGÊNCIA] -- [ ] Justificativa: [JUSTIFICATIVA] - ---- - -## Próximos Passos *(obrigatório)* - -### Ações Imediatas - -- [ ] [AÇÃO_1]: [DESCRIÇÃO] -- [ ] [AÇÃO_2]: [DESCRIÇÃO] -- [ ] [AÇÃO_3]: [DESCRIÇÃO] - -### Acompanhamento - -- [ ] Retorno em [TEMPO] -- [ ] Acompanhamento com [ESPECIALISTA] -- [ ] Monitoramento de [PARÂMETRO] - -### Sinais de Alerta - -**Sinais que Requerem Retorno Antecipado**: -- [SINAL_1]: [DESCRIÇÃO] -- [SINAL_2]: [DESCRIÇÃO] -- [SINAL_3]: [DESCRIÇÃO] - ---- - -## Notas Adicionais *(opcional)* - -[OBSERVAÇÕES_ADICIONAIS] - ---- - -## Checklist de Qualidade - -Antes de considerar esta anamnese completa, verifique: - -- [ ] Todas as seções obrigatórias preenchidas -- [ ] Nenhum placeholder [CAPS] restante -- [ ] Queixa principal claramente identificada -- [ ] Sintomas psiquiátricos documentados -- [ ] Uso de substâncias documentado -- [ ] Trauma e estresse documentados -- [ ] Funcionamento social e ocupacional documentado -- [ ] Histórico psiquiátrico documentado -- [ ] Avaliação de risco documentada -- [ ] Recomendações claras e acionáveis -- [ ] Impressão diagnóstica inicial fundamentada - ---- - -**Anamnese Concluída em**: [DATA_HORA] -**Responsável**: [NOME_DO_PROFISSIONAL] -**Especialidade**: [ESPECIALIDADE] -**Contexto**: [SAÚDE_MENTAL] - diff --git a/shared/templates/page-auth.template.tsx b/shared/templates/page-auth.template.tsx deleted file mode 100644 index ed7d9f2..0000000 --- a/shared/templates/page-auth.template.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { Card } from '@/components/ui/card'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; - -export default function { { PAGE_NAME } } Page() { - return ( -
- -

{{ PAGE_TITLE }}

-
- {{ FORM_FIELDS }} - -
-
-
- ); -} - diff --git a/shared/templates/page-dashboard.template.tsx b/shared/templates/page-dashboard.template.tsx deleted file mode 100644 index 21f0387..0000000 --- a/shared/templates/page-dashboard.template.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Header } from '@/components/Header'; -import { Sidebar } from '@/components/Sidebar'; - -export default function { { PAGE_NAME } } Page() { - return ( -
-
-
- -
-

{{ PAGE_TITLE }}

- {{ PAGE_CONTENT }} -
-
-
- ); -} - diff --git a/shared/templates/persona.template.md b/shared/templates/persona.template.md deleted file mode 100644 index 44b4ed6..0000000 --- a/shared/templates/persona.template.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -type: persona -created_at: {{CREATED_AT}} -updated_at: {{UPDATED_AT}} -based_on: {{RESEARCH_SOURCE}} -validated: {{VALIDATED}} ---- - -# {{PERSONA_NAME}} - {{PERSONA_ROLE}} - -> **Quote**: "{{PERSONA_QUOTE}}" - -![{{PERSONA_NAME}}]({{PHOTO_URL}}) - -## 👤 Demographics - -| Attribute | Value | -|-----------|-------| -| **Name** | {{PERSONA_NAME}} | -| **Age** | {{AGE}} years | -| **Location** | {{LOCATION}} | -| **Occupation** | {{OCCUPATION}} | -| **Tech Proficiency** | {{TECH_PROFICIENCY}} | - -## 🎯 Goals - -{{GOALS_LIST}} - -## ❌ Frustrations & Pain Points - -{{FRUSTRATIONS_LIST}} - -## 💡 Behaviors & Patterns - -{{BEHAVIORS_DESCRIPTION}} - -## 🔧 Needs - -{{NEEDS_DESCRIPTION}} - -## 📱 Technology & Tools - -**Daily tools**: -{{TOOLS_LIST}} - -**Devices**: -{{DEVICES_LIST}} - -**Preferred channels**: -{{CHANNELS_LIST}} - -## 📊 Metadata - -- **Created**: {{CREATED_AT}} -- **Last Updated**: {{UPDATED_AT}} -- **Based on**: {{RESEARCH_SOURCE}} -- **Validated**: {{VALIDATED}} -- **Confidence**: {{CONFIDENCE_LEVEL}} - -## 🔗 Related Artifacts - -- Journey Maps: {{JOURNEY_MAPS_LINKS}} -- Empathy Maps: {{EMPATHY_MAPS_LINKS}} -- User Stories: {{USER_STORIES_LINKS}} -- Research Findings: {{RESEARCH_LINKS}} - ---- - -**Usage**: Reference esta persona em specs, plans e design decisions para manter foco no usuário real. - diff --git a/shared/templates/slack-feature-synced.template.md b/shared/templates/slack-feature-synced.template.md deleted file mode 100644 index c822cfb..0000000 --- a/shared/templates/slack-feature-synced.template.md +++ /dev/null @@ -1,24 +0,0 @@ -🔄 *Feature Sincronizada com Trello* - -*Feature:* {{FEATURE_NAME}} -*Tasks:* {{TOTAL}} - -*Distribution:* - • 🚨 P0: {{P0_COUNT}} - • 🔴 P1: {{P1_COUNT}} - • 🟡 P2: {{P2_COUNT}} - • 🟢 P3: {{P3_COUNT}} - • ⚪ P4: {{P4_COUNT}} - -*Phases:* - • MVP: {{MVP_COUNT}} tasks - • Alpha: {{ALPHA_COUNT}} tasks - • Beta: {{BETA_COUNT}} tasks - • Production: {{PROD_COUNT}} tasks - -━━━━━━━━━━━━━━━━ -🔗 <{{BOARD_URL}}|View Board> -📁 Feature Index: `{{INDEX_PATH}}` - - - diff --git a/shared/templates/slack-milestone.template.md b/shared/templates/slack-milestone.template.md deleted file mode 100644 index fc5b944..0000000 --- a/shared/templates/slack-milestone.template.md +++ /dev/null @@ -1,17 +0,0 @@ -🎉 *Milestone Atingido!* - -*Feature:* {{FEATURE_NAME}} -*Milestone:* {{MILESTONE_NAME}} - -{{MILESTONE_DETAILS}} - -*Próxima fase:* {{NEXT_PHASE}} -*Tasks pendentes:* {{PENDING_COUNT}} - -━━━━━━━━━━━━━━━━ -Progress Geral: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) - -🔗 <{{BOARD_URL}}|View Board> - - - diff --git a/shared/templates/slack-task-completed.template.md b/shared/templates/slack-task-completed.template.md deleted file mode 100644 index f5369f3..0000000 --- a/shared/templates/slack-task-completed.template.md +++ /dev/null @@ -1,21 +0,0 @@ -✅ *Task Completada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Status:* in_progress → completed - -*{{TITLE}}* -✨ Task finalizada com sucesso! - -*Next Suggested:* {{NEXT_TASK_ID}} - {{NEXT_TITLE}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> - - - diff --git a/shared/templates/slack-task-created.template.md b/shared/templates/slack-task-created.template.md deleted file mode 100644 index ac54416..0000000 --- a/shared/templates/slack-task-created.template.md +++ /dev/null @@ -1,23 +0,0 @@ -✨ *Nova Task Criada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Category:* {{CATEGORY}} -*Status:* pending - -*{{TITLE}}* -{{DESCRIPTION_SUMMARY}} - -*Estimated Time:* {{ESTIMATED_TIME}} -*Phase:* {{PHASE_NAME}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> - - - diff --git a/shared/templates/slack-task-started.template.md b/shared/templates/slack-task-started.template.md deleted file mode 100644 index 0f1af3b..0000000 --- a/shared/templates/slack-task-started.template.md +++ /dev/null @@ -1,20 +0,0 @@ -🔨 *Task Iniciada* - -*Feature:* {{FEATURE_NAME}} -*Task:* {{TASK_ID}} - -*Priority:* {{PRIORITY_EMOJI}} {{PRIORITY}} -*Status:* pending → in_progress - -*{{TITLE}}* -{{DESCRIPTION_SUMMARY}} - -━━━━━━━━━━━━━━━━ -Progress: {{COMPLETED}}/{{TOTAL}} ({{PERCENT}}%) -{{PROGRESS_BAR}} - -🔗 <{{TRELLO_URL}}|View on Trello> -📁 Task File: `{{TASK_FILE_PATH}}` - - - diff --git a/shared/templates/sourcemap.json b/shared/templates/sourcemap.json deleted file mode 100644 index d6a4e92..0000000 --- a/shared/templates/sourcemap.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "metadata": { - "version": "1.0.0", - "generated_at": "[TIMESTAMP]", - "generator": "gerar-indices command", - "root_directory": "[ROOT_DIRECTORY]" - }, - "summary": { - "total_files": 0, - "total_directories": 0, - "max_depth": 0, - "file_types": {}, - "total_size_bytes": 0 - }, - "configuration": { - "exclude_patterns": [], - "include_hidden": false, - "max_depth": null - }, - "files": [ - { - "id": "unique-file-id", - "path": "/absolute/path/to/file", - "relative_path": "relative/path/to/file", - "name": "filename.ext", - "extension": "ext", - "type": "file", - "size_bytes": 0, - "modified_at": "2025-10-12T10:30:00Z", - "depth": 0, - "parent_directory": "/absolute/path/to", - "metadata": { - "language": "javascript", - "has_tests": false, - "is_config": false, - "is_documentation": false - } - } - ], - "tree": { - "name": "root", - "path": "[ROOT_DIRECTORY]", - "type": "directory", - "depth": 0, - "children": [] - }, - "statistics": { - "by_extension": {}, - "by_depth": {}, - "largest_files": [], - "recently_modified": [] - }, - "relationships": { - "imports": [], - "dependencies": [] - } -} \ No newline at end of file diff --git a/shared/templates/task.md b/shared/templates/task.md deleted file mode 100644 index d682903..0000000 --- a/shared/templates/task.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -task_id: {{TASK_ID}} -feature_id: {{FEATURE_ID}} -feature_name: {{FEATURE_NAME}} -title: {{TITLE}} -priority: {{PRIORITY}} -category: {{CATEGORY}} -status: pending -phase: {{PHASE}} -estimated_time: {{ESTIMATED_TIME}} -created_at: {{CREATED_AT}} -updated_at: {{UPDATED_AT}} -source_plan: {{SOURCE_PLAN}} -source_type: {{SOURCE_TYPE}} ---- - -# Task: {{TITLE}} - -## Metadata - -- **ID**: {{TASK_ID}} -- **Feature**: {{FEATURE_NAME}} ({{FEATURE_ID}}) -- **Priority**: {{PRIORITY_LABEL}} -- **Category**: {{CATEGORY}} -- **Status**: pending -- **Phase**: {{PHASE}} -- **Estimated Time**: {{ESTIMATED_TIME}} - -## Context - -**Feature**: {{FEATURE_NAME}} -**From Plan**: {{SOURCE_PLAN}} -**Plan Type**: {{SOURCE_TYPE}} -**Objective**: {{PLAN_OBJECTIVE}} - -{{CONTEXT_DESCRIPTION}} - -## Description - -{{FULL_DESCRIPTION}} - -## Affected Files - -{{AFFECTED_FILES}} - -## Dependencies - -**Depends On**: -{{DEPENDS_ON_LIST}} - -**Blocks**: -{{BLOCKS_LIST}} - -## Implementation Steps - -{{IMPLEMENTATION_STEPS}} - -## Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - -## Validation - -{{VALIDATION_CRITERIA}} - -## Notes - -{{ADDITIONAL_NOTES}} diff --git a/shared/templates/template.ci-cd-guide.md b/shared/templates/template.ci-cd-guide.md deleted file mode 100644 index d52df79..0000000 --- a/shared/templates/template.ci-cd-guide.md +++ /dev/null @@ -1,342 +0,0 @@ -# CI/CD Guide - [PROJECT_NAME] - -**Criado**: [DATE] -**Versão**: [VERSION] -**Workflows**: GitHub Actions - ---- - -## Overview - -Este projeto utiliza **GitHub Actions** para automação de CI/CD. Os workflows incluem: - -- **CI Pipeline**: Lint, test, build em cada push/PR -- **Publish Pipeline**: Publicação automática de pacotes -- **[ADDITIONAL_WORKFLOWS]**: [DESCRIPTION] - ---- - -## Workflows Configurados - -### 1. CI Pipeline (`.github/workflows/ci.yml`) - -**Trigger**: -- Push em branches: `[BRANCHES]` -- Pull Requests para: `[BRANCHES]` - -**Jobs**: -- `lint`: ESLint, Prettier, TypeScript check -- `test`: Unit tests + coverage -- `build`: Compilação de artefatos - -**Node Versions**: `[NODE_VERSIONS]` - -**Cache Strategy**: `[PACKAGE_MANAGER]` dependencies - -**Duração típica**: ~[DURATION] minutos - ---- - -### 2. Publish Pipeline (`.github/workflows/publish.yml`) - -**Trigger**: -- Push em branch `main` (após merge) -- Manual via workflow_dispatch - -**Jobs**: -- `detect-changes`: Identifica packages alterados -- `publish`: Publica para npm com provenance - -**Publish Targets**: -- [x] npm Registry (público) -- [ ] GitHub Packages -- [ ] Docker Hub -- [ ] [OTHER_TARGETS] - -**Versioning Strategy**: [CHANGESETS / SEMANTIC_RELEASE / MANUAL] - ---- - -### 3. [WORKFLOW_3_NAME] (`.github/workflows/[WORKFLOW_3_FILE]`) - -**Trigger**: [TRIGGER_DESCRIPTION] - -**Jobs**: [JOBS_DESCRIPTION] - ---- - -## Como Fazer Release - -### Monorepo (Changesets) - -1. **Criar Changeset**: - ```bash - [PACKAGE_MANAGER] changeset - ``` - Seguir prompts: - - Selecionar packages alterados - - Escolher tipo de bump (major, minor, patch) - - Escrever descrição da mudança - -2. **Commit Changeset**: - ```bash - git add .changeset/ - git commit -m "chore: add changeset for [FEATURE]" - git push - ``` - -3. **Merge PR**: - - Changesets bot criará PR de release automaticamente - - Review e merge do release PR - - Workflows publicarão automaticamente após merge - -4. **Verificar Publicação**: - - Ver em: https://github.com/[ORG]/[REPO]/actions - - Verificar npm: `npm view @[ORG]/[PACKAGE]` - -### Single Package (Semantic Release) - -1. **Fazer Commits Convencionais**: - ```bash - git commit -m "feat: add new feature" - git commit -m "fix: resolve bug" - ``` - -2. **Push para Main**: - ```bash - git push origin main - ``` - -3. **Semantic Release Automático**: - - Analisa commits - - Determina versão (major/minor/patch) - - Gera CHANGELOG - - Cria tag Git - - Publica para npm - ---- - -## Secrets e Configuração - -### GitHub Secrets Necessários - -| Secret | Propósito | Como Obter | -|--------|-----------|------------| -| `NPM_TOKEN` | Publicar no npm | [npm.com/settings/tokens](https://www.npmjs.com/settings/[USER]/tokens) | -| [OTHER_SECRET] | [PURPOSE] | [HOW_TO_GET] | - -**Adicionar secrets em**: `Settings → Secrets and variables → Actions → New repository secret` - -### npm Account Setup - -1. **Criar Token de Automação**: - - Acessar: https://www.npmjs.com/settings/[USER]/tokens - - Criar token tipo "Automation" - - Permissions: Read and write - - Copiar token (só aparece uma vez) - -2. **Habilitar 2FA**: - - Obrigatório para publicação - - Acessar: https://www.npmjs.com/settings/[USER]/tfa - -3. **Habilitar Provenance** (Recomendado): - - Workflows já configurados com `--provenance` - - Melhora security e transparency - - Docs: https://docs.npmjs.com/generating-provenance-statements - ---- - -## Branch Protection Rules - -**Para branch `main`** (Recomendado): - -``` -✅ Require a pull request before merging - ✅ Require approvals: 1 - ✅ Dismiss stale pull request approvals - -✅ Require status checks to pass before merging - ✅ Require branches to be up to date - ✅ Status checks required: - - lint - - test - - build - -✅ Require conversation resolution before merging - -✅ Require linear history - -❌ Do not allow bypassing the above settings -``` - -**Configurar em**: `Settings → Branches → Branch protection rules → Add rule` - ---- - -## Debugging Workflows - -### Ver Logs de Workflow - -1. Acessar: `https://github.com/[ORG]/[REPO]/actions` -2. Clicar no workflow falhado -3. Clicar no job falhado -4. Expandir step com erro - -### Reproduzir Localmente - -**Instalar act** (GitHub Actions local runner): -```bash -brew install act # macOS -# ou: https://github.com/nektos/act -``` - -**Executar job localmente**: -```bash -act -j lint -act -j test -act -j build -``` - -### Erros Comuns - -| Erro | Causa Provável | Solução | -|------|----------------|---------| -| `npm ERR! 404 Not Found` | Package não existe ou nome incorreto | Verificar `name` em package.json | -| `Error: No ESLint configuration found` | Config ESLint ausente | Criar `.eslintrc.js` ou adicionar em package.json | -| `401 Unauthorized` | NPM_TOKEN inválido | Gerar novo token e atualizar secret | -| `ENOENT: no such file` | Build não executou | Adicionar step de build antes | -| `Test suite failed to run` | Setup de test incorreto | Verificar jest.config.js e dependencies | - -### Reexecutar Workflow Falhado - -1. Ir para workflow falhado -2. Clicar "Re-run jobs" → "Re-run failed jobs" -3. Ou: "Re-run all jobs" (se mudou secrets/config) - ---- - -## Performance e Otimização - -### Caching - -Workflows usam cache para acelerar builds: - -```yaml -- uses: actions/setup-node@v4 - with: - cache: '[PACKAGE_MANAGER]' -``` - -**Cache hit**: ~30 segundos para restore -**Cache miss**: ~2-3 minutos para install - -### Paralelização - -Jobs independentes rodam em paralelo: - -``` -lint ────┐ - ├─→ (aguardar todos) -test ────┤ - │ -build ───┘ -``` - -### Matrix Builds - -Testar em múltiplas versões Node: - -```yaml -strategy: - matrix: - node-version: [18.x, 20.x] -``` - -Custo: 2x tempo de build (mas detecta incompatibilidades) - ---- - -## Monitoramento - -### Visualizar Status - -- **Badge de Status**: - ```markdown - ![CI](https://github.com/[ORG]/[REPO]/workflows/CI/badge.svg) - ``` - -- **GitHub Actions Tab**: Ver todos os runs -- **Email Notifications**: Configurar em Settings → Notifications - -### Métricas - -- **Success Rate**: % de workflows com sucesso -- **Duração Média**: Tempo médio de execução -- **Frequência**: Quantos workflows/dia - -Ver em: `Actions → [Workflow] → [Menu ⋯] → View workflow runs` - ---- - -## Troubleshooting - -### Workflow Não Triggou - -**Verificar**: -- [ ] Push foi para branch configurada em `on.push.branches` -- [ ] Paths modificados correspondem a `on.push.paths` (se configurado) -- [ ] Workflow file está em `.github/workflows/` (não `_github`) -- [ ] YAML é válido (sem erros de syntax) - -**Validar YAML localmente**: -```bash -yamllint .github/workflows/*.yml -``` - -### Workflow Lento - -**Causas comuns**: -- Cache miss (dependencies baixados do zero) -- Matrix builds muito largos -- Tests lentos (sem otimização) - -**Otimizações**: -- Habilitar caching se ausente -- Reduzir matrix (testar apenas LTS) -- Paralelizar tests (jest --maxWorkers) - -### Publish Não Funciona - -**Verificar**: -- [ ] NPM_TOKEN válido e com permissões -- [ ] Versão em package.json foi incrementada -- [ ] Package name disponível no registry -- [ ] 2FA configurado no npm account -- [ ] Provenance habilitado (workflow com `id-token: write`) - ---- - -## Recursos - -- [GitHub Actions Docs](https://docs.github.com/en/actions) -- [npm Publishing Guide](https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry) -- [Changesets Docs](https://github.com/changesets/changesets) -- [Semantic Release](https://semantic-release.gitbook.io/) -- [act (Local Runner)](https://github.com/nektos/act) - ---- - -## Suporte - -**Dúvidas ou problemas?** - -1. Verificar esta documentação -2. Consultar logs de workflow no GitHub -3. Executar localmente com `act` -4. Abrir issue no repositório - ---- - -_Última atualização: [DATE]_ - - diff --git a/shared/templates/template.commands.md b/shared/templates/template.commands.md deleted file mode 100644 index 45af46d..0000000 --- a/shared/templates/template.commands.md +++ /dev/null @@ -1,708 +0,0 @@ -# Template Universal de Commands - - - -**Criado**: $DATE -**Tipo de Command**: [COMMAND_TYPE] - ---- - -```markdown ---- -description: [COMMAND_VERB] [WHAT_IT_DOES] ---- - - - -## Entrada do Usuário - -```text -$ARGUMENTS -``` - -Você **DEVE** considerar a entrada do usuário antes de prosseguir (se não estiver vazia). - - - -## Objetivo - -[DESCRIPTION_PARAGRAPH_1] - -[DESCRIPTION_PARAGRAPH_2] - -**Quando usar**: [WHEN_TO_USE] - -**Pré-requisitos**: [PREREQUISITES_OR_NONE] - - - -## Descoberta & Validação - - - -Antes de prosseguir, você **DEVE** questionar o usuário para esclarecer: - -### Informações Obrigatórias - -1. **[INFO_1_NAME]**: [QUESTION_1]? - - Se não fornecido: [DEFAULT_VALUE_OR_ERROR_ACTION] - -2. **[INFO_2_NAME]**: [QUESTION_2]? - - Se não fornecido: [DEFAULT_VALUE_OR_ERROR_ACTION] - - - -### Preferências Opcionais - -1. **[PREFERENCE_1_NAME]**: [QUESTION_1]? - - Padrão: [SENSIBLE_DEFAULT] - - Opções: [OPTION_A] | [OPTION_B] | [OPTION_C] - -2. **[PREFERENCE_2_NAME]**: [QUESTION_2]? - - Padrão: [SENSIBLE_DEFAULT] - - - -## Fluxo de Execução - - - -### Fase 1: Inicializar - - - -1. **Validar Pré-requisitos**: - - [PREREQUISITE_CHECK_1] - - [PREREQUISITE_CHECK_2] - - Se ausente: [ERROR_ACTION] - -2. **Carregar Contexto**: - - [CONTEXT_LOAD_1] - - [CONTEXT_LOAD_2] - -3. **Parse da Entrada**: - - Extrair [DATA_1] de $ARGUMENTS - - Validar [VALIDATION_RULE] - - - -### Fase 2: [MAIN_TASK_NAME] - - - -1. [STEP_1_DESCRIPTION]: - - [SUB_STEP_1A] - - [SUB_STEP_1B] - -2. [STEP_2_DESCRIPTION]: - - [SUB_STEP_2A] - - [SUB_STEP_2B] - -3. [STEP_3_DESCRIPTION]: - - [SUB_STEP_3A] - - [SUB_STEP_3B] - - - -### Fase 3: [SECONDARY_TASK_OR_PROCESSING] - - - -1. [PROCESSING_STEP_1] -2. [PROCESSING_STEP_2] - -### Fase 4: Validar - - - -1. **Validar Output**: - - [VALIDATION_CHECK_1] - - [VALIDATION_CHECK_2] - - Se falhar: [FAILURE_ACTION] - -2. **Portões de Qualidade**: - - [ ] [QUALITY_CRITERION_1] - - [ ] [QUALITY_CRITERION_2] - - [ ] [QUALITY_CRITERION_3] - -3. **Tratamento de Erros**: - - Se [ERROR_CONDITION_1]: [RECOVERY_ACTION_1] - - Se [ERROR_CONDITION_2]: [RECOVERY_ACTION_2] - - - -### Fase 5: Output - - - -1. **Gerar Output**: - - [OUTPUT_GENERATION_1] - - [OUTPUT_GENERATION_2] - - Escrever em: [OUTPUT_PATH] - -2. **Reportar Resultados**: - ```markdown - ## [REPORT_TITLE] - - **Status**: [SUCCESS_OR_FAILURE] - - ### Resumo - - - [METRIC_1]: [VALUE] - - [METRIC_2]: [VALUE] - - [METRIC_3]: [VALUE] - - ### Artefatos Criados - - - [ARTIFACT_1_PATH] - - [ARTIFACT_2_PATH] - - ### Próximos Passos - - 1. [SUGGESTED_ACTION_1] - 2. [SUGGESTED_ACTION_2] - - - **Mensagem de commit sugerida**: - ``` - [COMMIT_TYPE]([SCOPE]): [COMMIT_MESSAGE] - - - [CHANGE_1] - - [CHANGE_2] - ``` - ``` - ``` - -3. **Atualizar Estado** *(opcional)*: - - [STATE_UPDATE_ACTION] - - - -## Princípios Operacionais - - - -### Padrões de Qualidade - -- **[STANDARD_1_NAME]**: [STANDARD_1_DESCRIPTION] -- **[STANDARD_2_NAME]**: [STANDARD_2_DESCRIPTION] -- **[STANDARD_3_NAME]**: [STANDARD_3_DESCRIPTION] - - - -### Tratamento de Erros - -- **Se [ERROR_CONDITION_1]**: [ACTION_1] -- **Se [ERROR_CONDITION_2]**: [ACTION_2] -- **Se [ERROR_CONDITION_3]**: [ACTION_3] - - - -### Restrições - -- [CONSTRAINT_1] -- [CONSTRAINT_2] -- [CONSTRAINT_3] - - - -### Regras de Comportamento - - - -- [BEHAVIOR_RULE_1] -- [BEHAVIOR_RULE_2] - - - -## Scripts - - - -### [SCRIPT_NAME_1].sh - -**Propósito**: [SCRIPT_PURPOSE] - -**Localização**: `vibes/scripts/bash/[SCRIPT_NAME_1].sh` - -**Uso**: -```bash -vibes/scripts/bash/[SCRIPT_NAME_1].sh [ARGS] --json -``` - -**Output** (JSON): -```json -{ - "[FIELD_1]": "[VALUE_OR_PATH]", - "[FIELD_2]": "[VALUE_OR_PATH]", - "[FIELD_3]": "[VALUE_OR_PATH]" -} -``` - -**Códigos de Erro**: -- `0`: Sucesso -- `1`: [ERROR_TYPE_1] -- `2`: [ERROR_TYPE_2] - - - -## Templates - - - -### [TEMPLATE_NAME].md - -**Propósito**: [TEMPLATE_PURPOSE] - -**Localização**: `vibes/structure/templates/[TEMPLATE_NAME].md` - -**Usado para**: [USAGE_DESCRIPTION] - -**Estrutura**: -- Seção 1: [SECTION_1_NAME] *(obrigatório)* -- Seção 2: [SECTION_2_NAME] *(opcional)* -- Seção 3: [SECTION_3_NAME] *(obrigatório)* - - - -## Exemplos - - - -### Exemplo 1: Input Bom → Output - -``` -Input: [EXAMPLE_GOOD_INPUT] - -Output: -[EXAMPLE_GOOD_OUTPUT] -``` - - - -### Exemplo 2: Pré-requisitos Ausentes → Erro - -``` -Input: [EXAMPLE_BAD_INPUT_OR_STATE] - -Output: -❌ ERRO: [ERROR_DESCRIPTION] - -Contexto: -- [CONTEXT_INFO] - -Razão: -- [REASON] - -Sugestão: -- [HOW_TO_FIX] - -Próxima Ação: -- [SPECIFIC_COMMAND_OR_STEP] -``` - - - -### Exemplo 3: [ADDITIONAL_EXAMPLE_NAME] - - - -``` -Input: [EXAMPLE_3_INPUT] - -Output: -[EXAMPLE_3_OUTPUT] -``` - -## Integração - - - -### Posição no Workflow - -**Precedido por**: [PREVIOUS_COMMAND_OR_NONE] - -**Seguido por**: [NEXT_COMMAND_OR_NONE] - -### Dependências - -**Commands Obrigatórios**: [COMMAND_1], [COMMAND_2] - -**Commands Opcionais**: [COMMAND_3], [COMMAND_4] - -### Fluxo de Dados - -``` -[PREVIOUS_COMMAND] - ↓ (produz: [ARTIFACT]) -[THIS_COMMAND] - ↓ (produz: [ARTIFACT]) -[NEXT_COMMAND] -``` - - - -## Contexto - -$ARGUMENTS - - - -## Checklist de Qualidade - - - -Antes de considerar este command completo, verifique: - -### Estrutura -- [ ] Frontmatter com description clara e concisa -- [ ] Seção Entrada do Usuário presente -- [ ] Objetivo com 2-3 parágrafos explicativos -- [ ] Quando usar e Pré-requisitos documentados -- [ ] Descoberta & Validação (se inputs podem ser ambíguos) -- [ ] Fluxo de Execução com fases numeradas -- [ ] Princípios Operacionais com standards, error handling, constraints -- [ ] Exemplos com pelo menos input bom e caso de erro - -### Qualidade de Conteúdo -- [ ] Propósito do command imediatamente compreensível -- [ ] Todos os passos de execução documentados -- [ ] Error handling explícito para casos conhecidos -- [ ] Exemplos realistas e úteis -- [ ] Nenhum placeholder [CAPS] não preenchido -- [ ] Seções [REMOVE IF UNUSED] avaliadas (usadas ou removidas) - -### Consistência -- [ ] Segue estrutura deste template -- [ ] Usa terminologia consistente com outros commands -- [ ] Referências a paths e arquivos estão corretas -- [ ] Scripts e templates referenciados existem -- [ ] Integração com outros commands documentada (se aplicável) - -### Governança -- [ ] Respeita princípios da constitution.md (se existir) -- [ ] Não viola constraints estabelecidos -- [ ] Segue padrões de qualidade do projeto - ---- - -## Metadados do Template - -**Versão**: 1.0 -**Framework**: QUEST (Question, Understand, Engineer, Solidify, Test) -**Última Atualização**: 2024-01-15 -**Mantido Por**: maker.command.md - -**Changelog**: -- 1.0 (2024-01-15): Template inicial baseado no Guia de Excelência de Commands -``` - - diff --git a/shared/templates/template.dockerfile.md b/shared/templates/template.dockerfile.md deleted file mode 100644 index 3fc7568..0000000 --- a/shared/templates/template.dockerfile.md +++ /dev/null @@ -1,450 +0,0 @@ -# Template de Dockerfile - - - -**Criado**: $DATE -**Versão**: 1.0 - ---- - -## Estrutura Base - -```dockerfile -# [PROJECT_TYPE] Dockerfile -# Multi-stage build otimizado para [ENVIRONMENT] - -# ============================================================================ -# STAGE 1: Dependencies -# ============================================================================ -FROM [BASE_IMAGE] AS dependencies - -LABEL stage="dependencies" - -WORKDIR /app - -# Instalar dependências do sistema -RUN apt-get update && apt-get install -y \ - [SYSTEM_DEPS] \ - && rm -rf /var/lib/apt/lists/* - -# Copiar arquivos de dependências -COPY [DEPS_FILES] ./ - -# Instalar dependências do projeto -RUN [INSTALL_CMD] - -# ============================================================================ -# STAGE 2: Build -# ============================================================================ -FROM [BASE_IMAGE] AS build - -LABEL stage="build" - -WORKDIR /app - -# Copiar dependências do stage anterior -COPY --from=dependencies /app/node_modules ./node_modules - -# Copiar código fonte -COPY [SOURCE_FILES] ./ - -# Executar build -RUN [BUILD_CMD] - -# ============================================================================ -# STAGE 3: Production -# ============================================================================ -FROM [PROD_BASE_IMAGE] AS production - -LABEL stage="production" - -# Criar usuário não-root -RUN groupadd -r appuser && useradd -r -g appuser appuser - -WORKDIR /app - -# Copiar apenas arquivos necessários do build -COPY --from=build /app/[BUILD_OUTPUT] ./ - -# Copiar node_modules de produção (se aplicável) -COPY --from=dependencies /app/node_modules ./node_modules - -# Definir permissões -RUN chown -R appuser:appuser /app - -# Mudar para usuário não-root -USER appuser - -# Expor porta -EXPOSE [PORT] - -# Health check -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD [HEALTH_CMD] - -# Comando de inicialização -CMD [START_CMD] -``` - ---- - -## Templates por Tipo de Projeto - -### Node.js (Express/API) - -```dockerfile -FROM node:18-alpine AS dependencies - -LABEL stage="dependencies" - -WORKDIR /app - -COPY package*.json ./ - -RUN npm ci --only=production && \ - npm cache clean --force - -FROM node:18-alpine AS build - -LABEL stage="build" - -WORKDIR /app - -COPY package*.json ./ -RUN npm ci - -COPY . . - -RUN npm run build - -FROM node:18-alpine AS production - -LABEL stage="production" - -RUN addgroup -g 1001 -S nodejs && \ - adduser -S nodejs -u 1001 - -WORKDIR /app - -COPY --from=dependencies --chown=nodejs:nodejs /app/node_modules ./node_modules -COPY --from=build --chown=nodejs:nodejs /app/dist ./dist -COPY --chown=nodejs:nodejs package*.json ./ - -USER nodejs - -EXPOSE 3000 - -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD node healthcheck.js - -CMD ["node", "dist/index.js"] -``` - -### Python (FastAPI/Django) - -```dockerfile -FROM python:3.11-slim AS dependencies - -LABEL stage="dependencies" - -WORKDIR /app - -RUN apt-get update && apt-get install -y \ - gcc \ - && rm -rf /var/lib/apt/lists/* - -COPY requirements.txt . - -RUN pip install --no-cache-dir -r requirements.txt - -FROM python:3.11-slim AS production - -LABEL stage="production" - -RUN groupadd -r appuser && useradd -r -g appuser appuser - -WORKDIR /app - -COPY --from=dependencies /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages -COPY --from=dependencies /usr/local/bin /usr/local/bin - -COPY --chown=appuser:appuser . . - -USER appuser - -EXPOSE 8000 - -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD python healthcheck.py - -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] -``` - -### React/Next.js (Frontend) - -```dockerfile -FROM node:18-alpine AS dependencies - -LABEL stage="dependencies" - -WORKDIR /app - -COPY package*.json ./ - -RUN npm ci - -FROM node:18-alpine AS build - -LABEL stage="build" - -WORKDIR /app - -COPY --from=dependencies /app/node_modules ./node_modules -COPY . . - -RUN npm run build - -FROM node:18-alpine AS production - -LABEL stage="production" - -RUN addgroup -g 1001 -S nodejs && \ - adduser -S nodejs -u 1001 - -WORKDIR /app - -COPY --from=build --chown=nodejs:nodejs /app/.next ./.next -COPY --from=build --chown=nodejs:nodejs /app/public ./public -COPY --from=build --chown=nodejs:nodejs /app/package*.json ./ -COPY --from=dependencies --chown=nodejs:nodejs /app/node_modules ./node_modules - -USER nodejs - -EXPOSE 3000 - -HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ - CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1 - -CMD ["npm", "start"] -``` - -### Go - -```dockerfile -FROM golang:1.21-alpine AS build - -LABEL stage="build" - -WORKDIR /app - -RUN apk add --no-cache git - -COPY go.mod go.sum ./ -RUN go mod download - -COPY . . - -RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app . - -FROM alpine:latest AS production - -LABEL stage="production" - -RUN apk --no-cache add ca-certificates - -WORKDIR /root/ - -COPY --from=build /app/app . - -EXPOSE 8080 - -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1 - -CMD ["./app"] -``` - -### Rust - -```dockerfile -FROM rust:1.75-slim AS build - -LABEL stage="build" - -WORKDIR /app - -RUN apt-get update && apt-get install -y \ - pkg-config \ - libssl-dev \ - && rm -rf /var/lib/apt/lists/* - -COPY Cargo.toml Cargo.lock ./ - -RUN mkdir src && \ - echo "fn main() {}" > src/main.rs && \ - cargo build --release && \ - rm -rf src - -COPY . . - -RUN touch src/main.rs && \ - cargo build --release - -FROM debian:bookworm-slim AS production - -LABEL stage="production" - -RUN apt-get update && apt-get install -y \ - ca-certificates \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /app - -COPY --from=build /app/target/release/[APP_NAME] . - -EXPOSE 8080 - -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1 - -CMD ["./[APP_NAME]"] -``` - ---- - -## Labels Recomendados - -```dockerfile -LABEL maintainer="[YOUR_EMAIL]" -LABEL version="1.0" -LABEL description="[PROJECT_DESCRIPTION]" -LABEL org.opencontainers.image.source="[REPO_URL]" -LABEL org.opencontainers.image.version="[VERSION]" -LABEL org.opencontainers.image.created="[DATE]" -LABEL org.opencontainers.image.revision="[COMMIT_HASH]" -``` - ---- - -## Health Checks por Tipo - -### Node.js -```dockerfile -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD node healthcheck.js -``` - -### Python -```dockerfile -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD python healthcheck.py -``` - -### HTTP/API -```dockerfile -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD wget --no-verbose --tries=1 --spider http://localhost:[PORT]/health || exit 1 -``` - -### TCP -```dockerfile -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD nc -z localhost [PORT] || exit 1 -``` - ---- - -## Otimizações Comuns - -### 1. Cache de Layers -```dockerfile -# Ordem: arquivos que mudam menos primeiro -COPY package*.json ./ -RUN npm ci -COPY . . -``` - -### 2. Multi-stage Build -```dockerfile -FROM [base] AS build -# ... build steps ... - -FROM [prod-base] AS production -COPY --from=build /app/dist ./dist -``` - -### 3. Usuário Não-root -```dockerfile -RUN groupadd -r appuser && useradd -r -g appuser appuser -USER appuser -``` - -### 4. Limpeza de Cache -```dockerfile -RUN npm ci && npm cache clean --force -RUN apt-get update && apt-get install -y [pkgs] && rm -rf /var/lib/apt/lists/* -``` - -### 5. .dockerignore -``` -node_modules -npm-debug.log -.git -.gitignore -.env -.env.local -dist -build -coverage -*.md -``` - ---- - -## Checklist de Qualidade - -Antes de considerar o Dockerfile completo: - -### Estrutura -- [ ] Multi-stage build implementado -- [ ] Labels informativos presentes -- [ ] Usuário não-root configurado -- [ ] Health check implementado -- [ ] .dockerignore configurado - -### Otimização -- [ ] Layers ordenadas para cache eficiente -- [ ] Dependências de sistema minimizadas -- [ ] Cache limpo após instalação -- [ ] Base image otimizada (alpine/distroless) -- [ ] Build output minimizado - -### Segurança -- [ ] Usuário não-root -- [ ] Secrets não expostos -- [ ] Base image oficial -- [ ] Dependências atualizadas -- [ ] Health check funcional - -### Performance -- [ ] Layers otimizadas para cache -- [ ] Tamanho de imagem minimizado -- [ ] Build time otimizado -- [ ] Startup time otimizado - ---- - -## Metadados do Template - -**Versão**: 1.0 -**Última Atualização**: 2025-01-18 -**Mantido Por**: maker.dockerize.md - -**Changelog**: -- 1.0 (2025-01-18): Template inicial com suporte para Node.js, Python, React, Go e Rust - diff --git a/shared/templates/template.project-report.md b/shared/templates/template.project-report.md deleted file mode 100644 index d7ec9e1..0000000 --- a/shared/templates/template.project-report.md +++ /dev/null @@ -1,578 +0,0 @@ - - -# Project Analysis Report: [PROJECT_NAME] - -**Analyzed at**: [TIMESTAMP] -**Project Path**: [PROJECT_PATH] -**Analyzed by**: ai - ---- - -## 📊 Executive Summary - -**Project Type**: [PROJECT_TYPE] -**Domain**: [DOMAIN] -**Primary Language**: [PRIMARY_LANGUAGE] -**Status**: [STATUS] - -**Quick Stats**: -- Dependencies: [N] declared, [STATUS] -- Files: [N] total ([N] source, [N] tests) -- Documentation: [PRESENT|PARTIAL|ABSENT] -- Tests: [CONFIGURED|NOT_CONFIGURED] -- Build Tools: [BUILD_TOOLS] - -**Overall Assessment**: [ASSESSMENT_SUMMARY] - ---- - -## 🎯 Project Overview - -### What is this project? - -[PROJECT_DESCRIPTION] - -### Purpose and Goals - -[PURPOSE_DESCRIPTION] - -### Target Audience - -[TARGET_AUDIENCE] - -### Main Features - -1. [FEATURE_1] -2. [FEATURE_2] -3. [FEATURE_3] -4. [FEATURE_N] - ---- - -## 🛠️ Technology Stack - -### Languages - -| Language | Usage | Files | -|----------|-------|-------| -| [LANGUAGE_1] | [USAGE_1] | [N] | -| [LANGUAGE_2] | [USAGE_2] | [N] | - -### Frameworks & Libraries - -**Core Frameworks**: -- [FRAMEWORK_1] ([VERSION]) -- [FRAMEWORK_2] ([VERSION]) - -**Key Libraries**: -- [LIBRARY_1] ([VERSION]) - [PURPOSE] -- [LIBRARY_2] ([VERSION]) - [PURPOSE] -- [LIBRARY_3] ([VERSION]) - [PURPOSE] - -### Development Tools - -- **Package Manager**: [PACKAGE_MANAGER] ([VERSION]) -- **Build Tool**: [BUILD_TOOL] ([VERSION]) -- **Test Framework**: [TEST_FRAMEWORK] ([VERSION]) -- **Linter**: [LINTER] ([VERSION]) -- **Formatter**: [FORMATTER] ([VERSION]) - ---- - -## 🏗️ Architecture - -### Architecture Pattern - -[ARCHITECTURE_PATTERN] - - - -### Directory Structure - -``` -[PROJECT_ROOT]/ -├── [DIR_1]/ # [DESCRIPTION_1] -│ ├── [SUBDIR_1]/ # [DESCRIPTION] -│ └── [SUBDIR_2]/ # [DESCRIPTION] -├── [DIR_2]/ # [DESCRIPTION_2] -├── [DIR_3]/ # [DESCRIPTION_3] -└── [DIR_N]/ # [DESCRIPTION_N] -``` - -### Entry Points - -- **Main Entry**: [MAIN_ENTRY_FILE] -- **Purpose**: [ENTRY_PURPOSE] -- **Initialization Flow**: [INIT_FLOW] - -### Key Modules/Components - -1. **[MODULE_1]** - - Location: [PATH] - - Purpose: [PURPOSE] - - Dependencies: [DEPENDENCIES] - -2. **[MODULE_2]** - - Location: [PATH] - - Purpose: [PURPOSE] - - Dependencies: [DEPENDENCIES] - ---- - -## 📦 Dependencies - -### Status Summary - -**Total Dependencies**: [N] -- Production: [N] -- Development: [N] - -**Installation Status**: [INSTALLED|NOT_INSTALLED|PARTIAL] - -**Lock Files**: -- [LOCK_FILE_1]: [PRESENT|ABSENT] -- [LOCK_FILE_2]: [PRESENT|ABSENT] - -### Production Dependencies - -| Dependency | Version | Purpose | -|------------|---------|---------| -| [DEP_1] | [VERSION] | [PURPOSE] | -| [DEP_2] | [VERSION] | [PURPOSE] | -| [DEP_3] | [VERSION] | [PURPOSE] | - -### Development Dependencies - -| Dependency | Version | Purpose | -|------------|---------|---------| -| [DEV_DEP_1] | [VERSION] | [PURPOSE] | -| [DEV_DEP_2] | [VERSION] | [PURPOSE] | - -### Missing or Outdated - -[LIST_MISSING_OR_OUTDATED_DEPENDENCIES] - - - ---- - -## ⚙️ Configuration - -### Configuration Files - -| File | Purpose | Status | -|------|---------|--------| -| [CONFIG_1] | [PURPOSE] | [PRESENT|ABSENT] | -| [CONFIG_2] | [PURPOSE] | [PRESENT|ABSENT] | -| [CONFIG_3] | [PURPOSE] | [PRESENT|ABSENT] | - -### Environment Variables - -**Required Variables** (from `.env.example` or code analysis): - -- `[VAR_1]`: [DESCRIPTION] -- `[VAR_2]`: [DESCRIPTION] -- `[VAR_3]`: [DESCRIPTION] - -**Status**: [CONFIGURED|NOT_CONFIGURED|PARTIAL] - -### Build Configuration - -**Build Tool**: [BUILD_TOOL] -**Configuration File**: [CONFIG_FILE] - -**Build Targets**: -- Development: [DEV_COMMAND] -- Production: [PROD_COMMAND] - -**Output Directory**: [OUTPUT_DIR] - ---- - -## 📜 Available Scripts - -| Script | Command | Purpose | -|--------|---------|---------| -| [SCRIPT_1] | `[COMMAND_1]` | [PURPOSE_1] | -| [SCRIPT_2] | `[COMMAND_2]` | [PURPOSE_2] | -| [SCRIPT_3] | `[COMMAND_3]` | [PURPOSE_3] | - ---- - -## 📁 Code Structure - -### File Statistics - -| Category | Count | -|----------|-------| -| Total Files | [N] | -| Source Files | [N] | -| Test Files | [N] | -| Config Files | [N] | - -### File Types - -| Extension | Count | Usage | -|-----------|-------|-------| -| [EXT_1] | [N] | [USAGE] | -| [EXT_2] | [N] | [USAGE] | -| [EXT_3] | [N] | [USAGE] | - -### Code Organization - -**Structure Pattern**: [PATTERN] - - - -**Key Directories**: -- `[DIR_1]`: [DESCRIPTION] -- `[DIR_2]`: [DESCRIPTION] -- `[DIR_3]`: [DESCRIPTION] - ---- - -## 🧪 Quality & Tooling - -### Testing - -**Test Framework**: [TEST_FRAMEWORK] -**Configuration**: [CONFIG_FILE] - -**Test Coverage**: [COVERAGE_INFO] - -**Test Commands**: -- Run tests: `[TEST_COMMAND]` -- Coverage: `[COVERAGE_COMMAND]` - -### Linting & Formatting - -**Linter**: [LINTER] -- Configuration: [LINTER_CONFIG] -- Command: `[LINT_COMMAND]` - -**Formatter**: [FORMATTER] -- Configuration: [FORMATTER_CONFIG] -- Command: `[FORMAT_COMMAND]` - -### Type Safety - -**Type System**: [TYPESCRIPT|FLOW|NONE] -**Configuration**: [TSCONFIG_OR_FLOWCONFIG] - -### CI/CD - -**CI Platform**: [CI_PLATFORM] -**Configuration**: [CI_CONFIG_FILE] - -**Workflows**: -- [WORKFLOW_1]: [DESCRIPTION] -- [WORKFLOW_2]: [DESCRIPTION] - -### Git Hooks - -**Hook Manager**: [HUSKY|NONE] -**Pre-commit**: [CONFIGURED|NOT_CONFIGURED] -**Pre-push**: [CONFIGURED|NOT_CONFIGURED] - ---- - -## 📚 Documentation Analysis - -### Existing Documentation - -| Document | Status | Quality | -|----------|--------|---------| -| README.md | [PRESENT|ABSENT] | [GOOD|PARTIAL|POOR] | -| CONTRIBUTING.md | [PRESENT|ABSENT] | [GOOD|PARTIAL|POOR] | -| docs/ directory | [PRESENT|ABSENT] | [GOOD|PARTIAL|POOR] | -| API docs | [PRESENT|ABSENT] | [GOOD|PARTIAL|POOR] | -| Code comments | [PRESENT|ABSENT] | [GOOD|PARTIAL|POOR] | - -### Documentation Gaps - -[LIST_DOCUMENTATION_GAPS] - - - -### Documentation Quality Assessment - -[ASSESSMENT] - - - ---- - -## ✅ To-Do List: Rodar o Projeto - -### Pré-requisitos - -1. [ ] Verificar ambiente: `/analyzer.pre-requirements` -2. [ ] Instalar [TOOL_1] (versão [VERSION_1]) - ```bash - [INSTALL_COMMAND_1] - ``` -3. [ ] Instalar [TOOL_2] (versão [VERSION_2]) - ```bash - [INSTALL_COMMAND_2] - ``` - -### Setup Inicial - -1. [ ] Clonar repositório - ```bash - git clone [REPO_URL] - cd [PROJECT_NAME] - ``` - -2. [ ] Instalar dependências - ```bash - [INSTALL_DEPENDENCIES_COMMAND] - ``` - -3. [ ] Configurar variáveis de ambiente - ```bash - cp .env.example .env - ``` - - [ ] Editar `.env` e preencher: - * `[VAR_1]` = [DESCRIPTION] - * `[VAR_2]` = [DESCRIPTION] - * `[VAR_3]` = [DESCRIPTION] - -4. [ ] [ADDITIONAL_SETUP_STEP] - ```bash - [SETUP_COMMAND] - ``` - -### Build - -1. [ ] Executar build - ```bash - [BUILD_COMMAND] - ``` - -2. [ ] Validar que build completou sem erros - -### Execução - -1. [ ] Iniciar projeto - ```bash - [START_COMMAND] - ``` - -2. [ ] Validar que projeto está rodando - - [ ] [VALIDATION_STEP_1] - - [ ] [VALIDATION_STEP_2] - -### Troubleshooting (se necessário) - -1. [ ] Limpar cache e rebuild - ```bash - [CLEAN_COMMAND] - [BUILD_COMMAND] - ``` - -2. [ ] Reinstalar dependências - ```bash - [CLEAN_DEPS_COMMAND] - [INSTALL_COMMAND] - ``` - -3. [ ] Verificar logs de erro - ```bash - [LOG_COMMAND] - ``` - -4. [ ] Consultar [TROUBLESHOOTING_RESOURCE] - ---- - -## 🚀 To-Do List: Contribuir como Dev - -### Setup de Desenvolvimento - -1. [ ] Configurar IDE - - [ ] Instalar [IDE_NAME] - - [ ] Instalar extensões recomendadas: - * [EXTENSION_1] - * [EXTENSION_2] - * [EXTENSION_3] - -2. [ ] Configurar Git - ```bash - git config user.name "[YOUR_NAME]" - git config user.email "[YOUR_EMAIL]" - ``` - -3. [ ] Instalar Git hooks (se configurado) - ```bash - [HOOKS_INSTALL_COMMAND] - ``` - -4. [ ] Configurar linter/formatter na IDE - - [ ] [LINTER_SETUP_STEP] - - [ ] [FORMATTER_SETUP_STEP] - -### Workflow de Desenvolvimento - -1. [ ] Criar branch para feature/fix - ```bash - git checkout -b [BRANCH_TYPE]/[BRANCH_NAME] - ``` - - -2. [ ] Fazer alterações no código - - [ ] Seguir padrões de código do projeto - - [ ] Adicionar/atualizar testes - - [ ] Atualizar documentação se necessário - -3. [ ] Executar testes - ```bash - [TEST_COMMAND] - ``` - -4. [ ] Executar linter - ```bash - [LINT_COMMAND] - ``` - -5. [ ] Executar formatter - ```bash - [FORMAT_COMMAND] - ``` - -6. [ ] Validar build - ```bash - [BUILD_COMMAND] - ``` - -### Commit e Push - -1. [ ] Adicionar arquivos modificados - ```bash - git add [FILES] - ``` - -2. [ ] Commit com mensagem descritiva - ```bash - git commit -m "[TYPE]: [DESCRIPTION]" - ``` - - -3. [ ] Push da branch - ```bash - git push origin [BRANCH_NAME] - ``` - -### Code Review e Merge - -1. [ ] Criar Pull Request - - [ ] Preencher descrição completa - - [ ] Linkar issues relacionadas - - [ ] Adicionar reviewers - -2. [ ] Aguardar code review - - [ ] Responder comentários - - [ ] Fazer alterações solicitadas - -3. [ ] Merge após aprovação - - [ ] Resolver conflitos se necessário - - [ ] Validar CI passou - -4. [ ] Deletar branch após merge - ```bash - git branch -d [BRANCH_NAME] - git push origin --delete [BRANCH_NAME] - ``` - -### Padrões de Código - -1. [ ] Seguir convenções de nomenclatura: - - [NAMING_CONVENTION_1] - - [NAMING_CONVENTION_2] - -2. [ ] Adicionar testes para novas features: - - [ ] Testes unitários - - [ ] Testes de integração (se aplicável) - -3. [ ] Documentar código complexo: - - [ ] Comentários explicativos - - [ ] JSDoc/TSDoc (se aplicável) - -4. [ ] Seguir estilo de commit: - - [COMMIT_STYLE] (ex: Conventional Commits) - ---- - -## 🎯 Recommended Next Steps - -### Immediate Actions (Priority 1) - -1. **[ACTION_1]** - - Why: [REASON] - - How: [STEPS] - -2. **[ACTION_2]** - - Why: [REASON] - - How: [STEPS] - -### Improvements (Priority 2) - -1. **[IMPROVEMENT_1]** - - Current State: [STATE] - - Desired State: [DESIRED] - - Benefit: [BENEFIT] - -2. **[IMPROVEMENT_2]** - - Current State: [STATE] - - Desired State: [DESIRED] - - Benefit: [BENEFIT] - -### Long-term (Priority 3) - -1. **[LONG_TERM_1]** - - Description: [DESCRIPTION] - - Impact: [IMPACT] - -2. **[LONG_TERM_2]** - - Description: [DESCRIPTION] - - Impact: [IMPACT] - ---- - -## 🔗 Additional Resources - -- **Repository**: [REPO_URL] -- **Documentation**: [DOCS_URL] -- **Issue Tracker**: [ISSUES_URL] -- **CI/CD**: [CI_URL] -- **Project Board**: [PROJECT_BOARD_URL] - ---- - -## 📝 Notes - -[ADDITIONAL_NOTES] - - - ---- - -**Generated by**: `/analyzer.project` -**Timestamp**: [TIMESTAMP] -**Version**: 1.0 - diff --git a/shared/templates/template.research-metadata.json b/shared/templates/template.research-metadata.json deleted file mode 100644 index 7a424ed..0000000 --- a/shared/templates/template.research-metadata.json +++ /dev/null @@ -1,631 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "Deep Research Metadata Schema", - "description": "Schema completo de metadados para pesquisas profundas. Usado por research.* commands.", - "type": "object", - "required": [ - "researchId", - "objective", - "status", - "created", - "updated" - ], - "properties": { - "researchId": { - "type": "string", - "description": "ID único da pesquisa (kebab-case, max 30 chars)", - "pattern": "^[a-z0-9-]{3,30}$", - "examples": [ - "auth-methods-2025", - "deep-learning-nlp" - ] - }, - "objective": { - "type": "object", - "required": [ - "question", - "scope" - ], - "properties": { - "question": { - "type": "string", - "description": "Pergunta de pesquisa clara e específica", - "minLength": 10, - "maxLength": 500 - }, - "scope": { - "type": "string", - "description": "Escopo e limites da pesquisa", - "minLength": 10, - "maxLength": 1000 - }, - "context": { - "type": "string", - "description": "Contexto adicional ou motivação" - }, - "successCriteria": { - "type": "array", - "description": "Critérios de sucesso da pesquisa", - "items": { - "type": "string" - }, - "minItems": 1 - } - } - }, - "status": { - "type": "string", - "enum": [ - "initialized", - "searching", - "scoring", - "analyzing", - "synthesizing", - "validating", - "completed", - "paused", - "cancelled" - ], - "description": "Status atual da pesquisa" - }, - "created": { - "type": "string", - "format": "date-time", - "description": "Data/hora de criação (ISO 8601)" - }, - "updated": { - "type": "string", - "format": "date-time", - "description": "Data/hora da última atualização (ISO 8601)" - }, - "inputSources": { - "type": "array", - "description": "Fontes de entrada da pesquisa", - "items": { - "type": "object", - "required": [ - "type", - "content" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "text", - "markdown", - "file", - "url" - ], - "description": "Tipo da fonte" - }, - "content": { - "type": "string", - "description": "Conteúdo ou path da fonte" - }, - "extractedKeywords": { - "type": "array", - "description": "Palavras-chave extraídas automaticamente", - "items": { - "type": "string" - } - } - } - } - }, - "searchPhase": { - "type": "object", - "description": "Metadados da fase de busca inicial", - "properties": { - "totalReferencesFound": { - "type": "integer", - "minimum": 0, - "description": "Total de referências encontradas" - }, - "searchQueries": { - "type": "array", - "description": "Queries utilizadas na busca", - "items": { - "type": "object", - "properties": { - "query": { - "type": "string" - }, - "tool": { - "type": "string", - "enum": [ - "web_search", - "web_search", - "web_search" - ] - }, - "resultsCount": { - "type": "integer" - }, - "timestamp": { - "type": "string", - "format": "date-time" - } - } - } - }, - "completedAt": { - "type": "string", - "format": "date-time" - } - } - }, - "references": { - "type": "array", - "description": "Lista de todas as referências encontradas", - "items": { - "type": "object", - "required": [ - "id", - "title", - "url", - "discoveredAt" - ], - "properties": { - "id": { - "type": "string", - "description": "ID único da referência (REF-001, REF-002, ...)", - "pattern": "^REF-\\d{3,}$" - }, - "title": { - "type": "string", - "description": "Título da referência" - }, - "url": { - "type": "string", - "format": "uri", - "description": "URL da referência" - }, - "snippet": { - "type": "string", - "description": "Snippet ou resumo inicial" - }, - "discoveredAt": { - "type": "string", - "format": "date-time", - "description": "Quando foi descoberta" - }, - "source": { - "type": "string", - "enum": [ - "web_search", - "web_search", - "web_search", - "snowballing", - "manual" - ], - "description": "Como foi descoberta" - }, - "scoring": { - "type": "object", - "description": "Resultado do scoring (após research.score)", - "properties": { - "totalScore": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Score total (0-10)" - }, - "dimensions": { - "type": "object", - "properties": { - "credibility": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Credibilidade da fonte (0-10)" - }, - "relevance": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Relevância para o objetivo (0-10)" - }, - "recency": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Quão recente é (0-10)" - }, - "depth": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Profundidade do conteúdo (0-10)" - }, - "authority": { - "type": "number", - "minimum": 0, - "maximum": 10, - "description": "Autoridade do autor/site (0-10)" - } - } - }, - "reasoning": { - "type": "string", - "description": "Explicação do score atribuído" - }, - "scoredAt": { - "type": "string", - "format": "date-time" - } - } - }, - "analysis": { - "type": "object", - "description": "Resultado da análise profunda (após research.analyze)", - "properties": { - "status": { - "type": "string", - "enum": [ - "pending", - "in_progress", - "completed", - "failed", - "skipped" - ], - "description": "Status da análise" - }, - "reportPath": { - "type": "string", - "description": "Path do relatório de análise completo" - }, - "keyFindings": { - "type": "array", - "description": "Principais descobertas", - "items": { - "type": "string" - } - }, - "quotes": { - "type": "array", - "description": "Citações importantes extraídas", - "items": { - "type": "object", - "properties": { - "text": { - "type": "string" - }, - "context": { - "type": "string" - } - } - } - }, - "analyzedAt": { - "type": "string", - "format": "date-time" - } - } - }, - "tags": { - "type": "array", - "description": "Tags da referência", - "items": { - "type": "string" - } - }, - "categories": { - "type": "array", - "description": "Categorias da referência", - "items": { - "type": "string", - "enum": [ - "academic", - "blog", - "documentation", - "news", - "tutorial", - "case-study", - "opinion", - "research-paper", - "whitepaper", - "video", - "other" - ] - } - } - } - } - }, - "statistics": { - "type": "object", - "description": "Estatísticas agregadas da pesquisa", - "properties": { - "totalReferences": { - "type": "integer", - "minimum": 0 - }, - "scoredReferences": { - "type": "integer", - "minimum": 0 - }, - "analyzedReferences": { - "type": "integer", - "minimum": 0 - }, - "averageScore": { - "type": "number", - "minimum": 0, - "maximum": 10 - }, - "topScoredCount": { - "type": "integer", - "description": "Quantidade no top 20% (para análise profunda)" - }, - "referencesByCategory": { - "type": "object", - "description": "Contagem por categoria", - "additionalProperties": { - "type": "integer" - } - }, - "referencesByScore": { - "type": "object", - "description": "Distribuição de scores", - "properties": { - "high": { - "type": "integer", - "description": "Score >= 7.0" - }, - "medium": { - "type": "integer", - "description": "Score 4.0-6.9" - }, - "low": { - "type": "integer", - "description": "Score < 4.0" - } - } - } - } - }, - "synthesis": { - "type": "object", - "description": "Sínteses progressivas realizadas", - "properties": { - "miniSyntheses": { - "type": "array", - "description": "Mini-sínteses incrementais", - "items": { - "type": "object", - "properties": { - "synthesisId": { - "type": "string", - "pattern": "^SYNTH-\\d{3}$" - }, - "referencesIncluded": { - "type": "array", - "description": "IDs das referências incluídas", - "items": { - "type": "string" - } - }, - "keyPatterns": { - "type": "array", - "description": "Padrões identificados", - "items": { - "type": "string" - } - }, - "gaps": { - "type": "array", - "description": "Gaps identificados", - "items": { - "type": "string" - } - }, - "contradictions": { - "type": "array", - "description": "Contradições encontradas", - "items": { - "type": "string" - } - }, - "reportPath": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - } - }, - "finalSynthesis": { - "type": "object", - "description": "Síntese final", - "properties": { - "reportPath": { - "type": "string", - "description": "Path do relatório final" - }, - "chapterPaths": { - "type": "array", - "description": "Paths dos capítulos individuais", - "items": { - "type": "string" - } - }, - "completedAt": { - "type": "string", - "format": "date-time" - } - } - } - } - }, - "validation": { - "type": "object", - "description": "Resultado da validação cruzada", - "properties": { - "consensus": { - "type": "array", - "description": "Pontos de consenso entre fontes", - "items": { - "type": "object", - "properties": { - "finding": { - "type": "string" - }, - "supportingReferences": { - "type": "array", - "items": { - "type": "string" - } - }, - "confidenceLevel": { - "type": "string", - "enum": [ - "very_high", - "high", - "medium", - "low" - ] - } - } - } - }, - "divergences": { - "type": "array", - "description": "Divergências entre fontes", - "items": { - "type": "object", - "properties": { - "topic": { - "type": "string" - }, - "perspectives": { - "type": "array", - "items": { - "type": "object", - "properties": { - "view": { - "type": "string" - }, - "references": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - } - } - } - }, - "biases": { - "type": "array", - "description": "Vieses identificados", - "items": { - "type": "object", - "properties": { - "biasType": { - "type": "string" - }, - "description": { - "type": "string" - }, - "affectedReferences": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }, - "reportPath": { - "type": "string" - }, - "completedAt": { - "type": "string", - "format": "date-time" - } - } - }, - "paths": { - "type": "object", - "description": "Paths de todos os artefatos gerados", - "properties": { - "baseDir": { - "type": "string", - "description": "Diretório base (vibes/memory/researches/[researchId])" - }, - "metadataFile": { - "type": "string", - "description": "Este arquivo de metadados" - }, - "referencesDir": { - "type": "string", - "description": "Diretório de análises de referências" - }, - "synthesisDir": { - "type": "string", - "description": "Diretório de sínteses" - }, - "finalReportDir": { - "type": "string", - "description": "Diretório do relatório final" - } - } - }, - "configuration": { - "type": "object", - "description": "Configurações da pesquisa", - "properties": { - "maxReferencesInitial": { - "type": "integer", - "minimum": 1, - "maximum": 200, - "default": 100, - "description": "Máximo de referências na busca inicial" - }, - "topPercentageForAnalysis": { - "type": "number", - "minimum": 0.05, - "maximum": 1.0, - "default": 0.2, - "description": "Percentual top para análise profunda (0.2 = 20%)" - }, - "pauseAfterScoring": { - "type": "boolean", - "default": true, - "description": "Pausar após scoring para aprovação" - }, - "synthesisInterval": { - "type": "integer", - "minimum": 1, - "maximum": 50, - "default": 10, - "description": "Criar mini-síntese a cada N referências" - } - } - }, - "notes": { - "type": "array", - "description": "Notas e observações durante a pesquisa", - "items": { - "type": "object", - "properties": { - "timestamp": { - "type": "string", - "format": "date-time" - }, - "author": { - "type": "string", - "description": "human ou ai" - }, - "content": { - "type": "string" - } - } - } - } - } -} \ No newline at end of file diff --git a/shared/templates/template.research-reference-analysis.md b/shared/templates/template.research-reference-analysis.md deleted file mode 100644 index e28d2c3..0000000 --- a/shared/templates/template.research-reference-analysis.md +++ /dev/null @@ -1,214 +0,0 @@ -# Reference Analysis: [REFERENCE_TITLE] - -**Reference ID**: [REF_ID] -**Research**: [RESEARCH_ID] -**Analyzed**: [TIMESTAMP] -**Analyst**: [HUMAN_OR_AI] - ---- - -## Reference Metadata - -**URL**: [URL] - -**Source Type**: [academic | blog | documentation | news | tutorial | case-study | opinion | research-paper | whitepaper | video | other] - -**Author(s)**: [AUTHOR_NAME(S)] - -**Publication Date**: [DATE_OR_UNKNOWN] - -**Discovery Method**: [web_search | snowballing | manual] - -**Score**: [TOTAL_SCORE]/10 -- Credibility: [SCORE]/10 -- Relevance: [SCORE]/10 -- Recency: [SCORE]/10 -- Depth: [SCORE]/10 -- Authority: [SCORE]/10 - -**Tags**: `[TAG1]`, `[TAG2]`, `[TAG3]` - ---- - -## Executive Summary - -[Parágrafo de 3-5 linhas resumindo o conteúdo principal desta referência e sua relevância para a pesquisa] - -**Key Contribution**: [1 frase sobre a contribuição única desta fonte] - ---- - -## Detailed Analysis - -### Main Content - -[Descrição detalhada do conteúdo da referência, organizado em seções lógicas] - -#### [Section 1 Name] - -[Conteúdo da seção 1] - -#### [Section 2 Name] - -[Conteúdo da seção 2] - -### Key Findings - -1. **[Finding 1 Title]** - - **Description**: [Descrição detalhada] - - **Evidence**: [Evidência ou citação] - - **Significance**: [Por que é importante] - - **Confidence Level**: [Very High | High | Medium | Low] - -2. **[Finding 2 Title]** - - **Description**: [Descrição detalhada] - - **Evidence**: [Evidência ou citação] - - **Significance**: [Por que é importante] - - **Confidence Level**: [Very High | High | Medium | Low] - -### Important Quotes - -> "[QUOTE_1]" -> -> **Context**: [Contexto da citação] -> **Page/Section**: [Localização] - -> "[QUOTE_2]" -> -> **Context**: [Contexto da citação] -> **Page/Section**: [Localização] - -### Data & Statistics - -[Se houver dados, estatísticas ou números importantes] - -| Metric | Value | Source/Context | -|--------|-------|----------------| -| [METRIC_1] | [VALUE] | [CONTEXT] | -| [METRIC_2] | [VALUE] | [CONTEXT] | - ---- - -## Critical Evaluation - -### Strengths - -- **[Strength 1]**: [Explicação] -- **[Strength 2]**: [Explicação] -- **[Strength 3]**: [Explicação] - -### Limitations - -- **[Limitation 1]**: [Explicação] -- **[Limitation 2]**: [Explicação] -- **[Limitation 3]**: [Explicação] - -### Potential Biases - -[Identificar possíveis vieses do autor, fonte ou metodologia] - -- **[Bias Type 1]**: [Descrição] -- **[Bias Type 2]**: [Descrição] - -### Credibility Assessment - -**Overall Credibility**: [Very High | High | Medium | Low | Very Low] - -**Reasoning**: [Explicação detalhada do nível de credibilidade atribuído, considerando: autoridade do autor, qualidade da fonte, presença de referências, metodologia, etc.] - ---- - -## Connections & Cross-References - -### Related References - -[Outras referências desta pesquisa que se conectam com esta] - -- **[REF-XXX]**: [Nome] - [Como se relaciona] -- **[REF-YYY]**: [Nome] - [Como se relaciona] - -### Citations & Links - -[Referências citadas nesta fonte que podem ser úteis para snowballing] - -1. [Citation 1] - [URL se disponível] -2. [Citation 2] - [URL se disponível] - -### Alignment with Research Objective - -**Relevance to Main Question**: [HIGH | MEDIUM | LOW] - -[Explicação de como esta referência responde (ou não) à pergunta principal da pesquisa] - -**Specific Contributions**: -- [Contribuição específica 1] -- [Contribuição específica 2] - ---- - -## Actionable Insights - -[Insights práticos ou ações derivadas desta referência] - -1. **[Insight 1]**: [Descrição] - - **Action**: [O que fazer com isso] - -2. **[Insight 2]**: [Descrição] - - **Action**: [O que fazer com isso] - ---- - -## Gaps & Questions - -### Questions Raised - -[Perguntas levantadas mas não respondidas por esta referência] - -1. [Question 1] -2. [Question 2] - -### Information Gaps - -[Gaps de informação que ainda precisam ser preenchidos] - -- [Gap 1] -- [Gap 2] - -### Further Investigation Needed - -[Áreas que precisam de pesquisa adicional] - -- [ ] [Investigation 1] -- [ ] [Investigation 2] - ---- - -## Notes - -[Notas adicionais, observações ou contexto que não se encaixam em outras seções] - ---- - -## Metadata for Processing - -**Content Type**: [text | video | audio | interactive] - -**Language**: [LANGUAGE_CODE] - -**Access**: [open | paywall | registration-required | archived] - -**Archive Link**: [ARCHIVE_URL_IF_AVAILABLE] - -**Downloaded/Cached**: [YES_OR_NO] -**Cache Path**: [PATH_IF_CACHED] - -**Processing Time**: [TIME_TAKEN] - -**Reviewed by Human**: [YES_OR_NO] - ---- - -**Analysis Version**: 1.0 -**Template**: template.research-reference-analysis.md -**Generated by**: research.analyze.md command - diff --git a/shared/templates/template.research-report.md b/shared/templates/template.research-report.md deleted file mode 100644 index 6425433..0000000 --- a/shared/templates/template.research-report.md +++ /dev/null @@ -1,444 +0,0 @@ -# [REPO_NAME] - Análise de Projeto GitHub - -**Repositório**: [GITHUB_URL] -**Owner**: [OWNER] -**Analisado em**: [TIMESTAMP] -**Profundidade**: [DEPTH] - ---- - -## Resumo Executivo - -[DESCRIPTION] - -**Linguagem Principal**: [PRIMARY_LANGUAGE] -**Licença**: [LICENSE] -**Stars**: [STARS] ⭐ | **Forks**: [FORKS] | **Issues Abertas**: [OPEN_ISSUES] - -**Última Release**: [LATEST_RELEASE_VERSION] ([RELEASE_DATE]) -**Última Atualização**: [LAST_UPDATE_DATE] - ---- - -## Stack Tecnológica - -**Linguagem(ns)**: [LANGUAGES] -**Framework(s)**: [FRAMEWORKS] -**Runtime**: [RUNTIME] - -### Dependências Principais - -[MAIN_DEPENDENCIES] - -### DevDependencies - -[DEV_DEPENDENCIES] - ---- - -## Estrutura do Projeto - -**Total de Arquivos**: [TOTAL_FILES] -**Total de Diretórios**: [TOTAL_DIRS] - -**Diretórios Principais**: - -``` -[DIRECTORY_TREE] -``` - -**Convenções Identificadas**: -- [CONVENTION_1] -- [CONVENTION_2] -- [CONVENTION_3] - -**Entry Points**: -- [ENTRY_POINT_1] -- [ENTRY_POINT_2] - ---- - -## Análise de Qualidade - -**Indicadores de Qualidade**: -- [✅/❌] Testes automatizados -- [✅/❌] CI/CD configurado -- [✅/❌] Linter/Formatter -- [✅/❌] TypeScript/Type checking -- [✅/❌] Documentação completa -- [✅/❌] Contributing guidelines -- [✅/❌] Security policy -- [✅/❌] Licença presente - -**Score de Qualidade**: [QUALITY_SCORE]/8 ⭐ - -### Detalhes de Qualidade - -**Testes**: -- Framework: [TEST_FRAMEWORK] -- Cobertura: [COVERAGE] (se disponível) -- Arquivos de teste: [TEST_FILES_COUNT] - -**CI/CD**: -- Plataforma: [CI_PLATFORM] -- Workflows: [WORKFLOWS_LIST] - -**Code Quality Tools**: -- Linter: [LINTER] -- Formatter: [FORMATTER] -- Type Checker: [TYPE_CHECKER] - ---- - -## Arquitetura - -**Padrão Detectado**: [ARCHITECTURE_PATTERN] - -**Descrição**: -[ARCHITECTURE_DESCRIPTION] - -**Organização de Código**: -- [CODE_ORG_1] -- [CODE_ORG_2] -- [CODE_ORG_3] - -**Padrões de Design Identificados**: -- [DESIGN_PATTERN_1] -- [DESIGN_PATTERN_2] - ---- - -## Dependências Detalhadas - -### Dependências de Produção - -| Package | Versão | Descrição | -|---------|--------|-----------| -| [PKG_1] | [VER_1] | [DESC_1] | -| [PKG_2] | [VER_2] | [DESC_2] | -| [PKG_3] | [VER_3] | [DESC_3] | - -### Dependências de Desenvolvimento - -| Package | Versão | Categoria | -|---------|--------|-----------| -| [DEV_PKG_1] | [VER_1] | [CATEGORY_1] | -| [DEV_PKG_2] | [VER_2] | [CATEGORY_2] | - -**Total de Dependências**: [TOTAL_DEPS] (prod: [PROD_DEPS], dev: [DEV_DEPS]) - ---- - -## Comunidade e Atividade - -**Contributors**: [TOTAL_CONTRIBUTORS] total - -**Top Contributors**: -1. [CONTRIBUTOR_1] - [COMMITS_1] commits -2. [CONTRIBUTOR_2] - [COMMITS_2] commits -3. [CONTRIBUTOR_3] - [COMMITS_3] commits -4. [CONTRIBUTOR_4] - [COMMITS_4] commits -5. [CONTRIBUTOR_5] - [COMMITS_5] commits - -**Atividade Recente**: -- Última atualização: [LAST_COMMIT_DATE] -- Commits (último mês): [COMMITS_LAST_MONTH] -- Issues abertas: [OPEN_ISSUES] -- PRs abertas: [OPEN_PRS] - -**Saúde do Projeto**: -- Tempo médio de resposta a issues: [AVG_ISSUE_RESPONSE] (se disponível) -- Taxa de resolução: [RESOLUTION_RATE] (se disponível) -- Atividade: [ACTIVITY_LEVEL] (Alta/Média/Baixa) - ---- - -## Instalação e Uso - -### Pré-requisitos - -[PREREQUISITES] - -### Instalação - -```bash -[INSTALLATION_COMMANDS] -``` - -### Comandos Principais - -**Build**: -```bash -[BUILD_COMMAND] -``` - -**Test**: -```bash -[TEST_COMMAND] -``` - -**Start/Run**: -```bash -[START_COMMAND] -``` - -**Outros Comandos**: -```bash -[OTHER_COMMANDS] -``` - -### Configuração - -[CONFIGURATION_NOTES] - ---- - -## Documentação Disponível - -**README.md**: [✅/❌] [QUALITY: Excelente/Bom/Básico] -**CONTRIBUTING.md**: [✅/❌] -**LICENSE**: [✅/❌] ([LICENSE_TYPE]) -**CHANGELOG.md**: [✅/❌] -**CODE_OF_CONDUCT.md**: [✅/❌] -**SECURITY.md**: [✅/❌] - -**Documentação Adicional**: -- [DOC_1] -- [DOC_2] -- [DOC_3] - -**Wiki**: [✅/❌] -**GitHub Pages**: [✅/❌] - ---- - -## Issues e PRs Recentes - -### Issues em Destaque - -1. **[ISSUE_1_TITLE]** ([ISSUE_1_NUMBER]) - - Status: [STATUS] - - Labels: [LABELS] - - Comentários: [COMMENTS] - -2. **[ISSUE_2_TITLE]** ([ISSUE_2_NUMBER]) - - Status: [STATUS] - - Labels: [LABELS] - - Comentários: [COMMENTS] - -### Tópicos Recorrentes - -- [RECURRING_TOPIC_1] -- [RECURRING_TOPIC_2] -- [RECURRING_TOPIC_3] - ---- - -## Releases - -**Última Release**: [LATEST_VERSION] ([DATE]) - -**Changelog**: -``` -[RELEASE_NOTES] -``` - -**Cadência de Releases**: -- Frequência: [FREQUENCY] (ex: mensal, semestral) -- Última releases: [RECENT_RELEASES] - -**Versionamento**: [VERSIONING_SCHEME] (ex: Semantic Versioning) - ---- - -## Tecnologias e Ferramentas - -### Build & Bundling -- [BUILD_TOOL_1] -- [BUILD_TOOL_2] - -### Testing -- [TEST_TOOL_1] -- [TEST_TOOL_2] - -### CI/CD -- [CI_TOOL_1] -- [CI_TOOL_2] - -### Code Quality -- [QUALITY_TOOL_1] -- [QUALITY_TOOL_2] - -### Deployment -- [DEPLOY_TOOL_1] -- [DEPLOY_TOOL_2] - ---- - -## Casos de Uso e Exemplos - -**Casos de Uso Principais**: -- [USE_CASE_1] -- [USE_CASE_2] -- [USE_CASE_3] - -**Exemplos Disponíveis**: -- [EXAMPLE_1] - [DESCRIPTION] -- [EXAMPLE_2] - [DESCRIPTION] - -**Demos/Showcases**: -- [DEMO_1] -- [DEMO_2] - ---- - -## Recursos e Links - -**Repositório**: [GITHUB_URL] -**Homepage**: [HOMEPAGE_URL] -**Documentação**: [DOCS_URL] -**Issues**: [ISSUES_URL] -**Pull Requests**: [PRS_URL] -**Releases**: [RELEASES_URL] -**Discussions**: [DISCUSSIONS_URL] -**NPM/Package**: [PACKAGE_URL] - -**Topics/Tags**: [TOPIC_1], [TOPIC_2], [TOPIC_3], [TOPIC_4] - -**Social**: -- Twitter: [TWITTER_URL] -- Discord/Slack: [COMMUNITY_URL] -- Blog: [BLOG_URL] - ---- - -## Análise SWOT - -### Strengths (Forças) -- [STRENGTH_1] -- [STRENGTH_2] -- [STRENGTH_3] - -### Weaknesses (Fraquezas) -- [WEAKNESS_1] -- [WEAKNESS_2] - -### Opportunities (Oportunidades) -- [OPPORTUNITY_1] -- [OPPORTUNITY_2] - -### Threats (Ameaças) -- [THREAT_1] -- [THREAT_2] - ---- - -## Comparação com Alternativas - -**Projetos Similares**: - -| Projeto | Stars | Licença | Última Release | Observações | -|---------|-------|---------|----------------|-------------| -| [ALT_1] | [STARS_1] | [LIC_1] | [DATE_1] | [NOTES_1] | -| [ALT_2] | [STARS_2] | [LIC_2] | [DATE_2] | [NOTES_2] | - -**Diferenciais**: -- [DIFF_1] -- [DIFF_2] - ---- - -## Recomendações - -**Para Adoção**: -- [RECOMMENDATION_1] -- [RECOMMENDATION_2] -- [RECOMMENDATION_3] - -**Considerações de Segurança**: -- [SECURITY_NOTE_1] -- [SECURITY_NOTE_2] - -**Pontos de Atenção**: -- [ATTENTION_POINT_1] -- [ATTENTION_POINT_2] - ---- - -## Notas da Análise - -**Metodologia**: -- Acesso via raw.githubusercontent.com para arquivos de texto -- GitHub API para metadados e estrutura -- Análise automatizada de configurações -- Score de qualidade baseado em 8 indicadores - -**Limitações**: -- Análise baseada em arquivos públicos -- Não inclui análise profunda de código -- Estatísticas podem estar desatualizadas -- [OTHER_LIMITATION] - -**Data da Análise**: [ANALYSIS_TIMESTAMP] -**Gerado por**: research.github command - ---- - -## Metadados - -```json -{ - "repository": { - "owner": "[OWNER]", - "name": "[REPO_NAME]", - "url": "[GITHUB_URL]", - "analyzedAt": "[ISO_TIMESTAMP]" - }, - "metadata": { - "stars": [STARS], - "forks": [FORKS], - "watchers": [WATCHERS], - "openIssues": [OPEN_ISSUES], - "language": "[PRIMARY_LANGUAGE]", - "license": "[LICENSE]", - "topics": ["[TOPIC_1]", "[TOPIC_2]"], - "createdAt": "[CREATED_DATE]", - "updatedAt": "[UPDATED_DATE]" - }, - "techStack": { - "languages": ["[LANG_1]", "[LANG_2]"], - "frameworks": ["[FW_1]", "[FW_2]"], - "runtime": "[RUNTIME]", - "dependencies": { - "production": [PROD_COUNT], - "development": [DEV_COUNT], - "total": [TOTAL_COUNT] - } - }, - "quality": { - "score": [QUALITY_SCORE], - "hasTests": [true/false], - "hasCI": [true/false], - "hasLinter": [true/false], - "hasTypeChecking": [true/false], - "hasDocumentation": [true/false], - "hasContributing": [true/false], - "hasSecurity": [true/false], - "hasLicense": [true/false] - }, - "structure": { - "totalFiles": [TOTAL_FILES], - "totalDirectories": [TOTAL_DIRS], - "entryPoints": ["[ENTRY_1]", "[ENTRY_2]"] - }, - "community": { - "contributors": [TOTAL_CONTRIBUTORS], - "commitsLastMonth": [COMMITS_LAST_MONTH], - "activityLevel": "[HIGH/MEDIUM/LOW]" - } -} -``` - ---- - -**Fim do Relatório** diff --git a/shared/templates/template.research-synthesis.md b/shared/templates/template.research-synthesis.md deleted file mode 100644 index c6623a8..0000000 --- a/shared/templates/template.research-synthesis.md +++ /dev/null @@ -1,268 +0,0 @@ -# Research Synthesis: [SYNTHESIS_TITLE] - -**Synthesis ID**: [SYNTH-XXX or FINAL] -**Research**: [RESEARCH_ID] -**Type**: [Mini-Synthesis | Final Synthesis] -**Created**: [TIMESTAMP] - ---- - -## Scope - -**References Included**: [N] references ([REF-XXX] to [REF-YYY]) - -**Coverage**: [Percentage or description of research covered so far] - ---- - -## Key Patterns Identified - -### Pattern 1: [Pattern Name] - -**Description**: [Descrição detalhada do padrão identificado] - -**Supporting Evidence**: -- **[REF-XXX]**: [Como esta referência suporta o padrão] -- **[REF-YYY]**: [Como esta referência suporta o padrão] -- **[REF-ZZZ]**: [Como esta referência suporta o padrão] - -**Significance**: [Por que este padrão é importante] - -**Confidence Level**: [Very High | High | Medium | Low] - -### Pattern 2: [Pattern Name] - -**Description**: [Descrição detalhada do padrão identificado] - -**Supporting Evidence**: -- **[REF-XXX]**: [Como esta referência suporta o padrão] -- **[REF-YYY]**: [Como esta referência suporta o padrão] - -**Significance**: [Por que este padrão é importante] - -**Confidence Level**: [Very High | High | Medium | Low] - ---- - -## Emerging Themes - -### Theme 1: [Theme Name] - -[Descrição do tema emergente] - -**Related References**: [REF-XXX], [REF-YYY], [REF-ZZZ] - -**Maturity**: [Well-established | Emerging | Speculative] - -### Theme 2: [Theme Name] - -[Descrição do tema emergente] - -**Related References**: [REF-XXX], [REF-YYY] - -**Maturity**: [Well-established | Emerging | Speculative] - ---- - -## Consensus Points - -[Pontos em que múltiplas fontes concordam] - -1. **[Consensus 1]** - - **Agreement among**: [REF-XXX], [REF-YYY], [REF-ZZZ] ([N] sources) - - **Strength**: [Strong | Moderate | Weak] - - **Implication**: [O que isso significa] - -2. **[Consensus 2]** - - **Agreement among**: [REF-XXX], [REF-YYY] ([N] sources) - - **Strength**: [Strong | Moderate | Weak] - - **Implication**: [O que isso significa] - ---- - -## Divergences & Contradictions - -[Pontos em que fontes discordam ou contradizem umas às outras] - -### Divergence 1: [Topic] - -**Perspective A**: [Descrição da perspectiva] -- **Supported by**: [REF-XXX], [REF-YYY] -- **Key Argument**: [Argumento principal] - -**Perspective B**: [Descrição da perspectiva] -- **Supported by**: [REF-ZZZ], [REF-WWW] -- **Key Argument**: [Argumento principal] - -**Analysis**: [Análise da divergência - possíveis razões, contextos diferentes, etc.] - -**Resolution Status**: [Resolved | Unresolved | Requires more data] - -### Divergence 2: [Topic] - -[Same structure as above] - ---- - -## Information Gaps - -[Áreas onde falta informação ou cobertura] - -1. **[Gap 1 Title]** - - **Description**: [Descrição do gap] - - **Why it matters**: [Por que é importante preencher este gap] - - **Potential sources**: [Onde buscar mais informação] - - **Priority**: [High | Medium | Low] - -2. **[Gap 2 Title]** - - **Description**: [Descrição do gap] - - **Why it matters**: [Por que é importante preencher este gap] - - **Potential sources**: [Onde buscar mais informação] - - **Priority**: [High | Medium | Low] - ---- - -## Quality of Evidence - -### High-Quality Sources ([N] references) - -[Referências com alta credibilidade e profundidade] - -- **[REF-XXX]**: [Title] - [Why high quality] -- **[REF-YYY]**: [Title] - [Why high quality] - -### Medium-Quality Sources ([N] references) - -[Referências com qualidade moderada] - -- **[REF-ZZZ]**: [Title] - [Limitations] - -### Low-Quality Sources ([N] references) - -[Referências com limitações significativas - incluir para transparência] - -- **[REF-WWW]**: [Title] - [Issues] - ---- - -## Synthesis Progress - -**Answered Questions**: [List of research questions answered so far] -1. [Question 1] - [Status: Fully answered | Partially answered | Unanswered] -2. [Question 2] - [Status] - -**Unanswered Questions**: [List of questions still pending] -1. [Question 1] -2. [Question 2] - -**Confidence in Findings**: -- **Very High Confidence**: [N] findings -- **High Confidence**: [N] findings -- **Medium Confidence**: [N] findings -- **Low Confidence**: [N] findings - ---- - -## Recommendations for Next Steps - -### Search Adjustments - -[Ajustes recomendados para busca secundária] - -1. **[Recommendation 1]** - - **Rationale**: [Por quê] - - **Suggested query**: [Query sugerida] - - **Expected outcome**: [O que espera encontrar] - -2. **[Recommendation 2]** - - **Rationale**: [Por quê] - - **Suggested query**: [Query sugerida] - - **Expected outcome**: [O que espera encontrar] - -### Prioritization Changes - -[Mudanças na priorização de referências para análise] - -- **Increase priority for**: [Type of references or topics] -- **Decrease priority for**: [Type of references or topics] -- **Skip**: [Tipos de referências que podem ser puladas] - -### Snowballing Targets - -[Referências citadas que devem ser buscadas] - -1. **[Citation 1]** (cited by [REF-XXX]) -2. **[Citation 2]** (cited by [REF-YYY], [REF-ZZZ]) - ---- - -## Preliminary Insights - -[Insights preliminares que emergem desta síntese - pode ser revisado na síntese final] - -### Insight 1: [Title] - -**Finding**: [Descrição do insight] - -**Evidence**: [Evidências que suportam] - -**Confidence**: [High | Medium | Low] - -**Implications**: [Implicações práticas ou teóricas] - -### Insight 2: [Title] - -[Same structure] - ---- - -## Visual Summary - -[Se aplicável, descrição de padrões visuais ou estrutura conceitual emergente] - -### Concept Map - -[Descrição de como os conceitos se relacionam] - -``` -[CONCEPT_A] ──influences──> [CONCEPT_B] - │ │ - │ │ - supports contradicts - │ │ - ↓ ↓ - [CONCEPT_C] ←───related─── [CONCEPT_D] -``` - -### Categories Hierarchy - -``` -Main Category -├── Subcategory 1 -│ ├── Topic A ([N] refs) -│ └── Topic B ([N] refs) -├── Subcategory 2 -│ ├── Topic C ([N] refs) -│ └── Topic D ([N] refs) -└── Subcategory 3 - └── Topic E ([N] refs) -``` - ---- - -## Notes & Observations - -[Notas adicionais, observações metodológicas ou contexto] - ---- - -## Metadata - -**References Analyzed**: [N] / [TOTAL] -**Progress**: [X]% -**Time Invested**: [HOURS/MINUTES] -**Next Synthesis at**: [After REF-XXX or MILESTONE] - -**Template**: template.research-synthesis.md -**Generated by**: research.synthesize.md command - diff --git a/shared/templates/template.task.md b/shared/templates/template.task.md deleted file mode 100644 index d840156..0000000 --- a/shared/templates/template.task.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -task_id: "{{TASK_ID}}" -feature_id: "{{FEATURE_ID}}" -feature_name: "{{FEATURE_NAME}}" -title: "{{TITLE}}" -priority: "{{PRIORITY}}" -category: "{{CATEGORY}}" -phase: {{PHASE}} -estimated_time: "{{ESTIMATED_TIME}}" -status: "pending" -created_at: "{{CREATED_AT}}" -updated_at: "{{UPDATED_AT}}" -source_plan: "{{SOURCE_PLAN}}" -source_type: "{{SOURCE_TYPE}}" -plan_objective: "{{PLAN_OBJECTIVE}}" ---- - -# {{TITLE}} - -**Task ID**: {{TASK_ID}} -**Feature**: {{FEATURE_NAME}} -**Priority**: {{PRIORITY}} -**Category**: {{CATEGORY}} -**Phase**: {{PHASE}} -**Estimated Time**: {{ESTIMATED_TIME}} - ---- - -## Context - -{{CONTEXT_DESCRIPTION}} - ---- - -## Description - -{{FULL_DESCRIPTION}} - ---- - -## Affected Files - -{{FILE_LIST}} - ---- - -## Dependencies - -**Depends On**: -{{DEPENDS_ON_LIST}} - -**Blocks**: -{{BLOCKS_LIST}} - ---- - -## Implementation Steps - -{{IMPLEMENTATION_STEPS}} - ---- - -## Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - ---- - -## Validation - -{{VALIDATION}} - ---- - -## Notes - -{{NOTES}} - ---- - -**Last Updated**: {{UPDATED_AT}} diff --git a/shared/templates/trello-card.template.md b/shared/templates/trello-card.template.md deleted file mode 100644 index acea047..0000000 --- a/shared/templates/trello-card.template.md +++ /dev/null @@ -1,45 +0,0 @@ -# {{TASK_ID}}: {{TITLE}} - -## 📋 Metadata - -- **Feature**: {{FEATURE_NAME}} ({{FEATURE_ID}}) -- **Priority**: {{PRIORITY}} -- **Category**: {{CATEGORY}} -- **Phase**: {{PHASE}} -- **Estimated Time**: {{ESTIMATED_TIME}} -- **Status**: {{STATUS}} - -## 📝 Description - -{{DESCRIPTION}} - -## 📂 Affected Files - -{{AFFECTED_FILES}} - -## 🔗 Dependencies - -**Depends On**: {{DEPENDS_ON}} -**Blocks**: {{BLOCKS}} - -## ✅ Implementation Checklist - -{{IMPLEMENTATION_CHECKLIST}} - -## 🎯 Validation - -{{VALIDATION}} - -## 📎 Links - -- Task File: `{{TASK_FILE_PATH}}` -- Feature Index: `vibes/tasks/{{FEATURE_ID}}/_INDEX.md` -- Source Plan: `{{SOURCE_PLAN}}` - ---- - -*Synced from filesystem* -*Last Sync: {{TIMESTAMP}}* - - - diff --git a/shared/templates/usability-test-plan.template.md b/shared/templates/usability-test-plan.template.md deleted file mode 100644 index 40235da..0000000 --- a/shared/templates/usability-test-plan.template.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -type: usability-test-plan -test_name: {{TEST_NAME}} -feature: {{FEATURE}} -test_type: {{TEST_TYPE}} -created_at: {{CREATED_AT}} ---- - -# Usability Test Plan: {{TEST_NAME}} - -**Feature**: {{FEATURE}} -**Type**: {{TEST_TYPE}} -**Participants**: {{PARTICIPANTS_COUNT}} -**Duration**: {{DURATION}} min per session -**Date**: {{CREATED_AT}} - -## 🎯 Test Objectives - -{{OBJECTIVES_LIST}} - -## 👥 Participants - -**Target**: {{TARGET_CRITERIA}} -**Sample Size**: {{PARTICIPANTS_COUNT}} -**Recruitment**: {{RECRUITMENT_METHOD}} - -## ✅ Test Tasks - -{{TASKS_LIST}} - -## 📊 Metrics - -- Task Completion Rate -- Time on Task -- Error Rate -- SUS Score (System Usability Scale) -- Satisfaction Rating (1-5) - -## 📝 Test Script - -{{TEST_SCRIPT}} - -## 📊 Results - -Use: `.cursor/ux/usability-tests/{{SLUG}}-results.md` - diff --git a/shared/templates/usability-test-results.template.md b/shared/templates/usability-test-results.template.md deleted file mode 100644 index 04728a0..0000000 --- a/shared/templates/usability-test-results.template.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -type: usability-test-results -test_plan: {{TEST_PLAN_PATH}} -test_date: {{TEST_DATE}} -participants: {{PARTICIPANTS_COUNT}} ---- - -# Usability Test Results: {{TEST_NAME}} - -**Test Plan**: [{{TEST_NAME}}]({{TEST_PLAN_PATH}}) -**Date**: {{TEST_DATE}} -**Participants**: {{PARTICIPANTS_COUNT}} - -## 📊 Metrics Summary - -| Metric | Result | -|--------|--------| -| **Task Completion Rate** | {{COMPLETION_RATE}}% | -| **Avg Time on Task** | {{AVG_TIME}} | -| **Error Rate** | {{ERROR_RATE}} | -| **SUS Score** | {{SUS_SCORE}}/100 | -| **Satisfaction** | {{SATISFACTION}}/5 | - -## ✅ Task Results - -{{TASK_RESULTS}} - -## 💡 Key Findings - -{{KEY_FINDINGS}} - -## 🎯 Recommendations - -{{RECOMMENDATIONS}} - diff --git a/shared/templates/youtube-search-report-template.md b/shared/templates/youtube-search-report-template.md deleted file mode 100644 index aa3d82e..0000000 --- a/shared/templates/youtube-search-report-template.md +++ /dev/null @@ -1,50 +0,0 @@ -# YouTube Search Report - -**Criado**: $TIMESTAMP -**Query**: $QUERY -**Total de Resultados**: $TOTAL_RESULTS -**Transcrições Processadas**: $TRANSCRIPT_COUNT - ---- - -## Top 5 Vídeos - -$TOP_VIDEOS_CONTENT - ---- - -## Análise de Conteúdo (Transcrições) - -$TRANSCRIPT_INSIGHTS_CONTENT - ---- - -## Análise Geral - -### Estatísticas - -- **Total de vídeos encontrados**: $TOTAL_RESULTS -- **Período de publicação**: $PUBLISH_DATE_RANGE -- **Canais mais relevantes**: $TOP_CHANNELS - -### Insights - -$INSIGHTS_CONTENT - -### Recomendações - -$RECOMMENDATIONS_CONTENT - ---- - -## Metadados da Busca - -**Parâmetros utilizados**: -- Ordenação: $ORDER -- Duração do vídeo: $VIDEO_DURATION -- Publicado após: $PUBLISHED_AFTER -- Máximo de resultados: $MAX_RESULTS -- Vídeos transcritos: $TRANSCRIBE_COUNT - -**Timestamp**: $TIMESTAMP -