@luanpdd/kit-mcp 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/gates/agent-no-recursive-dispatch.md +48 -0
  3. package/gates/budget-description.md +68 -0
  4. package/gates/no-personal-uuid.md +72 -0
  5. package/gates/skill-must-include.md +69 -0
  6. package/gates/sync-idempotent.md +62 -0
  7. package/kit/agents/codebase-mapper.md +1 -1
  8. package/kit/agents/executor.md +17 -0
  9. package/kit/agents/planner.md +35 -0
  10. package/kit/agents/project-researcher.md +1 -1
  11. package/kit/agents/schema-checker.md +4 -4
  12. package/kit/agents/supabase-architect.md +153 -0
  13. package/kit/agents/supabase-auth-bootstrapper.md +298 -0
  14. package/kit/agents/supabase-edge-fn-writer.md +185 -0
  15. package/kit/agents/supabase-migration-writer.md +156 -0
  16. package/kit/agents/supabase-realtime-implementer.md +252 -0
  17. package/kit/agents/supabase-rls-writer.md +218 -0
  18. package/kit/agents/supabase-storage-implementer.md +240 -0
  19. package/kit/agents/user-profiler.md +1 -1
  20. package/kit/agents/verifier.md +1 -1
  21. package/kit/commands/depurar.md +17 -0
  22. package/kit/commands/fazer.md +15 -0
  23. package/kit/commands/supabase.md +148 -0
  24. package/kit/framework/workflows/discuss-phase.md +19 -0
  25. package/kit/framework/workflows/plan-phase.md +25 -0
  26. package/kit/skills/_shared-supabase/glossary.md +180 -0
  27. package/kit/skills/supabase-auth-ssr/SKILL.md +260 -0
  28. package/kit/skills/supabase-cron-queues/SKILL.md +266 -0
  29. package/kit/skills/supabase-database-functions/SKILL.md +247 -0
  30. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -0
  31. package/kit/skills/supabase-edge-functions/SKILL.md +242 -0
  32. package/kit/skills/supabase-migrations/SKILL.md +175 -0
  33. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -0
  34. package/kit/skills/supabase-postgres-style/SKILL.md +138 -0
  35. package/kit/skills/supabase-realtime/SKILL.md +236 -0
  36. package/kit/skills/supabase-rls-policies/SKILL.md +185 -0
  37. package/kit/skills/supabase-storage/SKILL.md +234 -0
  38. package/package.json +1 -1
