Sync setup-foundation specs to main and archive change.

Promote five capability specs from the completed setup-foundation change into openspec/specs and move the change to archive.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-28 22:56:21 -03:00
parent 236a7d3ea9
commit 58ad990488
14 changed files with 235 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-07-28

View File

@@ -0,0 +1,124 @@
## Context
Repositório greenfield: contém [SPEC.md](../../../SPEC.md) (especificação normativa aprovada), scaffold OpenSpec e um commit inicial. Não existe aplicação Laravel, banco, CI ou contêiner.
Versões-alvo confirmadas no Packagist (jul/2026): Laravel 13.23, Filament 5.7, Livewire 4.3, Pest 4.7, Larastan 3.10, Pint 1.29. Ambiente local: PHP 8.5.8, Composer 2.9.5, Node 22, Docker 29 + Compose v5.3.
ADRs ADR-001..ADR-010 do SPEC §21 são aceitas e serão registradas em `docs/adr/` sem reabertura de decisões.
## Goals / Non-Goals
**Goals:**
- Entregar esqueleto Laravel funcional com Filament autenticado, Livewire/Tailwind configurados e Postgres local.
- Estabelecer gates de qualidade (Pint, Larastan, Pest, arch tests) e scripts Composer padronizados.
- Produzir imagem Docker FrankenPHP reproduzível com healthcheck e processos web/queue/scheduler.
- CI verde nos 5 jobs bloqueantes antes de avançar para Fase 1.
- Design tokens mínimos e layout público placeholder para validar pipeline visual futuro.
**Non-Goals:**
- Implementar requisitos funcionais das Fases 15 (site, CRM, eventos, financeiro, documentos).
- Deploy em staging ou produção (adiado).
- FrankenPHP worker mode, Redis, S3 em produção, integração de e-mail transacional.
- Qualquer item listado em SPEC §4.2 "Fora do MVP".
## Decisions
### 1. Bootstrap via `composer create-project` em diretório temporário
**Decisão:** Instalar Laravel 13 com `composer create-project laravel/laravel` em diretório temporário e mover arquivos para a raiz, preservando `SPEC.md`, `openspec/` e `.codex/`.
**Alternativas:** Instalar na raiz (conflita com arquivos existentes); copiar skeleton manualmente (mais erro-prone).
**Rationale:** Padrão Laravel garante estrutura correta; evita sobrescrever artefatos de spec.
### 2. PostgreSQL 17 via Docker Compose local
**Decisão:** Serviço `postgres:17` no Compose com volume nomeado, healthcheck e credenciais em `.env.example`.
**Alternativas:** SQLite local (proibido pelo SPEC §14.2 para integração); Postgres instalado no host (sem `psql` no ambiente).
**Rationale:** Alinha dev local com CI; evita diferenças SQLite/Postgres.
### 3. Sessão, cache e fila em `database`
**Decisão:** `SESSION_DRIVER=database`, `CACHE_STORE=database`, `QUEUE_CONNECTION=database`.
**Alternativas:** Redis (fora do MVP, ADR-008); file/cookie session (menos alinhado com deploy containerizado).
**Rationale:** ADR-008; sem dependência extra; migrations padrão Laravel cobrem tabelas.
### 4. Papéis via enum `UserRole` na coluna `users.role`
**Decisão:** Enum PHP `UserRole: admin|assistant` + coluna `is_active` boolean. Filament `canAccessPanel()` nega inativos.
**Alternativas:** Spatie Permission (proibido pelo SPEC §3.4); flags booleanas separadas.
**Rationale:** YAGNI; atende ADM-01 e §12.2 sem complexidade.
### 5. Design tokens como CSS custom properties + Tailwind theme extension
**Decisão:** Arquivo `resources/css/tokens.css` com custom properties; `tailwind.config.js` referencia tokens via `theme.extend`.
**Alternativas:** SCSS variables espalhadas; JSON tokens com build step extra.
**Rationale:** Centraliza SPEC §6.3; Tailwind consome nativamente; sem dependência extra.
### 6. Isolamento visual: layout público separado do painel Filament
**Decisão:** Layout Blade público em `resources/views/layouts/public.blade.php` com tokens próprios; Filament usa tema padrão do painel.
**Alternativas:** Tema Filament customizado para site (mistura concerns); component library compartilhada prematura.
**Rationale:** Mitiga conflito Tailwind 4 / Filament 5 / tema público premium.
### 7. FrankenPHP regular mode, multi-stage Dockerfile
**Decisão:** Dockerfile com stages `composer`, `frontend`, `runtime` (FrankenPHP). PHP fixado conforme suporte Laravel 13 no momento da instalação (8.4 ou 8.5). `config:cache` apenas no entrypoint/deploy, nunca em stage sem env final.
**Alternativas:** Nginx + PHP-FPM (SPEC exige FrankenPHP); worker mode (ADR-006 proíbe no MVP).
**Rationale:** ADR-006; imagem única para web/queue/scheduler (§15.2).
### 8. CI em GitHub Actions com PostgreSQL service container
**Decisão:** Workflow `.github/workflows/ci.yml` com jobs `static`, `unit`, `feature`, `browser`, `container`. Feature tests usam Postgres service; browser job builda imagem e roda Pest Browser com locale `pt-BR`, TZ `America/Fortaleza`, animações desabilitadas.
**Alternativas:** GitLab CI; CircleCI (remote já é GitHub).
**Rationale:** Remote `manoel-freitas/amore-site`; SPEC §14.1.
### 9. Estrutura de diretórios modular preparada, não populada
**Decisão:** Criar apenas diretórios quando primeiro arquivo for adicionado (SPEC §9.4). Na Fase 0, garantir `tests/Architecture/` e namespace base; não criar `app/Application/`, `app/Domain/` vazios.
**Rationale:** YAGNI; arch tests validam boundary quando Domain existir na Fase 2+.
## Risks / Trade-offs
| Risco | Mitigação |
|---|---|
| Conflito Tailwind 4 + Filament 5 + tema público | Layouts separados; Vite entries distintos se necessário |
| Snapshots visuais instáveis no CI | Imagem Linux fixa, fontes instaladas, relógio congelado, seed determinístico (preparação na Fase 1) |
| `config:cache` congela env incorreto | Cache apenas no entrypoint com env final do deploy |
| PHP 8.5 muito novo para alguma extensão | Fixar versão PHP no Dockerfile conforme matriz Laravel 13; testar build no job `container` |
| Filament panel + Livewire 4 coexistência | Seguir docs oficiais de instalação Filament 5; testes feature de login |
## Migration Plan
1. Bootstrap Laravel em diretório temp → mover para raiz.
2. Configurar `.env` / `.env.example` com Postgres e locale.
3. Instalar Filament, Pest, Larastan, Pint; configurar scripts Composer.
4. Adicionar Compose, Dockerfile, CI workflow.
5. Seed admin local; documentar credenciais apenas para dev.
6. Validar `composer quality` e jobs CI no PR.
**Rollback:** Reverter commit da Fase 0; repo volta ao estado spec-only.
## Open Questions
- **Staging target:** VPS próprio, Fly.io, Render ou Railway — decisão adiada; change futura para deploy.
- **Registry de imagem:** GitHub Container Registry vs Docker Hub — definir na change de deploy.
- **Provedor S3-compatible:** necessário na Fase 1+ para mídia pública; local usa `storage/app/public` ou MinIO opcional no Compose.
- **Provedor de e-mail:** necessário na Fase 2 (notificação de leads); Fase 0 usa `log` driver ou Mailpit no Compose opcional.

