@luanpdd/kit-mcp 1.6.1 → 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 (58) hide show
  1. package/CHANGELOG.md +126 -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/advisor-researcher.md +1 -14
  8. package/kit/agents/assumptions-analyzer.md +1 -14
  9. package/kit/agents/codebase-mapper.md +2 -15
  10. package/kit/agents/debugger.md +1 -19
  11. package/kit/agents/executor.md +18 -18
  12. package/kit/agents/integration-checker.md +1 -16
  13. package/kit/agents/nyquist-auditor.md +1 -16
  14. package/kit/agents/phase-researcher.md +1 -14
  15. package/kit/agents/plan-checker.md +1 -16
  16. package/kit/agents/planner.md +36 -16
  17. package/kit/agents/project-researcher.md +2 -15
  18. package/kit/agents/research-synthesizer.md +1 -9
  19. package/kit/agents/roadmapper.md +1 -14
  20. package/kit/agents/schema-checker.md +4 -4
  21. package/kit/agents/supabase-architect.md +153 -0
  22. package/kit/agents/supabase-auth-bootstrapper.md +298 -0
  23. package/kit/agents/supabase-edge-fn-writer.md +185 -0
  24. package/kit/agents/supabase-migration-writer.md +156 -0
  25. package/kit/agents/supabase-realtime-implementer.md +252 -0
  26. package/kit/agents/supabase-rls-writer.md +218 -0
  27. package/kit/agents/supabase-storage-implementer.md +240 -0
  28. package/kit/agents/ui-auditor.md +1 -16
  29. package/kit/agents/ui-checker.md +1 -16
  30. package/kit/agents/ui-researcher.md +1 -14
  31. package/kit/agents/user-profiler.md +2 -10
  32. package/kit/agents/verifier.md +2 -17
  33. package/kit/commands/depurar.md +17 -0
  34. package/kit/commands/expresso.md +9 -0
  35. package/kit/commands/fazer.md +32 -4
  36. package/kit/commands/proximo.md +7 -0
  37. package/kit/commands/rapido.md +6 -0
  38. package/kit/commands/supabase.md +148 -0
  39. package/kit/framework/references/output-style.md +22 -0
  40. package/kit/framework/workflows/discuss-phase.md +62 -327
  41. package/kit/framework/workflows/help.md +14 -1
  42. package/kit/framework/workflows/new-project.md +16 -107
  43. package/kit/framework/workflows/plan-phase.md +53 -147
  44. package/kit/skills/_shared-supabase/glossary.md +180 -0
  45. package/kit/skills/supabase-auth-ssr/SKILL.md +260 -0
  46. package/kit/skills/supabase-cron-queues/SKILL.md +266 -0
  47. package/kit/skills/supabase-database-functions/SKILL.md +247 -0
  48. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -0
  49. package/kit/skills/supabase-edge-functions/SKILL.md +242 -0
  50. package/kit/skills/supabase-migrations/SKILL.md +175 -0
  51. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -0
  52. package/kit/skills/supabase-postgres-style/SKILL.md +138 -0
  53. package/kit/skills/supabase-realtime/SKILL.md +236 -0
  54. package/kit/skills/supabase-rls-policies/SKILL.md +185 -0
  55. package/kit/skills/supabase-storage/SKILL.md +234 -0
  56. package/package.json +1 -1
  57. package/src/core/kit.js +55 -22
  58. package/src/core/sync.js +3 -1
@@ -210,69 +210,21 @@ Proceed to Step 4 (skip Steps 3 and 5).
210
210
 
211
211
  ## 3. Deep Questioning
212
212
 
213
- **If auto mode:** Skip (already handled in Step 2a). Extract project context from provided document instead and proceed to Step 4.
213
+ **Auto mode:** pular (handled em 2a) extrair contexto do documento e ir pra passo 4.
214
214
 
215
- **Display stage banner:**
215
+ **Banner:** `framework ► QUESTIONING`.
216
216
 
217
- ```
218
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
219
- framework ► QUESTIONING
220
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
221
- ```
222
-
223
- **Open the conversation:**
224
-
225
- Ask inline (freeform, NOT AskUserQuestion):
226
-
227
- "What do you want to build?"
228
-
229
- Wait for their response. This gives you the context needed to ask intelligent follow-up questions.
230
-
231
- **Research-before-questions mode:** Check if `workflow.research_before_questions` is enabled in `.planning/config.json` (or the config from init context). When enabled, before asking follow-up questions about a topic area:
232
-
233
- 1. Do a brief web search for best practices related to what the user described
234
- 2. Mention key findings naturally as you ask questions (e.g., "Most projects like this use X — is that what you're thinking, or something different?")
235
- 3. This makes questions more informed without changing the conversational flow
236
-
237
- When disabled (default), ask questions directly as before.
238
-
239
- **Follow the thread:**
240
-
241
- Based on what they said, ask follow-up questions that dig into their response. Use AskUserQuestion with options that probe what they mentioned — interpretations, clarifications, concrete examples.
242
-
243
- Keep following threads. Each answer opens new threads to explore. Ask about:
244
-
245
- - What excited them
246
- - What problem sparked this
247
- - What they mean by vague terms
248
- - What it would actually look like
249
- - What's already decided
250
-
251
- Consult `questioning.md` for techniques:
217
+ **Abrir:** pergunta inline freeform (NÃO AskUserQuestion): "What do you want to build?". Aguardar resposta.
252
218
 
