@brunosps00/dev-workflow 0.10.0 → 0.11.0

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.
package/README.md CHANGED
@@ -158,6 +158,31 @@ Shortcuts:
158
158
  /dw-redesign-ui "target" Visual redesign of a page or component
159
159
  ```
160
160
 
161
+ ## Constitution
162
+
163
+ A **constitution** is a declarative list of principles your team commits to (e.g., "every state-changing endpoint requires server-side authorization", "every bug fix ships with a regression test"). It lives at `.dw/constitution.md` and complements `.dw/rules/`:
164
+
165
+ | File | Type | Authored by |
166
+ |------|------|-------------|
167
+ | `.dw/rules/` | Analytical — describes what the code IS (observed patterns) | `/dw-analyze-project` |
168
+ | `.dw/constitution.md` | Declarative — describes what the code SHOULD BE (committed principles) | `/dw-analyze-project` (Step 8) or auto-installed defaults |
169
+
170
+ **How it works:**
171
+
172
+ - `/dw-analyze-project` offers three paths: synthesize from observed patterns (with your approval), install canonical defaults, or skip.
173
+ - If `/dw-create-prd`, `/dw-create-techspec`, or `/dw-code-review` run **without** a constitution, they auto-install the defaults template (10 canonical principles at `severity: info`), notify in chat, and continue. Ausência nunca bloqueia.
174
+ - Once principles exist:
175
+ - `severity: info` → reported, never blocks.
176
+ - `severity: high` → blocks PR/techspec when violated, unless an ADR justifies the deviation.
177
+ - `severity: critical` → blocks plus requires reviewer sign-off in the ADR.
178
+ - Defaults start at `info`; you promote severities as your team trusts enforcement.
179
+
180
+ **Tasks consistency check.** At the end of `/dw-create-tasks`, a 5-dimension consistency check validates PRD ↔ TechSpec ↔ Tasks alignment (FR coverage, task grounding, test coverage, dependency DAG, constitution alignment) and writes `.dw/spec/prd-<feature>/tasks-validation.md`. Any FAIL blocks user approval until resolved or explicitly overridden.
181
+
182
+ ## Template Overrides
183
+
184
+ Customize templates locally without losing dev-workflow updates. Drop a file at `.dw/templates/overrides/<name>.md`; the override is used in place of the bundled core template on every `update`. Subdirectories work too (e.g., `.dw/templates/overrides/functional-doc/e2e-runbook.md`). See `.dw/templates/overrides/README.md` (created on init) for the workflow and `diff` cadence guidance.
185
+
161
186
  ## Platform Support
162
187
 
163
188
  | Platform | Wrapper Location | Status |
@@ -176,10 +201,12 @@ your-project/
176
201
  ├── .dw/
177
202
  │ ├── commands/ # 30 workflow command files
178
203
  │ ├── templates/ # Document templates (PRD, TechSpec, etc.)
204
+ │ │ └── overrides/ # Project-local template customizations (override > core)
179
205
  │ ├── rules/ # Project-specific rules (run /dw-analyze-project)
206
+ │ ├── constitution.md # Declarative principles (auto-installed when missing)
180
207
  │ ├── references/ # Reference documentation
181
208
  │ ├── scripts/ # Utility scripts
182
- │ └── spec/ # PRD directories created by commands
209
+ │ └── spec/ # PRD directories each contains tasks-validation.md
183
210
  ├── .claude/
184
211
  │ ├── skills/ # Claude Code wrappers
185
212
  │ └── settings.json # MCP servers (Context7, Playwright)
@@ -259,6 +286,8 @@ Codebase intelligence (`/dw-intel`, `/dw-map-codebase`, the `dw-codebase-intel`
259
286
 
260
287
  Source-driven development, code simplification, debugging discipline, and git workflow patterns adapted from [`addyosmani/agent-skills`](https://github.com/addyosmani/agent-skills) by Addy Osmani (MIT) into the bundled `dw-source-grounding`, `dw-simplification`, `dw-debug-protocol`, and `dw-git-discipline` skills. Performance-optimization workflow (`vercel-react-best-practices/references/perf-discipline.md`), API-design discipline (`dw-codebase-intel/references/api-design-discipline.md`), and browser-DevTools patterns (`webapp-testing/references/{security-boundary, three-workflow-patterns}`) also incorporated as enhancements to existing bundled skills.
261
288
 
289
+ Spec-Driven Development patterns — declarative constitution (`.dw/constitution.md`), cross-artifact consistency check (PRD ↔ TechSpec ↔ Tasks), and template override layer (`.dw/templates/overrides/`) — adapted from [`github/spec-kit`](https://github.com/github/spec-kit) by GitHub (MIT). dev-workflow specifics: embedded into existing commands instead of new slash commands, severity-graded enforcement (`info`/`high`/`critical`) with ADR-justified deviation as the escape hatch, ausência-of-constitution never blocks (auto-installs defaults and continues), and integration with the analytical `.dw/rules/` already produced by `/dw-analyze-project`.
290
+
262
291
  ## License
263
292
 
264
293
  MIT
package/lib/init.js CHANGED
@@ -48,18 +48,35 @@ async function run({ force = false, lang = null, mode = 'init' }) {
48
48
  totalOverwritten += cmdResults.overwritten;
49
49
  console.log(` ${cmdResults.created} created, ${cmdResults.skipped} skipped, ${cmdResults.overwritten} overwritten\n`);
50
50
 
51
- // 3. Copy templates
51
+ // 3. Copy templates (override-aware: .dw/templates/overrides/<name> wins over scaffold core)
52
52
  console.log(' Templates:');
53
+ const templatesDir = path.join(projectRoot, '.dw', 'templates');
54
+ const overridesDir = path.join(templatesDir, 'overrides');
53
55
  const tplResults = copyDir(
54
56
  path.join(langDir, 'templates'),
55
- path.join(projectRoot, '.dw', 'templates'),
56
- managedForce
57
+ templatesDir,
58
+ managedForce,
59
+ overridesDir
57
60
  );
58
61
  totalCreated += tplResults.created;
59
62
  totalSkipped += tplResults.skipped;
60
63
  totalOverwritten += tplResults.overwritten;
61
64
  console.log(` ${tplResults.created} created, ${tplResults.skipped} skipped, ${tplResults.overwritten} overwritten\n`);
62
65
 
66
+ // 3.1. Seed .dw/templates/overrides/ with README on first init (never overwritten)
67
+ ensureDir(overridesDir);
68
+ const overridesReadmeSrc = path.join(SCAFFOLD_DIR, 'templates-overrides-readme.md');
69
+ const overridesReadmeDest = path.join(overridesDir, 'README.md');
70
+ if (require('fs').existsSync(overridesReadmeSrc)) {
71
+ const ovrStatus = writeFile(
72
+ overridesReadmeDest,
73
+ require('fs').readFileSync(overridesReadmeSrc, 'utf-8'),
74
+ false
75
+ );
76
+ if (ovrStatus === 'created') totalCreated++;
77
+ else totalSkipped++;
78
+ }
79
+
63
80
  // 3.5. Copy references (language-specific)
64
81
  const refsSrcDir = path.join(langDir, 'references');
65
82
  if (require('fs').existsSync(refsSrcDir)) {
package/lib/utils.js CHANGED
@@ -29,7 +29,7 @@ function writeFile(filePath, content, force = false) {
29
29
  return exists ? 'overwritten' : 'created';
30
30
  }
31
31
 
32
- function copyDir(srcDir, destDir, force = false) {
32
+ function copyDir(srcDir, destDir, force = false, overridesDir = null) {
33
33
  const results = { created: 0, skipped: 0, overwritten: 0 };
34
34
 
35
35
  if (!fs.existsSync(srcDir)) {
@@ -40,14 +40,19 @@ function copyDir(srcDir, destDir, force = false) {
40
40
  for (const entry of entries) {
41
41
  const srcPath = path.join(srcDir, entry.name);
42
42
  const destPath = path.join(destDir, entry.name);
43
+ const overridePath = overridesDir ? path.join(overridesDir, entry.name) : null;
43
44
 
44
45
  if (entry.isDirectory()) {
45
- const sub = copyDir(srcPath, destPath, force);
46
+ const subOverrides = overridePath && fs.existsSync(overridePath) ? overridePath : null;
47
+ const sub = copyDir(srcPath, destPath, force, subOverrides);
46
48
  results.created += sub.created;
47
49
  results.skipped += sub.skipped;
48
50
  results.overwritten += sub.overwritten;
49
51
  } else {
50
- const status = copyFile(srcPath, destPath, force);
52
+ // Override wins: copy from override path so dest reflects user customization.
53
+ // Always force-copy overrides so a manual edit to overrides/X.md propagates to templates/X.md on next update.
54
+ const effectiveSrc = overridePath && fs.existsSync(overridePath) ? overridePath : srcPath;
55
+ const status = copyFile(effectiveSrc, destPath, effectiveSrc === overridePath ? true : force);
51
56
  results[status]++;
52
57
  }
53
58
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brunosps00/dev-workflow",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "AI-driven development workflow commands for any project. Scaffolds a complete PRD-to-PR pipeline with multi-platform AI assistant support.",
5
5
  "bin": {
6
6
  "dev-workflow": "./bin/dev-workflow.js"
@@ -705,6 +705,67 @@ packages/auth → packages/db
705
705
  6. {apps/web} — depends on ui, db, auth
706
706
  ```
