---
stacks:
  - "*"
---

# MORPH-SPEC Workflow Rules

> Always-active rules for all MORPH-SPEC managed projects.

---

## Spec-First Mandate

**NEVER skip to code without a specification.** Every feature must progress through phases:

1. **Proposal** — Problem statement + scope + risks (`0-proposal/proposal.md`). No acceptance criteria: verifiable behaviour lives in the use cases.
2. **UI/UX Design** (optional, UI-heavy) — Design system + mockups + flows. The phase id is `uiux` (that is the gate name); the folder is `1-design/`
3. **Plan** — Use cases first, then technical spec + mandate + tasks (`2-plan/usecases/UC-{nn}-{slug}.md`, `spec.md`, `mandate.md`, `tasks.json`). Each use case post-condition must be observable in a test and reaches the task's `doneCriteria` verbatim.
4. **Implement** — Code + recap (`3-implement/recap.md`)
5. **Review** — Review report + Gate 3 (`4-review/review-report.md`)

---

## Phase Sequence

```
proposal → [uiux] → plan → implement → review
```

Use `morph-spec status {feature}` to see current phase and pending approval gates.

---

## Phase Commands

| Command | Purpose |
|---------|---------|
| `/morph-proposal {feature}` | Business understanding + plan — pauses at Gate 1 and Gate 2 |
| `/morph-apply {feature}` | Autonomous execution + review — pauses at Gate 3 |
| `/morph-status` | Feature dashboard |

The full slash-command and CLI surface lives in the resident `.claude/CLAUDE.md` and in
`.morph/framework/CLI.md` — this table only carries the three phase entry points.

---

## State & Outputs

| Path | Notes |
|------|-------|
| `.morph/features/{feature}/feature.json` | **Authoritative + committed** feature state. Write it through the CLI (`create`, `score`, `gate-check`, `approve`) — a hand Edit collides with the `state-sync` hook |
| `.morph/state.json` | **READ-ONLY** — thin, gitignored index rebuilt from `feature.json` on load; kept in sync by the `state-sync` hook |
| `.morph/features/{feature}/{phase}/` | Feature outputs organized by phase |
| `.morph/framework/` | **READ-ONLY** — framework files managed by morph-spec |
| `.morph/config/config.json` | Project configuration (editable) |

### output types

The canonical filename and phase folder of every output type are fixed by
morph-spec itself — the concrete paths are in the table below. State sync is
handled automatically by the `state-sync.js` PostToolUse hook: write the file
at the right path and it is recorded; the agent does not call any CLI to
register an output.

---

## Output Paths

All outputs go in `.morph/features/{feature}/`:

| Phase | Path |
|-------|------|
| Proposal | `0-proposal/proposal.md`, `stack-scan.md` |
| Design (optional) | `1-design/design-system.md`, `mockups.md`, `components.md`, `flows.md` |
| Plan | `2-plan/spec.md`, `mandate.md`, `tasks.json`, `decisions.md` |
| Implement | `3-implement/recap.md` + source code; `3-implement/evidencias/{taskId}.md` (condicional — task cujo `doneCriteria` julga saída de LLM) |
| Review | `4-review/review-report.md` |

---

## Formato obrigatório do `3-implement/recap.md`

> Esta exigência é **cobrada por hook** (`validate-completion`, no Stop). Ela está aqui, na regra
> sempre-ativa, e não só na skill `morph-implement`: descobrir o formato quando o hook dispara
> significa reescrever o recap depois de a fase já estar dada por encerrada.

**Para CADA task com `status: "done"` em `tasks.json`**, o recap precisa de um bloco próprio:

1. um heading `## T{N}` (o hook casa `^## T\d+` — uma linha de tabela `| T1 | … | done |` conta
   como menção, **não** como bloco);
2. uma linha `**Standard:** {standard-id}` **dentro de 12 linhas** do heading. Sem standard que
   cubra o caso, registre a decisão em `decisions.md` e cite
   `**Standard:** ad-hoc (see decisions.md ADR-{N})`.

```markdown
## T{N} — {title}

**Standard:** {standard-id} (`.morph/framework/standards/{path}.md`)
**Persona:** {mecanismo real usado}
**Files:**
- `{path}`

{2-3 frases sobre o que foi feito}

**Issues encontrados:** {breve descrição ou "nenhum"}
```

O `validate-completion` também acusa **drift**: uma task que aparece como concluída no recap mas
ainda está `pending`/`in_progress` no `tasks.json`. Template completo e regras de exceção em
`morph-implement` §6.

---

## Checkpoints

Run a checkpoint every 3 completed tasks:
- Validate architecture compliance
- Check package versions
- Scan for security issues
- Verify design system adherence (UI features)

---

## Approval Gates

Before completing any phase, verify pending approval gates:
- `morph-spec approval-status <feature>` — check which gates are pending
- `morph-spec approve <feature> <gate>` — approve a gate (`proposal`, `plan`, `review`; `uiux` if applicable)
- `morph-spec advance <feature>` — approve the current gate AND scaffold the next phase folder in one step
- Gates must be approved before advancing to the next phase