253
- - Challenge vagueness
254
- - Make abstract concrete
255
- - Surface assumptions
256
- - Find edges
257
- - Reveal motivation
219
+ **Modo `workflow.research_before_questions`:** se enabled, antes de follow-ups numa área, fazer breve web search por melhores práticas e mencionar findings naturalmente ("Most projects like this use X — is that what you're thinking?"). Default off, perguntar direto.
258
220
 
259
- **Check context (background, not out loud):**
221
+ **Follow the thread:** AskUserQuestion com options que provocam interpretações/clarificações/exemplos. Cada resposta abre novos threads. Cobrir: o que empolgou, problema que sparkou, termos vagos, como seria na prática, o que já está decidido.
260
222
 
261
- As you go, mentally check the context checklist from `questioning.md`. If gaps remain, weave questions naturally. Don't suddenly switch to checklist mode.
223
+ **Técnicas de `questioning.md`:** challenge vagueness, concretize abstract, surface assumptions, find edges, reveal motivation.
262
224
 
263
- **Decision gate:**
225
+ Mentalmente validar checklist do `questioning.md`; se gaps, tecer perguntas naturalmente (não modo checklist).
264
226
 
265
- When you could write a clear PROJECT.md, use AskUserQuestion:
266
-
267
- - header: "Ready?"
268
- - question: "I think I understand what you're after. Ready to create PROJECT.md?"
269
- - options:
270
- - "Create PROJECT.md" — Let's move forward
271
- - "Keep exploring" — I want to share more / ask me more
272
-
273
- If "Keep exploring" — ask what they want to add, or identify gaps and probe naturally.
274
-
275
- Loop until "Create PROJECT.md" selected.
227
+ **Decision gate:** quando puder escrever PROJECT.md claro, AskUserQuestion `Ready?` — "Create PROJECT.md" ou "Keep exploring". Loop até "Create".
276
228
 
277
229
  ## 4. Write PROJECT.md
278
230
 
@@ -449,60 +401,17 @@ questions: [
449
401
  ]
450
402
  ```
451
403
 
452
- **Round 2 — Workflow agents:**
404
+ **Round 2 — Workflow agents (opt-in, adicionam tokens/tempo, melhoram qualidade):**
453
405
 
454
- These spawn additional agents during planning/execution. They add tokens and time but improve quality.
406
+ | Agent | Quando | O que faz |
407
+ |---|---|---|
408
+ | Researcher | Antes de cada plan-phase | Investiga domínio, padrões, pitfalls |
409
+ | Plan Checker | Após plano criado | Verifica se plano atinge o goal |
410
+ | Verifier | Após execução | Confirma must-haves entregues |
455
411
 
456
- | Agent | When it runs | What it does |
457
- |-------|--------------|--------------|
458
- | **Researcher** | Before planning each phase | Investigates domain, finds patterns, surfaces gotchas |
459
- | **Plan Checker** | After plan is created | Verifies plan actually achieves the phase goal |
460
- | **Verifier** | After phase execution | Confirms must-haves were delivered |
412
+ Todos recomendados pra projetos sérios; pular pra experimentos rápidos.
461
413
 
462
- All recommended for important projects. Skip for quick experiments.
463
-
464
- ```
465
- questions: [
466
- {
467
- header: "Research",
468
- question: "Research before planning each phase? (adds tokens/time)",
469
- multiSelect: false,
470
- options: [
471
- { label: "Yes (Recommended)", description: "Investigate domain, find patterns, surface gotchas" },
472
- { label: "No", description: "Plan directly from requirements" }
473
- ]
474
- },
475
- {
476
- header: "Plan Check",
477
- question: "Verify plans will achieve their goals? (adds tokens/time)",
478
- multiSelect: false,
479
- options: [
480
- { label: "Yes (Recommended)", description: "Catch gaps before execution starts" },
481
- { label: "No", description: "Execute plans without verification" }
482
- ]
483
- },
484
- {
485
- header: "Verifier",
486
- question: "Verify work satisfies requirements after each phase? (adds tokens/time)",
487
- multiSelect: false,
488
- options: [
489
- { label: "Yes (Recommended)", description: "Confirm deliverables match phase goals" },
490
- { label: "No", description: "Trust execution, skip verification" }
491
- ]
492
- },
493
- {
494
- header: "AI Models",
495
- question: "Which AI models for planning agents?",
496
- multiSelect: false,
497
- options: [
498
- { label: "Balanced (Recommended)", description: "Sonnet for most agents — good quality/cost ratio" },
499
- { label: "Quality", description: "Opus for research/roadmap — higher cost, deeper analysis" },
500
- { label: "Budget", description: "Haiku where possible — fastest, lowest cost" },
501
- { label: "Inherit", description: "Use the current session model for all agents (OpenCode /model)" }
502
- ]
503
- }
504
- ]
505
- ```
414
+ AskUserQuestion: 4 perguntas `Research` (yes/no), `Plan Check` (yes/no), `Verifier` (yes/no), `AI Models` (Balanced=Sonnet recomendado / Quality=Opus / Budget=Haiku / Inherit=session model).
506
415
 
507
416
  Create `.planning/config.json` with all settings (CLI fills in remaining defaults automatically):
508
417
 
@@ -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
@@ -234,43 +259,15 @@ Se "Executar discuss-phase primeiro":
234
259
 
235
260
  ## 5. Tratar Pesquisa
236
261
 
237
- **Pular se:** flag `--gaps` ou flag `--skip-research` ou flag `--reviews`.
238
-
239
- **Se `has_research` for true (do init) E sem flag `--research`:** Usar existente, pular para o passo 6.
240
-
241
- **Se RESEARCH.md ausente OU flag `--research`:**
242
-
243
- **Se sem flag explícita (`--research` ou `--skip-research`) e não `--auto`:**
244
- Perguntar ao usuário se deseja pesquisar, com uma recomendação contextual baseada na fase:
262
+ **Pular se:** `--gaps`, `--skip-research`, ou `--reviews`.
245
263
 
246
- Se `TEXT_MODE` for true, apresentar como lista numerada de texto simples:
247
- ```
248
- Pesquisar antes de planejar a Fase {X}: {phase_name}?
264
+ **Se `has_research` true e sem `--research`:** usar existente, ir pra passo 6.
249
265
 