707
707
 
708
+ ### Step 8: Constitution Generation (Optional but Recommended)
709
+
710
+ After `.dw/rules/` is written, offer to generate `.dw/constitution.md` — the declarative principles the team wants enforced on PRDs, TechSpecs, and Code Reviews.
711
+
712
+ **Difference from `.dw/rules/`:**
713
+ - `.dw/rules/` is **analytical** — what the code IS (observed patterns, anti-patterns, conventions).
714
+ - `.dw/constitution.md` is **declarative** — what the code SHOULD BE (rules the team commits to).
715
+
716
+ **Behavior:**
717
+
718
+ If `.dw/constitution.md` already exists, print "Constitution already present at `.dw/constitution.md` — skipping (edit it manually if you want to update)" and finish.
719
+
720
+ Otherwise, present 3 options in the chat (use the user's preferred question UI when available; otherwise plain text):
721
+
722
+ ```
723
+ A constitution would help PRDs/TechSpecs/PRs stay aligned with project standards.
724
+ Three options:
725
+
726
+ A) Synthesize from observed patterns (recommended)
727
+ I read `.dw/rules/` and propose 5–8 principles grounded in real code,
728
+ each with `Why:` linked to evidence and `severity: info` (won't block).
729
+ You review and approve before anything is written.
730
+
731
+ B) Install defaults template
732
+ Copy `templates/constitution-template.md` to `.dw/constitution.md` with
733
+ 5 canonical principles (Code Quality, Testing, UX, Performance, Security)
734
+ pre-filled at `severity: info`. You customize manually.
735
+
736
+ C) Skip
737
+ No constitution. Downstream commands will operate without the gate.
738
+ You can run this step again later by re-running `/dw-analyze-project`.
739
+ ```
740
+
741
+ **Option A — Synthesize:**
742
+
743
+ 1. Read `.dw/rules/index.md` + each `.dw/rules/{module}.md`.
744
+ 2. Propose 5–8 principles. Each must:
745
+ - Have a unique `P-NNN` ID.
746
+ - Map to an observation in `.dw/rules/` (cite the rule file + section).
747
+ - Start at `severity: info` (never propose `high`/`critical` automatically — that's the team's call).
748
+ - Follow the format: `**P-NNN — <name>** (severity: info): <rule>. **Why:** <ground in evidence>. **Enforcement:** <how to check>.`
749
+ 3. **Show the proposed principles in the chat as a markdown list** (do not write the file yet). Include the evidence citation for each.
750
+ 4. Ask: "Edit any of these before I write the file? Reply with the IDs to drop/edit, or 'approve' to write as-is."
751
+ 5. After user approves (with edits applied), write to `.dw/constitution.md` using the same template structure as `templates/constitution-template.md`.
752
+ 6. Set frontmatter `mode: custom` and `last_updated: <today's ISO date>`.
753
+
754
+ **Option B — Defaults:**
755
+
756
+ 1. Locate `templates/constitution-template.md` (project-local at `.dw/templates/constitution-template.md`, falling back to the bundled scaffold).
757
+ 2. Copy to `.dw/constitution.md` verbatim. Set frontmatter `mode: defaults`.
758
+ 3. Print: "Installed defaults constitution at `.dw/constitution.md`. All 10 principles start at `severity: info` — they report but don't block. Edit the file to customize, then promote severities to `high`/`critical` when you trust the project enforces them."
759
+
760
+ **Option C — Skip:**
761
+
762
+ 1. Do nothing.
763
+ 2. Print: "Skipped. PRD/TechSpec/CodeReview will run without the constitution gate. Re-run `/dw-analyze-project` later if you want to enable it."
764
+
765
+ **No matter which option:**
766
+ - Never write `.dw/constitution.md` without explicit user approval (option A) or explicit choice (options B/C).
767
+ - Constitution file is committed to the repository like any other project artifact — never gitignored.
768
+
708
769
  ## Quality Checklist
709
770
 
710
771
  Before declaring the analysis complete, verify:
@@ -166,6 +166,34 @@ For each impacted project, verify project-specific rules from `.dw/rules/`:
166
166
  - [ ] API calls use project fetch utilities
167
167
  - [ ] UI follows project design system
168
168
 
169
+ ### 4.1. Constitution Compliance (Required when `.dw/constitution.md` exists)
170
+
171
+ <critical>**Auto-create if missing**: if `.dw/constitution.md` does NOT exist, copy `templates/constitution-template.md` (project-local `.dw/templates/constitution-template.md` first, falling back to bundled scaffold) verbatim with frontmatter `mode: defaults`. Print in chat: "Installed defaults constitution at `.dw/constitution.md` (all principles at `severity: info` — reported but not blocking this review). Continuing." Then proceed.</critical>
172
+
173
+ For each principle in `.dw/constitution.md`, check the diff for violations:
174
+
175
+ 1. **Parse principles**: read each `**P-NNN — <name>** (severity: <S>)` entry; capture `P-NNN`, `severity`, and the `Enforcement` description.
176
+ 2. **Apply enforcement**: for each principle, run the enforcement check against the diff (grep, file inspection, or pattern match per the Enforcement line).
177
+ 3. **Classify violations**:
178
+ - Principle severity `info` → add row to "Issues Found" table with severity `low`. **Does not block** the verdict.
179
+ - Principle severity `high` → add row with severity `critical`. **Blocks** the verdict to `REJECTED` UNLESS an ADR in the same PRD's `adrs/` directory documents the deviation (look for `Deviates: P-NNN` in any ADR body).
180
+ - Principle severity `critical` → add row with severity `critical` AND require the ADR to have a non-empty `Approved by:` field. Missing field = still `REJECTED`.
181
+ 4. **No silent skips**: if the diff is too large to analyze every principle, report which were checked and which were skipped due to scope.
182
+
183
+ **Output format in the report:**
184
+
185
+ ```markdown
186
+ ## Constitution Compliance
187
+
188
+ | Principle | Severity | Status | Evidence | ADR escape |
189
+ |-----------|----------|--------|----------|------------|
190
+ | P-001 — No `any` casts | info | VIOLATED | src/foo.ts:42 | n/a |
191
+ | P-009 — Server-side auth | high | VIOLATED | src/api/order.ts:18 missing auth middleware | none → BLOCKS |
192
+ | P-010 — Secrets in repo | critical | PASS | — | — |
193
+ ```
194
+
195
+ If any `high`/`critical` violation has no ADR escape: append to the verdict line "REJECTED — constitution violation(s) without ADR (see Constitution Compliance section)".
196
+
169
197
  ### 5. Code Quality Analysis (Required)
170
198
 
171
199
  | Aspect | Verification |
@@ -50,6 +50,22 @@
50
50
  - Use `.dw/rules/` as context, falling back to grep
51
51
  - Suggest running `/dw-map-codebase` for richer downstream context
52
52
 
53
+ ## Constitution Gate
54
+
55
+ <critical>BEFORE the clarification questions, check `.dw/constitution.md`:
56
+
57
+ **If MISSING**: copy `templates/constitution-template.md` (project-local at `.dw/templates/constitution-template.md`, falling back to bundled scaffold) verbatim to `.dw/constitution.md`. Set frontmatter `mode: defaults` and `last_updated` to today's ISO date. Print in chat:
58
+
59
+ > "I noticed `.dw/constitution.md` was missing. Installed defaults at `.dw/constitution.md` (10 canonical principles, all `severity: info` — they report but don't block). You can customize anytime — or re-run `/dw-analyze-project` for a tailored version. Continuing with PRD."
60
+
61
+ Then proceed normally, treating the new file as the constitution.
62
+
63
+ **If PRESENT**: read it before drafting requirements. Each FR in the PRD MUST include a "Constitution Alignment" line mapping to ≥1 relevant principle (`Respects: P-001, P-009`) OR explicitly declaring "no applicable principle" with a one-line reason. Missing alignment = the FR is incomplete.
64
+
65
+ **Severity rules** (applied by downstream commands, not enforced here):
66
+ - `severity: info` violations → reported, never block.
67
+ - `severity: high` / `critical` violations → block in `dw-create-techspec` and `dw-code-review` unless an ADR justifies the deviation.</critical>
68
+
53
69
  ## Multi-Project Features
54
70
 
55
71
  Many features may involve more than one project in the workspace (e.g., a feature may impact both frontend and backend, or multiple services).
@@ -149,5 +149,47 @@
149
149
  3. Create PR when all tasks are completed
150
150
  ```
151
151
 
152
+ ## Final Consistency Check (Auto-invoked before user approval)
153
+
154
+ <critical>BEFORE presenting tasks to the user, run a 5-dimension consistency check. This is mandatory; do not skip even if you're confident the tasks are clean.</critical>
155
+
156
+ Run these 5 checks against the generated PRD + TechSpec + tasks set:
157
+
158
+ 1. **FR coverage** — every numbered FR in the PRD maps to ≥1 task. Orphan FRs (PRD has it; no task covers it) are a FAIL.
159
+ 2. **Task grounding** — every generated task body references ≥1 FR (`Covers: FR-N.M`). Tasks without FR reference signal scope creep.
160
+ 3. **Test coverage** — every FR with user-facing behavior (UI, API endpoint, data mutation) has ≥1 task that adds a test (subtask containing "test", "spec", "e2e", or equivalent).
161
+ 4. **Dependency graph** — task dependencies (X.0 → Y.0 declared as "Depends on") form a DAG. No cycles. Topological order valid.
162
+ 5. **Constitution alignment** (only if `.dw/constitution.md` exists) — every task lists `Constitution: respects P-NNN, P-MMM` OR `Constitution: deviates P-NNN — ADR planned: <slug>` OR `Constitution: n/a — reason: <one-liner>`. Missing line = FAIL.
163
+
164
+ Write findings to `.dw/spec/prd-[feature-name]/tasks-validation.md` with this exact structure:
165
+
166
+ ```markdown
167
+ # Tasks Validation Report
168
+
169
+ Generated by /dw-create-tasks on YYYY-MM-DD.
170
+
171
+ | Dimension | Status | Findings |
172
+ |-----------|--------|----------|
173
+ | 1. FR coverage | PASS / FAIL | <orphan FR list or "all FRs covered"> |
174
+ | 2. Task grounding | PASS / FAIL | <ungrounded task list or "all tasks reference FRs"> |
175
+ | 3. Test coverage | PASS / FAIL | <FRs missing tests or "all user-facing FRs covered"> |
176
+ | 4. Dependency graph | PASS / FAIL | <cycles or "DAG valid"> |
177
+ | 5. Constitution alignment | PASS / FAIL / N/A | <unaligned tasks or "all aligned" or "no constitution"> |
178
+
179
+ ## Detailed Findings
180
+
181
+ <one section per FAILing dimension with concrete fixes; empty if all PASS>
182
+ ```
183
+
184
+ **Gate behavior:**
185
+
186
+ - **All 5 dimensions PASS (or N/A)** → present tasks to the user normally and ask for approval.
187
+ - **Any dimension FAIL** → STOP. Show the table in chat as markdown (do NOT bury it in the validation file; the user must see it before approving). Then ask the user:
188
+ - "(a) Want me to fix tasks automatically?" → regenerate the affected tasks, re-run the check.
189
+ - "(b) Will you edit tasks.md manually?" → wait for the user to signal completion, re-run the check.
190
+ - "(c) Override and proceed despite FAIL?" → require an explicit override message ("override: I accept the gap because <reason>"). Persist the override in `tasks-validation.md` so it's auditable.
191
+
192
+ The `tasks-validation.md` file is committed alongside `tasks.md`. Downstream commands (`/dw-run-plan`, `/dw-code-review`, `/dw-review-implementation`) may reference it.
193
+
152
194
  After completing the analysis and generating all necessary files, present the results to the user and wait for confirmation to proceed with implementation.
153
195
  </system_instructions>
@@ -39,6 +39,23 @@
39
39
  - Use `.dw/rules/` as context, falling back to grep
40
40
  - Suggest running `/dw-map-codebase` to enrich downstream context
41
41
 
42
+ ## Constitution Gate
43
+
44
+ <critical>BEFORE drafting architectural decisions, check `.dw/constitution.md`:
45
+
46
+ **If MISSING**: copy `templates/constitution-template.md` (project-local at `.dw/templates/constitution-template.md`, falling back to bundled scaffold) verbatim to `.dw/constitution.md`. Set frontmatter `mode: defaults`. Print in chat: "Installed defaults constitution at `.dw/constitution.md` (severity: info — won't block this techspec). Continuing." Then proceed.
47
+
48
+ **If PRESENT**: read it. Every framework / library / architectural choice in the techspec MUST carry one of:
49
+ - `Respects: P-NNN` — the decision actively honors the named principle(s).
50
+ - `Deviates: P-NNN — justification: <ADR slug or one-line rationale>` — the decision intentionally departs from the principle.
51
+
52
+ **Severity-graded gate:**
53
+ - Deviation from a `severity: info` principle → record only, never blocks.
54
+ - Deviation from a `severity: high` principle without a linked ADR (`.dw/spec/<prd>/adrs/adr-NNN.md`) → BLOCK the techspec. Instruct the user to either revise the decision OR create an ADR via `/dw-adr` documenting the trade-off.
55
+ - Deviation from a `severity: critical` principle → BLOCK the techspec with the same ADR requirement, additionally requiring reviewer acknowledgment captured in the ADR's `Approved by` field.
56
+
57
+ No exceptions for `high`/`critical` without an ADR. If the user pushes back, point them to `/dw-adr` — that's the escape hatch by design.</critical>
58
+
42
59
  ## Multi-Project Decision Flowchart
43
60
 
44
61
  ```dot
@@ -0,0 +1,111 @@
1
+ ---
2
+ schema_version: "1.0"
3
+ generated_by: dev-workflow
4
+ last_updated: YYYY-MM-DD
5
+ mode: defaults | custom
6
+ ---
7
+
8
+ # Project Constitution
9
+
10
+ > Declarative principles this team has chosen to follow. PRDs, TechSpecs, and Code Reviews read this file as a hard gate. Anything that violates a principle with `severity: critical` or `high` is blocked unless explicitly justified by an ADR.
11
+
12
+ ## How this file works
13
+
14
+ - **Each principle has an ID (`P-NNN`), a severity, a rule, a `Why`, and an `Enforcement`.**
15
+ - **Severity ladder:** `info` (reports only, never blocks) → `high` (blocks PR without ADR) → `critical` (blocks PR without ADR, requires reviewer sign-off).
16
+ - **Edit freely.** This file is yours to evolve. Promote principles from `info` to `high` once you trust the project enforces them.
17
+ - **ADR escape hatch.** A PR that violates a `high`/`critical` principle is unblocked only when an ADR in the same feature documents the deviation and trade-off.
18
+ - **Regenerate analytical version** anytime via `/dw-analyze-project` (offers to synthesize principles from observed code patterns).
19
+
20
+ ---
21
+
22
+ ## Code Quality
23
+
24
+ **P-001 — No `any` / `unknown` casts in TypeScript without justification** (severity: info)
25
+ **Rule:** Production code must not use `as any`, `as unknown`, or `// @ts-ignore` without an inline `// @ts-ignore — reason: <X>` comment naming the constraint.
26
+ **Why:** Silent type escapes leak runtime bugs that the type system was meant to catch. Each escape is a contract the type system stops enforcing.
27
+ **Enforcement:** `dw-code-review` greps the diff for `as any`/`@ts-ignore`/`@ts-expect-error` without an accompanying reason comment.
28
+
29
+ **P-002 — Functions must be testable in isolation** (severity: info)
30
+ **Rule:** A function that touches network, filesystem, database, or system clock must accept its dependency as a parameter (or via a factory) instead of importing it directly.
31
+ **Why:** Code that constructs its own dependencies cannot be tested without integration setup. Tests slow down, get skipped, and bugs ship.
32
+ **Enforcement:** `dw-code-review` flags functions importing `fs`, `axios`, `prisma`, `Date.now`, etc., directly inside business logic modules.
33
+
34
+ ---
35
+
36
+ ## Testing Standards
37
+
38
+ **P-003 — Every bug fix ships with a regression test** (severity: info)
39
+ **Rule:** A commit with type `fix:` must add or modify at least one test that would have caught the bug before the fix.
40
+ **Why:** Without the test, the bug returns the next time someone refactors the area. The fix decays.
41
+ **Enforcement:** `dw-code-review` checks that `fix:` commits include diff under `**/*test*` or `**/*spec*` paths.
42
+
43
+ **P-004 — Tests must be deterministic** (severity: info)
44
+ **Rule:** No sleep-based waits, no real-clock comparisons, no network calls to live services in unit tests. Mock at boundaries.
45
+ **Why:** Flaky tests train the team to ignore failures. The next real failure goes unnoticed.
46
+ **Enforcement:** `dw-code-review` greps tests for `setTimeout`, real fetch/axios calls, and `Date.now()` without `vi.useFakeTimers()`/`jest.useFakeTimers()`.
47
+
48
+ ---
49
+
50
+ ## UX Consistency
51
+
52
+ **P-005 — User-facing strings live in a single source** (severity: info)
53
+ **Rule:** All visible copy (labels, error messages, empty states) goes through a centralized i18n / strings module — not inline in components.
54
+ **Why:** Inline strings drift in tone, break i18n efforts, and cause duplicate-but-different copies of the same message.
55
+ **Enforcement:** `dw-code-review` flags JSX text nodes and error messages declared inside components instead of imported from `src/strings/`, `src/i18n/`, or equivalent.
56
+
57
+ **P-006 — Loading + empty + error states are mandatory for any data-fetching UI** (severity: info)
58
+ **Rule:** Any component or page that fetches data must explicitly render loading, empty, and error states — not just the happy path.
59
+ **Why:** "Just the spinner" experiences and silent error states are the #1 source of user-reported bugs.
60
+ **Enforcement:** `dw-review-implementation` checks data-fetching components for all three states in JSX or equivalent.
61
+
62
+ ---
63
+
64
+ ## Performance
65
+
66
+ **P-007 — Performance changes must cite a measurement** (severity: info)
67
+ **Rule:** Any commit that claims to improve performance must include the metric, the tool, and the before/after numbers in the commit body OR in the techspec.
68
+ **Why:** Without measurement, "performance" optimization is guesswork — and usually wrong (see `dw-simplification` + `perf-discipline.md`).
69
+ **Enforcement:** `dw-code-review` checks `perf:` commits for a numeric before/after; flags if missing.
70
+
71
+ **P-008 — N+1 queries are flagged at code review** (severity: info)
72
+ **Rule:** Loops or list operations that issue per-item database/HTTP calls must batch (e.g., `IN (...)`, `findMany`, DataLoader) or be explicitly justified.
73
+ **Why:** N+1 patterns scale linearly with data size and silently degrade until production load reveals them.
74
+ **Enforcement:** `dw-code-review` and `dw-refactoring-analysis` detect await-in-loop patterns against repository / API client modules.
75
+
76
+ ---
77
+
78
+ ## Security
79
+
80
+ **P-009 — Server-side authorization on every state-changing endpoint** (severity: info)
81
+ **Rule:** Any endpoint that creates, updates, or deletes data must verify caller authorization on the server. UI-level gating (hidden buttons, disabled forms) is not security.
82
+ **Why:** Browsers are untrusted (see `webapp-testing/security-boundary.md`). UI gating is convenience; only server checks protect data.
83
+ **Enforcement:** `dw-code-review` and `dw-security-check` require an explicit auth check (decorator, middleware, or in-handler assertion) on POST/PUT/PATCH/DELETE routes.
84
+
85
+ **P-010 — Secrets never enter the repository** (severity: info)
86
+ **Rule:** No API keys, passwords, signing keys, tokens, or production endpoints checked into source. `.env.example` documents shape only.
87
+ **Why:** Repository history is permanent. A secret committed once is leaked even if reverted next commit.
88
+ **Enforcement:** `dw-security-check` runs Trivy + secret scanners on the diff.
89
+
90
+ ---
91
+
92
+ ## Custom Principles
93
+
94
+ > Add your team's specific principles below. Follow the same format: `**P-NNN — <name>** (severity: info|high|critical): <rule>. **Why:** <reason>. **Enforcement:** <how>.`
95
+
96
+ <!-- Example:
97
+ **P-100 — All financial calculations use Decimal, never Number** (severity: critical)
98
+ **Rule:** Money values must use `Decimal` / `BigDecimal` types end-to-end. No `parseFloat`, no `Number` arithmetic.
99
+ **Why:** IEEE 754 rounding errors accumulate to cents lost over millions of transactions; audited environments mandate exact arithmetic.
100
+ **Enforcement:** `dw-code-review` greps for `Number(`/`parseFloat(` in any file under `src/billing/`, `src/payments/`, `src/finance/`.
101
+ -->
102
+
103
+ ---
104
+
105
+ ## How to evolve this file
106
+
107
+ 1. **Live in `info` for at least one release.** Watch how often each principle is violated organically; the data tells you if it's worth promoting.
108
+ 2. **Promote to `high` once violations are rare and the team agrees.** PRs that violate a `high` principle now need an ADR.
109
+ 3. **Promote to `critical` for principles that protect users / data / compliance.** Treat these as load-bearing; the ADR escape requires reviewer sign-off, not just author opt-out.
110
+ 4. **Demote or remove principles that don't earn their weight.** A constitution is a tool, not a museum.
111
+ 5. **Re-run `/dw-analyze-project`** when the codebase shifts substantially (new stack, major refactor); it can propose updates grounded in fresh observation.
@@ -645,6 +645,67 @@ packages/auth → packages/db
645
645
  - Crie o diretório .dw/rules/ se não existir
646
646
  </critical>
647
647
 
648
+ ### Step 8: Constitution Generation (Opcional, mas Recomendado)
649
+
650
+ Após escrever `.dw/rules/`, oferecer gerar `.dw/constitution.md` — os princípios declarativos que o time quer ver enforçados em PRDs, TechSpecs e Code Reviews.
651
+
652
+ **Diferença vs `.dw/rules/`:**
653
+ - `.dw/rules/` é **analítico** — o que o código É (padrões observados, anti-patterns, convenções).
654
+ - `.dw/constitution.md` é **declarativo** — o que o código DEVE SER (regras às quais o time se compromete).
655
+
656
+ **Comportamento:**
657
+
658
+ Se `.dw/constitution.md` já existir, imprimir "Constituição já existe em `.dw/constitution.md` — pulando (edite manualmente se quiser atualizar)" e encerrar.
659
+
660
+ Caso contrário, apresentar 3 opções no chat (use a UI de pergunta preferida quando disponível; caso contrário texto puro):
661
+
662
+ ```
663
+ Uma constitution ajudaria PRDs/TechSpecs/PRs a permanecerem alinhados aos padrões.
664
+ Três opções:
665
+
666
+ A) Sintetizar dos padrões observados (recomendado)
667
+ Leio `.dw/rules/` e proponho 5–8 princípios fundamentados no código real,
668
+ cada um com `Why:` ligado a evidência e `severity: info` (não bloqueia).
669
+ Você revisa e aprova antes de qualquer escrita.
670
+
671
+ B) Instalar template de defaults
672
+ Copia `templates/constitution-template.md` para `.dw/constitution.md` com
673
+ 5 princípios canônicos (Qualidade, Testes, UX, Performance, Segurança)
674
+ pré-preenchidos em `severity: info`. Você customiza manualmente.
675
+
676
+ C) Pular
677
+ Sem constitution. Comandos downstream operam sem o gate.
678
+ Você pode rodar este step novamente re-executando `/dw-analyze-project`.
679
+ ```
680
+
681
+ **Opção A — Sintetizar:**
682
+
683
+ 1. Ler `.dw/rules/index.md` + cada `.dw/rules/{module}.md`.
684
+ 2. Propor 5–8 princípios. Cada um deve:
685
+ - Ter ID único `P-NNN`.
686
+ - Mapear para uma observação em `.dw/rules/` (citar o arquivo + seção).
687
+ - Começar em `severity: info` (nunca propor `high`/`critical` automaticamente — isso é decisão do time).
688
+ - Seguir formato: `**P-NNN — <nome>** (severity: info): <regra>. **Why:** <fundamentar em evidência>. **Enforcement:** <como checar>.`
689
+ 3. **Mostrar os princípios propostos no chat como lista markdown** (não escreva o arquivo ainda). Incluir a citação de evidência para cada um.
690
+ 4. Perguntar: "Edita algum antes de eu gravar? Responda com os IDs para descartar/editar, ou 'aprovar' para escrever como está."
691
+ 5. Após aprovação (com edits aplicados), gravar em `.dw/constitution.md` usando a mesma estrutura de `templates/constitution-template.md`.
692
+ 6. Setar frontmatter `mode: custom` e `last_updated: <data ISO de hoje>`.
693
+
694
+ **Opção B — Defaults:**
695
+
696
+ 1. Localizar `templates/constitution-template.md` (projeto-local em `.dw/templates/constitution-template.md`, com fallback para scaffold bundled).
697
+ 2. Copiar para `.dw/constitution.md` literalmente. Setar frontmatter `mode: defaults`.
698
+ 3. Imprimir: "Constituição defaults instalada em `.dw/constitution.md`. Todos os 10 princípios começam em `severity: info` — reportam mas não bloqueiam. Edite o arquivo para customizar, depois promova severities para `high`/`critical` quando confiar."
699
+
700
+ **Opção C — Pular:**
701
+
702
+ 1. Nada a fazer.
703
+ 2. Imprimir: "Pulado. PRD/TechSpec/CodeReview rodarão sem o constitution gate. Re-rode `/dw-analyze-project` mais tarde se quiser habilitar."
704
+
705
+ **Em qualquer opção:**
706
+ - Nunca escrever `.dw/constitution.md` sem aprovação explícita (opção A) ou escolha explícita (opções B/C).
707
+ - Constitution é commitada ao repositório como qualquer outro artefato do projeto — nunca gitignored.
708
+
648
709
  ## Checklist de Qualidade
649
710
 
650
711
  - [ ] Estrutura do repositório escaneada
@@ -159,6 +159,34 @@ Para cada projeto impactado, verificar rules específicas em `.dw/rules/`:
159
159
  - [ ] Chamadas de API usam utilitários fetch do projeto
160
160
  - [ ] UI segue o design system do projeto
161
161
 
162
+ ### 4.1. Constitution Compliance (Obrigatório quando `.dw/constitution.md` existe)
163
+
164
+ <critical>**Auto-create se ausente**: se `.dw/constitution.md` NÃO existir, copie `templates/constitution-template.md` (project-local `.dw/templates/constitution-template.md` primeiro, com fallback para scaffold bundled) literalmente com frontmatter `mode: defaults`. Imprimir no chat: "Constituição defaults instalada em `.dw/constitution.md` (todos os princípios em `severity: info` — reportam mas não bloqueiam este review). Seguindo." Depois prossiga.</critical>
165
+
166
+ Para cada princípio em `.dw/constitution.md`, verificar o diff por violações:
167
+
168
+ 1. **Parsear princípios**: ler cada entrada `**P-NNN — <nome>** (severity: <S>)`; capturar `P-NNN`, `severity` e descrição de `Enforcement`.
169
+ 2. **Aplicar enforcement**: para cada princípio, rodar a checagem de enforcement contra o diff (grep, inspeção de arquivo ou pattern match conforme a linha Enforcement).
170
+ 3. **Classificar violações**:
171
+ - Princípio `severity: info` → adicione linha à tabela "Issues Found" com severity `low`. **Não bloqueia** o verdict.
172
+ - Princípio `severity: high` → adicione linha com severity `critical`. **Bloqueia** o verdict como `REJECTED` EXCETO se um ADR no `adrs/` do mesmo PRD documenta o desvio (busque `Deviates: P-NNN` no corpo de qualquer ADR).
173
+ - Princípio `severity: critical` → adicione linha com severity `critical` E exigir que o ADR tenha campo `Approved by:` não-vazio. Campo ausente = ainda `REJECTED`.
174
+ 4. **Sem skip silencioso**: se o diff for grande demais para analisar todos os princípios, reportar quais foram checados e quais foram pulados por escopo.
175
+
176
+ **Formato de saída no relatório:**
177
+
178
+ ```markdown
179
+ ## Constitution Compliance
180
+
181
+ | Princípio | Severity | Status | Evidência | ADR escape |
182
+ |-----------|----------|--------|-----------|------------|
183
+ | P-001 — Sem `any` casts | info | VIOLATED | src/foo.ts:42 | n/a |
184
+ | P-009 — Auth server-side | high | VIOLATED | src/api/order.ts:18 sem auth middleware | none → BLOQUEIA |
185
+ | P-010 — Secrets no repo | critical | PASS | — | — |
186
+ ```
187
+
188
+ Se houver violação `high`/`critical` sem ADR escape: adicionar à linha de verdict "REPROVADO — violação(ões) de constitution sem ADR (ver seção Constitution Compliance)".
189
+
162
190
  ### 5. Análise de Qualidade de Código (Obrigatório)
163
191
 
164
192
  | Aspecto | Verificação |
@@ -50,6 +50,22 @@
50
50
  - Use `.dw/rules/` como contexto, caindo para grep
51
51
  - Sugira rodar `/dw-map-codebase` para enriquecer contexto downstream
52
52
 
53
+ ## Constitution Gate
54
+
55
+ <critical>ANTES das clarification questions, cheque `.dw/constitution.md`:
56
+
57
+ **Se AUSENTE**: copie `templates/constitution-template.md` (project-local em `.dw/templates/constitution-template.md`, com fallback para scaffold bundled) literalmente para `.dw/constitution.md`. Setar frontmatter `mode: defaults` e `last_updated` para data ISO de hoje. Imprimir no chat:
58
+
59
+ > "Notei que `.dw/constitution.md` estava ausente. Instalei defaults em `.dw/constitution.md` (10 princípios canônicos, todos em `severity: info` — reportam mas não bloqueiam). Pode customizar a qualquer momento — ou re-rodar `/dw-analyze-project` para versão sob medida. Seguindo com o PRD."
60
+
61
+ Depois prossiga normalmente, tratando o arquivo recém-criado como a constitution.
62
+
63
+ **Se PRESENTE**: leia antes de redigir requisitos. Cada FR no PRD DEVE incluir linha "Constitution Alignment" mapeando para ≥1 princípio relevante (`Respects: P-001, P-009`) OU declarando explicitamente "no applicable principle" com motivo em uma linha. Sem alignment = FR está incompleto.
64
+
65
+ **Regras de severity** (aplicadas pelos comandos downstream, não enforçadas aqui):
66
+ - Violações `severity: info` → reportadas, nunca bloqueiam.
67
+ - Violações `severity: high` / `critical` → bloqueiam em `dw-create-techspec` e `dw-code-review` exceto se ADR justificar.</critical>
68
+
53
69
  ## Features Multi-Projeto
54
70
 
55
71
  Muitas funcionalidades podem envolver mais de um projeto no workspace.
@@ -149,5 +149,47 @@
149
149
  3. /dw-generate-pr [branch-alvo] quando todas tasks concluídas
150
150
  ```
151
151
 
152
+ ## Final Consistency Check (Auto-invocado antes da aprovação do usuário)
153
+
154
+ <critical>ANTES de apresentar tasks ao usuário, rode um check de consistência em 5 dimensões. Isto é mandatório; não pule mesmo se confiante de que as tasks estão limpas.</critical>
155
+
156
+ Rode estes 5 checks contra o conjunto PRD + TechSpec + tasks gerado:
157
+
158
+ 1. **Cobertura de RF** — cada RF numerada no PRD mapeia para ≥1 task. RFs órfãs (PRD tem; nenhuma task cobre) são FAIL.
159
+ 2. **Grounding das tasks** — cada task gerada referencia ≥1 RF em seu corpo (`Cobre: RF-N.M`). Tasks sem referência a RF sinalizam scope creep.
160
+ 3. **Cobertura de teste** — cada RF com comportamento user-facing (UI, endpoint de API, mutação de dado) tem ≥1 task que adiciona teste (subtask contendo "test", "spec", "e2e" ou equivalente).
161
+ 4. **Grafo de dependências** — dependências entre tasks (X.0 → Y.0 declarado como "Depende de") formam DAG. Sem ciclos. Ordem topológica válida.
162
+ 5. **Alinhamento com constitution** (só se `.dw/constitution.md` existir) — cada task lista `Constitution: respects P-NNN, P-MMM` OU `Constitution: deviates P-NNN — ADR planejado: <slug>` OU `Constitution: n/a — motivo: <one-liner>`. Linha ausente = FAIL.
163
+
164
+ Escreva findings em `.dw/spec/prd-[nome-funcionalidade]/tasks-validation.md` com esta estrutura exata:
165
+
166
+ ```markdown
167
+ # Relatório de Validação de Tasks
168
+
169
+ Gerado por /dw-create-tasks em YYYY-MM-DD.
170
+
171
+ | Dimensão | Status | Findings |
172
+ |----------|--------|----------|
173
+ | 1. Cobertura de RF | PASS / FAIL | <lista de RFs órfãs ou "todas RFs cobertas"> |
174
+ | 2. Grounding de tasks | PASS / FAIL | <lista de tasks sem RF ou "todas tasks referenciam RFs"> |
175
+ | 3. Cobertura de teste | PASS / FAIL | <RFs sem testes ou "todas RFs user-facing cobertas"> |
176
+ | 4. Grafo de dependências | PASS / FAIL | <ciclos ou "DAG válido"> |
177
+ | 5. Alinhamento constitution | PASS / FAIL / N/A | <tasks não-alinhadas ou "todas alinhadas" ou "sem constitution"> |
178
+
179
+ ## Findings Detalhados
180
+
181
+ <uma seção por dimensão FAIL com fixes concretos; vazio se tudo PASS>
182
+ ```
183
+
184
+ **Comportamento do gate:**
185
+
186
+ - **Todas as 5 dimensões PASS (ou N/A)** → apresente tasks ao usuário normalmente e peça aprovação.
187
+ - **Qualquer dimensão FAIL** → PARE. Mostre a tabela no chat como markdown (NÃO esconda no arquivo de validação; o usuário precisa ver antes de aprovar). Depois pergunte ao usuário:
188
+ - "(a) Quer que eu conserte as tasks automaticamente?" → regenerar tasks afetadas, re-rodar o check.
189
+ - "(b) Vai editar tasks.md manualmente?" → aguardar usuário sinalizar conclusão, re-rodar o check.
190
+ - "(c) Override e seguir mesmo com FAIL?" → exigir mensagem de override explícita ("override: aceito o gap porque <motivo>"). Persistir o override em `tasks-validation.md` para auditabilidade.
191
+
192
+ O arquivo `tasks-validation.md` é commitado junto com `tasks.md`. Comandos downstream (`/dw-run-plan`, `/dw-code-review`, `/dw-review-implementation`) podem referenciá-lo.
193
+
152
194
  Após completar a análise e gerar todos os arquivos necessários, apresente os resultados ao usuário e aguarde confirmação para prosseguir com a implementação.
153
195
  </system_instructions>
@@ -39,6 +39,23 @@
39
39
  - Use `.dw/rules/` como contexto, caindo para grep
40
40
  - Sugira rodar `/dw-map-codebase` para enriquecer contexto downstream
41
41
 
42
+ ## Constitution Gate
43
+
44
+ <critical>ANTES de redigir decisões arquiteturais, cheque `.dw/constitution.md`:
45
+
46
+ **Se AUSENTE**: copie `templates/constitution-template.md` (project-local em `.dw/templates/constitution-template.md`, com fallback para scaffold bundled) literalmente para `.dw/constitution.md`. Setar frontmatter `mode: defaults`. Imprimir no chat: "Constituição defaults instalada em `.dw/constitution.md` (severity: info — não bloqueia este techspec). Seguindo." Depois prossiga.
47
+
48
+ **Se PRESENTE**: leia. Toda escolha de framework / library / arquitetura no techspec DEVE carregar uma de:
49
+ - `Respects: P-NNN` — a decisão honra ativamente o(s) princípio(s) nomeado(s).
50
+ - `Deviates: P-NNN — justification: <slug do ADR ou racional em uma linha>` — a decisão se afasta intencionalmente do princípio.
51
+
52
+ **Gate graduado por severity:**
53
+ - Desvio de princípio `severity: info` → apenas registra, nunca bloqueia.
54
+ - Desvio de princípio `severity: high` sem ADR linkado (`.dw/spec/<prd>/adrs/adr-NNN.md`) → BLOQUEIA o techspec. Instrua o usuário a revisar a decisão OU criar ADR via `/dw-adr` documentando o trade-off.
55
+ - Desvio de princípio `severity: critical` → BLOQUEIA o techspec com mesma exigência de ADR, adicionalmente exigindo acknowledgment de reviewer no campo `Approved by` do ADR.
56
+
57
+ Sem exceções para `high`/`critical` sem ADR. Se o usuário resistir, aponte para `/dw-adr` — esse é o escape hatch por design.</critical>
58
+
42
59
  ## Fluxograma de Decisão Multi-Projeto
43
60
 
44
61
  ```dot
@@ -0,0 +1,111 @@
1
+ ---
2
+ schema_version: "1.0"
3
+ generated_by: dev-workflow
4
+ last_updated: YYYY-MM-DD
5
+ mode: defaults | custom
6
+ ---
7
+
8
+ # Constituição do Projeto
9
+
10
+ > Princípios declarativos que este time escolheu seguir. PRDs, TechSpecs e Code Reviews leem este arquivo como hard gate. Qualquer coisa que viole um princípio com `severity: critical` ou `high` é bloqueada — exceto quando justificada por um ADR explícito.
11
+
12
+ ## Como este arquivo funciona
13
+
14
+ - **Cada princípio tem um ID (`P-NNN`), severity, regra, `Why` e `Enforcement`.**
15
+ - **Escala de severity:** `info` (apenas reporta, nunca bloqueia) → `high` (bloqueia PR sem ADR) → `critical` (bloqueia PR sem ADR + exige aprovação de reviewer).
16
+ - **Edite à vontade.** Este arquivo é seu para evoluir. Promova princípios de `info` para `high` quando confiar que o projeto cumpre.
17
+ - **Escape via ADR.** Um PR que viola princípio `high`/`critical` é desbloqueado quando um ADR na mesma feature documenta o desvio e o trade-off.
18
+ - **Versão analítica regenerável** a qualquer momento via `/dw-analyze-project` (oferece sintetizar princípios a partir dos padrões observados no código).
19
+
20
+ ---
21
+
22
+ ## Qualidade de Código
23
+
24
+ **P-001 — Sem `any` / `unknown` em TypeScript sem justificativa** (severity: info)
25
+ **Regra:** Código de produção não pode usar `as any`, `as unknown` ou `// @ts-ignore` sem comentário inline `// @ts-ignore — motivo: <X>` nomeando a restrição.
26
+ **Why:** Escapes silenciosos do tipo vazam bugs de runtime que o type system existia para pegar. Cada escape é um contrato que o type system para de garantir.
27
+ **Enforcement:** `dw-code-review` greppa o diff por `as any`/`@ts-ignore`/`@ts-expect-error` sem comentário-razão correspondente.
28
+
29
+ **P-002 — Funções devem ser testáveis isoladamente** (severity: info)
30
+ **Regra:** Função que toca rede, filesystem, banco de dados ou system clock deve receber a dependência como parâmetro (ou via factory) em vez de importar diretamente.
31
+ **Why:** Código que constrói suas próprias dependências não pode ser testado sem setup de integração. Testes ficam lentos, são pulados, e bugs vão pra produção.
32
+ **Enforcement:** `dw-code-review` flagueia funções importando `fs`, `axios`, `prisma`, `Date.now`, etc., diretamente em módulos de business logic.
33
+
34
+ ---
35
+
36
+ ## Padrões de Teste
37
+
38
+ **P-003 — Todo bug fix carrega um regression test** (severity: info)
39
+ **Regra:** Commit com tipo `fix:` deve adicionar ou modificar pelo menos um teste que teria pego o bug antes do fix.
40
+ **Why:** Sem o teste, o bug volta na próxima vez que alguém refatora a área. O fix se deteriora.
41
+ **Enforcement:** `dw-code-review` verifica se commits `fix:` incluem diff em paths `**/*test*` ou `**/*spec*`.
42
+
43
+ **P-004 — Testes devem ser determinísticos** (severity: info)
44
+ **Regra:** Sem `sleep`-based waits, sem comparações de relógio real, sem chamadas a serviços live em unit tests. Mockar em boundaries.
45
+ **Why:** Testes flaky treinam o time a ignorar falhas. A próxima falha real passa despercebida.
46
+ **Enforcement:** `dw-code-review` greppa testes por `setTimeout`, chamadas reais de fetch/axios, e `Date.now()` sem `vi.useFakeTimers()`/`jest.useFakeTimers()`.
47
+
48
+ ---
49
+
50
+ ## Consistência de UX
51
+
52
+ **P-005 — Strings user-facing vivem em fonte única** (severity: info)
53
+ **Regra:** Toda copy visível (labels, mensagens de erro, empty states) passa por um módulo centralizado de i18n / strings — não inline em componentes.
54
+ **Why:** Strings inline driftam no tom, quebram esforços de i18n e causam duplicatas da mesma mensagem em variações sutis.
55
+ **Enforcement:** `dw-code-review` flagueia text nodes JSX e mensagens de erro declarados dentro de componentes em vez de importados de `src/strings/`, `src/i18n/`, ou equivalente.
56
+
57
+ **P-006 — Estados de loading + empty + error são obrigatórios em qualquer UI que busca dados** (severity: info)
58
+ **Regra:** Componente ou página que faz fetch deve renderizar explicitamente loading, empty e error — não só o happy path.
59
+ **Why:** Experiências "só com spinner" e estados de erro silencioso são a #1 fonte de bugs reportados por usuários.
60
+ **Enforcement:** `dw-review-implementation` verifica componentes de data-fetching pelos três estados em JSX ou equivalente.
61
+
62
+ ---
63
+
64
+ ## Performance
65
+
66
+ **P-007 — Mudanças de performance carregam medição** (severity: info)
67
+ **Regra:** Qualquer commit que afirme melhorar performance deve incluir a métrica, a ferramenta e os números antes/depois no body do commit OU no techspec.
68
+ **Why:** Sem medição, "otimização" de performance é palpite — e geralmente errado (ver `dw-simplification` + `perf-discipline.md`).
69
+ **Enforcement:** `dw-code-review` verifica commits `perf:` por números antes/depois; flagueia se ausente.
70
+
71
+ **P-008 — Queries N+1 são flagueadas em code review** (severity: info)
72
+ **Regra:** Loops ou operações em lista que disparam chamadas DB/HTTP por item devem batchar (ex: `IN (...)`, `findMany`, DataLoader) ou ser explicitamente justificadas.
73
+ **Why:** Padrões N+1 escalam linearmente com tamanho dos dados e silenciosamente degradam até que a carga de produção revele.
74
+ **Enforcement:** `dw-code-review` e `dw-refactoring-analysis` detectam padrões await-em-loop contra módulos de repository / API client.
75
+
76
+ ---
77
+
78
+ ## Segurança
79
+
80
+ **P-009 — Authorization server-side em todo endpoint que altera estado** (severity: info)
81
+ **Regra:** Endpoint que cria, atualiza ou deleta dado deve verificar autorização do caller no servidor. Gating em UI (botões escondidos, formulários disabled) não é segurança.
82
+ **Why:** Browsers são untrusted (ver `webapp-testing/security-boundary.md`). Gating em UI é conveniência; só checks server-side protegem dado.
83
+ **Enforcement:** `dw-code-review` e `dw-security-check` exigem check de auth explícito (decorator, middleware ou assertion in-handler) em rotas POST/PUT/PATCH/DELETE.
84
+
85
+ **P-010 — Secrets nunca entram no repositório** (severity: info)
86
+ **Regra:** Nenhuma API key, password, signing key, token ou endpoint de produção commitado em source. `.env.example` documenta forma apenas.
87
+ **Why:** Histórico de repositório é permanente. Um secret commitado uma vez está vazado mesmo que revertido no commit seguinte.
88
+ **Enforcement:** `dw-security-check` roda Trivy + secret scanners no diff.
89
+
90
+ ---
91
+
92
+ ## Princípios Customizados
93
+
94
+ > Adicione princípios específicos do seu time abaixo. Mesmo formato: `**P-NNN — <nome>** (severity: info|high|critical): <regra>. **Why:** <motivo>. **Enforcement:** <como>.`
95
+
96
+ <!-- Exemplo:
97
+ **P-100 — Todo cálculo financeiro usa Decimal, nunca Number** (severity: critical)
98
+ **Regra:** Valores monetários devem usar tipos `Decimal` / `BigDecimal` end-to-end. Sem `parseFloat`, sem aritmética com `Number`.
99
+ **Why:** Erros de arredondamento IEEE 754 acumulam centavos perdidos em milhões de transações; ambientes auditados exigem aritmética exata.
100
+ **Enforcement:** `dw-code-review` greppa por `Number(`/`parseFloat(` em qualquer arquivo sob `src/billing/`, `src/payments/`, `src/finance/`.
101
+ -->
102
+
103
+ ---
104
+
105
+ ## Como evoluir este arquivo
106
+
107
+ 1. **Viva em `info` por pelo menos um release-ciclo.** Observe quão frequentemente cada princípio é violado organicamente; o dado te diz se vale promover.
108
+ 2. **Promova para `high` quando violações forem raras e o time concordar.** PRs que violarem princípio `high` agora precisam de ADR.
109
+ 3. **Promova para `critical` os princípios que protegem usuários / dados / compliance.** Trate-os como load-bearing; o escape via ADR exige aprovação de reviewer, não só opt-out do autor.
110
+ 4. **Demote ou remova princípios que não ganharam seu peso.** Constitution é ferramenta, não museu.
111
+ 5. **Re-rode `/dw-analyze-project`** quando o codebase mudar substancialmente (nova stack, refactor grande); ele pode propor updates fundamentados em observação fresca.
@@ -0,0 +1,75 @@
1
+ # Template Overrides
2
+
3
+ Files in this directory override the corresponding templates in `.dw/templates/`. Use this when your team needs a customized PRD/TechSpec/Task/etc. shape **without** losing the ability to receive `dev-workflow` updates.
4
+
5
+ ## How it works
6
+
7
+ - During `dev-workflow init` or `dev-workflow update`, the CLI copies templates from the package into `.dw/templates/`.
8
+ - Before writing each file, the CLI checks `.dw/templates/overrides/` for a same-named file.
9
+ - If found, **the override is preserved and the core template is skipped**. Your customization wins.
10
+ - If not found, the core template is installed/updated normally.
11
+
12
+ ## How to override a template
13
+
14
+ ```bash
15
+ # 1. Copy the template you want to customize from .dw/templates/ to .dw/templates/overrides/
16
+ cp .dw/templates/prd-template.md .dw/templates/overrides/prd-template.md
17
+
18
+ # 2. Edit the override to fit your team's process
19
+ $EDITOR .dw/templates/overrides/prd-template.md
20
+
21
+ # 3. Commit it. Future updates won't touch this file.
22
+ git add .dw/templates/overrides/prd-template.md
23
+ git commit -m "chore(templates): customize PRD template for our team"
24
+ ```
25
+
26
+ The override takes effect immediately. Commands that consume the template (`/dw-create-prd`, etc.) will read from `.dw/templates/<name>.md`, which is preserved as your edited copy.
27
+
28
+ ## How to revert an override
29
+
30
+ ```bash
31
+ # 1. Delete the override
32
+ rm .dw/templates/overrides/prd-template.md
33
+
34
+ # 2. Re-run dev-workflow update to restore the core template
35
+ npx @brunosps00/dev-workflow update
36
+ ```
37
+
38
+ ## When an override is appropriate
39
+
40
+ - Adding required sections specific to your industry (compliance, finance, healthcare).
41
+ - Removing sections that don't apply.
42
+ - Renaming sections to match your team's vocabulary.
43
+ - Embedding links to internal tools, dashboards, runbooks.
44
+
45
+ ## When an override is **not** appropriate
46
+
47
+ - Removing critical-path sections like FR numbering or test plans — downstream commands rely on these.
48
+ - Adding fields that conflict with the YAML frontmatter schema.
49
+ - Anything that breaks `/dw-create-techspec` or `/dw-create-tasks` cross-references.
50
+
51
+ If in doubt, run the workflow end-to-end after editing — the consistency check at the end of `/dw-create-tasks` will surface most structural breakages.
52
+
53
+ ## Versioning your overrides
54
+
55
+ When `dev-workflow` releases a new minor version, the core templates may change shape (new sections, renamed fields). Your override will continue to work, but it might lack the new sections.
56
+
57
+ Recommended cadence: when you upgrade `dev-workflow`, `diff` your override against the new core template:
58
+
59
+ ```bash
60
+ diff .dw/templates/overrides/prd-template.md .dw/templates/prd-template.md
61
+ ```
62
+
63
+ Merge in anything you want from upstream. The override stays canonical; the core template is just a reference.
64
+
65
+ ## Subdirectories
66
+
67
+ Overrides can mirror the directory structure of `.dw/templates/`. For example, to override a file inside `functional-doc/`:
68
+
69
+ ```
70
+ .dw/templates/overrides/
71
+ └── functional-doc/
72
+ └── e2e-runbook.md
73
+ ```
74
+
75
+ The resolver descends recursively — each leaf file is checked independently against its corresponding path under `overrides/`.