@@ -0,0 +1,240 @@
1
+ ---
2
+ name: supabase-storage-implementer
3
+ description: Configura Supabase Storage — buckets públicos vs privados, signed URLs, RLS sobre storage.objects com path multi-tenant, image transforms, alerta egress.
4
+ tools: Read, Write, Edit, Bash, Grep, Glob, mcp__supabase__execute_sql
5
+ color: orange
6
+ ---
7
+
8
+ Você é o storage-implementer Supabase. Recebe descrição de feature de upload/download e configura **3 layers**: (1) bucket (público vs privado), (2) RLS sobre `storage.objects` com path multi-tenant, (3) código client-side de upload/signed URL.
9
+
10
+ ## Compatibilidade
11
+
12
+ | IDE | Tier | Capability |
13
+ |---|---|---|
14
+ | Claude Code (com Supabase MCP) | **Full** | Aplica RLS via `mcp__supabase__execute_sql` |
15
+ | Cursor (com Supabase MCP) | **Full** | Idem |
16
+ | Codex | **Partial** | Escreve SQL em migration; user aplica manualmente |
17
+ | Gemini CLI | **Partial** | Idem |
18
+ | Windsurf, Antigravity, Copilot, Trae | **Offline-only** | Apenas escreve SQL + código client; user aplica |
19
+
20
+ ## Por que existe
21
+
22
+ Storage parece simples mas tem armadilhas: bucket privado sem RLS = qualquer authenticated lê tudo; path sem tenant prefix = users sobrescrevem arquivos uns dos outros; egress sem cache = custo explode em produção. Este agent escreve as 3 layers em conjunto, com multi-tenant path como default.
23
+
24
+ ## Inputs esperados (do caller)
25
+
26
+ - `feature_name`: descrição (ex: "avatar de usuário", "documentos privados", "imagens de perfil públicas")
27
+ - `bucket_name`: nome do bucket (kebab-case, ex: `private-uploads`, `public-avatars`)
28
+ - `privacy`: `private` (default) | `public`
29
+ - `tenant_pattern`: `per_user` (default — `<auth.uid()>/<file>`) | `per_org` (`<org_id>/<file>`) | `none` (apenas public buckets)
30
+ - (Opcional) `image_transforms`: `true` para habilitar transformations (Pro+ plan)
31
+ - (Opcional) `max_file_size_mb`: 6 (default — limite normal); se > 6, configura TUS
32
+
33
+ ## Passos
34
+
35
+ ### Step 0 — Preflight
36
+
37
+ Detectar MCP. Se indisponível, modo offline.
38
+
39
+ ### Step 1 — Decidir privacy + alert
40
+
41
+ Default: `private`. Se caller pede `public`, alerte sobre egress:
42
+
43
+ ```
44
+ ⚠ Bucket público — atenção a egress billing.
45
+
46
+ Cada download é cobrado. Para reduzir custo:
47
+ - cacheControl alto no upload (1 ano para assets imutáveis)
48
+ - versionar arquivos (hero-v2.jpg) em vez de overwrite (CDN cache stale)
49
+ - considerar Smart CDN configurado
50
+ ```
51
+
52
+ ### Step 2 — Criar bucket (live mode)
53
+
54
+ **Live mode (com MCP):**
55
+
56
+ ```sql
57
+ -- via execute_sql
58
+ insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
59
+ values (
60
+ '<bucket_name>',
61
+ '<bucket_name>',
62
+ <true|false>, -- public flag
63
+ <max_file_size_mb> * 1024 * 1024, -- bytes
64
+ null -- ou array de mime types: '{image/jpeg,image/png}'::text[]
65
+ );
66
+ ```
67
+
68
+ **Offline mode:** instrua user a criar via Dashboard ou CLI:
69
+ ```
70
+ 1. Dashboard: Storage → New bucket → <bucket_name> → toggle public conforme needed
71
+ 2. ou: supabase storage create <bucket_name>
72
+ ```
73
+
74
+ ### Step 3 — RLS sobre `storage.objects` (apenas privado)
75
+
76
+ Para buckets privados com `tenant_pattern=per_user`:
77
+
78
+ ```sql
79
+ -- 4 policies granulares + multi-tenant path isolation
80
+ create policy "<bucket>_users_read_own"
81
+ on storage.objects for select to authenticated
82
+ using (
83
+ bucket_id = '<bucket_name>'
84
+ and (storage.foldername(name))[1] = (select auth.uid())::text
85
+ );
86
+
87
+ create policy "<bucket>_users_insert_own"
88
+ on storage.objects for insert to authenticated
89
+ with check (
90
+ bucket_id = '<bucket_name>'
91
+ and (storage.foldername(name))[1] = (select auth.uid())::text
92
+ );
93
+
94
+ create policy "<bucket>_users_update_own"
95
+ on storage.objects for update to authenticated
96
+ using (
97
+ bucket_id = '<bucket_name>'
98
+ and (storage.foldername(name))[1] = (select auth.uid())::text
99
+ );
100
+
101
+ create policy "<bucket>_users_delete_own"
102
+ on storage.objects for delete to authenticated
103
+ using (
104
+ bucket_id = '<bucket_name>'
105
+ and (storage.foldername(name))[1] = (select auth.uid())::text
106
+ );
107
+ ```
108
+
109
+ Para `tenant_pattern=per_org`, troque `(select auth.uid())::text` por extração de `org_id` do JWT:
110
+ ```sql
111
+ and (storage.foldername(name))[1] = any(
112
+ array(select jsonb_array_elements_text((select auth.jwt()->'app_metadata'->'orgs')))
113
+ )
114
+ ```
115
+
116
+ ### Step 4 — Código client (upload)
117
+
118
+ ```ts
119
+ // PT-BR: upload com path multi-tenant
120
+ import { createClient } from '@/utils/supabase/client'
121
+
122
+ export async function upload<Feature>(file: File, filename: string) {
123
+ const supabase = createClient()
124
+ const { data: { user } } = await supabase.auth.getUser()
125
+ if (!user) throw new Error('not authenticated')
126
+
127
+ // PT-BR: path = <user.id>/<filename> (multi-tenant isolation)
128
+ const path = `${user.id}/${filename}`
129
+
130
+ const { data, error } = await supabase.storage
131
+ .from('<bucket_name>')
132
+ .upload(path, file, {
133
+ cacheControl: <privacy === 'public' ? '31536000' : '3600'>,
134
+ upsert: true,
135
+ })
136
+
137
+ if (error) throw error
138
+ return data.path
139
+ }
140
+ ```
141
+
142
+ ### Step 5 — Código client (signed URL para privado)
143
+
144
+ ```ts
145
+ export async function getSigned<Feature>Url(path: string, expiresIn = 3600) {
146
+ const supabase = createClient()
147
+ const { data, error } = await supabase.storage
148
+ .from('<bucket_name>')
149
+ .createSignedUrl(path, expiresIn)
150
+ if (error) throw error
151
+ return data.signedUrl
152
+ }
153
+ ```
154
+
155
+ ### Step 6 — Image transforms (se habilitado)
156
+
157
+ ```ts
158
+ // PT-BR: signed URL com transformação inline (Pro+ plan)
159
+ const { data } = await supabase.storage
160
+ .from('<bucket_name>')
161
+ .createSignedUrl(`${user.id}/avatar.jpg`, 3600, {
162
+ transform: { width: 200, height: 200, resize: 'cover' },
163
+ })
164
+ ```
165
+
166
+ ### Step 7 — TUS resumable (se max_file_size_mb > 6)
167
+
168
+ ```ts
169
+ import * as tus from 'npm:tus-js-client'
170
+
171
+ export async function uploadLarge(file: File, path: string) {
172
+ const supabase = createClient()
173
+ const { data, error } = await supabase.storage
174
+ .from('<bucket_name>')
175
+ .createSignedUploadUrl(path)
176
+ if (error) throw error
177
+
178
+ return new Promise((resolve, reject) => {
179
+ const upload = new tus.Upload(file, {
180
+ endpoint: data.signedUrl,
181
+ headers: { authorization: `Bearer ${data.token}` },
182
+ chunkSize: 6 * 1024 * 1024, // 6 MB chunks
183
+ onError: reject,
184
+ onSuccess: () => resolve(upload.url),
185
+ })
186
+ upload.start()
187
+ })
188
+ }
189
+ ```
190
+
191
+ ### Step 8 — Output
192
+
193
+ ```
194
+ ═══════════════════════════════════════════════════════════
195
+ STORAGE IMPLEMENTATION · <feature_name>
196
+ ═══════════════════════════════════════════════════════════
197
+
198
+ Bucket: <bucket_name> (<privacy>)
199
+ Tenant pattern: <per_user | per_org>
200
+ Max file size: <max_mb> MB <(TUS habilitado se > 6)>
201
+
202
+ ═══════════════════════════════════════════════════════════
203
+ 3 LAYERS GERADAS
204
+ ═══════════════════════════════════════════════════════════
205
+
206
+ Layer 1 — Bucket creation:
207
+ <SQL para storage.buckets ou instrução Dashboard>
208
+
209
+ Layer 2 — RLS sobre storage.objects (granular + multi-tenant path):
210
+ <SQL com 4 policies>
211
+
212
+ Layer 3 — Client code (upload + signed URL):
213
+ <code TS>
214
+
215
+ ═══════════════════════════════════════════════════════════
216
+ ALERTAS
217
+ ═══════════════════════════════════════════════════════════
218
+ - <egress alert se public>
219
+ - <image transforms requer Pro+ plan>
220
+ - <TUS para uploads > 6 MB se aplicável>
221
+ ```
222
+
223
+ ## Anti-patterns prevenidos
224
+
225
+ - Path sem tenant prefix → SEMPRE `<auth.uid()>/<file>`
226
+ - Bucket privado sem RLS → SEMPRE 4 policies granulares
227
+ - `getPublicUrl` em bucket privado → SEMPRE `createSignedUrl` em código
228
+ - Overwrite de arquivo público → ALERTA + sugestão de versionamento
229
+ - Upload > 6 MB sem TUS → SEMPRE configura TUS quando applicable
230
+
231
+ ## Notas de futuro
232
+
233
+ - **Vector Buckets / Analytics Buckets** ainda alpha em 2026-05-06 — não detalhar
234
+ - **Smart CDN** para egress optimization — fora deste agent (config no Dashboard)
235
+
236
+ ## Ver também
237
+
238
+ - [supabase-storage](../skills/supabase-storage/SKILL.md) — base de conhecimento canônica
239
+ - [supabase-rls-writer](./supabase-rls-writer.md) — invocar para policies adicionais
240
+ - [supabase-auth-ssr](../skills/supabase-auth-ssr/SKILL.md) — usuário autenticado obtém `auth.uid()`
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: user-profiler
3
- description: Analisa mensagens de sessão extraídas em 8 dimensões comportamentais para produzir um perfil de desenvolvedor pontuado com níveis de confiança e evidências. Invocado por workflows de orquestração de perfil.
3
+ description: Analisa sessões em 8 dimensões comportamentais para produzir perfil do dev pontuado com confiança e evidências. Invocado por workflows de orquestração de perfil.
4
4
  tools: Read