View File

@@ -0,0 +1,47 @@
## Why
O repositório contém apenas a especificação normativa ([SPEC.md](../../SPEC.md)) e o scaffold OpenSpec, sem aplicação Laravel executável. Nenhuma fase funcional (site, CRM, eventos, financeiro) pode ser implementada com segurança sem esqueleto de projeto, gates de qualidade e imagem de contêiner reproduzível. A Fase 0 — Fundação (SPEC §18) é o pré-requisito obrigatório para validar o produto.
## What Changes
- Bootstrap de aplicação **Laravel 13** com **Filament 5** (`/admin`), **Livewire 4**, **Tailwind/Vite** e locale `pt-BR` / timezone `America/Fortaleza`.
- **PostgreSQL** local via Docker Compose; sessão, cache e fila em `database` (ADR-008).
- Papéis internos `admin` e `assistant` via enum `UserRole` (SPEC §3.4, ADM-01); usuário inativo bloqueado no painel.
- Ferramentas de qualidade: **Pint**, **Larastan**, **Pest 4**, **Pest Browser**, testes de arquitetura (SPEC §13.6).
- Scripts Composer padronizados: `test:unit`, `test:feature`, `test:browser`, `test`, `quality` (SPEC §13.9).
- **Dockerfile** multi-stage com **FrankenPHP** em modo regular (ADR-006); processos web, queue e scheduler na mesma imagem.
- Rota pública **`GET /up`** para healthcheck (SPEC §5.1, §15.5).
- **Design tokens** mínimos centralizados para o site público (SPEC §6.3).
- **Seed de admin** local documentado (SPEC §17.2 parcial — apenas usuário admin).
- **Pipeline CI** com jobs bloqueantes: `static`, `unit`, `feature`, `browser`, `container` (SPEC §14.1).
- Índice de **ADRs aceitas** (ADR-001..ADR-010) em `docs/adr/`.
## Non-Goals
Conforme [SPEC.md §4.2](../../SPEC.md), **não** fazem parte desta change:
- Site público, CMS, briefing, CRM, eventos, fornecedores, financeiro, documentos, dashboard operacional.
- Deploy em staging ou produção (adiado; critério de saída limitado a CI verde + build de imagem + healthcheck validado no contêiner).
- Microserviços, Redis, API pública, multi-tenancy, pagamentos online, portal do cliente.
- FrankenPHP worker mode (ADR-006).
## Capabilities
### New Capabilities
- `internal-authentication`: login no painel Filament, papéis `admin`/`assistant`, bloqueio de usuário inativo, reset de senha (SPEC §3.4, ADM-01, §12.112.2).
- `health-check`: endpoint `GET /up` sem autenticação para verificação de disponibilidade (SPEC §5.1, §15.5).
- `design-tokens`: tokens visuais centralizados para o site público (SPEC §6.3, §6.5).
- `quality-gates`: comandos Composer, testes de arquitetura e pipeline CI bloqueante (SPEC §13.6, §13.9, §14.114.2).
- `container-runtime`: imagem Docker multi-stage FrankenPHP com processos web/queue/scheduler (SPEC §15.115.4).
### Modified Capabilities
- _(nenhuma — repositório sem specs existentes em `openspec/specs/`)_
## Impact
- **Cria**: árvore Laravel completa (`app/`, `config/`, `database/`, `resources/`, `routes/`, `tests/`), `docker/`, `Dockerfile`, `docker-compose.yml`, `.github/workflows/`, `docs/adr/`.
- **Dependências novas**: Laravel 13, Filament 5, Livewire 4, Pest 4, Larastan, Pint, FrankenPHP.
- **Infraestrutura**: PostgreSQL em Compose local; CI em GitHub Actions contra o remote `manoel-freitas/amore-site`.
- **Sem impacto** em capabilities existentes (greenfield).