250
- 1. Pesquisar primeiro (Recomendado) Investigar domínio, padrões e dependências antes do planejamento. Melhor para novas funcionalidades, integrações desconhecidas ou mudanças arquiteturais.
251
- 2. Pular pesquisaPlanejar diretamente a partir do contexto e requisitos. Melhor para correções de bugs, refatorações simples ou tarefas bem compreendidas.
252
-
253
- Digite o número:
254
- ```
266
+ **Se ausente OR `--research`:** sem flag explícita e sem `--auto`, perguntar (AskUserQuestion ou lista numerada se TEXT_MODE):
267
+ - "Pesquisar primeiro (Recomendado)" investiga domínio/padrões/deps antes de planejar. Melhor pra features novas, integrações novas, mudanças arquiteturais.
268
+ - "Pular pesquisa" — planeja direto do contexto. Melhor pra bug fix, refactor simples, tarefas bem compreendidas.
255
269
 
256
- Caso contrário usar AskUserQuestion:
257
- ```
258
- AskUserQuestion([
259
- {
260
- question: "Pesquisar antes de planejar a Fase {X}: {phase_name}?",
261
- header: "Pesquisa",
262
- multiSelect: false,
263
- options: [
264
- { label: "Pesquisar primeiro (Recomendado)", description: "Investigar domínio, padrões e dependências antes do planejamento. Melhor para novas funcionalidades, integrações desconhecidas ou mudanças arquiteturais." },
265
- { label: "Pular pesquisa", description: "Planejar diretamente a partir do contexto e requisitos. Melhor para correções de bugs, refatorações simples ou tarefas bem compreendidas." }
266
- ]
267
- }
268
- ])
269
- ```
270
-
271
- Se o usuário selecionar "Pular pesquisa": pular para o passo 6.
272
-
273
- **Se `--auto` e `research_enabled` for false:** Pular pesquisa silenciosamente (preserva comportamento automatizado).
270
+ Se "Pular": passo 6. Se `--auto` e `research_enabled=false`: pular silenciosamente.
274
271
 
275
272
  Exibir banner:
276
273
  ```
@@ -365,51 +362,16 @@ test -f "${PHASE_DIR}/${PADDED_PHASE}-VALIDATION.md" && echo "VALIDATION_CREATED
365
362
  > Pular se `workflow.ui_phase` for explicitamente `false` E `workflow.ui_safety_gate` for explicitamente `false` em `.planning/config.json`. Se as chaves estiverem ausentes, tratar como habilitado.
366
363
 