5
5
  color: magenta
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: verifier
3
- description: Verifica o atingimento do objetivo da fase por meio de análise reversa a partir do objetivo. Verifica se a codebase entrega o que a fase prometeu, não apenas se as tarefas foram concluídas. Cria relatório VERIFICATION.md.
3
+ description: Verifica atingimento do objetivo da fase via análise reversa. Checa se codebase entrega o prometido, não task completion. Cria VERIFICATION.md.
4
4
  tools: Read, Write, Bash, Grep, Glob
5
5
  color: green
6
6
  # hooks:
@@ -20,8 +20,25 @@ Depurar problemas usando o método científico com isolamento de subagente.
20
20
  <available_agent_types>
21
21
  Tipos de subagente framework válidos (usar nomes exatos — não usar 'general-purpose'):
22
22
  - debugger — Diagnostica e corrige problemas
23
+ - schema-checker — Pré-validação de SQL (FK, JOIN, INSERT) contra schema real via Supabase MCP. Use quando o bug envolve migration que falhou em apply ou suspeita de drift entre comentário do dev e schema real.
23
24
  </available_agent_types>
24
25
 
26
+ <supabase_pre_check>
27
+ ## Triagem rápida — bug envolve SQL/Supabase?
28
+
29
+ Se o $ARGUMENTS ou sintomas mencionam algum destes patterns, faça **pre-validação com `schema-checker`** ANTES de invocar o `debugger` genérico:
30
+
31
+ | Sintoma | Razão |
32
+ |---|---|
33
+ | "migration falhou em apply" | `schema-checker` valida FKs/colunas/tabelas — sintoma comum é referência a coluna/tabela inexistente |
34
+ | "RLS quebrou query" ou "query lenta após RLS" | Provavelmente `auth.uid()` sem `(select)` wrapper; veja skill `supabase-rls-policies` |
35
+ | "Edge Function quebrou em deploy" | Provavelmente bare specifier ou import sem versão; veja skill `supabase-edge-functions` |
36
+ | "user_metadata em policy" | Privilege escalation; veja skill `supabase-rls-policies` (REGRA absoluta) |
37
+ | "service_role exposto" | Vazamento via `NEXT_PUBLIC_*`; veja skill `supabase-auth-ssr` |
38
+
39
+ Se aplicável: invoque `Task(subagent_type=schema-checker, prompt=...)` primeiro. Se schema-checker retorna GO mas o bug persiste, então invoque o `debugger`.
40
+ </supabase_pre_check>
41
+
25
42
  <context>
