# The Manifest — Notion × Claude Documentation Pipeline (Tabex)

Automatically generate technical documentation and user-facing release notes
whenever a task in the Tabex Notion **Tasks** database reaches `Dev-Status = Done`.

**The Manifest is a single public site (`/`), no login required.** It only
publishes user-facing release notes. Technical documentation (context, root
cause, fix, QA scenarios) is generated and organized directly in Notion —
inside the dev team's own folders/guidelines — and is never mirrored on the
site. The only password gate left (`MANIFEST_DEV_PASSWORD`) protects the
`/releases/...` admin tooling (sprint release email generation), which is
unrelated to documentation browsing.

## Architecture

```
Notion Webhook (page.properties_updated)
      │  POST /webhooks/notion
      ▼
NotionWebhookController
  └─ verifies HMAC signature (+ subscription verification handshake)
  └─ fetches the task; checks Dev-Status == NOTION_TRIGGER_STATUS ("Done")
  └─ skips if Documentation Status == Generated (idempotent)
  └─ dispatches GenerateDocumentationJob (async)
         │
         ▼
  GenerateDocumentationJob
    ├─ NotionService::getPage()          ← task properties (real Tabex schema)
    ├─ NotionService::getPageContent()   ← task body: relato, análise, correção, QA
    ├─ ClaudeService::generateDocumentation()
    │      └─ Claude API → JSON { technical_doc, user_release_note }  (pt-BR)
    ├─ createPage() → 🔒 Documentação Técnica / <categoria> <task>   (Notion only — not on the site)
    ├─ createPage() → 📖 Release Notes / <categoria> <task>          (feeds the public site)
    └─ updates task: Documentation Status = Generated, Technical Doc, Release Note
```

Docs are categorized automatically from the task properties:

| Categoria | Regra |
|-----------|-------|
| `bug` | Type "Bug 🐞" ou Tipo de Chamado BUG / MISTYPE / CORREÇÃO |
| `project` | Type "Epic ⛰️", Project vinculado ou Tipo de Chamado NEW RELEASE |
| `issue` | Todo o resto (Task 🔨, Small 🤪, MELHORIA...) |

At end of sprint:
```
GET /releases/{sprint}/preview          ← interactive browser preview
php artisan release:generate-email <sprint>
```
The sprint label is matched against the titles in the **Sprints** database
(relation on the task). Claude aggregates every documented task into an HTML
release email grouped by category.

## Setup

### 1. Share the Notion content with the integration

The API key in `.env` belongs to a Notion *internal integration*. In Notion, share with it:
- the **Tasks** database (⋯ → Connections → your integration)
- the **Sprints** database
- the **The Manifest** root page (create it manually — the API cannot create
  workspace-level pages; any location works, e.g. under your team wiki)

### 2. Run the setup command

```bash
php artisan manifest:setup <rootPageId>
```

This creates the two sections under the root page, adds the tracking
properties to the Tasks database (`Documentation Status`, `Technical Doc`,
`Release Note`) and writes all IDs to `.env`:

```
The Manifest (root — created manually)
├── 🔒 Documentação Técnica   ← lives only in Notion, organized by the dev team
└── 📖 Release Notes           ← user docs, feeds the public site
```

### 3. Configure the webhook

Notion integration settings → Webhooks → add
`https://yourdomain.com/webhooks/notion`, event `page.properties_updated`.
The first delivery carries a `verification_token` — it is logged by the app
(`storage/logs/laravel.log`); paste it back in Notion to verify, and set it
as `NOTION_WEBHOOK_SECRET` in `.env`.

### 4. Remaining environment

```
ANTHROPIC_API_KEY=sk-ant-...          # console.anthropic.com
NOTION_TRIGGER_STATUS=Done            # Dev-Status that triggers documentation
MANIFEST_DEV_PASSWORD=...             # gate for /releases/... admin tooling only
```

### 5. Run

```bash
php artisan serve          # the site
php artisan queue:work     # documentation jobs (Claude takes 5–15s)
```

## As skills do processo

| Skill | O que faz | Onde publica |
|-------|-----------|--------------|
| `document-this` | Lê a task no Notion e gera doc técnica + release note (Claude) | — |
| `manifest-it` | Publica a versão do usuário | Site público `/` (sem Notion) |

A doc técnica gerada fica organizada diretamente no Notion (seção 🔒
Documentação Técnica), dentro das pastas e diretrizes do time — não passa
por nenhuma skill de publicação no site.

## Demo / mockup mode

`MANIFEST_DEMO=true` no `.env` renderiza o site inteiro com dados fake
([app/Support/DemoManifest.php](../app/Support/DemoManifest.php)) — sem
precisar de Notion nem Claude. Ideal para apresentações. Desligue depois.
Font Awesome é servido localmente (`public/vendor/fontawesome`) para a demo
funcionar offline.

## Human review gate (Documentation Status)

| Status | Significado | Visível em |
|--------|-------------|------------|
| `Generated` | Rascunho gerado pelo Claude, aguardando revisão humana | Só no Notion (task ainda não publicada) |
| `Published` | Revisado e aprovado por um humano | Site público `/` |

Para publicar: revise a release note gerada e mude `Documentation Status`
para `Published` na task do Notion. Nada gerado por IA vai ao público sem
esse passo.

## The Manifest site

- `/` — public knowledge base. Lists every **Published** task grouped by
  🚀 Novos Projetos / ✨ Melhorias / 🐞 Correções; each card opens the
  user release note rendered from Notion (10 min cache). Public titles come
  from the Release Note page (user-facing), never the internal task name.
- `/porto` — Pátio do Porto: the same documents navigable through the
  Vessel = Sprint / Container = Card metaphor.
- Doc pages are only rendered if they belong to the Release Notes section,
  so technical docs (which live only in Notion) can never be reached
  through the site's routes.

## Release email workflow

```bash
# Browser: preview → regenerate → approve & save to Notion
open http://localhost:8000/releases/Sprint%2030/preview

# CLI
php artisan release:generate-email "Sprint 30" --dry-run --output=preview.html
```

Schedule it in `routes/console.php` with `Schedule::command(...)->lastDayOfMonth('17:00')`.

## Claude model cost guide

| Model                | Best for                          | Cost        |
|----------------------|-----------------------------------|-------------|
| `claude-opus-4-5`    | Highest quality docs, complex bugs| ~$15/Mtok   |
| `claude-sonnet-4-5`  | Good quality, cost-efficient      | ~$3/Mtok    |

Set `ANTHROPIC_MODEL=claude-sonnet-4-5` for day-to-day usage.

## Security notes

- Webhook endpoint is excluded from CSRF protection (external caller);
  HMAC verification uses `hash_equals()` to prevent timing attacks
- Public doc routes validate the page's parent section before rendering
- `/releases/...` (paid Claude calls + Notion writes) is the only part of
  the site behind a password
- API keys are never logged (only status codes and IDs)
- Queue jobs retry up to 3 times; duplicate webhook deliveries are idempotent
