docs: sync OpenSpec archives and propose foundation parity

Archive completed public-site and production-provider changes into main specs, remove duplicate active changes, and add complete-foundation-parity so Phase 0 staging and remaining foundation gaps block Phase 2 cleanly.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-01 21:55:04 -03:00
parent cafb1167ac
commit 9dd6fcf409
53 changed files with 885 additions and 828 deletions

32
SPEC.md
View File

@@ -2309,22 +2309,22 @@ O agente deve implementar na sequência, salvo instrução explícita.
**Entregas:** **Entregas:**
- [ ] projeto Laravel; - [x] projeto Laravel;
- [ ] PostgreSQL local e CI; - [x] PostgreSQL local e CI;
- [ ] Filament instalado e autenticado; - [x] Filament instalado e autenticado;
- [ ] Livewire configurado; - [x] Livewire configurado;
- [ ] Tailwind/Vite; - [x] Tailwind/Vite;
- [ ] FrankenPHP e Docker Compose local; - [x] FrankenPHP e Docker Compose local;
- [ ] papéis admin/assistant; - [x] papéis admin/assistant;
- [ ] Pint; - [x] Pint;
- [ ] PHPStan/Larastan; - [x] PHPStan/Larastan;
- [ ] Pest; - [x] Pest;
- [ ] Pest Browser; - [x] Pest Browser;
- [ ] Architecture tests; - [x] Architecture tests;
- [ ] pipeline CI inicial; - [x] pipeline CI inicial;
- [ ] design tokens mínimos; - [x] design tokens mínimos;
- [ ] healthcheck; - [x] healthcheck;
- [ ] seed de admin local. - [x] seed de admin local.
**Critério de saída:** pipeline verde e hello-world implantado em staging. **Critério de saída:** pipeline verde e hello-world implantado em staging.

View File

@@ -67,6 +67,6 @@
- [x] 8.1 Job `browser` do CI: executar `php artisan db:seed --class=VisualContentSeeder --force` antes da suíte - [x] 8.1 Job `browser` do CI: executar `php artisan db:seed --class=VisualContentSeeder --force` antes da suíte
- [x] 8.2 Job `browser` do CI: publicar screenshots, diffs de snapshot, logs da aplicação e logs do browser com `if: failure()` - [x] 8.2 Job `browser` do CI: publicar screenshots, diffs de snapshot, logs da aplicação e logs do browser com `if: failure()`
- [ ] 8.3 Confirmar os cinco jobs verdes (`static`, `unit`, `feature`, `browser`, `container`) em pull request - [x] 8.3 Confirmar os cinco jobs verdes (`static`, `unit`, `feature`, `browser`, `container`) em pull request
- [x] 8.4 Rodar `composer quality` completo e registrar o resultado no PR - [x] 8.4 Rodar `composer quality` completo e registrar o resultado no PR
- [x] 8.5 Revisar o critério de saída da Fase 1 (conteúdo gerenciável no Filament e site público aprovado visualmente) e atualizar `SPEC.md` §18 marcando apenas itens comprovados - [x] 8.5 Revisar o critério de saída da Fase 1 (conteúdo gerenciável no Filament e site público aprovado visualmente) e atualizar `SPEC.md` §18 marcando apenas itens comprovados

View File

@@ -1,97 +0,0 @@
## Context
Fase 0 entregou Laravel 13, Filament 5 em `/admin`, design tokens, autenticação interna e pipeline CI. O repositório possui apenas home placeholder em [routes/web.php](../../routes/web.php). Esta change implementa a **metade CMS** da Fase 1 (SPEC §18): persistência e gestão Filament de conteúdo, sem rotas públicas.
Padrões existentes a seguir:
- Resources Filament com form/table separados ([app/Filament/Resources/Users/](../../app/Filament/Resources/Users/))
- Policies admin-only ([app/Policies/UserPolicy.php](../../app/Policies/UserPolicy.php))
- `declare(strict_types=1);` em todo PHP próprio
## Goals / Non-Goals
**Goals:**
- Assessora admin gerencia settings, serviços, portfólio e depoimentos no Filament.
- Dados persistidos conforme SPEC §8.2, prontos para consumo pela change `build-public-site`.
- Feature tests locais em PostgreSQL (jsonb, constraints reais).
- Seed determinístico parcial para desenvolvimento e testes futuros.
**Non-Goals:**
- Rotas públicas, home, SEO, sitemap, snapshots visuais, briefing.
- Actions de publicação com auditoria (`PublishPortfolioCase` etc.) — adiadas até Fase 5.
- Variantes responsivas de imagem, page builder, categorias dinâmicas.
## Decisions
### 1. Publicação via `published_at` único
**Decisão:** `published_at` nullable timestamp é a única fonte de verdade. Scope `published()` no model (`whereNotNull('published_at')`). Sem coluna `is_published`.
**Alternativa rejeitada:** boolean `is_published` + `published_at` — viola SPEC §1.1 (não persistir status derivável).
### 2. Mídia em disco `public` local, S3 em produção
**Decisão:** uploads de capa/galeria/foto usam disco Laravel configurável via `FILESYSTEM_DISK`. Local: `public` + `php artisan storage:link`. Produção: `s3`. Path gerado com UUID/hash, nunca nome original.
**Alternativa rejeitada:** blobs no PostgreSQL — proibido por SPEC §6.4.
### 3. Validação de mídia centralizada
**Decisão:** classe em `app/Support/` (ex.: `PublicImageUploadRules`) com allowlist MIME (`image/jpeg`, `image/png`, `image/webp`), extensões correspondentes, limite 10 MB, alt text obrigatório quando imagem presente. Reutilizada nos Resources Filament.
### 4. Sem Actions de domínio nesta fase
**Decisão:** Filament Resources salvam diretamente via Eloquent. Actions (`PublishPortfolioCase`, `UnpublishPortfolioCase`) só serão criadas quando auditoria (Fase 5) exigir efeito colateral transacional.
**Rationale:** SPEC §9.5 — não criar Action para CRUD sem regra adicional.
### 5. Auditoria de publicação adiada
**Decisão:** publicar/despublicar **não** grava `audit_logs` nesta change.
**Desvio documentado:** ADM-02 lista publicação como auditável, mas tabela `audit_logs` é Fase 5. Retomar em change de hardening.
### 6. Autorização admin-only para CMS
**Decisão:** Policies espelham `UserPolicy``$user->isAdmin()` para view/create/update/delete em conteúdo do site. Assistant recebe 403 em todos os Resources de conteúdo.
**Referência:** WEB-02 — "admin pode gerenciar; assistant não pode".
### 7. Site settings como singleton Filament Page
**Decisão:** model `SiteSetting` com método `instance()` (primeiro registro ou create default). Filament `ManageSiteSettings` page (não Resource de lista) — evita CRUD genérico de chave/valor (SPEC §WEB-06).
### 8. Slug automático a partir do título
**Decisão:** slug gerado no model (observer ou mutator) com `Str::slug()`, unique constraint no banco. Admin pode editar slug no form.
### 9. Navegação Filament
**Decisão:** grupo `Conteúdo do site` com sort order conforme SPEC §5.2:
1. Configurações (singleton page)
2. Serviços
3. Portfólio
4. Depoimentos
## Risks / Trade-offs
| Risco | Mitigação |
|---|---|
| Uploads locais sem S3 em dev | `Storage::fake()` nos testes; documentar `storage:link` no README |
| Galeria ordenada complexa no Filament | Relation manager com `sort_order` e reorderable |
| jsonb `social_links` difere SQLite | phpunit.xml já migrado para PostgreSQL |
| Conteúdo criado sem rotas públicas | seed + testes Filament validam CMS; rotas vêm em `build-public-site` |
| Auditoria ausente em publicação | desvio explícito; retomar Fase 5 |
## Migration Plan
1. Rodar migrations em ordem: `site_settings``services``portfolio_cases` + `portfolio_images``testimonials`.
2. Executar seed de conteúdo após migrations.
3. Sem rollback de dados em produção (greenfield); `migrate:rollback` suportado em dev.
## Open Questions
- Nenhuma bloqueante. Fontes tipográficas finais da home ficam para `build-public-site`.

View File