View File

@@ -0,0 +1,55 @@
## ADDED Requirements
### Requirement: Production image uses multi-stage FrankenPHP build
The system SHALL provide a multi-stage Dockerfile that builds Composer dependencies, frontend assets, and a FrankenPHP runtime image serving `public/`.
#### Scenario: Image builds reproducibly in CI
- **WHEN** the `container` CI job builds the Docker image from a clean checkout
- **THEN** the build completes successfully and produces a runnable image
### Requirement: FrankenPHP runs in regular mode only
The system MUST NOT enable FrankenPHP worker mode in the MVP. The runtime SHALL use FrankenPHP in regular mode (ADR-006).
#### Scenario: Runtime configuration is regular mode
- **WHEN** the production image starts the web process
- **THEN** FrankenPHP serves requests in regular mode without worker persistence
### Requirement: Runtime image runs as non-root when supported
The system SHALL configure the production runtime to run as a non-root user when the base image supports it.
#### Scenario: Container process is non-root
- **WHEN** the web container is running in production configuration
- **THEN** the primary process MUST NOT run as root
### Requirement: Same image supports web queue and scheduler processes
The system SHALL use the same application image for web, queue worker, and scheduler processes with distinct commands (SPEC §15.2).
#### Scenario: Queue worker starts from application image
- **WHEN** the queue process is started with `php artisan queue:work`
- **THEN** it uses the same built image as the web process
### Requirement: Production image contains no secrets in layers
The system MUST NOT embed secrets, credentials, or private keys in Docker image layers.
#### Scenario: Image inspection finds no embedded secrets
- **WHEN** the image is built in CI
- **THEN** build arguments and layers MUST NOT contain production secrets or `.env` values
### Requirement: Container healthcheck validates application availability
The system SHALL define a container healthcheck that verifies application availability via the `/up` endpoint or equivalent boot check.
#### Scenario: Unhealthy container is detected
- **WHEN** the application inside the container fails to respond healthy on `/up`
- **THEN** the container healthcheck MUST report unhealthy status