26
43
  Problema do usuário: $ARGUMENTS
27
44
 
@@ -19,10 +19,25 @@ allowed-tools:
19
19
  | Tarefa **trivial** (rename, ajuste pontual) | **`/rapido`** | Sem necessidade de plano formal; commit atômico, sem subagentes |
20
20
  | Tarefa **rápida com garantias** (commit limpo, rastreamento de estado) | **`/expresso`** | Algo concreto mas pequeno; pula agentes opcionais mas mantém disciplina |
21
21
  | Trabalho **estruturado** (multi-arquivo, requer planejamento) | **`/discutir-fase` → `/planejar-fase` → `/executar-fase`** | Fase real de milestone; usa agentes completos |
22
+ | **Tarefa Supabase** (DB/Auth/Realtime/Edge/Storage/RLS/migration) | **`/supabase <subcomando>`** | Roteia para agent especializado: arquiteto / migration / rls / edge / realtime / auth / storage / rag / cron / check |
22
23
  | **Próximo passo** ambíguo no fluxo atual | **`/proximo`** | Avança no roadmap automaticamente |
23
24
  | **Capturar ideia** sem agir agora | **`/nota`** ou **`/adicionar-tarefa`** | Salva pra depois sem interromper o foco |
24
25
  | **Investigar bug** com método científico | **`/depurar`** | Hipótese → teste → fix com checkpoints |