@@ -1,42 +0,0 @@
## Why
A Fase 0 — Fundação está concluída e arquivada; o próximo passo do MVP é permitir que a assessora gerencie conteúdo do site no Filament antes de expor rotas públicas. Sem modelos, migrations e Resources internos para configurações, serviços, portfólio e depoimentos, a Fase 1 não pode avançar e o site permanece estático.
## What Changes
- Criar tabelas e models conforme SPEC §8.2: `site_settings`, `services`, `portfolio_cases`, `portfolio_images`, `testimonials`.
- Implementar CMS Filament no grupo **Conteúdo do site** (SPEC §5.2) para WEB-02, WEB-03, WEB-04 e WEB-06.
- Introduzir regras compartilhadas de upload de mídia pública (allowlist MIME, limite de tamanho, path aleatório, alt text obrigatório).
- Policies admin-only para conteúdo do site; assistant não gerencia CMS (WEB-02).
- Factories e seed parcial de demonstração (3 serviços, 3 casos, 3 depoimentos, settings).
- Alinhar `phpunit.xml` para feature tests locais em PostgreSQL (delta de `quality-gates`).
## Non-Goals
Conforme [SPEC.md §4.2](../../SPEC.md) e a divisão da Fase 1:
- Rotas públicas, home editorial (WEB-01), páginas institucionais (WEB-07), briefing (WEB-05).
- SEO, sitemap, robots, snapshots visuais e testes de acessibilidade do site público.
- Page builder, CRUD de categorias, auditoria de publicação (`audit_logs` — Fase 5).
- Variantes responsivas de imagem (adiadas para change `build-public-site`).
## Capabilities
### New Capabilities
- `site-settings`: singleton tipado de configurações globais do site (WEB-06).
- `service-catalog`: CRUD de serviços publicáveis com slug único (WEB-02).
- `portfolio-cases`: casos de portfólio com galeria ordenada (WEB-03).
- `testimonials`: depoimentos publicáveis (WEB-04).
- `content-media`: validação e armazenamento compartilhado de imagens públicas (SPEC §6.4, §12.4).
### Modified Capabilities
- `quality-gates`: feature tests locais MUST usar PostgreSQL, alinhados ao CI (SPEC §14.2, §20).
## Impact
- **Cria**: migrations, models, factories, Policies, Filament Resources/Pages em `app/Filament/`, seeders, testes feature em `tests/Feature/Marketing/`.
- **Altera**: `phpunit.xml`, `DatabaseSeeder`, navegação do painel Filament.
- **Depende de**: specs arquivadas da fundação (`internal-authentication`, `design-tokens`, `quality-gates`).
- **Sem impacto** em rotas públicas existentes além do placeholder `/`.

View File

@@ -1,32 +0,0 @@
## ADDED Requirements
### Requirement: Public content images are validated and stored securely
The system SHALL validate public content uploads (service covers, portfolio covers/gallery, testimonial photos, site OG image) per SPEC §6.4 and §12.4. Validation MUST enforce MIME allowlist (jpeg, png, webp), matching extensions, maximum size of 10 MB, and mandatory alt text when an image is uploaded.
#### Scenario: Invalid MIME is rejected
- **WHEN** an admin uploads a file with disallowed MIME type
- **THEN** validation MUST fail with a pt-BR error message
#### Scenario: Oversized file is rejected
- **WHEN** an admin uploads an image exceeding 10 MB
- **THEN** validation MUST fail
#### Scenario: Storage path is not derived from original filename
- **WHEN** an image is stored
- **THEN** the physical path MUST be generated (UUID/hash based)
- **AND** MUST NOT use the original upload filename as the storage key
#### Scenario: Alt text required with image
- **WHEN** an admin uploads a cover or gallery image without alt text
- **THEN** validation MUST fail
#### Scenario: Images are not stored in PostgreSQL
- **WHEN** content with images is persisted
- **THEN** only the filesystem path MUST be stored in the database
- **AND** binary image data MUST NOT be written to PostgreSQL columns

View File

@@ -1,31 +0,0 @@
## ADDED Requirements
### Requirement: Portfolio cases support editorial content and ordered gallery
The system SHALL allow admins to manage portfolio cases (SPEC WEB-03) with title, unique slug, summary, event type, optional city/venue/event date, challenge, solution, optional result, cover image with alt text, featured flag, sort order, `published_at`, and optional SEO meta fields. Each case MUST support an ordered gallery via `portfolio_images` (path, alt text, optional caption, sort order).
#### Scenario: Draft case is not publicly visible
- **WHEN** a portfolio case has `published_at` null
- **THEN** the `published()` scope MUST exclude it
#### Scenario: Published case meets acceptance criteria
- **WHEN** an admin fills required fields and sets `published_at`
- **THEN** the case MUST be included in the `published()` scope
- **AND** cover and gallery images MUST have alt text when present
#### Scenario: Gallery images maintain order
- **WHEN** an admin reorders gallery images in Filament
- **THEN** `sort_order` MUST reflect the chosen order per `portfolio_case_id`
#### Scenario: Assistant cannot manage portfolio
- **WHEN** an assistant attempts to access portfolio cases
- **THEN** access MUST be denied with HTTP 403
#### Scenario: Cascade delete removes gallery images
- **WHEN** a portfolio case is deleted
- **THEN** associated `portfolio_images` records MUST be removed (FK cascade)

View File

@@ -1,16 +0,0 @@
## ADDED Requirements
### Requirement: Local feature tests use PostgreSQL
The system SHALL configure `phpunit.xml` so that the Feature test suite uses PostgreSQL with the same connection parameters as CI (`DB_CONNECTION=pgsql`, host, port, database `amare_test`, credentials). Local feature tests MUST NOT default to SQLite `:memory:`.
#### Scenario: Developer runs feature tests locally
- **WHEN** a developer runs `composer test:feature` with PostgreSQL available
- **THEN** tests MUST execute against PostgreSQL
- **AND** MUST NOT silently fall back to SQLite
#### Scenario: Feature tests exercise PostgreSQL-specific types
- **WHEN** feature tests persist records with jsonb columns (e.g., `social_links`)
- **THEN** migrations and constraints MUST be validated against PostgreSQL semantics

View File

@@ -1,30 +0,0 @@
## ADDED Requirements
### Requirement: Services are managed in Filament with publication control
The system SHALL allow admins to create, update, and delete services (SPEC WEB-02). Each service MUST have title, unique slug, summary, description, optional cover image with alt text, sort order, featured flag, and `published_at`.
#### Scenario: Unpublished service is not publicly visible
- **WHEN** a service has `published_at` null
- **THEN** the `published()` scope MUST exclude it from public queries
#### Scenario: Published service is queryable
- **WHEN** an admin sets `published_at` on a service with required fields
- **THEN** the service MUST be included in the `published()` scope
#### Scenario: Slug uniqueness is enforced
- **WHEN** an admin attempts to save two services with the same slug
- **THEN** validation or database constraint MUST reject the duplicate
#### Scenario: Assistant cannot manage services
- **WHEN** an assistant attempts to access the services Resource
- **THEN** access MUST be denied with HTTP 403
#### Scenario: Delete requires confirmation
- **WHEN** an admin deletes a service in Filament
- **THEN** the UI MUST require explicit confirmation before deletion

View File

@@ -1,28 +0,0 @@
## ADDED Requirements
### Requirement: Site settings singleton is manageable by admin only
The system SHALL persist site-wide settings in a `site_settings` table as a typed singleton (SPEC WEB-06, §8.2). Fields MUST include brand name, hero copy (eyebrow, title, subtitle, CTA label), about summary, contact email/phone/city, social links (jsonb), default meta title/description, default OG image path and alt text, and optional analytics fields disabled by default.
#### Scenario: Admin updates site settings
- **WHEN** an admin saves the site settings form in Filament
- **THEN** the singleton record is updated
- **AND** labels and validation messages are in pt-BR
#### Scenario: Assistant cannot access site settings
- **WHEN** an assistant navigates to site settings in Filament
- **THEN** access MUST be denied with HTTP 403
#### Scenario: Default OG image requires alt text
- **WHEN** an admin uploads a default OG image without alt text
- **THEN** validation MUST fail with a pt-BR error message
- **AND** alt text MUST remain optional when no default OG image is present
#### Scenario: Singleton avoids generic key-value store
- **WHEN** site settings are stored
- **THEN** the system MUST use typed columns on `site_settings`
- **AND** MUST NOT introduce a generic key/value configuration table

View File