View File

@@ -0,0 +1,28 @@
## ADDED Requirements
### Requirement: Design tokens are centralized for the public site
The system SHALL define minimum design tokens in a single source consumed by the public site layout and components. Tokens MUST cover typography families, font scale, spacing, border radius, container width, background/text/border/accent/state colors, shadows, and transition duration/easing.
#### Scenario: Public layout uses shared tokens
- **WHEN** a public page is rendered
- **THEN** visual properties MUST be derived from the centralized token definitions rather than arbitrary inline values
### Requirement: Public site respects reduced motion preference
The system SHALL honor `prefers-reduced-motion` by disabling or minimizing non-essential animations and transitions on the public site.
#### Scenario: User prefers reduced motion
- **WHEN** a visitor has `prefers-reduced-motion: reduce` enabled
- **THEN** the public site MUST NOT play non-essential motion effects
### Requirement: Public site meets baseline accessibility contrast
The system SHALL use color combinations on the public site that meet WCAG AA contrast requirements for text and interactive elements defined in the token palette.
#### Scenario: Primary text is readable
- **WHEN** primary body text is rendered on its background color
- **THEN** the contrast ratio MUST meet WCAG AA minimums

View File

@@ -0,0 +1,24 @@
## ADDED Requirements
### Requirement: Public health endpoint responds without authentication
The system SHALL expose `GET /up` as a public healthcheck endpoint that does not require authentication.
#### Scenario: Application is healthy
- **WHEN** a client sends `GET /up` while the application is running normally
- **THEN** the system responds with HTTP 200 in a timely manner
#### Scenario: Health endpoint exposes no secrets
- **WHEN** a client sends `GET /up`
- **THEN** the response MUST NOT include credentials, tokens, stack traces, or environment secrets
### Requirement: Health endpoint reflects application failure
The system SHALL return a failure status when the application cannot initialize properly.
#### Scenario: Application cannot boot
- **WHEN** the application fails to boot due to misconfiguration or missing dependencies
- **THEN** the health endpoint MUST NOT return HTTP 200

View File