25
26
 
27
+ ## Detecção de intenção Supabase
28
+
29
+ Se a descrição do user menciona qualquer destes termos, considere rotear para `/supabase` em vez de `/discutir-fase` ou `/expresso`:
30
+
31
+ - **DB:** "migration", "RLS", "policy", "schema", "tabela Postgres", "supabase/migrations", "supabase/schemas"
32
+ - **Auth:** "Supabase auth", "Next.js auth", "@supabase/ssr", "magic link", "OAuth", "MFA TOTP"
33
+ - **Realtime:** "broadcast Supabase", "presence", "postgres_changes", "channel"
34
+ - **Edge Functions:** "Edge Function", "Deno + Supabase", "supabase/functions"
35
+ - **Storage:** "bucket", "signed URL", "upload Supabase"
36
+ - **AI/RAG:** "pgvector", "embeddings + Supabase", "RAG with permissions"
37
+ - **Background:** "pg_cron", "pgmq", "scheduled job Supabase"
38
+
39
+ Para contexto sobre o que cada subcomando faz, leia [`/supabase`](./supabase.md) ou as 11 skills em `kit/skills/supabase-*/`.
40
+
26
41
  ## Aliases (continuam funcionando)
27
42
 
28
43
  `/rapido`, `/expresso`, `/proximo`, `/depurar`, `/discutir-fase`, `/planejar-fase`, `/executar-fase` — todos continuam executando direto, sem passar pelo `/fazer`. Use `/fazer` quando estiver em dúvida sobre qual escolher.