@@ -1,25 +0,0 @@
## ADDED Requirements
### Requirement: Testimonials are managed with publication control
The system SHALL allow admins to manage testimonials (SPEC WEB-04) with quote text, author name, optional context, optional photo with alt text, sort order, featured flag, and `published_at`.
#### Scenario: Unpublished testimonial is excluded
- **WHEN** a testimonial has `published_at` null
- **THEN** the `published()` scope MUST exclude it
#### Scenario: Published testimonial is queryable
- **WHEN** an admin sets `published_at` with required quote and author name
- **THEN** the testimonial MUST be included in the `published()` scope
#### Scenario: Assistant cannot manage testimonials
- **WHEN** an assistant attempts to access the testimonials Resource
- **THEN** access MUST be denied with HTTP 403
#### Scenario: Featured testimonials are filterable
- **WHEN** content is queried with featured filter
- **THEN** records with `is_featured` true MUST be retrievable independently of sort order

View File

@@ -1,57 +0,0 @@
## 1. Pré-requisitos e alinhamento de testes
- [x] 1.1 Confirmar `phpunit.xml` com PostgreSQL (`amare_test`) e documentar criação do banco de teste no README
- [x] 1.2 Registrar Policies de conteúdo no `AppServiceProvider` ou descoberta automática
- [x] 1.3 Criar diretório `tests/Feature/Marketing/` para testes desta change
## 2. Content media (content-media)
- [x] 2.1 Criar `app/Support/PublicImageUploadRules.php` com allowlist MIME/extensão, limite 10 MB e regra de alt text obrigatório
- [x] 2.2 Escrever teste unitário ou feature validando rejeição de MIME inválido e arquivo oversize
- [x] 2.3 Documentar `php artisan storage:link` e disco `public` no README
- [x] 2.4 Reforçar uploads Filament com validação compartilhada de MIME, extensão e limite de 10 MB, incluindo mensagens em pt-BR e testes regressivos
## 3. Site settings (site-settings / WEB-06)
- [x] 3.1 Criar migration `site_settings` conforme SPEC §8.2 (incluindo `social_links` jsonb)
- [x] 3.2 Criar model `SiteSetting` com `instance()` singleton e casts (jsonb, timestamps)
- [x] 3.3 Criar `SiteSettingPolicy` admin-only
- [x] 3.4 Criar Filament Page `ManageSiteSettings` no grupo **Conteúdo do site** com form tipado (hero, contato, meta, OG image, analytics desabilitados por padrão)
- [x] 3.5 Escrever feature tests: admin salva settings; assistant recebe 403
- [x] 3.6 Adicionar alt text condicional à imagem OG padrão na migration, model, formulário, seed determinístico e testes
## 4. Service catalog (service-catalog / WEB-02)
- [x] 4.1 Criar migration `services` com índices em `slug`, `sort_order`, `is_featured`, `published_at`
- [x] 4.2 Criar model `Service` com scope `published()`, slug único e fillable conforme SPEC
- [x] 4.3 Criar `ServiceFactory` e `ServicePolicy` admin-only
- [x] 4.4 Criar `ServiceResource` Filament (form, table, confirmação de exclusão, upload de capa com alt text via PublicImageUploadRules)
- [x] 4.5 Escrever feature tests: slug único, publicação via `published_at`, assistant 403
## 5. Portfolio cases (portfolio-cases / WEB-03)
- [x] 5.1 Criar migrations `portfolio_cases` e `portfolio_images` (FK cascade, índice composto `portfolio_case_id, sort_order`)
- [x] 5.2 Criar models `PortfolioCase` e `PortfolioImage` com relação hasMany ordenada e scope `published()`
- [x] 5.3 Criar factories e `PortfolioCasePolicy` admin-only
- [x] 5.4 Criar `PortfolioCaseResource` com relation manager de galeria (reorderable, alt text, caption opcional)
- [x] 5.5 Escrever feature tests: publicação, ordem da galeria, cascade delete, assistant 403
## 6. Testimonials (testimonials / WEB-04)
- [x] 6.1 Criar migration `testimonials` conforme SPEC §8.2
- [x] 6.2 Criar model `Testimonial` com scope `published()` e `TestimonialFactory`
- [x] 6.3 Criar `TestimonialPolicy` e `TestimonialResource` Filament
- [x] 6.4 Escrever feature tests: publicação, featured filter, assistant 403
## 7. Seed de conteúdo de demonstração
- [x] 7.1 Criar `ContentSeeder` ou estender `DatabaseSeeder` com settings padrão, 3 serviços, 3 casos (com galeria), 3 depoimentos
- [x] 7.2 Adicionar imagens fixture versionadas em `tests/fixtures/images/` e referenciá-las no seed
- [x] 7.3 Garantir datas e conteúdo determinísticos para testes visuais futuros (SPEC §17.3)
## 8. Verificação final
- [x] 8.1 Executar `composer pint:check` e `composer phpstan`
- [x] 8.2 Executar `composer test:feature` contra PostgreSQL local
- [x] 8.3 Executar `composer quality` e corrigir falhas
- [x] 8.4 Reportar conclusão no formato SPEC §24 (requisitos WEB-02/03/04/06, alterações, testes, comandos, aceite, pendências)

View File

@@ -1,2 +1,2 @@
schema: spec-driven schema: spec-driven
created: 2026-07-29 created: 2026-07-30

View File

@@ -0,0 +1,99 @@
## Context
Fases 01 e provedores de produção (Resend + R2) estão em `main` com CI verde. OpenSpec ativo foi limpo: specs promovidas e changes arquivadas. Gaps remanescentes da Fase 0:
- Critério de saída §18 exige hello-world em staging; só existe workflow CI.
- `docker-compose.yml` sobe apenas PostgreSQL; app local usa `artisan serve`.
- README declara PHP 8.5+; Docker/CI usam 8.4; Composer aceita `^8.3`.
- `composer quality` não roda `npm audit`; CI unit/feature usam `coverage: none` (SPEC §13.7 pede 80% Domain/Application).
- `User` bloqueia inativos em `canAccessPanel`, mas não implementa `MustVerifyEmail`; reset de senha Filament não está validado por teste.
- Destino de staging escolhido: VPS própria com Dokploy (não Railway).
## Goals / Non-Goals
**Goals:**
- Staging em Dokploy com a mesma imagem FrankenPHP por SHA para web, queue e scheduler.
- Deploy automático em `main` após CI: build → GHCR → Dokploy API → migrate → health → smoke.
- Compose local com app FrankenPHP + Postgres.
- PHP 8.4 canônico em docs/Docker/CI.
- Gates com `npm audit` e cobertura Domain/Application ≥ 80%.
- E-mail verificado + reset de senha seguros no painel (ADM-01 / SPEC §12.1).
- Strict types em PHP próprio faltante.
**Non-Goals:**
- Produção, promoção humana, provisionamento de VPS para clientes.
- Fase 2 (briefing/CRM/E2E-01/02).
- Redis, worker mode, CDN automation, signed private media.
## Decisions
### D1 — Dokploy Compose na VPS, imagem imutável no GHCR
GitHub Actions (após CI verde em `main`) constrói **uma** imagem `ghcr.io/<owner>/<repo>:<git-sha>` (+ alias `:staging`), faz push privado e chama `POST /api/compose.deploy` (ou `compose.update` + `compose.deploy`) no Dokploy com `x-api-key`.
Compose de staging referencia `${APP_IMAGE}` / `IMAGE_TAG` para `web`, `queue`, `scheduler` e job `migrate` one-shot (`php artisan migrate --force`). PostgreSQL é serviço Dokploy separado (não na imagem da app).
*Alternativas rejeitadas:* Railway (Pro para GHCR privado + desvio de plataforma); rebuild por serviço no Dokploy (quebra “mesma imagem” SPEC §14.3/§15.2); tag só `:latest` (rollback frágil).
### D2 — Processos e health
| Serviço | Comando |
|---|---|
| web | entrypoint padrão FrankenPHP (`CMD` da imagem) |
| queue | `php artisan queue:work --sleep=2 --tries=3` |
| scheduler | `php artisan schedule:work` |
| migrate | one-shot antes/ao lado do deploy |
Healthcheck Docker/Dokploy e smoke pós-deploy usam `GET /up` (sem auth, sem secrets). Smoke mínimo: `/up`, home pública `/`, `/admin/login` respondem 200.
### D3 — Secrets e providers
Secrets em GitHub Actions + env Dokploy: `APP_KEY`, DB, `MAIL_MAILER=resend` / `RESEND_API_KEY`, `FILESYSTEM_DISK=r2` / `R2_*`, tokens Dokploy/GHCR. Nunca embeds em layer. Local continua `MAIL_MAILER=log` e disco `public`.
### D4 — Compose local com app
Adicionar serviço `app` (build do `Dockerfile`) dependendo de `postgres` healthy, porta 8000, volumes só para storage local se útil. Documentar `docker compose up` como caminho preferido; `artisan serve` permanece opcional para iteração rápida sem rebuild.
### D5 — PHP 8.4 canônico
Alinhar README, CI (`setup-php` 8.4) e `Dockerfile` `ARG PHP_VERSION=8.4`. Manter `composer.json` `^8.3` (compatibilidade de instalação), mas documentação e runtime canônicos = 8.4.
### D6 — Quality gates
- `composer quality` / job `static`: adicionar `npm audit --omit=dev` (ou política documentada equivalente) após `npm ci` onde assets forem necessários; falha bloqueia merge.
- Jobs `unit` (e, se aplicável, coverage dedicada): habilitar cobertura e falhar se Domain+Application < 80%. Escopo limitado a `app/Domain` e `app/Application` (SPEC §13.7). Views/migrations/framework fora.
### D7 — Auth parity
- `User` implementa `MustVerifyEmail`; `canAccessPanel` exige ativo **e** e-mail verificado.
- Seed local marca admin/assistant como verificados.
- Habilitar fluxo de reset Filament/Laravel; feature tests: unverified denied, verified ok, reset request não revela existência de e-mail.
- Correção pontual de `declare(strict_types=1);` em providers/arquivos próprios faltantes.
### D8 — Rollback
Rollback = apontar Compose staging para tag SHA anterior no GHCR e `compose.deploy`/`redeploy`. Falha de healthcheck impede promoção. Sem rebuild.
## Risks / Trade-offs
- **[GHCR privado + pull na VPS]** → configurar registry no Dokploy com PAT `read:packages`; documentar checklist.
- **[Migrate one-shot falha]** → deploy não promove web; manter migrations backward-compatible.
- **[Cobertura 80% com Domain quase vazio]** → medir só namespaces existentes; baseline sobe conforme Fase 2 adiciona Domain.
- **[npm audit ruido]** → `--omit=dev` + allowlist documentada se necessário; sem silenciar sem justificativa.
- **[E-mail verification em staging]** → seed/users de staging com `email_verified_at`; Resend para reset real quando configurado.
- **[Compose local rebuild lento]** → documentar serve opcional; CI permanece fonte FrankenPHP.
## Migration Plan
1. Implementar auth/coverage/npm/strict_types/docs/Compose local; CI verde.
2. Criar projeto Dokploy + Postgres + Compose app; registrar GHCR.
3. Adicionar workflow deploy; primeiro push de imagem SHA; smoke `/up` + home + login.
4. Atualizar SPEC §18 Fase 0 apenas com itens comprovados; evidência no PR.
5. Rollback: redeploy tag SHA anterior.
## Open Questions
- Domínio público exato do staging (DNS) — preencher na implementação com valor do operador.
- Se Dokploy Compose API exigir `compose.saveEnvironment` para `IMAGE_TAG` a cada deploy: confirmar payload na primeira fatia de integração.

