@guilhermefsousa/open-spec-kit 0.0.10 → 0.0.11

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 (28) hide show
  1. package/README.md +1 -1
  2. package/bin/open-spec-kit.js +7 -0
  3. package/package.json +1 -1
  4. package/src/commands/doctor.js +107 -197
  5. package/src/commands/init.js +112 -347
  6. package/src/commands/install.js +393 -0
  7. package/src/commands/update.js +117 -165
  8. package/src/schemas/spec.schema.js +3 -3
  9. package/src/utils/global-path.js +73 -0
  10. package/templates/agents/agents/spec-hub.agent.md +13 -13
  11. package/templates/agents/rules/hub_structure.instructions.md +1 -1
  12. package/templates/agents/rules/ownership.instructions.md +39 -39
  13. package/templates/agents/skills/dev-orchestrator/SKILL.md +17 -17
  14. package/templates/agents/skills/discovery/SKILL.md +17 -17
  15. package/templates/agents/skills/setup-project/SKILL.md +12 -12
  16. package/templates/agents/skills/specifying-features/SKILL.md +28 -28
  17. package/templates/github/agents/spec-hub.agent.md +5 -5
  18. package/templates/github/copilot-instructions.md +9 -9
  19. package/templates/github/instructions/hub_structure.instructions.md +1 -1
  20. package/templates/github/instructions/ownership.instructions.md +9 -9
  21. package/templates/github/skills/dev-orchestrator/SKILL.md +619 -5
  22. package/templates/github/skills/discovery/SKILL.md +419 -5
  23. package/templates/github/skills/setup-project/SKILL.md +496 -5
  24. package/templates/github/skills/specifying-features/SKILL.md +417 -5
  25. /package/templates/github/prompts/{dev.prompt.md → osk-build.prompt.md} +0 -0
  26. /package/templates/github/prompts/{discovery.prompt.md → osk-discover.prompt.md} +0 -0
  27. /package/templates/github/prompts/{setup.prompt.md → osk-init.prompt.md} +0 -0
  28. /package/templates/github/prompts/{nova-feature.prompt.md → osk-spec.prompt.md} +0 -0
@@ -1,9 +1,421 @@
1
1
  ---
2
- name: specifying-features
3
- description: "Criar especificacoes de features com brief, cenarios (Given/When/Then), contratos e tasks divididas por repo."
2
+ name: osk-spec
3
+ description: "Breaks an approved PRD into N feature specifications with brief, scenarios (Given/When/Then), contracts, and repo-partitioned tasks. Generates/updates Design Document on Confluence."
4
+ metadata:
5
+ works_on: [copilot, antigravity, claude]
6
+ argument-hint: "[feature description or Confluence PRD link]"
4
7
  ---
5
8
 
6
- # Specifying Features (Copilot)
9
+ # Specifying Features
7
10
 