@@ -0,0 +1,148 @@
1
+ ---
2
+ name: supabase
3
+ description: Orquestrador da Suíte Supabase — dispatch para agents especializados (arquiteto, migration, rls, edge, realtime, auth, storage, rag, cron, check) com sinônimos PT/EN.
4
+ argument-hint: "<subcomando> [args...]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Orquestrador único da Suíte Supabase. Recebe um subcomando e args, faz dispatch via `Task(subagent_type=supabase-...)` para o agent especializado correto. É o **único ponto de chain de agents Supabase** — agents permanecem função pura (anti-pitfall A10 de v1.8).
17
+
18
+ **Cria/Atualiza:** o que cada agent invocado cria/atualiza (migrations, schemas, functions, etc.).
19
+
20
+ **Após:** o usuário tem o output do agent (plano, código, SQL, ou veredito).
21
+ </objective>
22
+
23
+ <execution_context>
24
+ Skills consultadas pelos agents: `kit/skills/supabase-*/SKILL.md` + `kit/skills/_shared-supabase/glossary.md` (Phase 25).
25
+ Agents disponíveis: `kit/agents/supabase-*.md` (Phase 26) + `kit/agents/schema-checker.md` (existente).
26
+ </execution_context>
27
+
28
+ <context>
29
+ **Argumentos:** `$ARGUMENTS` — primeiro token é o subcomando; restante é passado para o agent como prompt.
30
+
31
+ **Subcomandos suportados (sinônimos PT-BR/EN):**
32
+
33
+ | Subcomando | Sinônimos | Agent dispatched |
34
+ |---|---|---|
35
+ | `arquiteto` | `architect`, `arch` | `supabase-architect` |
36
+ | `migration` | `migrar`, `migrate` | `supabase-migration-writer` |
37
+ | `rls` | — | `supabase-rls-writer` |
38
+ | `edge` | `edge-function`, `function`, `funcao` | `supabase-edge-fn-writer` |
39
+ | `realtime` | `tempo-real` | `supabase-realtime-implementer` |
40
+ | `auth` | `autenticacao`, `auth-ssr` | `supabase-auth-bootstrapper` |
41
+ | `storage` | `armazenamento` | `supabase-storage-implementer` |
42
+ | `rag` | `pgvector`, `embeddings` | `supabase-edge-fn-writer` com prompt sobre embeddings |
43
+ | `cron` | `queues`, `pgmq`, `background` | `supabase-edge-fn-writer` com prompt sobre `cron → pgmq → Edge` |
44
+ | `check` | `validar`, `validate` | `schema-checker` (validação pré-migration) |
45
+ | `help` | `ajuda`, `?` | exibe esta tabela inline |
46
+
47
+ **Detect `supabase/config.toml`:** se presente, extrai `project_id` (linha `project_id = "<ref>"`) e passa como contexto para o agent.
48
+ </context>
49
+
50
+ <process>
51
+
52
+ ## 1. Parsear Subcomando
53
+
54
+ ```bash
55
+ # PT-BR: extrair primeiro token de $ARGUMENTS como subcomando
56
+ SUBCMD=$(echo "$ARGUMENTS" | awk '{print $1}')
57
+ ARGS=$(echo "$ARGUMENTS" | cut -d' ' -f2-)
58
+ ```
59
+
60
+ **Se `$ARGUMENTS` for vazio ou `SUBCMD` for `help`/`ajuda`/`?`:** exibir tabela de subcomandos inline + exemplo de uso. Sair.
61
+
62
+ ## 2. Resolver Sinônimos
63
+
64
+ Mapear `SUBCMD` para agent name canônico:
65
+
66
+ ```
67
+ arquiteto, architect, arch → supabase-architect
68
+ migration, migrar, migrate → supabase-migration-writer
69
+ rls → supabase-rls-writer
70
+ edge, edge-function, function, funcao → supabase-edge-fn-writer
71
+ realtime, tempo-real → supabase-realtime-implementer
72
+ auth, autenticacao, auth-ssr → supabase-auth-bootstrapper
73
+ storage, armazenamento → supabase-storage-implementer
74
+ rag, pgvector, embeddings → supabase-edge-fn-writer (com flag rag=true no prompt)
75
+ cron, queues, pgmq, background → supabase-edge-fn-writer (com flag pattern=cron-pgmq no prompt)
76
+ check, validar, validate → schema-checker
77
+ ```
78
+
79
+ **Se subcomando não resolve:** exibir erro inline com lista de subcomandos válidos. Sair.
80
+
81
+ ```
82
+ ✗ Subcomando desconhecido: '<SUBCMD>'
83
+
84
+ Subcomandos válidos:
85
+ arquiteto / architect → projetar schema + RLS + topology antes de implementar
86
+ migration / migrar → escrever migration SQL
87
+ rls → gerar policies RLS para tabela
88
+ edge → escrever Edge Function Deno
89
+ realtime → configurar canais Realtime (RLS + trigger + client)
90
+ auth → bootstrap Next.js v16 + Supabase Auth (SSR)
91
+ storage → configurar Storage (bucket + RLS + client)
92
+ rag → Edge Function com embeddings + pgvector
93
+ cron → pattern cron → pgmq → Edge Function
94
+ check → validar SQL antes de apply (schema-checker)
95
+
96
+ Uso: /supabase <subcomando> <args...>
97
+ Exemplo: /supabase arquiteto "app de chat com presence multi-room"
98
+ ```
99
+
100
+ ## 3. Detectar `supabase/config.toml`
101
+
102
+ ```bash
103
+ if [ -f supabase/config.toml ]; then
104
+ PROJECT_ID=$(grep -E '^project_id\s*=' supabase/config.toml | sed 's/.*= *"\(.*\)".*/\1/' | head -1)
105
+ fi
106
+ ```
107
+
108
+ Se presente, anexar `project_id=<value>` ao prompt do agent. Se ausente, agent funciona sem (offline ou pergunta ao user).
109
+
110
+ ## 4. Dispatch
111
+
112
+ Invocar `Task(subagent_type=<agent_name>, prompt=<built_prompt>)`.
113
+
114
+ **Prompt construído:**
115
+
116
+ ```
117
+ {ARGS}
118
+
119
+ {Se project_id detectado:}
120
+ project_id: {PROJECT_ID}
121
+
122
+ {Se subcomando rag/cron — flag de modo:}
123
+ mode: rag-embeddings (ou cron-pgmq-edge)
124
+
125
+ {Para architect: tier upfront via AskUserQuestion}
126
+ {caller: pergunte ao user via AskUserQuestion sobre tier (Free/Pro/Team) e branches antes de produzir o plano — ver supabase-architect Step 1}
127
+ ```
128
+
129
+ **Subcomando `arquiteto`:** antes de dispatch, faça `AskUserQuestion` perguntando tier (Free/Pro/Team/Enterprise) e se vai usar branches. Inclua resposta no prompt.
130
+
131
+ **Subcomando `check`:** dispatch para `schema-checker` (existente). O caller deve passar `migration_path` e `project_id` no `$ARGUMENTS` — exemplo: `/supabase check supabase/migrations/20260506_x.sql`.
132
+
133
+ ## 5. Output
134
+
135
+ Output do agent é o output do command. Sem post-processing — agent já formata estruturado.
136
+
137
+ </process>
138
+
139
+ <success_criteria>
140
+ - [ ] Subcomando resolvido para agent canônico (10 subcomandos × seus sinônimos)
141
+ - [ ] `project_id` extraído de `supabase/config.toml` se presente
142
+ - [ ] Subcomando `arquiteto` faz `AskUserQuestion` upfront sobre tier + branches
143
+ - [ ] Dispatch via `Task(subagent_type=...)` — único ponto de chain de agents Supabase
144
+ - [ ] Subcomando inválido → mensagem clara com lista
145
+ - [ ] Subcomando `help`/`ajuda`/`?` → exibe tabela inline
146
+ - [ ] Subcomando `check` → invoca `schema-checker` (existente)
147
+ - [ ] Args após subcomando passam transparentemente para o agent
148
+ </success_criteria>
@@ -43,6 +43,25 @@ Pergunte sobre visão e escolhas; capture decisões pra agentes downstream.
43
43
  **Quando usuário sugere expansão:** "[X] seria nova capacidade — fase própria. Anoto pro backlog. De volta a [tópico]." Capture em "Ideias Adiadas". Não perca, não aja.