@@ -0,0 +1,56 @@
## ADDED Requirements
### Requirement: Internal users authenticate via Filament panel
The system SHALL provide authenticated access to the internal panel at `/admin` using Laravel's session-based authentication integrated with Filament 5.
#### Scenario: Active admin logs in successfully
- **WHEN** an active user with role `admin` submits valid credentials on the login page
- **THEN** the system authenticates the user and redirects to the Filament dashboard
#### Scenario: Active assistant logs in successfully
- **WHEN** an active user with role `assistant` submits valid credentials on the login page
- **THEN** the system authenticates the user and redirects to the Filament dashboard
#### Scenario: Inactive user is denied panel access
- **WHEN** a user with `is_active` set to false submits valid credentials
- **THEN** the system MUST NOT grant access to the Filament panel
### Requirement: User roles are limited to admin and assistant
The system SHALL store user roles using the `UserRole` enum with exactly two cases: `admin` and `assistant`. The system MUST NOT implement a granular permission system in the MVP.
#### Scenario: User is created with a valid role
- **WHEN** an administrator creates a user with role `admin` or `assistant`
- **THEN** the role is persisted and enforced on subsequent authorization checks
### Requirement: Email addresses are unique per user
The system SHALL enforce a unique constraint on user email addresses.
#### Scenario: Duplicate email rejected
- **WHEN** a user is created or updated with an email already assigned to another user
- **THEN** the system MUST reject the operation with a validation error
### Requirement: Password reset is available for internal users
The system SHALL support secure password reset for internal users using Laravel's built-in reset flow.
#### Scenario: User requests password reset
- **WHEN** a user submits a registered email on the password reset form
- **THEN** the system sends a reset link without revealing whether the email exists
### Requirement: Only admin manages internal users
The system SHALL restrict user management (create, update, deactivate) to users with role `admin`. Users with role `assistant` MUST NOT manage other users.
#### Scenario: Assistant cannot access user management
- **WHEN** an authenticated assistant attempts to access user management in the panel
- **THEN** the system MUST deny access via authorization policy

View File

@@ -0,0 +1,42 @@
## ADDED Requirements
### Requirement: Standardized Composer test scripts exist
The system SHALL expose Composer scripts equivalent to `test:unit`, `test:feature`, `test:browser`, `test`, and `quality` with the composition defined in SPEC §13.9.
#### Scenario: Developer runs full quality gate locally
- **WHEN** a developer runs `composer quality`
- **THEN** the command executes static analysis, audits, and the applicable test suites
### Requirement: Architecture tests enforce domain boundaries
The system SHALL include Pest architecture tests that verify `App\Domain` uses strict types and does not depend on `App\Filament` or `App\Livewire`.
#### Scenario: Domain layer violates boundary
- **WHEN** code in `App\Domain` imports from `App\Filament` or `App\Livewire`
- **THEN** the architecture test suite MUST fail
### Requirement: CI pipeline blocks merge on five jobs
The system SHALL run a CI pipeline with blocking jobs named `static`, `unit`, `feature`, `browser`, and `container` as defined in SPEC §14.1.
#### Scenario: Static analysis fails on pull request
- **WHEN** a pull request introduces a Pint, PHPStan/Larastan, or Composer audit failure
- **THEN** the `static` job MUST fail and block merge
#### Scenario: Feature tests use PostgreSQL
- **WHEN** the `feature` CI job runs integration tests
- **THEN** the job MUST use PostgreSQL and MUST NOT substitute SQLite
### Requirement: Browser tests run against FrankenPHP-served application
The system SHALL execute browser tests using Pest Browser/Playwright against an application served by FrankenPHP in CI.
#### Scenario: Browser job validates served application
- **WHEN** the `browser` CI job runs
- **THEN** tests execute against the built application artifact or equivalent production-like image

View File