View File

@@ -0,0 +1,43 @@
## Why
Fases 0 e 1 estão implementadas e mescladas, mas o critério de saída da Fase 0 (SPEC §18) ainda exige hello-world em staging, e a auditoria de paridade comprovou desvios de fundação: Compose local sem FrankenPHP, `npm audit` e cobertura Domain/Application ausentes dos gates, e-mail verificado e reset de senha incompletos, documentação de PHP divergente e um arquivo PHP próprio sem `strict_types`. Sem fechar esses gaps, a Fase 2 (leads) avançaria sobre uma fundação incompleta frente ao SPEC.
## What Changes
- Implantar staging na VPS própria via Dokploy (Docker Compose): imagem única por SHA no GHCR, serviços `web`/`queue`/`scheduler`/migrate, PostgreSQL gerenciado, healthcheck `/up`, smoke pós-deploy e rollback por tag SHA anterior.
- Adicionar workflow GitHub Actions de deploy em `main` após CI verde (build → push GHCR → acionar API Dokploy).
- Estender `docker-compose.yml` local com serviço de aplicação FrankenPHP (além do PostgreSQL).
- Fixar PHP **8.4** como versão canônica em Docker, CI e documentação.
- Incluir `npm audit` e cobertura mínima de 80% para `Domain` e `Application` nos gates de qualidade (SPEC §12.6, §13.7, §13.9).
- Exigir e-mail verificado no painel Filament e entregar reset de senha seguro (SPEC §12.1; ADM-01).
- Corrigir `declare(strict_types=1);` em PHP próprio que ainda falte e cobrir regressões.
## Non-Goals
Conforme [SPEC.md §4.2](../../SPEC.md):
- Produção com promoção humana, portal do cliente, multi-tenancy, Redis, FrankenPHP worker mode.
- Fase 2 (WEB-05 briefing, CRM, E2E-01/E2E-02) — change futura `build-leads-crm` após esta fechar.
- Provisionamento genérico de VPS/Dokploy para clientes finais.
- Templates de e-mail de lead, auditoria completa (ADM-02), documentos privados.
## Capabilities
### New Capabilities
- `staging-deployment`: deploy automático de staging na VPS via Dokploy com imagem imutável por SHA, processos web/queue/scheduler, migração, healthcheck, smoke e rollback (SPEC §14.3, §15.2, §18 Fase 0).
### Modified Capabilities
- `container-runtime`: Compose local com app FrankenPHP; PHP 8.4 canônico; alinhamento da mesma imagem a processos de staging.
- `quality-gates`: `npm audit` no gate; cobertura mínima 80% para Domain/Application; job de deploy staging após CI.
- `health-check`: healthcheck e smoke pós-deploy de staging usam `/up` sem autenticação.
- `internal-authentication`: e-mail verificado obrigatório para acesso ao painel; reset de senha seguro disponível (SPEC §12.1, ADM-01).
## Impact
- **Cria**: `docker-compose` de staging (ou extensão), workflow `.github/workflows/deploy-staging.yml`, docs operacionais de Dokploy/GHCR, testes de auth verification/reset e cobertura.
- **Altera**: `docker-compose.yml`, `Dockerfile`/docs PHP, `composer.json`/`package.json` scripts, `.github/workflows/ci.yml`, `User`/`AdminPanelProvider`, README, `.env.example`.
- **Infra (manual)**: projeto Dokploy na VPS, registry GHCR, secrets (`DOKPLOY_*`, `GHCR_*`, DB, `APP_KEY`, Resend/R2).
- **Depende de**: specs já arquivadas (`container-runtime`, `quality-gates`, `health-check`, `internal-authentication`, `transactional-email`, `object-storage`).
- **Risco**: secrets e registry privados; mitigações: tokens com escopo mínimo, imagem por SHA, healthcheck antes de promover, rollback por tag anterior.

View File

@@ -0,0 +1,30 @@
## ADDED Requirements
### Requirement: Local Compose runs FrankenPHP application alongside PostgreSQL
The local Docker Compose stack SHALL include a FrankenPHP application service built from the project Dockerfile, dependent on a healthy PostgreSQL service, exposing the application on port 8000 (or documented equivalent). FrankenPHP MUST run in regular mode (ADR-006).
#### Scenario: Developer starts full local stack
- **WHEN** a developer runs `docker compose up -d` with the application service enabled
- **THEN** PostgreSQL and the FrankenPHP app containers MUST become healthy
- **AND** `GET /up` on the app port MUST return HTTP 200
#### Scenario: App waits for database readiness
- **WHEN** the application service starts
- **THEN** it MUST depend on the PostgreSQL healthcheck succeeding before becoming ready
### Requirement: Runtime PHP version is canonically 8.4
Docker, CI, and project documentation MUST treat PHP 8.4 as the canonical runtime for this MVP. Statements that require PHP 8.5+ MUST NOT remain in project docs while the runtime image uses 8.4.
#### Scenario: Dockerfile pins PHP 8.4
- **WHEN** the production/runtime image is built
- **THEN** the FrankenPHP base image MUST use PHP 8.4
#### Scenario: Documentation matches the runtime
- **WHEN** a contributor reads the README requirements
- **THEN** the documented PHP version MUST be 8.4 (compatible with Composer `^8.3`)

View File