---

## Protected Files

**NEVER directly edit:**
- `.morph/state.json` — Managed by CLI only
- `.morph/framework/**` — Read-only framework content

---

## Test File Policy

When a test fails, always follow this order:

1. **Analyze first** — determine if the IMPLEMENTATION is wrong or the TEST SPEC is wrong
2. **Fix implementation first** — the test is the spec; trust it by default
3. **Only modify a test file if the test expectation itself is incorrect** — wrong expected value, wrong behavior modeled
4. **Before modifying any test file, explain WHY the test spec is wrong** — what the correct behavior is and why the test doesn't model it

Do not modify test files to make a failing test pass when the implementation is the actual problem.

---

## Context Maintenance

After making structural changes (new packages, dependencies, project config changes), update the project context:
- Edit `.morph/context/README.md` — update Tech Stack, Architecture, Key Integrations sections
- Update `.morph/config/config.json` — update stack, architecture, integrations, paths
- Structural changes include: package.json, .csproj, next.config.*, tsconfig.json, docker-compose.yml

---

## Spec-Driven Task Execution (implement phase)

BEFORE implementing ANY task during the implement phase:

1. **Read tasks.json** → identify the current task object (`id`, `description`, `doneCriteria`, `dependencies`)
2. **Read spec.md** → the FR sections that the task `description` references
3. **Read the contracts** → the DTOs/interfaces are defined inside `spec.md` (v5 keeps contracts in the spec, not separate files)
4. Only then begin implementation

This is **NON-NEGOTIABLE**. The spec is the source of truth. Code that doesn't match the spec is a bug.

Every task in `tasks.json` MUST reference its FR(s) in the `description` field so the link to the spec is explicit:
```json
{
  "id": "T1",
  "title": "Create user endpoint",
  "description": "Implement user CRUD (FR001) and input validation (FR003). Contracts: CreateUserRequest, CreateUserResponse, UserErrors.",
  "dependencies": [],
  "effort": "M",
  "doneCriteria": "POST /users creates a user and rejects invalid input",
  "status": "pending",
  "outputs": ["Features/UserFeature/Create/Handler.cs", "Validator.cs", "Endpoint.cs"],
  "group": "backend"
}
```

---

## Debugging

When a bug or unexpected behavior shows up mid-task, invoke `superpowers:systematic-debugging`
with the `Skill()` tool **before proposing a fix** — root cause first, never a patch on the
symptom. This is MANDATORY; do NOT skip it.

Everything else that a rule like this might list is owned by the flow itself, and duplicating it
here would put a second, staler copy in permanent context:

| Concern | Where it actually lives |
|---------|-------------------------|
| TDD before writing code | The feature's `mandate.md` (TDD is built in) — the resident `.claude/CLAUDE.md` says to prefer `morph-*` over the generic `superpowers:*` equivalents |
| Verifying a task before `status: "done"` | `morph-spec verify {feature} [task]` (build + tests + validators + e2e), then the `morph-eval` skill for the 0-10 score |
| Parallel dispatch | `morph-spec dag {feature}` decides sequential vs parallel; execution and isolation rules are in `morph-apply` §2/§3b |
| Closing the phase / opening the PR | `morph-review` for Gate 3, then `morph-spec finish {feature} --pr\|--merge` |

---

## Scope Escalation

The plan contract frozen at Gate 2 — `spec.md`, `mandate.md`, and the immutable `tasks.json`
fields listed in `morph-task-tracking.md` — is enforced by the `protect-spec-files` hook. When a
task turns out to be bigger than estimated, three different situations resolve three different ways:

| Situation | Path |
|-----------|------|
| **Small addition**, still inside the task's scope | Record it in the task's `notes` (a mutable field) — no gate to revoke, no contract to amend |
| **Error of fact**: the spec asserts something about the code that the code contradicts, with no scope change | Append an `## Errata` block at the END of the file. Body untouched, append-only, accepted by `protect-spec-files` **without revoking the gate** — freezing the CONTRACT is not freezing an ERROR OF FACT (MORPH.md §3) |
| **The scope itself changed**: the contract no longer describes the work | `morph-spec unapprove {feature} plan --reason "..."`, amend the plan, then re-approve. There is no shortcut around the gate for this one |

Scope ambiguity the `mandate.md` does not cover is **not** an escalation: record it in
`decisions.md`, resolve it the conservative way, and keep going — only pause if it is genuinely
blocking (`morph-implement` §5).

**Never** implement extra functionality within a task without registering it — `notes` for small
additions, gate revocation for anything that changes the plan contract.

---

## Context Window Tip

When using 3+ MCPs, add `"experimental": { "mcpCliMode": true }` to `.claude/settings.json`.
MCP tools load on-demand instead of all at startup — keeps context clean for actual work.

---

*MORPH-SPEC by Polymorphism Tech*