@@ -0,0 +1,71 @@
## 1. Bootstrap do projeto
- [x] 1.1 Criar app Laravel 13 via `composer create-project` em diretório temporário e mover para raiz preservando `SPEC.md`, `openspec/` e `.codex/`
- [x] 1.2 Configurar `.env` e `.env.example` com `APP_LOCALE=pt_BR`, `APP_TIMEZONE=America/Fortaleza`, `DB_CONNECTION=pgsql`
- [x] 1.3 Adicionar `declare(strict_types=1);` como convenção documentada e habilitar strict types nos arquivos PHP criados nesta fase
- [x] 1.4 Criar índice de ADRs aceitas em `docs/adr/` referenciando ADR-001..ADR-010 do SPEC §21
## 2. Banco de dados e Docker Compose local
- [x] 2.1 Adicionar `docker-compose.yml` com serviço PostgreSQL 17, volume nomeado e healthcheck
- [x] 2.2 Configurar conexão PostgreSQL no Laravel e validar `php artisan migrate` em banco limpo
- [x] 2.3 Configurar `SESSION_DRIVER=database`, `CACHE_STORE=database`, `QUEUE_CONNECTION=database`
- [x] 2.4 Documentar comandos locais (`docker compose up`, `artisan migrate`) no README
## 3. Filament, autenticação e papéis
- [x] 3.1 Instalar Filament 5 com painel em `/admin` e autenticação habilitada
- [x] 3.2 Criar migration adicionando `role` (varchar indexed) e `is_active` (boolean default true) em `users`
- [x] 3.3 Implementar enum `UserRole` (`admin`, `assistant`) e integrar ao model `User`
- [x] 3.4 Implementar `canAccessPanel()` negando usuários inativos
- [x] 3.5 Criar `UserResource` restrito a admin via Policy
- [x] 3.6 Criar `DatabaseSeeder` com usuário admin local (credenciais documentadas apenas para dev)
- [x] 3.7 Escrever feature tests: login admin, login assistant, bloqueio de inativo, assistant sem acesso a usuários
## 4. Livewire, Tailwind, Vite e design tokens
- [x] 4.1 Instalar Livewire 4 e configurar Vite + Tailwind para site público
- [x] 4.2 Criar `resources/css/tokens.css` com custom properties (tipografia, escala, espaçamento, raio, container, cores, sombras, transições)
- [x] 4.3 Estender `tailwind.config.js` para consumir tokens centralizados
- [x] 4.4 Criar layout público mínimo (`resources/views/layouts/public.blade.php`) com `prefers-reduced-motion` e contraste AA
- [x] 4.5 Criar rota `/` com página placeholder usando layout público e tokens
- [x] 4.6 Escrever teste feature validando renderização da home sem erro
## 5. Healthcheck
- [x] 5.1 Garantir rota `GET /up` respondendo HTTP 200 sem autenticação
- [x] 5.2 Validar que resposta não expõe segredos ou stack traces
- [x] 5.3 Escrever feature test para endpoint `/up`
## 6. Qualidade: Pint, Larastan, Pest, arch tests e scripts Composer
- [x] 6.1 Instalar e configurar Laravel Pint com script `composer pint` / check no CI
- [x] 6.2 Instalar Larastan/PHPStan com nível definido e script no CI job `static`
- [x] 6.3 Instalar Pest 4 e Pest Browser; configurar `phpunit.xml` / `Pest.php`
- [x] 6.4 Criar testes de arquitetura: `App\Domain` strict types, sem dependência de Filament/Livewire
- [x] 6.5 Adicionar scripts Composer: `test:unit`, `test:feature`, `test:browser`, `test`, `quality` conforme SPEC §13.9
- [x] 6.6 Configurar `composer audit` no job `static`
## 7. Docker multi-stage FrankenPHP
- [x] 7.1 Criar Dockerfile multi-stage (composer → frontend → runtime FrankenPHP regular mode)
- [x] 7.2 Fixar versão PHP compatível com Laravel 13; usuário non-root quando suportado
- [x] 7.3 Definir comandos para processos web, queue (`queue:work`) e scheduler (`schedule:work`)
- [x] 7.4 Adicionar healthcheck do contêiner apontando para `/up`
- [x] 7.5 Garantir que nenhum secret ou `.env` de produção entra em layer da imagem
- [x] 7.6 Validar build local e no CI
## 8. CI GitHub Actions
- [x] 8.1 Criar workflow `.github/workflows/ci.yml` com jobs `static`, `unit`, `feature`, `browser`, `container`
- [x] 8.2 Job `feature`: PostgreSQL service container (nunca SQLite)
- [x] 8.3 Job `browser`: build de imagem, servir via FrankenPHP, rodar Pest Browser com locale `pt_BR` e TZ `America/Fortaleza`
- [x] 8.4 Job `container`: build da imagem final + healthcheck
- [x] 8.5 Configurar cache seguro de Composer e npm nos jobs
## 9. Verificação final e critério de saída
- [x] 9.1 Executar `composer quality` localmente e corrigir falhas
- [x] 9.2 Executar `composer test:browser` (smoke mínimo: home + login)
- [x] 9.3 Confirmar critério de saída da Fase 0: pipeline CI verde + build de imagem + healthcheck validado no contêiner
- [x] 9.4 Reportar conclusão no formato SPEC §24 (requisito, alterações, testes, comandos, aceite, pendências)