@guilhermefsousa/open-spec-kit 0.0.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 (31) hide show
  1. package/README.md +57 -0
  2. package/bin/open-spec-kit.js +39 -0
  3. package/package.json +51 -0
  4. package/src/commands/doctor.js +324 -0
  5. package/src/commands/init.js +981 -0
  6. package/src/commands/update.js +210 -0
  7. package/src/commands/validate.js +615 -0
  8. package/src/parsers/markdown-sections.js +271 -0
  9. package/src/schemas/projects.schema.js +111 -0
  10. package/src/schemas/spec.schema.js +760 -0
  11. package/templates/agents/agents/spec-hub.agent.md +99 -0
  12. package/templates/agents/rules/hub_structure.instructions.md +49 -0
  13. package/templates/agents/rules/ownership.instructions.md +138 -0
  14. package/templates/agents/scripts/notify-gchat.ps1 +99 -0
  15. package/templates/agents/scripts/notify-gchat.sh +131 -0
  16. package/templates/agents/skills/dev-orchestrator/SKILL.md +573 -0
  17. package/templates/agents/skills/discovery/SKILL.md +406 -0
  18. package/templates/agents/skills/setup-project/SKILL.md +459 -0
  19. package/templates/agents/skills/specifying-features/SKILL.md +379 -0
  20. package/templates/github/agents/spec-hub.agent.md +75 -0
  21. package/templates/github/copilot-instructions.md +102 -0
  22. package/templates/github/instructions/hub_structure.instructions.md +33 -0
  23. package/templates/github/instructions/ownership.instructions.md +45 -0
  24. package/templates/github/prompts/dev.prompt.md +19 -0
  25. package/templates/github/prompts/discovery.prompt.md +20 -0
  26. package/templates/github/prompts/nova-feature.prompt.md +19 -0
  27. package/templates/github/prompts/setup.prompt.md +18 -0
  28. package/templates/github/skills/dev-orchestrator/SKILL.md +9 -0
  29. package/templates/github/skills/discovery/SKILL.md +9 -0
  30. package/templates/github/skills/setup-project/SKILL.md +9 -0
  31. package/templates/github/skills/specifying-features/SKILL.md +9 -0