367
364
  ```bash
368
- UI_PHASE_CFG=$(node "./.claude/framework/bin/tools.cjs" config-get workflow.ui_phase 2>/dev/null || echo "true")
369
- UI_GATE_CFG=$(node "./.claude/framework/bin/tools.cjs" config-get workflow.ui_safety_gate 2>/dev/null || echo "true")
370
- ```
371
-
372
- **Se ambos forem `false`:** Pular para o passo 6.
373
-
374
- Verificar se a fase tem indicadores de frontend:
375
-
376
- ```bash
377
- PHASE_SECTION=$(node "./.claude/framework/bin/tools.cjs" roadmap get-phase "${PHASE}" 2>/dev/null)
378
- echo "$PHASE_SECTION" | grep -iE "UI|interface|frontend|component|layout|page|screen|view|form|dashboard|widget" > /dev/null 2>&1
379
- HAS_UI=$?
380
- ```
365
+ `UI_PHASE_CFG` / `UI_GATE_CFG` (default true). Se ambos false, pular pra passo 6.
381
366
 
382
- **Se `HAS_UI` for 0 (indicadores de frontend encontrados):**
367
+ **Detecção:** grep `-iE "UI|interface|frontend|component|layout|page|screen|view|form|dashboard|widget"` na descrição da fase. Se sem match, pular silenciosamente.
383
368
 
384
- Verificar UI-SPEC existente:
385
- ```bash
386
- UI_SPEC_FILE=$(ls "${PHASE_DIR}"/*-UI-SPEC.md 2>/dev/null | head -1)
387
- ```
388
-
389
- **Se UI-SPEC.md encontrado:** Definir `UI_SPEC_PATH=$UI_SPEC_FILE`. Exibir: `Usando contrato de design de UI: ${UI_SPEC_PATH}`
390
-
391
- **Se UI-SPEC.md ausente E `UI_GATE_CFG` for `true`:**
392
-
393
- Se `TEXT_MODE` for true, apresentar como lista numerada de texto simples:
394
- ```
395
- A Fase {N} tem indicadores de frontend mas sem UI-SPEC.md. Gerar um contrato de design antes do planejamento?
396
-
397
- 1. Gerar UI-SPEC primeiro — Execute /fase-ui {N} então re-execute /planejar-fase {N}
398
- 2. Continuar sem UI-SPEC
399
- 3. Não é uma fase de frontend
400
-
401
- Digite o número:
402
- ```
403
-
404
- Caso contrário usar AskUserQuestion:
405
- - header: "Contrato de Design de UI"
406
- - question: "A Fase {N} tem indicadores de frontend mas sem UI-SPEC.md. Gerar um contrato de design antes do planejamento?"
407
- - options:
408
- - "Gerar UI-SPEC primeiro" → Exibir: "Execute `/fase-ui {N} ${WS}` então re-execute `/planejar-fase {N} ${WS}`". Sair do workflow.
409
- - "Continuar sem UI-SPEC" → Continuar para o passo 6.
410
- - "Não é uma fase de frontend" → Continuar para o passo 6.
411
-
412
- **Se `HAS_UI` for 1 (sem indicadores de frontend):** Pular silenciosamente para o passo 6.
369
+ **Se match encontrado:**
370
+ - UI-SPEC.md existe → usar (`UI_SPEC_PATH`); exibir confirmação
371
+ - UI-SPEC.md ausente E `UI_GATE_CFG=true` → AskUserQuestion (ou lista numerada se TEXT_MODE):
372
+ - "Gerar UI-SPEC primeiro" → exibir `/fase-ui {N} ${WS}` e sair do workflow
373
+ - "Continuar sem UI-SPEC" → passo 6
374
+ - "Não é frontend" passo 6
413
375
 
414
376
  ## 6. Verificar Planos Existentes
415
377
 
@@ -511,28 +473,13 @@ Output consumed by /execute-phase. Plans need:
511
473
 
512
474
  Every task MUST include these fields — they are NOT optional:
513
475
 