@@ -0,0 +1,16 @@
## ADDED Requirements
### Requirement: Staging health and smoke use the public /up endpoint
Staging healthchecks and post-deploy smoke MUST call `GET /up` without authentication and MUST treat a non-200 response as deployment failure (SPEC §15.5, §16.2). The health response MUST NOT expose secrets.
#### Scenario: Staging healthcheck probes /up
- **WHEN** Dokploy or the container runtime evaluates application health after deploy
- **THEN** it MUST request `/up`
- **AND** MUST require HTTP 200 before marking the service healthy
#### Scenario: Smoke failure on /up fails the deploy gate
- **WHEN** post-deploy smoke requests `/up` and receives a non-200 response
- **THEN** the staging promotion MUST be considered failed

View File

@@ -0,0 +1,34 @@
## ADDED Requirements
### Requirement: Verified email is required for panel access
Internal users MUST have a verified email address to access the Filament panel (SPEC §12.1, ADM-01). Active users with unverified email MUST be denied panel access. Development seeds MUST mark local demo users as verified.
#### Scenario: Unverified active user is denied panel access
- **WHEN** an active user with null `email_verified_at` authenticates
- **THEN** the system MUST NOT grant access to the Filament panel
#### Scenario: Verified active user can access the panel
- **WHEN** an active user with a non-null `email_verified_at` submits valid credentials
- **THEN** the system authenticates the user and allows Filament panel access subject to role rules
#### Scenario: Local seed users are verified
- **WHEN** `DatabaseSeeder` creates the local admin and assistant
- **THEN** both users MUST have `email_verified_at` set
### Requirement: Password reset flow is covered by automated tests
The secure password reset flow for internal users MUST be covered by feature tests that assert a reset request for a registered email queues/sends a reset notification without revealing whether the email exists to the client (SPEC §12.1; existing password-reset requirement).
#### Scenario: Reset request does not reveal account existence
- **WHEN** a visitor submits a password reset for an unknown email
- **THEN** the response MUST not disclose that the email is unregistered
#### Scenario: Registered email receives reset notification
- **WHEN** a visitor submits a password reset for a registered email
- **THEN** the system MUST dispatch the password reset notification (faked in tests)

View File

@@ -0,0 +1,38 @@
## ADDED Requirements
### Requirement: Quality gate includes npm dependency audit
The system SHALL run an npm audit as part of the quality/static gate according to the project policy (SPEC §12.6, §13.9). Audit failure MUST block merge unless an explicit, documented exception exists.
#### Scenario: Vulnerable dependency fails static gate
- **WHEN** `npm audit` reports a policy-violating vulnerability in production dependencies
- **THEN** the static/quality gate MUST fail and block merge
#### Scenario: Developer runs quality locally with audit
- **WHEN** a developer runs `composer quality` (or the documented npm audit step it requires)
- **THEN** the npm audit MUST execute as part of the gate sequence
### Requirement: Domain and Application maintain minimum coverage
The CI unit gate SHALL measure code coverage for `App\Domain` and `App\Application` and MUST fail when either namespace falls below 80% (SPEC §13.7). Views, migrations, generated code, and framework code MUST NOT be required to meet this threshold.
#### Scenario: Coverage drop below threshold blocks merge
- **WHEN** Domain or Application coverage is below 80% on the unit CI job
- **THEN** the job MUST fail
#### Scenario: Coverage ignores non-domain layers
- **WHEN** coverage is computed for the gate
- **THEN** Blade views and migrations MUST NOT be counted toward the Domain/Application threshold
### Requirement: Staging deploy job runs only after blocking CI jobs
When deploying from `main`, the staging deploy workflow MUST require the five blocking CI jobs (`static`, `unit`, `feature`, `browser`, `container`) to succeed before building/pushing the image and triggering Dokploy (SPEC §14.1, §14.3).
#### Scenario: Failed browser job prevents staging deploy
- **WHEN** the `browser` CI job fails on `main`
- **THEN** the staging deploy workflow MUST NOT promote a new image

View File

@@ -0,0 +1,57 @@
## ADDED Requirements
### Requirement: Staging deploys an immutable application image by commit SHA
The system SHALL deploy staging from a single FrankenPHP application image tagged with the Git commit SHA and published to GHCR (SPEC §14.3, §15.2). Web, queue worker, and scheduler processes MUST use that same image digest. Rebuilds per process on the staging host MUST NOT be the promotion path.
#### Scenario: Same image serves all application processes
- **WHEN** a staging deployment is promoted for commit SHA `abc123`
- **THEN** web, queue, and scheduler MUST run from `ghcr.io/<owner>/<repo>:abc123` (or equivalent digest)
- **AND** MUST NOT rebuild distinct images per process
#### Scenario: CI publishes the image before Dokploy deploy
- **WHEN** `main` passes the blocking CI jobs
- **THEN** the deploy workflow MUST build and push the SHA-tagged image before triggering Dokploy
### Requirement: Staging runs on Dokploy Compose on the operator VPS
Staging SHALL be operated as a Dokploy Docker Compose deployment on the operator-managed VPS. PostgreSQL MUST be a managed private database service; application media MUST use the configured production object storage disk (`r2`) and mail MUST use the configured Resend transport when enabled.
#### Scenario: Compose defines required processes
- **WHEN** staging Compose is deployed
- **THEN** it MUST include web, queue worker, scheduler, and a one-shot migrate job using the application image
#### Scenario: Database is not embedded in the application image
- **WHEN** staging boots
- **THEN** PostgreSQL MUST be provided by the Dokploy/database service
- **AND** MUST NOT live inside the application image layers
### Requirement: Staging deploy migrates then proves health with smoke checks
A staging promotion MUST run database migrations against the staging database, wait for `/up` to report healthy, and execute smoke HTTP checks for `/up`, the public home, and `/admin/login` (SPEC §14.3, §15.5, §16.2).
#### Scenario: Unhealthy deploy is not considered successful
- **WHEN** `/up` fails after a staging deploy attempt
- **THEN** the deployment MUST be treated as failed
- **AND** MUST NOT be recorded as a successful Phase 0 exit criterion
#### Scenario: Smoke checks cover public and login surfaces
- **WHEN** staging deploy health succeeds
- **THEN** smoke checks MUST request `/`, `/up`, and `/admin/login`
- **AND** each MUST return HTTP 200
### Requirement: Staging rollback uses the previous image SHA
Rollback SHALL redeploy a previously published SHA-tagged image without rebuilding from source (SPEC §14.3).
#### Scenario: Operator rolls back to previous SHA
- **WHEN** the operator points staging Compose at a previous SHA tag and redeploys
- **THEN** web, queue, and scheduler MUST run that previous image
- **AND** no source rebuild MUST be required

View File

@@ -0,0 +1,41 @@
## 1. Auth and strict types parity
- [ ] 1.1 Add `MustVerifyEmail` to `User` and require verified + active in `canAccessPanel`; update seed so admin/assistant are verified; feature tests for unverified denial and verified access
- [ ] 1.2 Confirm Filament/Laravel password reset is enabled; add feature tests for registered vs unknown email without account enumeration
- [ ] 1.3 Add `declare(strict_types=1);` to project-owned PHP files missing it (e.g. `AdminPanelProvider`); architecture/unit regression as needed
- [ ] 1.4 Run `composer pint`, `composer phpstan`, and `composer test:feature` for auth changes
## 2. Local runtime and PHP 8.4 alignment
- [ ] 2.1 Extend `docker-compose.yml` with FrankenPHP `app` service (build Dockerfile, depend on healthy postgres, publish 8000); document in README
- [ ] 2.2 Align README/docs to PHP 8.4 canonical (keep Composer `^8.3`); verify Dockerfile/CI already on 8.4
- [ ] 2.3 Smoke local compose: `docker compose up -d``GET /up` returns 200
- [ ] 2.4 Run `composer quality` after compose/docs changes
## 3. Quality gates: npm audit and coverage
- [ ] 3.1 Add npm audit step to `composer quality` and CI `static` (policy: production deps; document any allowlist)
- [ ] 3.2 Enable Domain/Application coverage in CI `unit` with 80% fail threshold; exclude views/migrations/framework
- [ ] 3.3 Add/adjust unit tests if current Domain/Application coverage is below threshold
- [ ] 3.4 Verify CI `static` and `unit` fail appropriately on intentional audit/coverage breakage in a branch experiment or equivalent proof
## 4. Staging Compose and Dokploy prep
- [ ] 4.1 Add versioned staging Compose template (web, queue, scheduler, migrate one-shot) parameterized by `APP_IMAGE`/`IMAGE_TAG`
- [ ] 4.2 Document Dokploy project setup: GHCR registry credentials, Postgres service, Compose import, required env vars (APP_KEY, DB, Resend, R2)
- [ ] 4.3 Document rollback procedure: redeploy previous SHA tag without rebuild
## 5. Deploy workflow and smoke
- [ ] 5.1 Create `.github/workflows/deploy-staging.yml` gated on successful CI on `main`: build image, push `ghcr.io/...:<sha>` + `:staging`, trigger Dokploy `compose.deploy`
- [ ] 5.2 Wire migrate-before-serve (Compose migrate service or Dokploy deploy command) and healthcheck on `/up`
- [ ] 5.3 Add post-deploy smoke script/job for `/up`, `/`, `/admin/login` returning 200
- [ ] 5.4 Store secrets only in GitHub/Dokploy; ensure no secrets in image layers (reuse container CI check)
## 6. Phase 0 exit evidence
- [ ] 6.1 Perform first successful staging deploy of a `main` SHA and capture evidence (workflow URL, smoke output)
- [ ] 6.2 Verify rollback to previous SHA works once
- [ ] 6.3 Update `SPEC.md` §18 Fase 0 checkboxes only for items with evidence; note remaining deferred items if any
- [ ] 6.4 Run full `composer quality` and confirm all five CI jobs + staging deploy path green
- [ ] 6.5 Report in SPEC §24 format and mark this change ready to archive after merge