@@ -0,0 +1,379 @@
1
+ ---
2
+ name: specifying-features
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]"
7
+ ---
8
+
9
+ # Specifying Features
10
+
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: "/setup não foi executado."
20
+ 2. Read `docs/architecture.md` — if file does not exist: **stop** — "/setup não gerou architecture.md. Execute /setup primeiro."
21
+ 3. In Confluence (via MCP — same as /setup), 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 /spec. Execute /discovery 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 /discovery 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
+ ## Inputs
47
+
48
+ - Approved PRD on Confluence (label `prd-aprovado`) — read via MCP
49
+ - Feature context from Discovery phase (questions answered, decisions taken)
50
+
51
+ ## Artifacts produced
52
+
53
+ | File | Purpose | Max size |
54
+ |------|---------|----------|
55
+ | `brief.md` | Problem, solution, out of scope | 1 page |
56
+ | `scenarios.md` | Given/When/Then for every behavior | As many as needed |
57
+ | `contracts.md` | Event schemas, entities, enums, business rules | As many as needed |
58
+ | `tasks.md` | Checklist grouped by repo | As many as needed |
59
+ | `links.md` | PRs, boards, Confluence feature page link | Updated during implementation |
60
+
61
+ ## Flow
62
+
63
+ ### 1. Read PRD from Confluence
64
+
65
+ From Confluence (via MCP), read the approved PRD on the feature page.
66
+ Extract: requirements, decisions, scope, out of scope, assumptions.
67
+
68
+ ### 2. Identify features in the PRD
69
+
70
+ A single PRD may contain N features. Each feature becomes a spec directory.
71
+ Numbering is sequential: find the highest existing number in `specs/` and increment.
72
+
73
+ ### 3. Write specs (per feature)
74
+
75
+ > **⚠️ MANDATORY: generate ALL 5 files per feature — `brief.md`, `scenarios.md`, `contracts.md`, `tasks.md`, `links.md`.**
76
+ > `/dev` rejects specs with missing files (checks in Phase A). `open-spec-kit validate` fails on Rule-01 if any of the 5 are absent.
77
+ > `links.md` is frequently forgotten because it's the smallest — it is **mandatory** and `/dev` depends on it to track post-merge PRs.
78
+
79
+ **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).
80
+
81
+ #### brief.md
82
+ - Start with the PROBLEM, not the solution
83
+ - One page maximum
84
+ - Include "Out of Scope" section
85
+ - Reference contracts.md for event/API details
86
+ - Include "Appetite" section — timebox (S/M/L or days/weeks) with justification for the investment level
87
+
88
+ #### scenarios.md
89
+ - Every behavior gets a Given/When/Then scenario
90
+ - Include happy path AND failure paths
91
+ - Include edge cases (duplicates, missing fields, timeouts, boundary values)
92
+ - Each scenario maps to at least one test
93
+ - 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.
94
+ - **CT ID format (MANDATORY)**: every scenario heading MUST use the format:
95
+ `### CT-NNN-XX: description (REQ-NNN)`
96
+ Where NNN = feature spec number, XX = sequential within that REQ.
97
+
98
+ Example for spec 001:
99
+ ```
100
+ ## REQ-001: Idempotent shipment ingestion
101
+
102
+ ### CT-001-01: New shipment arrives (REQ-001)
103
+ - **Given:** no record exists with sourceId="SHP-001"
104
+ - **When:** ShipmentPaymentCalculated event arrives
105
+ - **Then:** a new record is created with status=Pending
106
+
107
+ ### CT-001-02: Duplicate of unbilled shipment (REQ-001)
108
+ - **Given:** record exists with sourceId="SHP-001" and status=Pending
109
+ - **When:** event arrives with different totalAmount
110
+ - **Then:** record is updated with new totalAmount
111
+
112
+ ## REQ-002: Payload validation
113
+
114
+ ### CT-002-01: Required field missing (REQ-002)
115
+ - **Given:** event arrives without tripId
116
+ - **When:** consumer processes
117
+ - **Then:** event sent to dead-letter queue
118
+ ```
119
+
120
+ The `open-spec-kit validate` command enforces this format. Specs without CT IDs will fail validation.
121
+ - **Bidirectional traceability (MANDATORY)**:
122
+ - Every scenario MUST reference at least one REQ-NNN
123
+ - Every REQ-NNN from the PRD MUST have at least one scenario covering it
124
+ - If a REQ has no scenario, either the REQ is unverifiable (fix the PRD) or a scenario is missing (add it)
125
+ - **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.
126
+ - **Mandatory auth scenario**: if the feature has ANY authenticated endpoint, include a scenario testing access WITHOUT a token (expected: 401 NAO_AUTORIZADO). One per feature is sufficient — it validates the auth middleware applies.
127
+ - **Mandatory pagination scenarios**: if ANY endpoint uses explicit pagination (PaginatedResponse, page/pageSize params, or similar envelope), include scenarios for:
128
+ - Default pagination (no params → uses defaults)
129
+ - Last page (partial results)
130
+ - Invalid page values (page ≤ 0, pageSize > max) — expected: 400 or clamped to defaults
131
+ - **No unresolved markers (MANDATORY)**: specs MUST NOT contain any of these markers anywhere — including inside code blocks and code examples:
132
+ `MOCKADO`, `TODO`, `A CONFIRMAR`, `TBD`, `FIXME`, `PLACEHOLDER`, `TKTK`
133
+ If any assumption is not validated, go back to /discovery to resolve it.
134
+ The `open-spec-kit validate` command will ERROR on any unresolved marker.
135
+ - **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:
136
+ `> Dependency: Uses entity Tutor defined in specs/002 (see contracts.md of feature 002)`
137
+ REQs are testable requirements — a reference to another spec is not testable.
138
+ - Descriptions in Gherkin MUST have accents (ex: "não revela", "usuário autenticado", "credenciais inválidas")
139
+
140
+ #### contracts.md
141
+
142
+ **Mandatory sections** (every contracts.md MUST have ALL of these):
143
+
144
+ 1. **Endpoint table**: Method | Route | Description | Authenticated
145
+ 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).
146
+ 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.
147
+ 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:
148
+ ```
149
+ ## Entidade: User
150
+ | Campo | Tipo | Obrigatório | Descrição |
151
+ |-------|------|-------------|-----------|
152
+ | Id | Guid | Sim | Identificador único |
153
+ | CreatedAt | DateTime | Sim | Data de criação |
154
+ | UpdatedAt | DateTime | Sim | Data de última atualização |
155
+ ```
156
+ 5. **Error codes**: every error code specific to this feature, as constants/enum
157
+ 5. **Validation rules** (as a top-level `##` section, NOT nested inside a per-stack section): every field validation (required, format, max length, valid values)
158
+ 6. **Response examples**: at least one success example and one error example per endpoint, with HTTP status code
159
+ 7. **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.
160
+
161
+ 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.
162
+
163
+ Additional rules:
164
+ - Define event schemas, entities, enums
165
+ - Include field types and required/optional
166
+ - Include business rules (idempotency, validation)
167
+ - Code comments MUST have accents (ex: `// Validação padrão`, NOT `// Validacao padrao`)
168
+
169
+ #### tasks.md
170
+ - **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).
171
+ - Group tasks by repo (from `projects.yml`) — each `## repo` heading is one **execution unit** (1 agent or 1 dev)
172
+ - **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 /dev will auto-create it in Phase A.1. Log: "Repo '{name}' adicionado ao projects.yml com status: planned."
173
+ - 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)
174
+ - **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`
175
+ - **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`
176
+ - Each task = 1 PR
177
+ - Reference REQ-NNN from scenarios
178
+ - **Feature grande**: if the PRD has more than 15 behaviors/requirements or spans 4+ repos, /discovery 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."
179
+
180
+ #### links.md
181
+ - Link to Confluence feature page
182
+ - Empty PR table with this schema (filled by /dev during implementation):
183
+
184
+ ```markdown
185
+ ## PRs
186
+
187
+ | Repo | Branch | MR/PR | Status |
188
+ |------|--------|-------|--------|
189
+ ```
190
+
191
+ Status values: `open`, `em-review`, `merged`, `closed`. The /dev uses the Status column to detect merged MRs for post-merge Phase D.
192
+
193
+ #### ✅ Artifact checklist (MANDATORY — verify before proceeding to self-review)
194
+
195
+ Confirm you generated all **5 files** for this feature:
196
+
197
+ - [ ] `brief.md` — problem, solution, out of scope
198
+ - [ ] `scenarios.md` — Given/When/Then per behavior
199
+ - [ ] `contracts.md` — endpoints, entities, enums, rules
200
+ - [ ] `tasks.md` — checklist per repo (use EXACT repo name from projects.yml as heading `##`)
201
+ - [ ] `links.md` — Confluence URL + PR table ← **frequently forgotten; /dev depends on this file**
202
+
203
+ If any file is missing, **create it now** before continuing.
204
+
205
+
206
+
207
+ Before generating the DD or closing the loop, run ALL checks below. Fix any failures, then generate the audit report.
208
+
209
+ **Checks:**
210
+
211
+ 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.
212
+ 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.
213
+ 3. **Contracts completeness**: for each endpoint in the endpoint table, confirm:
214
+ - Request type defined (or N/A for GET/DELETE without body)
215
+ - Response type defined
216
+ - At least one success example and one error example
217
+ - Error codes cover all failure scenarios
218
+ 4. **Auth consistency**: if feature has authenticated endpoints, confirm a CT for "sem token → 401" exists
219
+ 5. **Pagination consistency**: if any endpoint returns lists, confirm pagination scenarios exist
220
+ 6. **Cross-feature types**: if contracts.md defines a type that already exists in another feature's contracts.md, replace with a reference
221
+
222
+ If ANY check fails, fix the spec files BEFORE proceeding. Report what was fixed.
223
+
224
+ **Generate audit report**: after completing all checks (and fixing any issues), save the results to `specs/NNN-name/audit-report.md`:
225
+
226
+ ```markdown
227
+ # Audit Report — NNN: Feature Name
228
+
229
+ | # | Check | Result | Details |
230
+ |---|-------|--------|---------|
231
+ | 1 | REQ → Scenarios | ✅ 12/12 | All REQs have ≥1 scenario |
232
+ | 2 | RN → Scenarios | ✅ 8/8 | All RNs have ≥1 scenario |
233
+ | 3 | Endpoints → Contracts | ✅ 6/6 | All endpoints have request/response/errors |
234
+ | 4 | Auth (401 scenario) | ✅ 1/1 | CT-NNN-XX covers |
235
+ | 5 | Pagination scenarios | ✅ 2/2 | CT-NNN-XX, CT-NNN-YY |
236
+ | 6 | Cross-feature types | ✅ OK | References only, no redefinitions |
237
+
238
+ **Generated**: YYYY-MM-DD
239
+ **Fixed during review**: (list what was added/corrected, or "none")
240
+ ```
241
+
242
+ Result values:
243
+ - ✅ = all items pass
244
+ - ⚠️ = partially passing, documented exceptions (include reason)
245
+ - ❌ = failing — MUST be fixed before proceeding (this state should not appear in the final report since all failures are fixed first)
246
+
247
+ The /dev reads this report in Phase A before starting implementation. If it contains ⚠️ items, the dev evaluates whether to proceed or request spec changes.
248
+
249
+ ### 5. Validate Glossary on Confluence (read-only)
250
+
251
+ > **Ownership rule**: the Glossário is updated ONLY by /discovery (exit gate). The /spec only VALIDATES.
252
+
253
+ Check if the /discovery phase identified new terms (see "GLOSSÁRIO" notes on the feature page or in the PRD). If yes:
254
+ 1. Read the current Glossário on Confluence (in storage format)
255
+ 2. Verify that ALL new terms listed in the PRD section "GLOSSÁRIO: termos novos" are present in the Glossário page
256
+ 3. **If any term is MISSING**: **stop** — "Glossário incompleto. O /discovery deveria ter adicionado os termos '{missing}' no exit gate. Re-execute /discovery para corrigir."
257
+ 4. **If all terms are present**: proceed (no update needed)
258
+
259
+ Do NOT add terms directly — this is /discovery's responsibility.
260
+
261
+ ### 6. Generate/update Design Document on Confluence
262
+
263
+ > **Ownership rule**: the DD is owned by the `design-doc` agent (Labs). The /spec delegates creation/update to it. Only uses MCP directly as a fallback.
264
+
265
+ Read `projects.yml` → `agents.design_doc`. If configured (not null), use that agent to generate or update the DD on Confluence with:
266
+ - Updated architecture (if feature adds components)
267
+ - New data flows
268
+ - Security considerations
269
+ - Contract definitions
270
+ - Rollout strategy
271
+
272
+ **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:
273
+ ```mermaid
274
+ C4Context
275
+ Person(user, "Usuário")
276
+ System(api, "API Gateway")
277
+ System_Ext(ext, "Serviço Externo")
278
+ Rel(user, api, "Usa")
279
+ Rel(api, ext, "Consulta")
280
+ ```
281
+
282
+ **Fallback**: if `design-doc` agent is not available, update the DD directly no Confluence:
283
+ 1. Read the DD page in storage format
284
+ 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.
285
+ 3. Update the page (preserving ALL existing content — NEVER use placeholders)
286
+
287
+ ### 7. Close the loop
288
+
289
+ - Change feature label on Confluence → `em-spec`
290
+ - Notify Google Chat (if `GCHAT_WEBHOOK_URL` is not set, the script skips silently):
291
+
292
+ ./scripts/notify-gchat.sh --card \
293
+ --title "📐 Specs prontas pra review" \
294
+ --subtitle "{project_name}" \
295
+ --body "<b>Feature:</b> {feature_name}
296
+
297
+ 📄 <b>Artefatos gerados:</b>
298
+ • brief.md — problema e solução
299
+ • scenarios.md — {scenario_count} cenários BDD
300
+ • contracts.md — contratos por stack (conforme projects.yml)
301
+ • tasks.md — {task_count} tasks por repo
302
+
303
+ 📊 <b>Cobertura:</b> {req_count} REQs → {scenario_count} cenários" \
304
+ --next "Review técnico antes de iniciar /dev" \
305
+ --button-text "Ver spec no Confluence" \
306
+ --button-url "{feature_page_url}"
307
+
308
+ Replace `{}` placeholders with actual values. Notifications always in pt-BR.
309
+
310
+ ## MCP failure recovery
311
+
312
+ If a Confluence operation fails mid-flow (updating DD, changing labels, reading Glossary):
313
+ 1. Log which operations succeeded and which failed
314
+ 2. Save pending operations to `docs/pending-confluence-updates.md` with: target page, content to add/update, operation type, date
315
+ 3. Report to dev: "Confluence indisponível — {N} operações pendentes salvas em docs/pending-confluence-updates.md."
316
+ 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.
317
+
318
+ ## Agents used
319
+
320
+ - Agent configured in `projects.yml` → `agents.design_doc` — to generate/update Design Document on Confluence
321
+
322
+ ## Rules
323
+
324
+ 1. Read existing context before creating anything
325
+ 2. Never invent business context — ask the developer
326
+ 3. Brief max 1 page
327
+ 4. Scenarios use Given/When/Then
328
+ 5. Tasks grouped by repo (see `projects.yml`)
329
+ 6. Each task = 1 PR
330
+ 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`).
331
+ 8. Apply lessons from `docs/lessons/`
332
+ 9. Design Document (DD) is ONE document per project, updated per feature
333
+ 10. links.md must link to the Confluence feature page
334
+ 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.
335
+
336
+ ## Validation checklist
337
+
338
+ ### Traceability (MUST pass — do not ship without these)
339
+ - [ ] Every scenario references at least one REQ-NNN
340
+ - [ ] Every REQ-NNN from the PRD has at least one scenario
341
+ - [ ] Every RN referenced in scenarios exists in Domínio/Regras on Confluence
342
+ - [ ] No RN relevant to this feature was left unreferenced
343
+
344
+ ### Scenarios quality
345
+ - [ ] Every scenario has Given/When/Then
346
+ - [ ] Happy path covered for every endpoint/behavior
347
+ - [ ] Failure scenarios covered (validation errors, not found, ownership)
348
+ - [ ] Auth scenario (401 without token) present if feature has authenticated endpoints
349
+ - [ ] Pagination scenarios present if any endpoint returns paginated lists
350
+ - [ ] Edge cases covered (boundary values, empty results, duplicates)
351
+
352
+ ### Contracts quality
353
+ - [ ] contracts.md has ALL mandatory sections (endpoint table, per-stack contracts, entities, error codes, validation rules, examples, shared types)
354
+ - [ ] Contracts defined for EVERY stack in projects.yml (ex: C# AND TypeScript)
355
+ - [ ] Shared types referenced, not redefined
356
+
357
+ ### Structure
358
+ - [ ] PRD was read from Confluence
359
+ - [ ] Brief is 1 page or less, starts with the problem
360
+ - [ ] Tasks grouped by repo (per projects.yml)
361
+ - [ ] Dependencies between tasks explicit
362
+ - [ ] Each task = 1 PR
363
+ - [ ] links.md has correct Confluence page link
364
+
365
+ ### Integration
366
+ - [ ] DD updated on Confluence
367
+ - [ ] Feature label updated on Confluence → `em-spec`
368
+ - [ ] GChat notification sent
369
+ - [ ] Lessons from docs/lessons/ applied
370
+
371
+ ## Exit gate (BLOCKING — cannot close the loop without these)
372
+
373
+ The /spec CANNOT be considered done until ALL of the following are true. If any item fails, fix it before moving to /dev.
374
+
375
+ 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.
376
+ 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 /discovery para adicionar os termos faltantes." The /spec does NOT add terms — it only validates that /discovery did its job.
377
+ 3. **All decisions resolved** — read `docs/architecture.md` "Decisões em Aberto" section. If ANY decision is still open that blocks /dev, the /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 /discovery — the /spec does not resolve decisions, only validates.
378
+ 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.
379
+ 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.
@@ -0,0 +1,75 @@
1
+ ---
2
+ name: spec-agent
3
+ description: "Orquestra o ciclo de especificação: invoca skills (/setup, /discovery, /spec, /dev) e coordena agents do Labs."
4
+ user-invocable: true
5
+ disable-model-invocation: false
6
+ tools:
7
+ - agent
8
+ - read
9
+ - edit
10
+ - search
11
+ - execute
12
+ - web
13
+ agents:
14
+ - design-doc
15
+ - dotnet-engineer
16
+ - nodejs-engineer
17
+ - java-engineer
18
+ - frontend-expert
19
+ - labs-secops-agent
20
+ - labs-code-reviewer
21
+ - principal-engineer
22
+ mcp-servers:
23
+ - confluence
24
+ ---
25
+
26
+ # Spec Agent
27
+
28
+ > Source of truth: `.agents/agents/spec-hub.agent.md`
29
+ > Este arquivo registra o agent no Copilot com ferramentas e sub-agents declarados.
30
+ > As instruções completas estão em `.agents/`.
31
+
32
+ ## Antes de qualquer trabalho
33
+
34
+ Leia `.agents/agents/spec-hub.agent.md` e siga TODAS as instruções de lá.
35
+
36
+ Em resumo:
37
+
38
+ 1. Leia `projects.yml`, `docs/architecture.md`, `docs/lessons/`, `docs/decisions/`, specs recentes
39
+ 2. Leia `.agents/rules/ownership.instructions.md` — matriz RACI obrigatória
40
+ 3. Leia `.agents/rules/hub_structure.instructions.md` — convenções de estrutura
41
+ 4. Nunca invente contexto de negócio — pergunte ao dev
42
+ 5. Todo conteúdo em Português (pt-BR) com acentuação correta, termos técnicos em inglês
43
+
44
+ ## Skills disponíveis
45
+
46
+ Cada skill tem instruções completas em `.agents/skills/*/SKILL.md`:
47
+
48
+ | Skill | Prompt file | O que faz |
49
+ |-------|-------------|-----------|
50
+ | Setup | `/setup` | Bootstrap do projeto a partir do Confluence |
51
+ | Discovery | `/discovery` | Análise de demanda, Q&A com PO, gera PRD |
52
+ | Spec | `/nova-feature` | Quebra PRD em specs técnicas (brief, cenários, contratos, tasks) |
53
+ | Dev | `/dev` | Orquestra implementação (TDD, MR, security, docs vivas) |
54
+
55
+ ## Sub-agents
56
+
57
+ Este agent pode delegar para os seguintes agents do Labs:
58
+
59
+ | Agent | Quando usar |
60
+ |-------|------------|
61
+ | `design-doc` | Gerar/atualizar Design Document no Confluence |
62
+ | `dotnet-engineer` | Implementar código .NET/C# |
63
+ | `nodejs-engineer` | Implementar código Node.js/TypeScript |
64
+ | `java-engineer` | Implementar código Java/Spring |
65
+ | `frontend-expert` | Implementar frontend React |
66
+ | `labs-secops-agent` | Security scan pré-merge |
67
+ | `labs-code-reviewer` | Code review automatizado |
68
+ | `principal-engineer` | Trade-offs arquiteturais |
69
+
70
+ **Nota:** Estes agents vivem no repositório `padrao-labs-agents`. Para que a delegação funcione no Copilot, os arquivos `.agent.md` correspondentes devem estar disponíveis em `.github/agents/` deste repo ou no repo `.github-private` da organização. Se um sub-agent não estiver disponível, siga as instruções de fallback no SKILL.md correspondente.
71
+
72
+ ## MCP Confluence
73
+
74
+ Operações Confluence são feitas via MCP server `confluence` configurado em `.vscode/mcp.json`.
75
+ Se MCP falhar, salve operações pendentes em `docs/pending-confluence-updates.md`.
@@ -0,0 +1,102 @@
1
+ # Spec Repo — Copilot Instructions
2
+
3
+ > Source of truth: `.agents/` directory
4
+ > Regras detalhadas em `.agents/rules/`. Skills completos em `.agents/skills/*/SKILL.md`.
5
+
6
+ ## Contexto
7
+
8
+ Repositório de especificações de projeto (ver `projects.yml`).
9
+ Os repos de código são separados — este repo contém specs, contratos e tasks.
10
+ O Confluence é o mundo do PO. Este repo é o mundo do DEV.
11
+
12
+ ## Antes de qualquer trabalho
13
+
14
+ 1. Leia `.agents/rules/ownership.instructions.md` — matriz RACI (quem cria, lê, atualiza cada artefato). **Obrigatório antes de alterar qualquer skill ou spec.**
15
+ 2. Leia `.agents/rules/hub_structure.instructions.md` — convenções de estrutura
16
+ 3. Leia `projects.yml` — repos, stack, dependências, Confluence space
17
+ 4. Leia `docs/architecture.md` — estrutura do sistema
18
+ 5. Leia TODOS os arquivos em `docs/lessons/` — aprendizados do time
19
+ 6. Leia `docs/decisions/` — decisões técnicas
20
+ 7. Leia specs recentes em `specs/` — o que já foi feito
21
+
22
+ ## Skills disponíveis
23
+
24
+ Invoke via prompt files (digite `/` no chat):
25
+
26
+ | Comando | Skill | O que faz |
27
+ |---------|-------|-----------|
28
+ | `/setup` | setup-project | Bootstrap do projeto a partir do Confluence |
29
+ | `/discovery` | discovery | Análise de demanda, Q&A com PO, gera PRD |
30
+ | `/nova-feature` | specifying-features | Quebra PRD em specs técnicas |
31
+ | `/dev` | dev-orchestrator | Orquestra implementação TDD |
32
+
33
+ Cada prompt file aponta para o SKILL.md completo em `.agents/skills/*/SKILL.md`.
34
+
35
+ ## Sub-agents disponíveis
36
+
37
+ O spec-agent pode delegar para agents do Labs quando disponíveis:
38
+
39
+ | Agent | Stack/função |
40
+ |-------|-------------|
41
+ | `design-doc` | Gerar Design Document no Confluence |
42
+ | `dotnet-engineer` | Implementar .NET/C# |
43
+ | `nodejs-engineer` | Implementar Node.js/TypeScript |
44
+ | `java-engineer` | Implementar Java/Spring |
45
+ | `frontend-expert` | Implementar frontend React |
46
+ | `labs-secops-agent` | Security scan |
47
+ | `labs-code-reviewer` | Code review automatizado |
48
+ | `principal-engineer` | Trade-offs arquiteturais |
49
+
50
+ **Nota:** Estes agents vivem no repositório `padrao-labs-agents`. Para delegação funcionar, os `.agent.md` devem estar em `.github/agents/` deste repo ou no `.github-private` da org. Se não disponível, siga os fallbacks no SKILL.md.
51
+
52
+ ## MCP Confluence
53
+
54
+ Configurado em `.vscode/mcp.json`. Operações Confluence (ler páginas, criar páginas, gerenciar labels) são feitas via MCP.
55
+
56
+ Se MCP falhar: salve operações pendentes em `docs/pending-confluence-updates.md`.
57
+
58
+ ## Regras obrigatórias
59
+
60
+ - Todo conteúdo em Português (pt-BR) com acentuação correta
61
+ - Termos técnicos em inglês (endpoint, JWT, token, hash)
62
+ - Brief máx 1 página
63
+ - Cenários usam Given/When/Then
64
+ - Tasks agrupadas por repo (ver `projects.yml`)
65
+ - Cada task = 1 PR
66
+ - Nunca invente contexto de negócio — pergunte ao dev
67
+ - Aplique lições de `docs/lessons/`
68
+ - links.md deve linkar pra feature page no Confluence
69
+
70
+ ## Dual-platform sync
71
+
72
+ Este projeto suporta Claude Code e Copilot. Ao modificar agents, rules ou skills, atualize ambas as plataformas. Consulte a regra 6 em `.agents/rules/ownership.instructions.md` para a tabela de mapeamento.
73
+
74
+ ## Estrutura do Confluence
75
+
76
+ ```
77
+ Projeto (Space ou página raiz)
78
+ +-- Visão do Produto <- /setup gera
79
+ +-- Glossário <- /setup gera | /discovery e /dev atualizam
80
+ +-- DD (Design Document) <- design-doc agent gera | /dev atualiza
81
+ +-- Demandas/ <- PO joga docs aqui
82
+ +-- Features/ <- /setup cria | /discovery escreve dúvidas + PRD
83
+ +-- Domínio/ <- /setup gera | /dev atualiza
84
+ | +-- Regras
85
+ | +-- Fluxos
86
+ | +-- Tabelas de Referência
87
+ | +-- Integrações
88
+ +-- Arquivados/
89
+ ```
90
+
91
+ ## Estrutura do spec repo
92
+
93
+ ```
94
+ specs/NNN-nome/
95
+ brief.md <- problema + solução (1 página)
96
+ contracts.md <- schemas, tipos, regras
97
+ scenarios.md <- Given/When/Then (viram testes)
98
+ tasks.md <- tarefas por repo
99
+ links.md <- PRs + link da feature page
100
+ audit-report.md <- resultado do self-review
101
+ conformance-report.json <- validação pós-implementação
102
+ ```
@@ -0,0 +1,33 @@
1
+ ---
2
+ applyTo: "specs/**,docs/**,projects.yml"
3
+ ---
4
+
5
+ # Rule: Spec Repo Structure
6
+
7
+ > Source of truth: `.agents/rules/hub_structure.instructions.md`
8
+
9
+ ## Convenções de diretório
10
+
11
+ - Specs vivem em `specs/NNN-short-name/` (numeração sequencial)
12
+ - Docs de arquitetura em `docs/architecture.md`
13
+ - ADRs em `docs/decisions/ADR-NNN-title.md`
14
+ - Lições em `docs/lessons/NNN-short-title.md`
15
+ - Repos do projeto em `projects.yml`
16
+
17
+ ## Cada spec contém
18
+
19
+ | Arquivo | Propósito |
20
+ |---------|-----------|
21
+ | `brief.md` | Problema + solução (máx 1 página) |
22
+ | `scenarios.md` | Given/When/Then (viram testes) |
23
+ | `contracts.md` | Schemas, tipos, regras de negócio |
24
+ | `tasks.md` | Tarefas por repo (1 task = 1 PR) |
25
+ | `links.md` | Tracking de PRs + link Confluence |
26
+ | `audit-report.md` | Resultado do self-review do /spec |
27
+ | `conformance-report.json` | Validação de conformidade pós-implementação |
28
+
29
+ ## Regras
30
+
31
+ - Specs NÃO são arquivadas ou movidas. O diretório com tasks checadas É o histórico.
32
+ - Contratos são DEFINIDOS aqui e IMPLEMENTADOS nos repos de código.
33
+ - Todo conteúdo em Português (pt-BR) com acentuação correta, termos técnicos em inglês.
@@ -0,0 +1,45 @@
1
+ ---
2
+ applyTo: "specs/**,projects.yml,docs/**,.agents/**"
3
+ ---
4
+
5
+ # Rule: Artifact Ownership (RACI)
6
+
7
+ > Source of truth: `.agents/rules/ownership.instructions.md`
8
+ > Este arquivo aplica as regras de ownership automaticamente quando Copilot edita specs, docs ou projects.yml.
9
+
10
+ Antes de criar ou modificar qualquer artefato, leia `.agents/rules/ownership.instructions.md` para consultar a matriz RACI completa.
11
+
12
+ ## Resumo
13
+
14
+ - Cada artefato tem exatamente **um Owner** (cria) e no máximo **um Updater** (modifica após criação).
15
+ - Outros skills podem **Ler** ou **Validar**, mas nunca **Escrever**.
16
+ - Se dois skills escrevem no mesmo artefato, um deles está errado.
17
+
18
+ ## Artefatos locais — quem escreve o quê
19
+
20
+ | Artefato | Owner | Updater |
21
+ |----------|-------|---------|
22
+ | `projects.yml` | /setup | /spec, /dev |
23
+ | `docs/architecture.md` | /setup | /discovery |
24
+ | `specs/NNN/brief.md` | /spec | — |
25
+ | `specs/NNN/scenarios.md` | /spec | — |
26
+ | `specs/NNN/contracts.md` | /spec | — |
27
+ | `specs/NNN/tasks.md` | /spec | — |
28
+ | `specs/NNN/links.md` | /spec | /dev |
29
+ | `specs/NNN/audit-report.md` | /spec | — |
30
+ | `specs/NNN/conformance-report.json` | /dev | — |
31
+
32
+ ## Labels de feature (fluxo sequencial)
33
+
34
+ ```
35
+ em-discovery -> aguardando-po -> prd-review -> prd-aprovado -> em-spec -> em-dev -> done
36
+ ```
37
+
38
+ - `prd-aprovado` e `prd-rejeitado` são adicionados pelo **PO manualmente**
39
+ - Todos os outros labels são adicionados pelo skill automaticamente
40
+
41
+ ## Dual-platform sync
42
+
43
+ Este projeto suporta Claude Code e Copilot. Ao modificar agents, rules ou skills, atualize ambas as plataformas. Consulte a regra 6 em `.agents/rules/ownership.instructions.md` para a tabela de mapeamento completa.
44
+
45
+ Para a matriz RACI completa (incluindo artefatos Confluence), consulte `.agents/rules/ownership.instructions.md`.
@@ -0,0 +1,19 @@
1
+ ---
2
+ description: "Orquestrar implementação de uma spec aprovada"
3
+ mode: agent
4
+ tools:
5
+ - github
6
+ - terminal
7
+ - filesystem
8
+ - fetch
9
+ ---
10
+
11
+ Orquestre a implementação de uma spec aprovada. Siga o fluxo:
12
+
13
+ 1. Leia `.agents/skills/dev-orchestrator/SKILL.md` e siga TODAS as instruções
14
+ 2. Leia a spec aprovada em `specs/NNN-nome/`
15
+ 3. Leia `specs/NNN-nome/audit-report.md` — se tem ❌, pare e reporte
16
+ 4. Selecione o agent certo pela stack (projects.yml)
17
+ 5. Crie issues, branches, implemente com TDD, valide, crie MRs
18
+ 6. Após merge, atualize docs vivas no Confluence
19
+ 7. Notifique no Google Chat em cada transição