514
- 1. **`<read_first>`** — Files the executor MUST read before touching anything. Always include:
515
- - The file being modified (so executor sees current state, not assumptions)
516
- - Any "source of truth" file referenced in CONTEXT.md (reference implementations, existing patterns, config files, schemas)
517
- - Any file whose patterns, signatures, types, or conventions must be replicated or respected
518
-
519
- 2. **`<acceptance_criteria>`** — Verifiable conditions that prove the task was done correctly. Rules:
520
- - Every criterion must be checkable with grep, file read, test command, or CLI output
521
- - NEVER use subjective language ("looks correct", "properly configured", "consistent with")
522
- - ALWAYS include exact strings, patterns, values, or command outputs that must be present
523
- - Examples:
524
- - Code: `auth.py contains def verify_token(` / `test_auth.py exits 0`
525
- - Config: `.env.example contains DATABASE_URL=` / `Dockerfile contains HEALTHCHECK`
526
- - Docs: `README.md contains '## Installation'` / `API.md lists all endpoints`
527
- - Infra: `deploy.yml has rollback step` / `docker-compose.yml has healthcheck for db`
528
-
529
- 3. **`<action>`** — Must include CONCRETE values, not references. Rules:
530
- - NEVER say "align X with Y", "match X to Y", "update to be consistent" without specifying the exact target state
531
- - ALWAYS include the actual values: config keys, function signatures, SQL statements, class names, import paths, env vars, etc.
532
- - If CONTEXT.md has a comparison table or expected values, copy them into the action verbatim
533
- - The executor should be able to complete the task from the action text alone, without needing to read CONTEXT.md or reference files (read_first is for verification, not discovery)
534
-
535
- **Why this matters:** Executor agents work from the plan text. Vague instructions like "update the config to match production" produce shallow one-line changes. Concrete instructions like "add DATABASE_URL=postgresql://... , set POOL_SIZE=20, add REDIS_URL=redis://..." produce complete work. The cost of verbose plans is far less than the cost of re-doing shallow execution.
476
+ 1. **`<read_first>`** — files o executor DEVE ler antes de tocar em qualquer coisa: o arquivo sendo modificado, "source of truth" do CONTEXT.md, qualquer arquivo cujas convenções/tipos/assinaturas precisem ser replicados.
477
+
478
+ 2. **`<acceptance_criteria>`** condições verificáveis com grep/file read/test command/CLI output. NUNCA linguagem subjetiva ("looks correct"); SEMPRE strings/patterns exatos. Ex: `auth.py contains "def verify_token("`, `test_auth.py exits 0`, `.env.example contains "DATABASE_URL="`.
479
+
480
+ 3. **`<action>`** — valores CONCRETOS, nunca referências. NUNCA "align X with Y"; SEMPRE valores reais (config keys, function signatures, SQL, imports, env vars). Se CONTEXT.md tem tabela de comparação, copie no `<action>` literal. Executor deve completar só com texto do action.
481
+
482
+ **Por quê:** instruções vagas ("update config to match production") geram one-line changes; instruções concretas ("add DATABASE_URL=..., POOL_SIZE=20, REDIS_URL=...") geram trabalho completo. Custo de plano verboso é ínfimo vs custo de redo de execução shallow.
536
483
  </deep_work_rules>
537
484
 
538
485
  <quality_gate>
@@ -725,58 +672,17 @@ Rotear para `<offer_next>` OU `auto_advance` dependendo de flags/config.
725
672
 
726
673
  Verificar gatilho de avanço automático:
727
674
 
728
- 1. Analisar flag `--auto` de $ARGUMENTS
729
- 2. **Sincronizar flag de cadeia com intenção** — se o usuário invocou manualmente (sem `--auto`), limpar a flag de cadeia efêmera de qualquer cadeia `--auto` anterior interrompida. Isso NÃO toca em `workflow.auto_advance` (preferência persistente do usuário):
730
- ```bash
731
- if [[ ! "$ARGUMENTS" =~ --auto ]]; then
732
- node "./.claude/framework/bin/tools.cjs" config-set workflow._auto_chain_active false 2>/dev/null
733
- fi
734
- ```
735
- 3. Ler tanto a flag de cadeia quanto a preferência do usuário:
736
- ```bash
737
- AUTO_CHAIN=$(node "./.claude/framework/bin/tools.cjs" config-get workflow._auto_chain_active 2>/dev/null || echo "false")
738
- AUTO_CFG=$(node "./.claude/framework/bin/tools.cjs" config-get workflow.auto_advance 2>/dev/null || echo "false")
739
- ```
740
-
741
- **Se flag `--auto` presente OU `AUTO_CHAIN` for true OU `AUTO_CFG` for true:**
742
-
743
- Exibir banner:
744
- ```
745
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
746
- framework ► AVANÇANDO AUTOMATICAMENTE PARA EXECUÇÃO
747
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
675
+ **Detecção:** flag `--auto` em $ARGUMENTS, OR `workflow._auto_chain_active=true`, OR `workflow.auto_advance=true`.
748
676
 
749
- Planos prontos. Iniciando execute-phase...
750
- ```
751
-
752
- Iniciar execute-phase usando a ferramenta Skill para evitar sessões Task aninhadas (que causam freezes de runtime devido ao aninhamento profundo de agentes):
753
- ```
754
- Skill(skill="framework:executar-fase", args="${PHASE} --auto --no-transition ${WS}")
755
- ```
677
+ **Sync de cadeia:** se invocação manual (sem `--auto`), zere `workflow._auto_chain_active` (não toque `workflow.auto_advance`).
756
678
 