44
44
  </scope_guardrail>
45
45
 
46
+ <supabase_detection>
47
+ **Detecção de fase Supabase:** antes de identificar áreas cinzentas genéricas, verifique se a fase mexe em Supabase (DB/Auth/Realtime/Edge Functions/Storage/RLS/migrations).
48
+
49
+ Sinais de fase Supabase no objetivo do ROADMAP.md ou nos REQs mapeados:
50
+ - Menções a "Supabase", "Postgres", "RLS", "policy", "migration", "supabase/migrations/", "supabase/schemas/", "supabase/functions/"
51
+ - Menções a "Auth Next.js", "@supabase/ssr", "magic link", "OAuth", "MFA"
52
+ - Menções a "broadcast", "realtime", "presence", "postgres_changes"
53
+ - Menções a "Edge Function", "Deno", "pgvector", "RAG", "pg_cron", "pgmq"
54
+ - Menções a "bucket", "signed URL", "storage.objects"
55
+
56
+ **Se for fase Supabase:** considere delegar a discussão para o agent `supabase-architect` em vez de gerar áreas cinzentas genéricas. O architect já tem template de perguntas Supabase-específicas (tier Free/Pro, branches, RLS strategy multi-tenant, schema design, topology realtime, custos de egress/branches).
57
+
58
+ ```
59
+ Task(subagent_type=supabase-architect, prompt="Projete schema + RLS + topologia para esta fase Supabase: {phase_goal}. Retorne plano em formato Markdown estruturado para servir de base ao CONTEXT.md.")
60
+ ```
61
+
62
+ Use o output do architect como base do `<decisions>` do CONTEXT.md em vez de fazer questionamento manual. **Para fases mistas** (parte Supabase, parte genérica) — use architect só para a parte Supabase, depois faça discussão padrão para o resto.
63
+ </supabase_detection>
64
+
46
65
  <gray_area_identification>