View File

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

View File

@@ -1,124 +0,0 @@
## 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

@@ -1,47 +0,0 @@
## 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

@@ -1,55 +0,0 @@
## 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

@@ -1,28 +0,0 @@
## 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

@@ -1,24 +0,0 @@
## 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

@@ -1,56 +0,0 @@
## 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

@@ -1,42 +0,0 @@
## 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

@@ -1,71 +0,0 @@
## 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)

View File

@@ -1,7 +1,7 @@
# content-media Specification # content-media Specification
## Purpose ## Purpose
Define validation, storage, and accessibility requirements for public content images. Define validation, storage, responsive variants, disk selection, and accessibility requirements for public content images.
## Requirements ## Requirements
### Requirement: Public content images are validated and stored securely ### Requirement: Public content images are validated and stored securely
@@ -34,3 +34,73 @@ The system SHALL validate public content uploads (service covers, portfolio cove
- **WHEN** content with images is persisted - **WHEN** content with images is persisted
- **THEN** only the filesystem path MUST be stored in the database - **THEN** only the filesystem path MUST be stored in the database
- **AND** binary image data MUST NOT be written to PostgreSQL columns - **AND** binary image data MUST NOT be written to PostgreSQL columns
### Requirement: Public images are served in responsive variants
The system SHALL generate or serve responsive variants for public content images (service covers, portfolio covers and gallery, testimonial photos) and reference them with `srcset` and `sizes` so browsers download an appropriately sized file (SPEC §6.4). Variant generation MUST happen on upload, not on each request.
#### Scenario: Variants are produced on upload
- **WHEN** an admin uploads a public content image
- **THEN** responsive variants MUST be generated and stored alongside the original
- **AND** the database MUST keep only paths, never binary data
#### Scenario: Public markup offers multiple sources
- **WHEN** a public page renders a content image
- **THEN** the `img` element MUST expose `srcset` with the available variants
- **AND** MUST expose a `sizes` attribute matching the layout
#### Scenario: Missing variant falls back to the original
- **GIVEN** an image stored before variant generation existed
- **WHEN** it is rendered on a public page
- **THEN** the original file MUST be used without breaking the page
### Requirement: Public images avoid layout shift and defer offscreen loading
Public content images SHALL reserve their space through explicit `width` and `height` (or equivalent aspect-ratio styling) and MUST use `loading="lazy"` when rendered below the fold. Above-the-fold hero imagery MUST NOT be lazy loaded (SPEC §6.4, §6.6).
#### Scenario: Offscreen image is lazy loaded
- **WHEN** a page renders an image below the first viewport
- **THEN** the `img` element MUST carry `loading="lazy"`
#### Scenario: Hero image loads eagerly
- **WHEN** the home hero image is rendered
- **THEN** it MUST NOT carry `loading="lazy"`
#### Scenario: Dimensions are reserved
- **WHEN** any public content image is rendered
- **THEN** width and height (or aspect ratio) MUST be declared so layout does not shift after load
### Requirement: Production images are not served from ephemeral container disk
Public image variants SHALL be stored on the configured filesystem disk (S3-compatible in production) and referenced by URL, so a container restart or redeploy does not lose media (SPEC §6.4).
#### Scenario: Media survives container replacement
- **GIVEN** production uses the S3-compatible disk
- **WHEN** the application container is replaced
- **THEN** previously uploaded images and variants MUST remain reachable
### Requirement: CMS public image uploads select production object storage disk
Public content image uploads (Filament FileUpload via `PublicImageUploadRules`) MUST store files on the disk matching the configured default filesystem (SPEC §6.4). When `FILESYSTEM_DISK` is `r2`, uploads MUST use the `r2` disk. When `FILESYSTEM_DISK` is `s3`, uploads MUST use the `s3` disk. Otherwise uploads MUST use the local `public` disk.
#### Scenario: Production R2 disk is used for CMS uploads
- **WHEN** `FILESYSTEM_DISK=r2`
- **THEN** `PublicImageUploadRules::disk()` MUST return `r2`
#### Scenario: Legacy S3 default still supported
- **WHEN** `FILESYSTEM_DISK=s3`
- **THEN** `PublicImageUploadRules::disk()` MUST return `s3`
#### Scenario: Local development uses public disk
- **WHEN** `FILESYSTEM_DISK` is `local`, unset, or any value other than `r2`/`s3`
- **THEN** `PublicImageUploadRules::disk()` MUST return `public`

View File

@@ -0,0 +1,48 @@
# object-storage Specification
## Purpose
Define Cloudflare R2 as the production S3-compatible filesystem disk for public media.
## Requirements
### Requirement: Cloudflare R2 is available as dedicated filesystem disk
The system SHALL provide an `r2` filesystem disk using Laravel's S3-compatible driver pointed at Cloudflare R2 (SPEC §6.4, §9.1, §15.4). Configuration MUST use explicit `R2_*` environment variables: `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET`, `R2_ENDPOINT`, and `R2_URL`.
#### Scenario: R2 disk is defined in filesystem config
- **WHEN** the application boots
- **THEN** `config('filesystems.disks.r2')` MUST exist
- **AND** the disk driver MUST be `s3`
- **AND** credentials MUST resolve from `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY`
#### Scenario: R2 endpoint uses path-style addressing
- **WHEN** the `r2` disk is configured
- **THEN** `use_path_style_endpoint` MUST be `true`
- **AND** `endpoint` MUST resolve from `R2_ENDPOINT`
#### Scenario: Public URLs use custom domain
- **WHEN** a file is stored on the `r2` disk with public visibility
- **THEN** generated URLs MUST use `R2_URL` as base
- **AND** MUST NOT require signed URLs for browser-facing media
### Requirement: Production default filesystem disk is R2
Production deployments MUST set `FILESYSTEM_DISK=r2` so application code using the default disk stores files on R2.
#### Scenario: Default disk resolves to R2 in production
- **WHEN** `FILESYSTEM_DISK=r2` is set
- **THEN** `config('filesystems.default')` MUST be `r2`
#### Scenario: Local development keeps local disk
- **WHEN** `FILESYSTEM_DISK` is unset or set to `local`/`public` in development
- **THEN** the default disk MUST NOT require R2 credentials to boot
#### Scenario: Tests do not call R2
- **WHEN** the test suite runs
- **THEN** tests MUST use `Storage::fake('r2')` or local fakes
- **AND** no live HTTP request to Cloudflare R2 MUST occur during CI

View File

@@ -0,0 +1,94 @@
# public-seo Specification
## Purpose
Define per-page SEO metadata, Open Graph, sitemap, robots, structured data, and conditional analytics for public routes.
## Requirements
### Requirement: Every public page emits title, description and canonical
The system SHALL render a unique `<title>`, a `<meta name="description">` and a `<link rel="canonical">` on every public route (SPEC §6.6, §19). Portfolio cases MUST use `meta_title`/`meta_description` when filled and fall back to title/summary otherwise. Pages without page-level metadata MUST fall back to `default_meta_title` and `default_meta_description` from `site_settings`.
#### Scenario: Page-level metadata overrides defaults
- **GIVEN** a published case with `meta_title` and `meta_description` filled
- **WHEN** a visitor loads the case detail
- **THEN** the rendered title and description MUST use the case values
#### Scenario: Missing metadata falls back to site defaults
- **GIVEN** a published case without `meta_title`
- **WHEN** a visitor loads the case detail
- **THEN** the rendered title MUST be derived from the case title
- **AND** the description MUST fall back to the case summary or the site default
#### Scenario: Canonical points to the absolute route URL
- **WHEN** any public page is rendered
- **THEN** the canonical URL MUST be the absolute URL of that route without query parameters
### Requirement: Open Graph metadata is emitted for sharing
The system SHALL emit Open Graph tags (`og:title`, `og:description`, `og:type`, `og:url`, `og:image`) on public pages. The image MUST use the page cover image when available and `default_og_image_path` from `site_settings` otherwise.
#### Scenario: Case detail uses its cover as OG image
- **GIVEN** a published case with a cover image
- **WHEN** the case detail is rendered
- **THEN** `og:image` MUST reference the case cover image URL
#### Scenario: Pages without cover use the default OG image
- **WHEN** a page without its own image is rendered
- **THEN** `og:image` MUST reference `default_og_image_path`
### Requirement: Sitemap and robots are served by the application
The system SHALL serve `/sitemap.xml` listing the home, institutional routes, the services listing, the portfolio listing and every published case slug with its last modification date. `/robots.txt` MUST be served by an application route referencing the sitemap URL.
#### Scenario: Sitemap contains only published slugs
- **GIVEN** one published case and one draft case
- **WHEN** `/sitemap.xml` is requested
- **THEN** the response MUST include the published slug
- **AND** MUST NOT include the draft slug
#### Scenario: Newly published case enters the sitemap
- **WHEN** an admin publishes a case
- **THEN** the case slug MUST appear in `/sitemap.xml` on the next request
#### Scenario: Robots references the sitemap
- **WHEN** `/robots.txt` is requested
- **THEN** the response MUST be `text/plain`
- **AND** MUST contain the absolute `/sitemap.xml` URL
### Requirement: Basic structured data is emitted where applicable
The system SHALL emit JSON-LD structured data: `Organization` on the home using `site_settings`, and `Article` or equivalent creative work on the case detail.
#### Scenario: Home exposes organization data
- **WHEN** the home is rendered
- **THEN** a JSON-LD block of type `Organization` MUST be present with brand name and contact data
#### Scenario: Structured data is valid JSON
- **WHEN** any public page emits JSON-LD
- **THEN** the script content MUST parse as valid JSON
### Requirement: Analytics script is injected only when explicitly enabled
The system SHALL render the analytics snippet from `site_settings` only when `analytics_enabled` is true and the script field is non-empty (WEB-06). Analytics MUST be disabled by default.
#### Scenario: Analytics disabled emits nothing
- **GIVEN** `analytics_enabled` is false
- **WHEN** any public page is rendered
- **THEN** the analytics snippet MUST NOT appear in the HTML
#### Scenario: Analytics enabled injects the configured snippet
- **GIVEN** `analytics_enabled` is true and a snippet is configured
- **WHEN** a public page is rendered
- **THEN** the snippet MUST be present exactly once

View File

@@ -0,0 +1,119 @@
# public-site-pages Specification
## Purpose
Define public routes, editorial home, catalog pages, institutional/error pages, and contact placeholder for the marketing site.
## Requirements
### Requirement: Public routes serve published content without authentication
The system SHALL expose the public routes of SPEC §5.1: `home` (`/`), `services.index` (`/servicos`), `portfolio.index` (`/portfolio`), `portfolio.show` (`/portfolio/{slug}`), `about` (`/sobre`), `contact` (`/contato`) and `privacy` (`/privacidade`). Every public route MUST respond without authentication and MUST NOT expose unpublished content, internal fields, or internal notes (SPEC §19).
#### Scenario: Guest reaches every public route
- **WHEN** an unauthenticated visitor requests any public route
- **THEN** the response status MUST be 200
- **AND** no redirect to `/admin/login` MUST occur
#### Scenario: Unpublished content is invisible
- **GIVEN** a service, portfolio case, or testimonial with `published_at` null
- **WHEN** a visitor loads the corresponding public page
- **THEN** the record MUST NOT appear in the rendered output
#### Scenario: Unpublished case detail returns 404
- **GIVEN** a portfolio case saved as draft
- **WHEN** a visitor requests `/portfolio/{slug}` for that case
- **THEN** the response status MUST be 404
#### Scenario: Published case detail becomes reachable
- **GIVEN** a portfolio case saved as draft
- **WHEN** an admin fills the required fields and publishes the case
- **THEN** `/portfolio/{slug}` MUST respond 200
- **AND** the case MUST appear in the `/portfolio` listing
### Requirement: Home renders the editorial structure from CMS content
The home page SHALL render, in the order defined by SPEC §6.2, header/navigation, hero, featured visual proof, services summary, working method, selected cases, testimonials, final briefing CTA, and footer with contact, social links and legal links (WEB-01). Hero copy, brand name and contact data MUST come from `site_settings`; services, cases and testimonials MUST come from published records.
#### Scenario: Published content is displayed in configured order
- **GIVEN** published services, cases and testimonials exist
- **WHEN** a visitor loads the home
- **THEN** the published content MUST be displayed following the `sort_order` and featured flags
- **AND** the hero MUST show the values stored in `site_settings`
#### Scenario: CTA leads to the briefing page
- **WHEN** a visitor activates the primary or final CTA on the home
- **THEN** the visitor MUST be taken to the `contact` route
#### Scenario: Empty content does not break the home
- **GIVEN** no published services, cases or testimonials
- **WHEN** a visitor loads the home
- **THEN** the response MUST be 200
- **AND** the affected sections MUST be omitted instead of rendering empty containers
#### Scenario: Home has no console errors
- **WHEN** the home is loaded in a real browser at desktop and mobile viewports
- **THEN** the browser console MUST contain no JavaScript errors
### Requirement: Listing and detail pages exist for catalog content
The system SHALL render a services listing (WEB-02) and a portfolio listing plus case detail (WEB-03). The case detail MUST present summary, event type, optional city/venue/date, challenge, solution, optional result, cover image and the ordered gallery.
#### Scenario: Services listing shows published services
- **WHEN** a visitor loads `/servicos`
- **THEN** every published service MUST be listed with title and summary in `sort_order`
#### Scenario: Gallery respects stored order
- **GIVEN** a published case with multiple gallery images
- **WHEN** a visitor loads the case detail
- **THEN** the images MUST be rendered ordered by `sort_order`
#### Scenario: Listings paginate open-ended growth
- **WHEN** the number of published cases exceeds the page size
- **THEN** `/portfolio` MUST paginate instead of rendering all records
### Requirement: Institutional and error pages have brand identity
The system SHALL provide the Sobre and Política de privacidade pages and branded error pages (WEB-07). The 404 page MUST use the public layout, and the 500 page MUST NOT expose stack traces or internal details when `APP_DEBUG` is false.
#### Scenario: Unknown URL renders branded 404
- **WHEN** a visitor requests a non-existent public URL
- **THEN** the response status MUST be 404
- **AND** the page MUST use the public layout and offer navigation back to the home
#### Scenario: Server error hides internals in production
- **GIVEN** `APP_DEBUG` is false
- **WHEN** an unhandled exception occurs on a public route
- **THEN** the response MUST be a generic branded error page
- **AND** MUST NOT contain a stack trace, file path, or environment variable
### Requirement: Contact page presents contact data as briefing placeholder
The `contact` route SHALL render the contact page using `site_settings` (e-mail, phone, city, social links) so the home CTA has a valid destination before the briefing form exists. The page MUST NOT create leads in this change.
#### Scenario: Contact page shows configured contact data
- **WHEN** a visitor loads `/contato`
- **THEN** the e-mail and phone stored in `site_settings` MUST be displayed
- **AND** no lead record MUST be created
### Requirement: Public pages avoid N+1 queries
Public pages SHALL load related content with explicit eager loading through dedicated read Queries in the Application layer. Rendering a page MUST NOT issue one query per related record (SPEC §19).
#### Scenario: Case detail loads gallery in bounded queries
- **WHEN** a case detail page with many gallery images is rendered
- **THEN** the gallery MUST be loaded with eager loading
- **AND** the query count MUST NOT grow with the number of images

View File

@@ -1,7 +1,8 @@
# quality-gates Specification # quality-gates Specification
## Purpose ## Purpose
TBD - created by archiving change setup-foundation. Update Purpose after archive. Define Composer quality scripts, architecture boundaries, PostgreSQL-backed feature tests, and the five blocking CI jobs including browser visual and accessibility coverage.
## Requirements ## Requirements
### Requirement: Standardized Composer test scripts exist ### Requirement: Standardized Composer test scripts exist
@@ -52,9 +53,20 @@ The system SHALL configure `phpunit.xml` so that the Feature test suite uses Pos
### Requirement: Browser tests run against FrankenPHP-served application ### 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. The system SHALL execute browser tests using Pest Browser/Playwright against an application served by FrankenPHP in CI. The `browser` job MUST cover the E2E journeys available in the current phase, the visual regression assertions and the automated accessibility checks for public routes, and MUST run in assertion mode without regenerating baselines (SPEC §13.4, §13.5, §13.8, §14.1).
#### Scenario: Browser job validates served application #### Scenario: Browser job validates served application
- **WHEN** the `browser` CI job runs - **WHEN** the `browser` CI job runs
- **THEN** tests execute against the built application artifact or equivalent production-like image - **THEN** tests execute against the built application artifact or equivalent production-like image
#### Scenario: Browser job covers visual and accessibility assertions
- **WHEN** the `browser` CI job runs
- **THEN** it MUST execute the visual regression suite and the accessibility suite
- **AND** a failing snapshot or a critical/serious accessibility issue MUST block merge
#### Scenario: Browser failures publish diagnostics
- **WHEN** a browser test fails in CI
- **THEN** the job MUST publish screenshots, snapshot diffs, application logs and browser logs as artifacts

View File

@@ -0,0 +1,36 @@
# transactional-email Specification
## Purpose
Define Resend as the production transactional mail transport with safe local and test defaults.
## Requirements
### Requirement: Production transactional email uses Resend
The system SHALL support Resend as the production mail transport via Laravel's native `resend` mailer (SPEC §9.1, §15.4). The Resend API key MUST be read from `RESEND_API_KEY` through `config/services.php`. Production deployments MUST set `MAIL_MAILER=resend` when transactional email is enabled.
#### Scenario: Resend mailer is configured
- **WHEN** the application boots with valid configuration
- **THEN** a `resend` mailer MUST exist in `config/mail.php`
- **AND** `config('services.resend.key')` MUST resolve from `RESEND_API_KEY`
#### Scenario: Local development uses safe mail default
- **WHEN** `APP_ENV` is `local` and `MAIL_MAILER` is unset
- **THEN** the default mailer MUST be `log`
- **AND** no outbound email MUST be sent to external providers
#### Scenario: Tests do not call Resend
- **WHEN** the test suite runs
- **THEN** `MAIL_MAILER` MUST be `array` (or tests MUST use `Mail::fake`)
- **AND** no live HTTP request to Resend MUST occur during CI
### Requirement: Global from address is configurable
The system SHALL read the global sender address and name from `MAIL_FROM_ADDRESS` and `MAIL_FROM_NAME` (SPEC §15.4).
#### Scenario: From address applied to outbound mail
- **WHEN** the application sends mail through the configured mailer
- **THEN** the message MUST use the configured from address and name

View File

@@ -0,0 +1,55 @@
# visual-regression Specification
## Purpose
Define deterministic visual baselines for public screens and the explicit baseline update workflow.
## Requirements
### Requirement: Public screens have desktop and mobile visual baselines
The system SHALL keep versioned screenshot baselines for the public screens available in this phase (SPEC §13.5): Home, Serviços, Portfólio and Detalhe do portfólio, at 1440×1000 desktop and 390×844 mobile. A rendering change that alters those screens MUST fail the browser suite until the diff is reviewed.
#### Scenario: Unintended visual change fails the suite
- **GIVEN** approved baselines exist
- **WHEN** a code change alters the rendering of a covered screen
- **THEN** the visual assertion MUST fail and report the diff
#### Scenario: Both viewports are covered
- **WHEN** the visual suite runs
- **THEN** each covered screen MUST be asserted at 1440×1000 and 390×844
### Requirement: Visual runs are deterministic
Visual runs SHALL be deterministic per SPEC §13.5: fixed Chromium and Linux image, fixed viewport, timezone `America/Fortaleza`, locale `pt-BR`, fonts installed in the image, frozen clock, deterministic seed, animations and transitions disabled, and no dependency on external network.
#### Scenario: Repeated run without code change produces no diff
- **WHEN** the visual suite runs twice against the same commit and seed
- **THEN** both runs MUST pass with no pixel diff
#### Scenario: Time-dependent content does not cause drift
- **GIVEN** the clock is frozen and the seed is deterministic
- **WHEN** the suite runs on a different calendar day
- **THEN** rendered dates MUST remain identical to the baseline
#### Scenario: Motion is disabled during capture
- **WHEN** a screenshot is captured
- **THEN** CSS animations and transitions MUST be disabled
### Requirement: Baseline updates are explicit and reviewed
Baselines SHALL only be updated through the explicit `composer visual:update` command, and the resulting diff MUST be reviewed by a human before merge. Baselines MUST NOT be regenerated automatically to make CI pass.
#### Scenario: CI does not regenerate baselines
- **WHEN** the `browser` CI job runs
- **THEN** it MUST run in assertion mode
- **AND** MUST NOT write new baselines
#### Scenario: Developer updates baselines intentionally
- **WHEN** a developer runs `composer visual:update`
- **THEN** the updated baseline files MUST be written to the versioned baseline directory for review

View File

@@ -0,0 +1,72 @@
# web-accessibility Specification
## Purpose
Define automated accessibility checks, semantic structure, keyboard operability, reduced motion, and console hygiene for public routes.
## Requirements
### Requirement: Public routes have no critical or serious accessibility issues
The system SHALL run automated accessibility checks on the public routes covered by the browser suite (SPEC §6.5, §13.8). A critical or serious issue MUST fail the suite.
#### Scenario: Critical issue blocks the suite
- **WHEN** the automated accessibility check reports a critical or serious issue on a covered route
- **THEN** the browser suite MUST fail and report the offending rule and selector
#### Scenario: Covered routes are checked
- **WHEN** the accessibility suite runs
- **THEN** the home, services listing, portfolio listing and case detail MUST each be checked
### Requirement: Public pages use accessible semantic structure
Public pages SHALL provide semantic landmarks, exactly one `h1` per page, a coherent heading order, alt text on every content image, and visible focus on interactive elements (SPEC §6.5).
#### Scenario: Single h1 per page
- **WHEN** any public page is rendered
- **THEN** exactly one `h1` element MUST be present
#### Scenario: Landmarks are present
- **WHEN** any public page is rendered
- **THEN** `header`, `main`, `nav` and `footer` landmarks MUST be present
#### Scenario: Content images expose alt text
- **WHEN** a page renders a cover or gallery image
- **THEN** the `alt` attribute MUST contain the stored alt text
### Requirement: Public pages are fully keyboard operable
Visitors SHALL be able to reach and activate every interactive element with the keyboard, with a visible focus indicator and a skip link to the main content.
#### Scenario: Keyboard reaches the primary CTA
- **WHEN** a visitor navigates the home with the Tab key
- **THEN** the primary CTA MUST receive focus with a visible indicator
- **AND** activating it with the keyboard MUST navigate to the contact route
#### Scenario: Skip link bypasses navigation
- **WHEN** a visitor focuses the first element of a public page
- **THEN** a skip link to the main content MUST be available
### Requirement: Reduced motion preference is honored
The system SHALL suppress non-essential animation and transition when the user agent reports `prefers-reduced-motion: reduce`.
#### Scenario: Reduced motion disables transitions
- **GIVEN** the browser reports `prefers-reduced-motion: reduce`
- **WHEN** a public page is loaded
- **THEN** decorative transitions and animations MUST NOT run
### Requirement: Public pages emit no console errors
Covered public routes SHALL load without JavaScript console errors in a real browser (SPEC §13.8, §19).
#### Scenario: Console stays clean on covered routes
- **WHEN** a covered public route is loaded in the browser suite
- **THEN** the console MUST contain no error-level messages