757
- A flag `--no-transition` diz ao execute-phase para retornar status após verificação em vez de encadear mais. Isso mantém a cadeia de avanço automático plana — cada fase roda no mesmo nível de aninhamento em vez de criar agentes Task mais profundos.
679
+ **Quando ativo:** dispare `Skill(skill="framework:executar-fase", args="${PHASE} --auto --no-transition ${WS}")`. A flag `--no-transition` diz pra execute-phase retornar status após verificação (não encadear), mantendo cadeia plana.
758
680
 
759
- **Lidar com retorno do execute-phase:**
760
- - **FASE CONCLUÍDA**Exibir resumo final:
761
- ```
762
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
763
- framework ► FASE ${PHASE} CONCLUÍDA ✓
764
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
765
-
766
- Pipeline de avanço automático finalizado.
767
-
768
- Próximo: /discutir-fase ${NEXT_PHASE} --auto ${WS}
769
- ```
770
- - **LACUNAS ENCONTRADAS / VERIFICAÇÃO FALHOU** → Exibir resultado, parar cadeia:
771
- ```
772
- Avanço automático parado: Execução precisa de revisão.
773
-
774
- Revisar a saída acima e continuar manualmente:
775
- /executar-fase ${PHASE} ${WS}
776
- ```
681
+ **Roteamento de retorno:**
682
+ - `FASE CONCLUÍDA`próximo: `/discutir-fase ${NEXT_PHASE} --auto ${WS}` (após `/clear`)
683
+ - `LACUNAS ENCONTRADAS` / `VERIFICAÇÃO FALHOU` → parar cadeia. Continuar: `/executar-fase ${PHASE} ${WS}`
777
684
 
778
- **Se nem `--auto` nem config habilitado:**
779
- Rotear para `<offer_next>` (comportamento existente).
685
+ **Quando inativo:** rotear para `<offer_next>`.
780
686
 
781
687
  </process>
782
688
 