8
- > Source of truth: `.agents/skills/specifying-features/SKILL.md`
9
- > Leia o SKILL.md completo em `.agents/skills/specifying-features/` e siga todas as instrucoes de la.
11
+ ## Objective
12
+
13
+ Take an approved PRD and produce minimal, unambiguous feature specifications that enable parallel implementation across multiple repos. Also generate or update the Design Document on Confluence.
14
+
15
+ ## Before you start
16
+
17
+ ### Validate prerequisites
18
+
19
+ 1. Read `projects.yml` — if empty, **stop** with message: "/osk-init não foi executado."
20
+ 2. Read `docs/architecture.md` — if file does not exist: **stop** — "/osk-init não gerou architecture.md. Execute /osk-init primeiro."
21
+ 3. In Confluence (via MCP — same as /osk-init), find the feature page and check its labels:
22
+ - If label `prd-aprovado` is NOT present: **stop** — "PRD não aprovado. A feature precisa ter label 'prd-aprovado' antes de rodar /osk-spec. Execute /osk-discover primeiro."
23
+ - If label `prd-rejeitado` is present AND its addition date is MORE RECENT than `prd-aprovado` (check via MCP — page metadata or label timestamps): **stop** — "PRD foi rejeitado após aprovação. Execute /osk-discover para resolver antes de prosseguir."
24
+ - If `prd-aprovado` IS present and no subsequent `prd-rejeitado`: proceed
25
+ 4. Read the feature page content — verify it has a "## PRD" section with "### Requisitos aceitos". If not: **stop** — "PRD não encontrado na página da feature."
26
+ 5. **Idempotency check**: if `specs/` already contains a directory for this feature (matching name or Confluence page ID in links.md):
27
+ - If all 5 files exist and are complete: **stop** — "Spec já existe em specs/NNN-name/. Para re-gerar, delete o diretório primeiro ou passe --force."
28
+ - If some files are missing or incomplete: **warn** and continue — will overwrite/complete the existing spec.
29
+
30
+ ### Read context
31
+
32
+ Read these files FIRST:
33
+
34
+ 1. `projects.yml` — repos, stack, dependencies
35
+ 2. `docs/architecture.md` — system structure
36
+ 3. ALL files in `docs/lessons/` — past mistakes to avoid
37
+ 4. ALL files in `docs/decisions/` — technical choices
38
+ 5. ALL existing `specs/` — read `contracts.md` of every previous spec to know which entities, endpoints, types, and error formats already exist. This is the **baseline** for the new spec.
39
+
40
+ **Evolution rule**: when the project already has specs, the new spec MUST:
41
+ - **Reference** existing types with "Ver contracts.md da feature NNN" — never redefine
42
+ - **Extend** existing entities by documenting only the NEW fields (e.g., "Adiciona campo `saldo` à entidade `Conta` definida em 002")
43
+ - **Reuse** shared types (ErrorResponse, PaginatedResponse) by reference
44
+ - If the new feature MODIFIES behavior of an existing endpoint, document the change explicitly in brief.md: "Modifica GET /api/contas para incluir campo `saldoAtual` no response"
45
+
46
+ **Figma freshness check (if Figma configured):**
47
+ If `projects.yml` has `figma.file_url` and Figma MCP is available:
48
+ 1. Read `get_metadata()` for the feature's frames
49
+ 2. Compare key elements (screen count, form fields) against what /osk-discover captured in the PRD
50
+ 3. If significant changes detected (new screens, removed fields) → WARN: "Design no Figma mudou desde o /osk-discover. Diferenças: {list}. Continuar com o design atual ou re-executar /osk-discover?"
51
+ 4. If no changes or Figma unavailable → proceed silently
52
+
53
+ ## Inputs
54
+
55
+ - Approved PRD on Confluence (label `prd-aprovado`) — read via MCP
56
+ - Feature context from Discovery phase (questions answered, decisions taken)
57
+
58
+ ## Artifacts produced
59
+
60
+ | File | Purpose | Max size |
61
+ |------|---------|----------|
62
+ | `brief.md` | Problem, solution, out of scope | 1 page |
63
+ | `scenarios.md` | Given/When/Then for every behavior | As many as needed |
64
+ | `contracts.md` | Event schemas, entities, enums, business rules | As many as needed |
65
+ | `tasks.md` | Checklist grouped by repo | As many as needed |
66
+ | `links.md` | PRs, boards, Confluence feature page link | Updated during implementation |
67
+
68
+ ## Flow
69
+
70
+ ### 1. Read PRD from Confluence
71
+
72
+ From Confluence (via MCP), read the approved PRD on the feature page.
73
+ Extract: requirements, decisions, scope, out of scope, assumptions, and NFRs (if the PRD has a "Requisitos Não-Funcionais" section).
74
+
75
+ ### 2. Identify features in the PRD
76
+
77
+ A single PRD may contain N features. Each feature becomes a spec directory.
78
+ Numbering is sequential: find the highest existing number in `specs/` and increment.
79
+
80
+ ### 3. Write specs (per feature)
81
+
82
+ > **⚠️ MANDATORY: generate ALL 5 files per feature — `brief.md`, `scenarios.md`, `contracts.md`, `tasks.md`, `links.md`.**
83
+ > `/osk-build` rejects specs with missing files (checks in Phase A). `open-spec-kit validate` fails on Rule-01 if any of the 5 are absent.
84
+ > `links.md` is frequently forgotten because it's the smallest — it is **mandatory** and `/osk-build` depends on it to track post-merge PRs.
85
+
86
+ **MANDATORY LANGUAGE for ALL generated files**: Brazilian Portuguese (pt-BR) with correct accents. This includes code comments, Gherkin descriptions, and free text. Examples: "não" NOT "nao", "autenticação" NOT "autenticacao", "código" NOT "codigo", "é" NOT "e", "já" NOT "ja", "número" NOT "numero", "válido" NOT "valido", "obrigatório" NOT "obrigatorio", "mínimo" NOT "minimo". Technical terms stay in English (endpoint, token, hash, bcrypt, JWT).
87
+
88
+ #### brief.md
89
+ - Start with the PROBLEM, not the solution
90
+ - One page maximum
91
+ - Include "Out of Scope" section
92
+ - Reference contracts.md for event/API details
93
+ - Include "Appetite" section — timebox (S/M/L or days/weeks) with justification for the investment level
94
+
95
+ #### scenarios.md
96
+ - Every behavior gets a Given/When/Then scenario
97
+ - Include happy path AND failure paths
98
+ - Include edge cases (duplicates, missing fields, timeouts, boundary values)
99
+ - Each scenario maps to at least one test
100
+ - Use REQ-NNN identifiers (from PRD requirements). **Format: 3-digit zero-padded** — REQ-001, REQ-011, NOT REQ-1 or REQ-11. The `open-spec-kit validate` command enforces this format.
101
+ - **CT ID format (MANDATORY)**: every scenario heading MUST use the format:
102
+ `### CT-NNN-XX: description (REQ-NNN)`
103
+ Where NNN = feature spec number, XX = sequential within that REQ.
104
+
105
+ Example for spec 001:
106
+ ```
107
+ ## REQ-001: Idempotent shipment ingestion
108
+
109
+ ### CT-001-01: New shipment arrives (REQ-001)
110
+ - **Given:** no record exists with sourceId="SHP-001"
111
+ - **When:** ShipmentPaymentCalculated event arrives
112
+ - **Then:** a new record is created with status=Pending
113
+
114
+ ### CT-001-02: Duplicate of unbilled shipment (REQ-001)
115
+ - **Given:** record exists with sourceId="SHP-001" and status=Pending
116
+ - **When:** event arrives with different totalAmount
117
+ - **Then:** record is updated with new totalAmount
118
+
119
+ ## REQ-002: Payload validation
120
+
121
+ ### CT-002-01: Required field missing (REQ-002)
122
+ - **Given:** event arrives without tripId
123
+ - **When:** consumer processes
124
+ - **Then:** event sent to dead-letter queue
125
+ ```
126
+
127
+ The `open-spec-kit validate` command enforces this format. Specs without CT IDs will fail validation.
128
+ - **Bidirectional traceability (MANDATORY)**:
129
+ - Every scenario MUST reference at least one REQ-NNN
130
+ - Every REQ-NNN from the PRD MUST have at least one scenario covering it
131
+ - If a REQ has no scenario, either the REQ is unverifiable (fix the PRD) or a scenario is missing (add it)
132
+ - **Cross-check with business rules**: read `Domínio/Regras` on Confluence and verify that every RN referenced in the scenarios exists. If a scenario contradicts an RN, flag it as error.
133
+ - **Mandatory security scenarios**: if the feature has ANY authenticated endpoint, include:
134
+ - At least 1 scenario: request WITHOUT token → expected 401 NAO_AUTORIZADO
135
+ - At least 1 scenario: request with WRONG role → expected 403 ACESSO_NEGADO
136
+ - At least 1 scenario per endpoint accepting user input: malformed/malicious input → expected 400 with validation error (NOT 500)
137
+ If feature has NO authenticated endpoints, skip auth scenarios.
138
+ - **Mandatory pagination scenarios**: if ANY endpoint uses explicit pagination (PaginatedResponse, page/pageSize params, or similar envelope), include scenarios for:
139
+ - Default pagination (no params → uses defaults)
140
+ - Last page (partial results)
141
+ - Invalid page values (page ≤ 0, pageSize > max) — expected: 400 or clamped to defaults
142
+ - **NFR scenarios (if PRD has "Requisitos Não-Funcionais")**: for each measurable NFR target (e.g., "GET /bills < 200ms p95"), create at least one CT-NNN-XX scenario with a concrete Given/When/Then. Example: `Given 50 concurrent users, When GET /api/v1/bills with filters, Then p95 response time < 200ms`. If the NFR is not measurable in a test (e.g., "99.9% uptime"), include it in brief.md under "Restrições" instead. Add NFR-related tasks to tasks.md (e.g., "add response time middleware", "configure rate limiting").
143
+ - **No unresolved markers (MANDATORY)**: specs MUST NOT contain any of these markers anywhere — including inside code blocks and code examples:
144
+ `MOCKADO`, `TODO`, `A CONFIRMAR`, `TBD`, `FIXME`, `PLACEHOLDER`, `TKTK`
145
+ If any assumption is not validated, go back to /osk-discover to resolve it.
146
+ The `open-spec-kit validate` command will ERROR on any unresolved marker.
147
+ - **Cross-spec dependencies are NOT REQs**: if a feature uses an entity or type defined in another spec, do NOT create a REQ for it. Instead, use a `> Dependency:` block in the brief:
148
+ `> Dependency: Uses entity Tutor defined in specs/002 (see contracts.md of feature 002)`
149
+ REQs are testable requirements — a reference to another spec is not testable.
150
+ - Descriptions in Gherkin MUST have accents (ex: "não revela", "usuário autenticado", "credenciais inválidas")
151
+
152
+ #### contracts.md
153
+
154
+ **Mandatory sections** (every contracts.md MUST have ALL of these):
155
+
156
+ 1. **Endpoint table**: Method | Route | Description | Authenticated
157
+ 2. **Contracts per stack**: if `projects.yml` lists repos with different stacks (ex: dotnet + nodejs), contracts MUST include BOTH. Typically: C# (backend) AND TypeScript (frontend). One language is NOT sufficient. Use separate sections with headings: `## Contratos C# (.NET API)` and `## Contratos TypeScript (React Frontend)` (or equivalent for the project's stack).
158
+ 3. **Full endpoint paths in ALL contract examples**: every code example (backend AND frontend, any stack) MUST use the COMPLETE route path exactly as defined in the endpoint table (e.g., `/api/auth/login`, NOT `/auth/login`). This eliminates ambiguity about path prefixes and ensures consistency between backend route definitions and frontend API calls. The endpoint table is the single source of truth for paths — every code example must match it literally.
159
+ 4. **Entities/models**: every new entity introduced by this feature MUST have its own heading in the format `## Entidade: EntityName` followed by a table with columns `Campo | Tipo | Obrigatório | Descrição` (or English equivalents `Field | Type | Required | Description`). This heading format is required by the validator. Example:
160
+ ```
161
+ ## Entidade: User
162
+ | Campo | Tipo | Obrigatório | Descrição |
163
+ |-------|------|-------------|-----------|
164
+ | Id | Guid | Sim | Identificador único |
165
+ | CreatedAt | DateTime | Sim | Data de criação |
166
+ | UpdatedAt | DateTime | Sim | Data de última atualização |
167
+ ```
168
+ 5. **Error codes**: every error code specific to this feature, as constants/enum
169
+ 6. **Validation rules** (as a top-level `##` section, NOT nested inside a per-stack section): every field validation (required, format, max length, valid values)
170
+ 7. **Response examples**: at least one success example and one error example per endpoint, with HTTP status code
171
+ 8. **Shared types**: if this feature DEFINES types that other features will reuse (ex: ErrorResponse, PaginatedResponse), mark them in a `## Tipos compartilhados` section. If this feature USES types from another feature, REFERENCE them ("Ver contracts.md da feature NNN") — do NOT copy the full definition. If extending a type, define only the extension.
172
+
173
+ Additional structural rule: **editável entities MUST have both `CriadoEm` and `AtualizadoEm` fields**. If an entity can be modified via PUT/PATCH, it needs `AtualizadoEm` for auditability.
174
+
175
+ Additional rules:
176
+ - Define event schemas, entities, enums
177
+ - Include field types and required/optional
178
+ - Include business rules (idempotency, validation)
179
+ - Code comments MUST have accents (ex: `// Validação padrão`, NOT `// Validacao padrao`)
180
+
181
+ #### tasks.md
182
+ - **IMPORTANT**: use the EXACT repo name as declared in `projects.yml` as heading `## repo-name`. E.g., `## todo-app-api`, NOT `## Backend`. The `open-spec-kit validate` command checks that headings match repos from projects.yml (Rule 21).
183
+ - Group tasks by repo (from `projects.yml`) — each `## repo` heading is one **execution unit** (1 agent or 1 dev)
184
+ - **Validate repos**: every repo referenced in tasks.md MUST exist in `projects.yml`. If a task references a repo not in projects.yml, **add it** with `status: planned` and `url: null`. The /osk-build will auto-create it in Phase A.1. Log: "Repo '{name}' adicionado ao projects.yml com status: planned."
185
+ - Within each `## repo` block, list tasks in execution order — the list order IS the dependency order (no need to annotate dependencies between tasks of the same block)
186
+ - **Parallelism between blocks**: if a repo block depends ONLY on contracts (already defined in contracts.md) and NOT on the implementation of another block, mark with `[P]` — it can start in parallel. Example: `### todo-front [P] — can start after contracts are defined`
187
+ - **Dependency between blocks**: if a repo block REQUIRES another block to be COMPLETED first, declare explicitly with `> Dependency: todo-api block must be completed before starting`
188
+ - Each task = 1 PR
189
+ - Reference REQ-NNN from scenarios
190
+ - **Size estimate**: each task line should include a size indicator (P/M/G):
191
+ - P (pequeno): < 2h, single file change, well-understood pattern
192
+ - M (médio): 2-8h, multiple files, may need investigation
193
+ - G (grande): > 8h, complex logic, new patterns, integration work
194
+ - Format: `- [ ] [P] T-NNN-REPO-XX: description (REQ-NNN)`
195
+ - **Feature grande**: if the PRD has more than 15 behaviors/requirements or spans 4+ repos, /osk-discover should have flagged it already. If it arrived here approved, proceed without questioning. Just note in brief.md: "Feature com {N} requisitos — escopo aprovado pelo PO."
196
+
197
+ #### links.md
198
+ - Link to Confluence feature page
199
+ - Empty PR table with this schema (filled by /osk-build during implementation):
200
+
201
+ ```markdown
202
+ ## PRs
203
+
204
+ | Repo | Branch | MR/PR | Status |
205
+ |------|--------|-------|--------|
206
+ ```
207
+
208
+ Status values: `open`, `em-review`, `merged`, `closed`. The /osk-build uses the Status column to detect merged MRs for post-merge Phase D.
209
+
210
+ #### ✅ Artifact checklist (MANDATORY — verify before proceeding to self-review)
211
+
212
+ Confirm you generated all **5 files** for this feature:
213
+
214
+ - [ ] `brief.md` — problem, solution, out of scope
215
+ - [ ] `scenarios.md` — Given/When/Then per behavior
216
+ - [ ] `contracts.md` — endpoints, entities, enums, rules
217
+ - [ ] `tasks.md` — checklist per repo (use EXACT repo name from projects.yml as heading `##`)
218
+ - [ ] `links.md` — Confluence URL + PR table ← **frequently forgotten; /osk-build depends on this file**
219
+
220
+ If any file is missing, **create it now** before continuing.
221
+
222
+ #### Optional: OpenAPI stub (if API endpoints exist)
223
+
224
+ If contracts.md defines REST endpoints, generate a minimal OpenAPI 3.0 stub file at `specs/NNN-name/openapi.yaml` containing:
225
+ - paths (from endpoint table: method + route)
226
+ - request/response schemas (from contract types)
227
+ - auth scheme (if authenticated endpoints: bearerAuth)
228
+
229
+ This is a STUB — /osk-build may extend it during implementation. Mark as draft: `info.description: "Auto-generated from contracts.md — draft"`
230
+
231
+ If the feature has no REST endpoints (e.g., worker-only feature), skip this step.
232
+
233
+ ### 4. Self-review and audit
234
+
235
+ Before generating the DD or closing the loop, run ALL checks below. Fix any failures, then generate the audit report.
236
+
237
+ **Checks:**
238
+
239
+ 1. **Traceability matrix**: for each REQ-NNN in the PRD, confirm at least one CT-XX exists in scenarios.md. For each CT-XX, confirm it references a valid REQ-NNN. List any orphans and fix them.
240
+ 2. **RN coverage**: for each RN listed as relevant in brief.md, confirm at least one CT-XX references it. If a relevant RN has no scenario, add one.
241
+ 3. **Contracts completeness**: for each endpoint in the endpoint table, confirm:
242
+ - Request type defined (or N/A for GET/DELETE without body)
243
+ - Response type defined
244
+ - At least one success example and one error example
245
+ - Error codes cover all failure scenarios
246
+ 4. **Auth consistency**: if feature has authenticated endpoints, confirm CTs exist for: "sem token → 401", "role errado → 403"
247
+ 5. **Input validation**: for each endpoint accepting user input, confirm at least one CT for "input malformado → 400" exists
248
+ 6. **Pagination consistency**: if any endpoint returns lists, confirm pagination scenarios exist
249
+ 7. **Cross-feature types**: if contracts.md defines a type that already exists in another feature's contracts.md, replace with a reference
250
+ 8. **NFR coverage**: if the PRD has a "Requisitos Não-Funcionais" section, confirm each measurable NFR has at least one CT scenario. Non-measurable NFRs should appear in brief.md "Restrições"
251
+
252
+ If ANY check fails, fix the spec files BEFORE proceeding. Report what was fixed.
253
+
254
+ **Generate audit report**: after completing all checks (and fixing any issues), save the results to `specs/NNN-name/audit-report.md`:
255
+
256
+ ```markdown
257
+ # Audit Report — NNN: Feature Name
258
+
259
+ | # | Check | Result | Details |
260
+ |---|-------|--------|---------|
261
+ | 1 | REQ → Scenarios | ✅ 12/12 | All REQs have ≥1 scenario |
262
+ | 2 | RN → Scenarios | ✅ 8/8 | All RNs have ≥1 scenario |
263
+ | 3 | Endpoints → Contracts | ✅ 6/6 | All endpoints have request/response/errors |
264
+ | 4 | Auth (401 + 403 scenarios) | ✅ 2/2 | CT-NNN-XX (401), CT-NNN-YY (403) |
265
+ | 5 | Input validation (400 scenarios) | ✅ 3/3 | One per input endpoint |
266
+ | 6 | Pagination scenarios | ✅ 2/2 | CT-NNN-XX, CT-NNN-YY |
267
+ | 7 | Cross-feature types | ✅ OK | References only, no redefinitions |
268
+ | 8 | NFR coverage | ✅ 2/2 | Each measurable NFR has CT scenario |
269
+
270
+ **Generated**: YYYY-MM-DD
271
+ **Fixed during review**: (list what was added/corrected, or "none")
272
+ ```
273
+
274
+ Result values:
275
+ - ✅ = all items pass
276
+ - ⚠️ = partially passing, documented exceptions (include reason)
277
+ - ❌ = failing — MUST be fixed before proceeding (this state should not appear in the final report since all failures are fixed first)
278
+
279
+ The /osk-build reads this report in Phase A before starting implementation. If it contains ⚠️ items, the dev evaluates whether to proceed or request spec changes.
280
+
281
+ ### 5. Validate Glossary on Confluence (read-only)
282
+
283
+ > **Ownership rule**: the Glossário is updated ONLY by /osk-discover (exit gate). The /osk-spec only VALIDATES.
284
+
285
+ Check if the /osk-discover phase identified new terms (see "GLOSSÁRIO" notes on the feature page or in the PRD). If yes:
286
+ 1. Read the current Glossário on Confluence (in storage format)
287
+ 2. Verify that ALL new terms listed in the PRD section "GLOSSÁRIO: termos novos" are present in the Glossário page
288
+ 3. **If any term is MISSING**: **stop** — "Glossário incompleto. O /osk-discover deveria ter adicionado os termos '{missing}' no exit gate. Re-execute /osk-discover para corrigir."
289
+ 4. **If all terms are present**: proceed (no update needed)
290
+
291
+ Do NOT add terms directly — this is /osk-discover's responsibility.
292
+
293
+ ### 6. Generate/update Design Document on Confluence
294
+
295
+ > **Ownership rule**: the DD is owned by the `design-doc` agent (Labs). The /osk-spec delegates creation/update to it. Only uses MCP directly as a fallback.
296
+
297
+ Read `projects.yml` → `agents.design_doc`. If configured (not null), use that agent to generate or update the DD on Confluence with:
298
+ - Updated architecture (if feature adds components)
299
+ - New data flows
300
+ - Security considerations
301
+ - Contract definitions
302
+ - Rollout strategy
303
+
304
+ **Diagram format**: all architecture and data flow diagrams MUST use **Mermaid** blocks. Use `flowchart` for data flows, `sequenceDiagram` for API interactions, `C4Context` for high-level architecture. Never use ASCII art. Example C4:
305
+ ```mermaid
306
+ C4Context
307
+ Person(user, "Usuário")
308
+ System(api, "API Gateway")
309
+ System_Ext(ext, "Serviço Externo")
310
+ Rel(user, api, "Usa")
311
+ Rel(api, ext, "Consulta")
312
+ ```
313
+
314
+ **Fallback**: if `design-doc` agent is not available, update the DD directly no Confluence:
315
+ 1. Read the DD page in storage format
316
+ 2. Add a new section for this feature with: components, endpoints, data model changes. MUST include Mermaid diagrams for any new data flows or architecture changes.
317
+ 3. Update the page (preserving ALL existing content — NEVER use placeholders)
318
+
319
+ ### 7. Close the loop
320
+
321
+ - Change feature label on Confluence → `em-spec`
322
+ - Notify Google Chat (if `GCHAT_WEBHOOK_URL` is not set, the script skips silently):
323
+
324
+ ./scripts/notify-gchat.sh --card \
325
+ --title "📐 Specs prontas pra review" \
326
+ --subtitle "{project_name}" \
327
+ --body "<b>Feature:</b> {feature_name}
328
+
329
+ 📄 <b>Artefatos gerados:</b>
330
+ • brief.md — problema e solução
331
+ • scenarios.md — {scenario_count} cenários BDD
332
+ • contracts.md — contratos por stack (conforme projects.yml)
333
+ • tasks.md — {task_count} tasks por repo
334
+
335
+ 📊 <b>Cobertura:</b> {req_count} REQs → {scenario_count} cenários" \
336
+ --next "Review técnico antes de iniciar /osk-build" \
337
+ --button-text "Ver spec no Confluence" \
338
+ --button-url "{feature_page_url}"
339
+
340
+ Replace `{}` placeholders with actual values. Notifications always in pt-BR.
341
+
342
+ ## MCP failure recovery
343
+
344
+ If a Confluence operation fails mid-flow (updating DD, changing labels, reading Glossary):
345
+ 1. Log which operations succeeded and which failed
346
+ 2. Save pending operations to `docs/pending-confluence-updates.md` with: target page, content to add/update, operation type, date
347
+ 3. Report to dev: "Confluence indisponível — {N} operações pendentes salvas em docs/pending-confluence-updates.md."
348
+ 4. On re-execution, check if `docs/pending-confluence-updates.md` exists and attempt to apply pending operations FIRST before proceeding with new work. Remove applied entries from the file.
349
+
350
+ ## Agents used
351
+
352
+ - Agent configured in `projects.yml` → `agents.design_doc` — to generate/update Design Document on Confluence
353
+
354
+ ## Rules
355
+
356
+ 1. Read existing context before creating anything
357
+ 2. Never invent business context — ask the developer
358
+ 3. Brief max 1 page
359
+ 4. Scenarios use Given/When/Then
360
+ 5. Tasks grouped by repo (see `projects.yml`)
361
+ 6. Each task = 1 PR
362
+ 7. **Language**: ALL generated content — Confluence pages AND local files — MUST be in **Brazilian Portuguese (pt-BR) with correct accents** (e.g., "não" NOT "nao", "autenticação" NOT "autenticacao", "código" NOT "codigo"). Technical terms stay in English. Code comments MUST also have accents (e.g., `// Validação padrão` NOT `// Validacao padrao`).
363
+ 8. Apply lessons from `docs/lessons/`
364
+ 9. Design Document (DD) is ONE document per project, updated per feature
365
+ 10. links.md must link to the Confluence feature page
366
+ 11. **Cross-platform scripts**: when running `./scripts/notify-gchat.*`, detect the OS. On Windows use `powershell -ExecutionPolicy Bypass -File ./scripts/notify-gchat.ps1`, on Linux/macOS use `bash ./scripts/notify-gchat.sh`. Parameters are the same for both.
367
+
368
+ ## Validation checklist
369
+
370
+ ### Traceability (MUST pass — do not ship without these)
371
+ - [ ] Every scenario references at least one REQ-NNN
372
+ - [ ] Every REQ-NNN from the PRD has at least one scenario
373
+ - [ ] Every RN referenced in scenarios exists in Domínio/Regras on Confluence
374
+ - [ ] No RN relevant to this feature was left unreferenced
375
+
376
+ ### Scenarios quality
377
+ - [ ] Every scenario has Given/When/Then
378
+ - [ ] Happy path covered for every endpoint/behavior
379
+ - [ ] Failure scenarios covered (validation errors, not found, ownership)
380
+ - [ ] Auth scenarios (401 without token + 403 wrong role) present if feature has authenticated endpoints
381
+ - [ ] Input validation scenarios (malformed input → 400) present for each endpoint accepting user input
382
+ - [ ] Pagination scenarios present if any endpoint returns paginated lists
383
+ - [ ] NFR scenarios present if PRD has "Requisitos Não-Funcionais" section (each measurable target has a CT)
384
+ - [ ] Edge cases covered (boundary values, empty results, duplicates)
385
+
386
+ ### Contracts quality
387
+ - [ ] contracts.md has ALL mandatory sections (endpoint table, per-stack contracts, entities, error codes, validation rules, examples, shared types)
388
+ - [ ] Contracts defined for EVERY stack in projects.yml (ex: C# AND TypeScript)
389
+ - [ ] Shared types referenced, not redefined
390
+
391
+ ### Structure
392
+ - [ ] PRD was read from Confluence
393
+ - [ ] Brief is 1 page or less, starts with the problem
394
+ - [ ] Tasks grouped by repo (per projects.yml)
395
+ - [ ] Dependencies between tasks explicit
396
+ - [ ] Each task = 1 PR
397
+ - [ ] links.md has correct Confluence page link
398
+
399
+ ### Artifacts
400
+ - [ ] `audit-report.md` generated with all checks passing
401
+ - [ ] `openapi.yaml` generated (if feature has REST endpoints)
402
+ - [ ] Figma freshness check performed (if configured)
403
+
404
+ ### Integration
405
+ - [ ] DD updated on Confluence
406
+ - [ ] Glossary validated on Confluence (all PRD terms present)
407
+ - [ ] All open decisions in architecture.md resolved (no blockers for /osk-build)
408
+ - [ ] Feature label updated on Confluence → `em-spec`
409
+ - [ ] All spec files committed and pushed
410
+ - [ ] GChat notification sent
411
+ - [ ] Lessons from docs/lessons/ applied
412
+
413
+ ## Exit gate (BLOCKING — cannot close the loop without these)
414
+
415
+ The /osk-spec CANNOT be considered done until ALL of the following are true. If any item fails, fix it before moving to /osk-build.
416
+
417
+ 1. **Design Document exists and is updated on Confluence** — the DD page MUST exist under the project root. If it doesn't exist, create it. If it exists, add/update the section for this feature. NEVER skip this step. Verify by reading the DD page after updating.
418
+ 2. **Glossary validated** — if any feature PRD has a "GLOSSÁRIO: termos novos" section, ALL listed terms MUST be present in the Glossário page. Read the Glossário page and verify. If any term is MISSING: **stop** — "Glossário incompleto. Re-execute /osk-discover para adicionar os termos faltantes." The /osk-spec does NOT add terms — it only validates that /osk-discover did its job.
419
+ 3. **All decisions resolved** — read `docs/architecture.md` "Decisões em Aberto" section. If ANY decision is still open that blocks /osk-build, the /osk-spec CANNOT close. Technical decisions can be resolved by the dev team. Business decisions must go back to the PO. If an open decision needs resolution, go back to /osk-discover — the /osk-spec does not resolve decisions, only validates.
420
+ 4. **Self-review completed** — the traceability matrix (REQ → CT, CT → REQ) MUST be verified. Report what was checked and any fixes applied. Do NOT skip silently.
421
+ 5. **Commit and push** — all spec files MUST be committed and pushed to the spec repo before closing. Verify with `git status` that working directory is clean.