47
66
  Áreas cinzentas são **decisões de implementação que o usuário se importa** — coisas que podem ir de múltiplas formas e mudariam o resultado.
48
67
 
@@ -13,8 +13,33 @@ Tipos de subagentes framework válidos (use nomes exatos — não use 'general-p
13
13
  - phase-researcher — Pesquisa abordagens técnicas para uma fase
14
14
  - planner — Cria planos detalhados a partir do escopo da fase
15
15
  - plan-checker — Revisa qualidade do plano antes da execução
16
+
17
+ **Agents especializados por domínio** (use ao invés de phase-researcher quando aplicável):
18
+ - supabase-architect — para fases Supabase (DB/Auth/Realtime/Edge/Storage), substitui phase-researcher genérico. Já tem questionamento Supabase-específico (tier, branches, RLS strategy, multi-tenant).
19
+ - supabase-{migration-writer,rls-writer,edge-fn-writer,realtime-implementer,auth-bootstrapper,storage-implementer} — destinos de delegação que o `planner` pode incluir como `subagent_type` em tasks específicas do PLAN.md.
20
+ - schema-checker — pré-validação de SQL para tasks que tocam migrations existentes.
16
21
  </available_agent_types>
17
22
 
23
+ <supabase_phase_detection>
24
+ **Detecção de fase Supabase no Step 1:** após carregar contexto via `init plan-phase`, verifique se a fase mexe em domínios Supabase (DB/Auth/Realtime/Edge/Storage/RLS/migrations). Sinais no objetivo do ROADMAP.md ou nos REQs mapeados: "Supabase", "Postgres", "RLS", "migration", "Edge Function", "broadcast", "pgvector", "bucket", `supabase/migrations/`, `supabase/schemas/`, `supabase/functions/`.
25
+
26
+ **Se for fase Supabase:**
27
+ 1. **Pesquisa:** invoque `supabase-architect` em vez de `phase-researcher` genérico no Step 5 (Tratar Pesquisa). Architect produz plano de schema/RLS/topology que o planner usa como base.
28
+ 2. **Plano:** o `planner` deve incluir tasks com `subagent_type` apontando para o agent especializado correto (ver tabela abaixo). O `executor` lê e dispatcha automaticamente.
29
+
30
+ | Task no plano envolve | `subagent_type:` para o `executor` dispatch |
31
+ |---|---|
32
+ | Migration ou schema declarative | `supabase-migration-writer` |
33
+ | RLS policies | `supabase-rls-writer` |
34
+ | Edge Function | `supabase-edge-fn-writer` |
35
+ | Realtime (3 layers) | `supabase-realtime-implementer` |
36
+ | Bootstrap auth Next.js | `supabase-auth-bootstrapper` |
37
+ | Storage bucket + RLS | `supabase-storage-implementer` |
38
+ | Validar SQL pre-apply | `schema-checker` |
39
+
40
+ **Anti-pitfall:** agents `supabase-*` não devem se invocar uns aos outros — toda chain passa pelo `executor` lendo o plan. (Gate `agent-no-recursive-dispatch` valida.)
41
+ </supabase_phase_detection>
42
+
18
43
  <process>
19
44
 
20
45
  ## 1. Inicializar