@@ -0,0 +1,180 @@
1
+ # Glossário Supabase — Termos, Comandos e Patterns Canônicos
2
+
3
+ > Arquivo de referência compartilhado pelas skills `supabase-*`. **NÃO é skill** — não tem `description:` triggerável; não aparece em `listKit`. Cross-referenciado pelas 11 skills via Markdown link relativo.
4
+
5
+ ---
6
+
7
+ ## (a) Termos PT-BR ↔ EN
8
+
9
+ ### Authorization e Auth
10
+
11
+ | EN | PT-BR / Significado |
12
+ |---|---|
13
+ | **RLS** | Row Level Security — segurança em nível de linha. Filtra automaticamente quais linhas de uma tabela cada usuário vê/modifica baseado em policies. |
14
+ | **policy** | Política de RLS — regra `create policy ... on <table> for <op> ...`. Sempre granular por operação (SELECT/INSERT/UPDATE/DELETE). |
15
+ | **`auth.uid()`** | Função que retorna o UUID do usuário autenticado da sessão atual. **Sempre** usar em `(select auth.uid())` em policies. |
16
+ | **`auth.jwt()`** | Função que retorna o JWT decodificado da sessão. Acesso via `auth.jwt()->'app_metadata'` ou `auth.jwt()->>'aal'`. |
17
+ | **`app_metadata`** | Metadata controlado pelo backend (apenas service_role pode mutar). **Use para roles/permissions** em RLS. |
18
+ | **`user_metadata`** | Metadata controlado pelo cliente (`auth.updateUser({data: ...})`). **NUNCA** use em policy de autorização — privilege escalation. |
19
+ | **service_role** | Role do Postgres com bypass total de RLS. **NUNCA** expor ao cliente — vazamento = acesso total ao DB. |
20
+ | **anon** | Role para requests sem autenticação. RLS aplicado normalmente. |
21
+ | **authenticated** | Role para usuário autenticado. RLS aplicado normalmente. |
22
+ | **public** | Role default — equivale a anon + authenticated juntos. Evite — sempre use `to authenticated` ou `to anon` explícito. |
23
+ | **AAL** | Authentication Assurance Level. `aal1` = senha apenas; `aal2` = senha + 2FA. Verifica via `(auth.jwt()->>'aal')::text`. |
24
+
25
+ ### Database e Schema
26
+
27
+ | EN | PT-BR / Significado |
28
+ |---|---|
29
+ | **`schemas/`** | Pasta `supabase/schemas/` — fonte da verdade declarative do schema. Editar aqui, depois `db diff` gera migration. |
30
+ | **`migrations/`** | Pasta `supabase/migrations/` — arquivos `YYYYMMDDHHmmss_<name>.sql` versionados em git. |
31
+ | **`db diff`** | `supabase db diff -f <name>` — gera migration a partir do diff entre schemas/ declarado e DB local atual. |
32
+ | **`db reset`** | `supabase db reset` — recria DB local do zero + reaplica todas as migrations + seeds. |
33
+ | **`search_path`** | Caminho de busca de schema do Postgres. **Sempre** `set search_path = ''` em funções. |
34
+ | **schema-qualified** | Referência a objeto com schema explícito: `public.tasks` em vez de só `tasks`. Obrigatório quando `search_path = ''`. |
35
+ | **`SECURITY INVOKER`** | Função executa com permissões de quem chamou. Default obrigatório. |
36
+ | **`SECURITY DEFINER`** | Função executa com permissões do owner. Apenas com justificativa documentada. |
37
+ | **`IMMUTABLE`** | Função sempre retorna o mesmo para os mesmos inputs (sem consultar DB). |
38
+ | **`STABLE`** | Função consulta DB mas não modifica — mesmo resultado dentro de uma transação. |
39
+ | **`VOLATILE`** | Default. Função pode retornar valores diferentes ou ter side effects. |
40
+
41
+ ### Realtime
42
+
43
+ | EN | PT-BR / Significado |
44
+ |---|---|
45
+ | **broadcast** | Mensagens custom via WebSocket — tipo recomendado em 2026 (substitui `postgres_changes` em apps novos). |
46
+ | **postgres_changes** | Pattern legado de receber mudanças do DB via stream. Single-threaded — não escala. **Migrar para broadcast.** |
47
+ | **presence** | Tracking de "quem está online". Usar **com moderação** — só para presence real (online status, cursor de colaboração). |
48
+ | **channel** | Canal de comunicação — naming canônico `scope:entity:id` (ex: `room:123:messages`). |
49
+ | **private channel** | Canal autenticado — `private: true` + RLS sobre `realtime.messages`. **Default em produção.** |
50
+ | **`realtime.broadcast_changes`** | Função SQL para emitir broadcast de dentro do Postgres (de trigger). |
51
+ | **`realtime.send`** | Função SQL para emitir mensagem custom (não amarrada a tabela). |
52
+
53
+ ### Edge Functions
54
+
55
+ | EN | PT-BR / Significado |
56
+ |---|---|
57
+ | **Edge Function** | Função serverless Deno hospedada por Supabase. Roda perto do usuário. |
58
+ | **`Deno.serve`** | Built-in para HTTP server em Edge Functions (NÃO usar `serve` de `deno.land/std`). |
59
+ | **`EdgeRuntime.waitUntil`** | Permite tarefa background continuar após response retornar. |
60
+ | **`npm:` / `jsr:`** | Specifiers de import obrigatórios (sem bare specifiers). Ex: `import x from "npm:hono@4.6.7"`. |
61
+
62
+ ### Storage e Vector
63
+
64
+ | EN | PT-BR / Significado |
65
+ |---|---|
66
+ | **bucket** | Container de arquivos — público ou privado. Privado por default. |
67
+ | **signed URL** | URL temporária com expiration para download de arquivo privado. |
68
+ | **`storage.objects`** | Tabela onde Storage grava metadados — RLS aplicado aqui controla acesso. |
69
+ | **multi-tenant path isolation** | Pattern: prefixar path do arquivo com `auth.uid()` (`{user_id}/file.png`) para isolar por tenant via RLS. |
70
+ | **TUS** | Tus Resumable Upload protocol — upload em chunks resumable. |
71
+ | **pgvector** | Extensão Postgres para embeddings/similarity search. |
72
+ | **HNSW** | Hierarchical Navigable Small World — index para vector. **Recall melhor.** Default em 2026. |
73
+ | **IVFFlat** | Inverted File Flat — index alternativo. Mais rápido com volumes grandes mas recall menor. |
74
+ | **`<=>`** | Operador cosine distance em pgvector. |
75
+ | **`<#>`** | Operador inner product em pgvector. |
76
+ | **`<->`** | Operador L2 (euclidean) distance em pgvector. |
77
+
78
+ ### Background Jobs
79
+
80
+ | EN | PT-BR / Significado |
81
+ |---|---|
82
+ | **`pg_cron`** | Extensão para jobs cron dentro do Postgres. Schedule SQL/funções. |
83
+ | **`pgmq`** | Postgres Message Queue — extensão de queues. Requer Postgres 15.6.1.143+. |
84
+ | **`pg_net`** | Extensão para requests HTTP de dentro do Postgres. v0.10.0+. |
85
+
86
+ ### Branching
87
+
88
+ | EN | PT-BR / Significado |
89
+ |---|---|
90
+ | **branch database** | Cópia preview do DB de produção para feature branches. |
91
+ | **persistent branch** | Branch que sobrevive entre PRs (staging long-lived). |
92
+ | **preview branch** | Branch criado para PR específico — destruído ao merge. |
93
+
94
+ ---
95
+
96
+ ## (b) Comandos CLI canônicos
97
+
98
+ ```bash
99
+ # Schema declarative
100
+ supabase stop # parar containers (necessário antes de db diff)
101
+ supabase db diff -f <name> # gera migration de schemas/ → migrations/
102
+ supabase db reset # reset local + reaplica migrations + seeds
103
+ supabase db push # aplica migrations não aplicadas no DB remote
104
+ supabase db pull # pulla mudanças remote → cria migration local
105
+
106
+ # Migrations
107
+ supabase migration new <name> # cria migration vazia com timestamp UTC
108
+
109
+ # Edge Functions
110
+ supabase functions new <name> # cria boilerplate de Edge Function
111
+ supabase functions deploy <name> # deploy para Supabase
112
+ supabase functions invoke <name> --body '{}' # invoca localmente
113
+
114
+ # Tipos
115
+ supabase gen types typescript --local > types/db.ts # gera tipos do schema local
116
+ supabase gen types typescript --linked > types/db.ts # gera tipos do remote linked
117
+
118
+ # Project lifecycle
119
+ supabase init # inicializa supabase/ no projeto
120
+ supabase start # sobe stack local (Postgres + Studio + Auth + ...)
121
+ supabase stop # derruba stack local
122
+ supabase status # status dos containers locais
123
+ supabase link --project-ref <ref> # linka projeto local com remote
124
+
125
+ # Branching
126
+ supabase branches create <name> # cria preview branch
127
+ supabase branches list # lista branches
128
+ supabase branches delete <name> # deleta branch (importante para custo!)
129
+
130
+ # Secrets
131
+ supabase secrets set --env-file .env.production # setar secrets em remote
132
+ supabase secrets list # listar (sem revelar valores)
133
+ ```
134
+
135
+ ---
136
+
137
+ ## (c) Patterns canônicos consolidados
138
+
139
+ ### Pattern: `(select auth.uid())` wrapper em RLS
140
+ - Sem `(select)`: degradação até **1000×** em queries com filtro RLS
141
+ - Detalhes: [supabase-rls-policies](../supabase-rls-policies/SKILL.md)
142
+
143
+ ### Pattern: `set search_path = ''` em funções
144
+ - Sem isso: vulnerável a hijack de schema via `search_path` manipulation
145
+ - Detalhes: [supabase-database-functions](../supabase-database-functions/SKILL.md)
146
+
147
+ ### Pattern: `getAll`/`setAll` cookies em SSR (Next.js)
148
+ - Pacote `@supabase/ssr` — **NUNCA** `@supabase/auth-helpers-nextjs` (deprecated)
149
+ - Detalhes: [supabase-auth-ssr](../supabase-auth-ssr/SKILL.md)
150
+
151
+ ### Pattern: `cron → pgmq → Edge Function` (background jobs)
152
+ - Schedule via `pg_cron` → enqueue em `pgmq` → consumir e disparar `pg_net.http_post()` para Edge Function
153
+ - Sem dep externa (Inngest/Trigger.dev) — tudo dentro de Supabase
154
+ - Detalhes: [supabase-cron-queues](../supabase-cron-queues/SKILL.md)
155
+
156
+ ### Pattern: RAG with permissions (similarity + RLS)
157
+ - Embeddings em coluna vector + RLS policy filtrando por `user_id` ou `org_id`
158
+ - Sem RLS, qualquer cliente vê embeddings de todos os tenants
159
+ - Detalhes: [supabase-pgvector-rag](../supabase-pgvector-rag/SKILL.md)
160
+
161
+ ### Pattern: multi-tenant path isolation em Storage
162
+ - Path do arquivo prefixado com `auth.uid()` ou `org_id`: `{user_id}/avatar.png`, `{org_id}/docs/file.pdf`
163
+ - RLS sobre `storage.objects` valida que o cliente acessa apenas o próprio prefixo
164
+ - Detalhes: [supabase-storage](../supabase-storage/SKILL.md)
165
+
166
+ ### Pattern: declarative-first → diff → migration
167
+ - Editar schemas em `supabase/schemas/*.sql`
168
+ - Rodar `supabase stop && supabase db diff -f <name>` para gerar migration em `supabase/migrations/`
169
+ - Revisar migration manualmente antes de aplicar
170
+ - Detalhes: [supabase-declarative-schema](../supabase-declarative-schema/SKILL.md)
171
+
172
+ ### Pattern: `private: true` em Realtime channels
173
+ - Default em produção (2026) — desabilita acesso anônimo
174
+ - Requer RLS sobre `realtime.messages` para SELECT (read) e INSERT (write)
175
+ - Detalhes: [supabase-realtime](../supabase-realtime/SKILL.md)
176
+
177
+ ### Pattern: schema-qualified em Edge Functions chamando Supabase
178
+ - Function consulta `public.tasks` (não `tasks`) quando usar service-role client
179
+ - Combina com `set search_path = ''` em DB functions chamadas via RPC
180
+ - Detalhes: [supabase-edge-functions](../supabase-edge-functions/SKILL.md)