--- name: dev-designer description: Use when analyzing high-level requirements to design a complete software Epic across Web Applications, Flutter, Android Native, iOS Native, Python, or Rust projects, including High-Level Design (HLD), Mermaid diagrams, Integration Test Plans, and Kanban task breakdowns with BDD & TDD specifications. --- # Development Designer ## Overview This skill transforms high-level product or technical requirements into a structured, developer-ready Epic for **Web Applications**, **Flutter**, **Android Native**, **iOS Native**, **Python**, and **Rust Core / Polyglot** projects. It creates a centralized High-Level Design (HLD) document, formalizes an **Integration Test Plan** covering analyzed use cases and boundary edge cases, and breaks the work down into granular Kanban tasks enforcing Behavior-Driven Development (BDD), Test-Driven Development (TDD), and strict Definition of Done (DoD), fully aligned with `dev-implementation`'s Tri-Persona workflow (QA Red Team + TDD Master + System Integration Engineer). This skill is **Stage 2** of the Epic Lifecycle. The surrounding stages, the five approval gates, and what each stage hands over are owned by the [`dev-lifecycle`](../dev-lifecycle/SKILL.md) skill. Gate 2 (task breakdown confirmed) is enforced below, at the Checkpoint before task files are written. ## When to Use - When the user provides a high-level requirement or problem statement and asks for a technical design or task breakdown. - When starting a new major feature, epic, or large-scale refactoring. - When generating architecture diagrams (Use Cases, Sequence, Architecture) and converting them into actionable tasks. - When the `dev-brainstorming` skill routes here after spec approval, for a spec it judged epic-scale. ## Input This skill can start from either: 1. **A raw high-level requirement** given directly by the user (standalone use). 2. **An approved spec from the `dev-brainstorming` skill** (preferred entry point — the spec has already been through clarifying questions, alternatives, and user approval). For epic-scale work, `dev-brainstorming` relocates the `.en.md` and `.vi.md` spec pair into this epic's own directory before invoking this skill — so both specs already live alongside the HLD and task files this skill generates. When invoked with an approved spec, **treat it as the source of truth for scope and decisions already made** — do not re-litigate architecture choices or trade-offs the user already approved. Your job is to *formalize* it: translate its architecture/components/data-flow into the Mermaid diagrams and structured sections below, and break it into Kanban tasks. If the spec is missing something this skill requires (e.g., a rollout strategy), fill the gap, but don't override decisions the spec already made. Record the link back to the matching-language source in each Epic **Meta Data** section: the English HLD links to the `.en.md` spec and the Vietnamese HLD links to the `.vi.md` spec. These are same-directory links, so the HLD and original spec pair remain traceable without leaving `.devtool/epic//`. If there is no source spec (standalone use), omit this field. If the original `dev-brainstorming` request was decomposed into multiple sub-project specs, each spec maps to **its own separate epic** — never merge multiple specs into one epic directory. ## Workflow / Prompt Instructions When invoked, you MUST strictly follow this exact 3-step workflow to organize the user's requirements: ### Step 0: Detect Target Platform & Polyglot Worktree Bootstrap Detect the active project platform architecture: - **Web Applications / Frontend**: Root or app package contains `package.json` with web frameworks (`astro.config.*`, `vite.config.*`, `next.config.*`, `nuxt.config.*`, `svelte.config.*`, `webpack.config.*`). - **Flutter**: Root contains `pubspec.yaml` or `melos.yaml`. - **Android Native**: Root contains `settings.gradle.kts`, `settings.gradle`, or `build.gradle.kts` (without root `pubspec.yaml`). - **iOS Native**: Root contains `Project.swift`, `Tuist.swift`, or `Package.swift`. - **Python**: Root contains `pyproject.toml`, `setup.py`, `Pipfile`, or `requirements.txt`. - **Rust Core / Polyglot**: Root contains `Cargo.toml`. For polyglot repositories containing multiple project layers (e.g. Python backend + Web frontend + Rust core), `detect_project_type.sh --all` detects all active project types, and `bootstrap_worktree.sh` executes sequential bootstrap steps. In Python projects, `.agents/quality/python-quality.json` supports an optional `"bootstrap"` command list (e.g. `[["uv", "sync"], ["uv", "run", "playwright", "install"]]`) executed automatically during worktree creation. ### Step 1: Create the Epic Overview Document (HLD/RFC — Human-Facing System Overview & Maintenance Map) Generate the Epic Overview documents inside a dedicated directory: `.devtool/epic//`. **Document Separation Principle ("Prompt to Maintain" vs Execution SSOT)**: To prevent LLM context bloat while maximizing human maintainability and edge-case coverage, the Epic documentation is strictly separated by audience and purpose: - **HLD (`.en.md` / `.vi.md`) — For Humans & System Maintenance ("Prompt to Maintain")**: A concise, high-signal architectural overview and feature maintenance map so developers (and future maintenance sessions) immediately grasp how the feature works, where its entry points live, and how components interact — enabling targeted *"Prompt to Maintain"* workflows instead of *"Prompt and Pray"*. **Do NOT embed raw Gherkin BDD blocks inside the HLD.** - **BDD Suite (`bdd_scenarios.en.md` / `.vi.md`) — Exhaustive Edge-Case & Exception Matrix**: Dedicated exclusively to catching the maximum number of boundary conditions, malformed inputs, race conditions, exceptions, and failure/rollback paths across all 5 dimensions. - **Task Files (`task_*.md`) — LLM Execution SSOT**: Self-contained execution contracts (containing `Allowed files`, `Decisions Already Made`, assigned `### BDD SCENARIOS`, and `## Verification`) loaded one task at a time during `dev-implementation` so the coding model stays 100% focused. **Self-sufficiency check (source spec placement)**: if this epic has a source spec and its `.en.md` and `.vi.md` pair is not already inside `.devtool/epic//` — for example, the pair is still under `docs/superpowers/specs/` — relocate both files before writing anything else. Check every relative link in both files from the new location and fix failures. Commit the pair's move on its own before generating the HLD. Never move only one language or leave the pair split across `docs/` and `.devtool/epic/`. You MUST generate two language variants for the overview document: - English: `.devtool/epic//.en.md` - Vietnamese: `.devtool/epic//.vi.md` Each document MUST contain the following sections: 1. **Table of Contents (Mục lục)**: A linked entry for every `##` section in the document. 2. **Meta Data**: Epic name, Status, Target Release, Platform (`Web Application`, `Flutter`, `Android Native`, `iOS Native`, `Python`, or `Rust Core`), `Depends on epic` (`- **Depends on epic**: `), and `Source Spec` link if this epic was derived from an approved `dev-brainstorming` spec. 3. **Background (Bối cảnh)**: The problem statement or context (Why are we doing this?). 4. **Goals & Non-Goals**: Clearly define what is expected to be achieved and what is strictly out of scope to avoid scope creep. 5. **Architecture, Feature Map & Technical Design ("Prompt to Maintain")**: - **High-Level Architecture (Mandatory — 1 Diagram)**: Use `mermaid flowchart TD` (or `flowchart LR`) to show component boundaries, data flow, and module dependencies. NEVER use legacy `graph TD` (`graph` is legacy Mermaid syntax; `flowchart` is the modern standard that enables per-subgraph `direction` control, richer node shapes, better rendering engines, and styling). - **Sequence Diagram (Conditional — Only for Multi-Actor / Async / Stateful Flows)**: Use `mermaid sequenceDiagram` with explicit participants and message flows **only** when the epic involves cross-service/API calls, IPC/FFI bridges, async concurrency/cancellation protocols, or non-trivial state machine transitions. Omit for single-module, CLI, or static transforms, and do **not** generate redundant Actor-to-Use-Case flowcharts (which duplicate Goals and BDD scenarios). - **Feature Maintenance Map ("Prompt to Maintain" Index)**: Include a concise table or structured list mapping each capability of the feature to: 1. **Canonical Source Paths & Entry Points** (key modules, classes, functions, routes, or CLI subcommands). 2. **Core Invariants & State/Config Knobs** (what must always hold true, environment variables, config files). 3. **Extension & Troubleshooting Guide** (where future developers or agents should look to extend behavior or diagnose failures without guessing). - **Diagram Standards & Lint Rules (Mermaid & Graphviz DOT)**: - All Mermaid diagrams MUST use `flowchart` instead of `graph`, quote node labels containing special characters, parentheses `()`, brackets `[]`, braces `{}`, colons `:`, slashes `/`, ampersands `&` (e.g. `node1["Component (Core Logic)"]`), use clean alphanumeric IDs with underscores, avoid trailing semicolons, and properly close subgraphs (`end`). - Any Graphviz (DOT) diagrams MUST follow semantic shapes (`diamond` for decisions `?`, `box` for actions, `plaintext` for commands, `ellipse` for states, `octagon` for warnings, `doublecircle` for start/complete), terminate statements with semicolons `;`, quote multi-word IDs/labels, use `->` in `digraph`, and prefix visual subgraphs with `cluster_`. - **Markdown Lint Standards**: All generated markdown files (`.en.md`, `.vi.md`, `bdd_scenarios.*.md`, `task_*.md`) MUST strictly adhere to markdown lint rules: single H1 top-level title, no skipped heading levels, space after `#`, no trailing punctuation in headings, all code blocks tagged with language identifiers (no bare fences), and clean formatting hygiene (no trailing whitespace, no hard tabs). - **Check 1 (Shift-Left Impact Analysis)**: Run `check_code_impact.py` on planned touchpoints and core symbols: ```bash python3 skills/impact-analysis/resources/scripts/check_code_impact.py \ --files \ --symbols \ --base-ref develop ``` Inspect blast radius, downstream callers, native `MethodChannel` bridges, and coverage safety nets before freezing contracts. - **Integration Test Plan & Boundary Matrix**: Map the architectural boundaries and failure seams into an explicit Integration Test Plan. Detail the end-to-end integration boundaries, mock/live services, data stores, and multi-component seams. For Web/UI applications, explicitly specify the **Visual & Browser Verification Matrix** (target viewports, URL routes/query parameters, interactive states, audio/video playback, and DOM verification). - **Integration Test Roots**: The Integration Test Plan MUST contain the line `Integration test roots: , ` naming every directory that holds integration tests. Defaults: `tests/e2e/` (Web), `integration_test/` (Flutter), `app/src/test/` and `shell/src/test/` (Android), `App/Tests/` and `Shell/Tests/` (iOS), `tests/integration/` and `tests/e2e/` (Python), `tests/` (Rust). `check_bdd_traceability.py` scans exactly these directories. - **Protected Paths & Integration Results (3-Level Test Scope Pyramid — Level 2 Blast-Radius Scoped)**: Beside `Integration test roots:`, the Integration Test Plan MUST carry these lines, which the recorder, the done gate and Gate 4 read: ```text Protected paths: .agents/quality/**, .devtool/epic//bdd_scenarios.en.md, .devtool/epic//bdd_scenarios.vi.md Integration results: uv run pytest --junitxml=build/test-results/py.xml -> build/test-results/py.xml ``` `Protected paths:` lists explicit paths and globs; the three shown are the minimum, and a tracked program that a Verification row runs is protected implicitly. Write one `Integration results:` line per platform, at least one: the command Gate 4 runs, then ` -> `, then the report it writes. **Blast-Radius Scoped `Integration results:` Rule**: Instead of blindly running the entire repository's test suite (`pytest tests/` or `./gradlew test`) on every Gate 4 / pre-review check, derive the test paths in `Integration results:` directly from `check_code_impact.py` (Step 1 Check 1): include only **(a) the current Epic's integration/e2e test files** and **(b) the test files covering Downstream Callers in the Blast Radius**. Full-repository `Test All` executes once at Stage 4 (`finishing-a-development-branch`) after rebasing onto `develop` right before landing. For opt-in live integration suites (such as local LLM or live provider benchmarks requiring environment variables like `PLT_LIVE_OLLAMA_MODEL` or `EVI_LIVE_MODEL`), declare: ```text Integration results (live, needs: VAR1, VAR2): uv run pytest tests/integration/test_live.py --junitxml=build/test-results/live.xml -> build/test-results/live.xml ``` This satisfies `R6` Tier C coverage checks in `check_epic_readiness.py` while `run_external_review.py` skips the live execution cleanly at Gate 4 when declared environment variables are unset without failing the gate. - **Verification Environment**: The HLD MUST also carry a `## Verification Environment` section: how tests are isolated from real data, which live resources are forbidden, and every variable a `Needs` column may name. When the project has a live data store, the first task carries a sentinel row proving tests cannot write to it. 6. **Shared Contract Impact (Cross-Repo Contract Impact Analysis)**: In multi-repo ecosystems (e.g. `D3Nexus` hub with `lyrics-sync` and `nexus` satellite repos connected via `shared-contracts/` symlinks), waiting until local implementation finishes to update inter-service contracts creates bottlenecks. When deriving tasks from an approved spec, **read `## Shared Contract Warnings`** to discover all human-approved contract decisions, pending drifts, and waivers planned during Stage 1. During the HLD / Architecture design step (before finalizing the task breakdown at Gate 2), if the workspace contains a `shared-contracts/` directory (or interacts with external services, satellite repos, or FFI boundaries): - **Workspace Dual-Mode Detection**: Inspect whether `shared-contracts/` is a physical directory or a symbolic link: - **Hub Mode (`shared-contracts/` is a physical directory)**: The current workspace is the canonical Contract Owner (Hub). The Lead acts under the **Contract Owner / System Architect Persona**, responsible for maintaining canonical SSOT contracts and broadcasting parallel handoffs. - **Satellite Mode (`shared-contracts/` is a symbolic link)**: The current workspace is a Satellite Consumer or Producer (e.g. `lyrics-sync`, `nexus`). The Lead acts under the **Satellite Consumer Architect Persona**, responsible for specifying upstream contract requirements and ensuring internal adapters gracefully tolerate contract evolution without violating Git symlink boundaries. - **Contract & Ledger Audit**: Inspect `shared-contracts//api_contract.md`, `architecture_and_flow.md`, and `gaps_and_rfcs.md` before finalizing technical designs. - **Dedicated Overview Section**: Explicitly document any required schema additions, field rules, IPA/linguistic formatting rules, or protocol changes in a dedicated `## Shared Contract Impact` section inside the bilingual epic overview (`.devtool/epic//.en.md` and `.vi.md`), linked in the Table of Contents. If no shared contract is affected, explicitly declare `None — self-contained feature`. - **Non-Breaking Schema Guarantee**: Enforce backward compatibility across repository boundaries (optional new fields with safe defaults, non-breaking enum additions, or explicit fallback rules). Breaking schema changes without backward-compatible transition windows or fallback shims are strictly forbidden. 7. **Exhaustive Edge-Case & Exception BDD Suite (`bdd_scenarios.{en,vi}.md`)**: - Keep raw Gherkin blocks **out of the HLD** (so the HLD remains a clean human overview) and generate a dedicated, synchronized pair in the epic directory: - English, canonical: `.devtool/epic//bdd_scenarios.en.md` - Vietnamese: `.devtool/epic//bdd_scenarios.vi.md` - Each file MUST contain a linked table of contents covering every `##` section. - **Adversarial Edge-Case & Exception Hunting Mandate**: Both files MUST organize scenarios by Use Case across the **Mandatory 5-Dimension Boundary Matrix**, with primary emphasis on **Dimensions 2–5 (maximizing edge cases, boundary violations, exceptions, and recovery invariants)**: 1. **Happy Paths (`HP`)**: Concise baseline nominal flows (1–2 scenarios per use case). 2. **Edge Cases, Boundaries & Malformed Inputs (`EC`)**: Null/empty/whitespace strings, unicode/special-character extremes, off-by-one and min/max numeric/collection bounds, missing or unexpected payload fields, malformed JSON/YAML/CLI flags, and path traversal/symlink edge cases. 3. **Invalid State Transitions & Invariant Guards (`ST`)**: Out-of-order events, duplicate/idempotent requests, illegal lifecycle transitions, stale leases/watermarks, unauthorized/permission-denied states, and precondition failures. 4. **Async, Concurrency & Race Conditions (`AR`)**: Rapid consecutive user actions (debouncing/throttling), mid-flight cancellation, timeout vs late-response arrival, file/DB lock contention, and interrupted execution. 5. **Exceptions, Fault Injection & Atomic Rollback (`FR`)**: Network/IO exceptions (4xx/5xx, socket drop, timeout), disk full / read-only filesystem, subprocess non-zero exit, corrupt persistence state, and **atomic rollback invariants** (proving no partial writes, corrupt state, or orphan temporary files remain when an exception occurs). - **Scenario IDs**: Every `Scenario:` or `Scenario Outline:` line starts with a unique identifier in brackets, before any tier tag: `Scenario: [PY-EC-01] [Tier A - Unit] ...`. Shape: uppercase segments joined by `-`, ending in digits; convention `--` with `HP`, `EC`, `ST`, `AR`, `FR` for the five dimensions. The `.vi.md` file carries exactly the same identifiers, untranslated. The first segment is this epic's prefix and MUST NOT be used by any other epic in the project, because integration test roots hold every epic's tests; list the prefixes already taken with `grep -ho '\[[A-Z][A-Z0-9]*-' .devtool/epic/*/bdd_scenarios.en.md | sort -u`. - **Dual Value Purpose**: 1. *Human Maintenance & Regression Shield*: Gives developers a complete catalog of every edge case, exception, and failure invariant the system guarantees. 2. *Task-Scoped AI Context Injection*: Each scenario block in `bdd_scenarios.en.md` is embedded verbatim into its assigned `task_*.md` (`### BDD SCENARIOS`), driving TDD (`RED -> GREEN`) without requiring the coding agent to load the entire epic's documentation at once. 8. **Rollout Strategy & Mitigation**: Describe how to deploy this safely (e.g., phased rollout, feature flags) and fallback plans. 9. **Kanban Tasks Breakdown**: A list of links pointing to the individual task files created in Step 2. 10. **Spec Errata (Đính chính đặc tả)**: When an epic in-flight requires formal design corrections, scope amendments, or clarifications after initial approval, document each change under `## Spec Errata` using standardized `[SE-NN]` entries (e.g., `- [SE-01] : <description>`). This section MUST be mirrored symmetrically across both `.en.md` and `.vi.md` variants, and linked in the Table of Contents. **Canonical language**: Every durable design document uses an `.en.md` and `.vi.md` pair. The `.en.md` variant is the source of truth for tooling/agents — always write and update it first. The `.vi.md` variant is a translation for local team communication and MUST be kept in sync whenever the `.en.md` changes; never let the two diverge in structure, facts, or table-of-contents coverage. Before the task-breakdown checkpoint, verify both design-document pairs mechanically: ```bash python3 skills/doc_quality_check/resources/scripts/check_document.py \ --require-toc --require-bilingual \ .devtool/epic/<epic_name>/<epic_name>.en.md \ .devtool/epic/<epic_name>/<epic_name>.vi.md \ .devtool/epic/<epic_name>/bdd_scenarios.en.md \ .devtool/epic/<epic_name>/bdd_scenarios.vi.md ``` ### Checkpoint: Confirm Task Breakdown Before Writing Task Files Before generating any task file, list the proposed tasks as a short numbered summary (title + one-line scope each) and ask the user to confirm the breakdown and granularity. This is a lightweight check, not a full brainstorming dialogue — the architecture is already approved (from the spec or from this skill's own Step 1); only the *task split* is new and unapproved. Only proceed to write task files once the user confirms or adjusts the list. Beside each proposed task, list the epic scenario identifiers it will cover (its future `Covers:` line, see Tier C — BDD Automation below), so the user approves the scenario-to-task mapping together with the split. #### Contract-First Prioritization (`task_01` Rule) When breaking the design into tasks at **Gate 2**, evaluate whether `shared-contracts/` is impacted and check the detected workspace mode: - **Hub Mode (`shared-contracts/` is a physical directory)**: - **Persona Roles**: The **Contract Owner / System Architect Persona** drafts canonical schema shapes, while the **QA Red Team Persona** authors verification scenarios enforcing backward compatibility. - **`task_01` Rule**: **`task_01` MUST always be the Contract & Ledger Update task** (updating `shared-contracts/<domain>/api_contract.md`, `architecture_and_flow.md`, and logging cross-repo requirements in `gaps_and_rfcs.md`). Updating shared contracts FIRST in Stage 3 unblocks satellite repos to develop in parallel rather than serializing work behind local feature implementation. - **Parallel Handoff Summary**: Once `task_01` is drafted and confirmed at Gate 2, output a concise handoff prompt so the developer can immediately trigger AI Agents in satellite repos (e.g. `lyrics-sync`, `nexus`) to work in parallel while local implementation proceeds. The handoff summary MUST include: 1. Affected domain and canonical contract paths updated (e.g. `shared-contracts/<domain>/api_contract.md`). 2. Concrete payload additions, optional fields, IPA/linguistic rules, or protocol changes. 3. Actionable task prompts for satellite repo agents (e.g. updating consumer models, mocking endpoints, or adjusting downstream UI components). - **Satellite Mode (`shared-contracts/` is a symbolic link, e.g. `lyrics-sync`)**: - **Persona Roles**: The **Satellite Consumer Architect Persona** drafts the upstream contract delta and handoff prompt, while the **TDD Master Persona** implements consumer models and internal adapters. - **Git Symlink Invariant**: A satellite repo NEVER includes `shared-contracts/...` in `Files Allowed` for git tasks, because git cannot commit paths beyond a symbolic link (`fatal: pathspec is beyond a symbolic link`). - **Upstream Contract Handoff Summary & Automated Cross-Repo Flow**: At Gate 2, output a ready-to-run prompt for the AI Agent at the Hub repo (`D3Nexus`) to update and commit the canonical contract. - **Interactive One-Click Cross-Repo Automation**: If working on a shared local filesystem, the agent can streamline this workflow without manual workspace switching: 1. Write the proposed RFC or contract additions directly through the symlink into the Hub's physical files (`shared-contracts/<domain>/gaps_and_rfcs.md` and `api_contract.md`). 2. Run `git -C $(readlink -f shared-contracts)/.. diff shared-contracts/<domain>/` and display the diff to the developer. 3. Halt and ask for explicit human confirmation: *"Do you confirm committing this contract change to the Hub repository? (Y/N)"*. 4. Upon explicit developer confirmation (satisfying Critical Rule 7.1), execute the cross-repo commit command: `git -C $(readlink -f shared-contracts)/.. add shared-contracts/<domain>/ && git -C $(readlink -f shared-contracts)/.. commit -m "[CONTRACT] <title>"` 5. Run `python3 skills/sync-shared-contracts/resources/scripts/sync_contracts.py ack --domain <domain> --snapshot <new_snapshot_id>` in the Satellite workspace to immediately record the new baseline in `.agents/contract_sync.json`, seamlessly unblocking Stage 3 `dev-implementation` without cross-repo stalls. - **`task_01` Rule**: **`task_01` MUST always be the Consumer DTOs & Adapter Synchronization task** (updating satellite-internal DTOs, serializers, mock fixtures, and BDD test stubs). ### Concurrent-Epic Backlog Rule Before writing any task file, check `.devtool/features/*.md` (excluding the `done/` and `archived/` subfolders) for a task whose `epic:` frontmatter field names a *different* epic and whose `status` is `todo`, `in-progress`, or `review` — that means another epic is actively being worked on right now. If so: - Set every task this run generates for the new epic to `status: "backlog"` instead of the usual default `"todo"`, so it's queued rather than shown as ready-to-pick-up while the other epic is still active. - Note in the new Epic Overview's Meta Data **Status** field that the epic is queued behind the other epic by name (e.g. `Status: Queued (backlog) — behind logging-refactor`). - This skill does not flip tasks from `backlog` to `todo` itself later — that's a human call once the blocking epic's tasks all reach `done`. If no other epic has any active (`todo`/`in-progress`/`review`) task, generate tasks with the normal default `status: "todo"` as usual. ### Step 2: Generate LachyFS Kanban Tasks Break the Epic down into granular implementation tasks. **Crucially, each task must be structured around Behavior-Driven Development (BDD), Test-Driven Development (TDD), and Integration Flow Testing** to feed directly into the Tri-Persona (QA Red Team + TDD Master + System Integration Engineer) execution workflow in `dev-implementation`. Wherever the task produces testable behavior, generate Markdown task files located at `.devtool/features/task_<number>_<name>.md` (and mirrored in `.devtool/epic/<epic_name>/task_<number>_<name>.md` as permanent epic outputs). #### Task Lifecycle & Archival Model - **Creation**: Tasks are generated into `.devtool/features/task_<number>_<name>.md` and mirrored into `.devtool/epic/<epic_name>/task_<number>_<name>.md`. - **In-Flight**: As tasks complete during `dev-implementation`, `sync_task_status.py` moves them from `.devtool/features/` into `.devtool/features/done/`. - **Epic Completion Archival**: When all tasks of an epic finish and the epic status transitions to `Done` (`sync_task_status.py epic <epic_dir> Done`), all completed tasks and draft superpowers documents are archived permanently into `.devtool/epic/<epic_dir>/`. Relative markdown links are rewritten to point locally, and `.devtool/features/done/` is left clean with zero lingering task files. #### Mandatory Contract-First Task Structure (`task_01` when `shared-contracts/` is impacted) When `shared-contracts/` is affected, `task_01` is reserved strictly for contract synchronization before local feature tasks begin, structured per the active mode and persona: ##### Case A — Hub Mode (Physical Directory) - **Persona**: **Contract Owner / System Architect (Dev Persona)** + **QA Red Team (QA Persona)**. - **Title**: `# Task 1: Update Canonical Shared Contracts and Cross-Repo Ledger (<domain>)` - **Files Allowed**: `shared-contracts/<domain>/api_contract.md` (append `(new)` if creating for the first time), `shared-contracts/<domain>/architecture_and_flow.md` (append `(new)` if creating for the first time), `shared-contracts/<domain>/gaps_and_rfcs.md` (append `(new)` if creating for the first time). - **Decisions Already Made**: Exact schema shapes, field types, default values, and Non-Breaking Schema Guarantees. - **Verification**: Markdown structure check (`check_document.py`), schema diff audit, and verification that Non-Breaking Schema Guarantees are preserved. - **Output**: Generates or confirms the **Parallel Handoff Summary** for satellite repositories. ##### Case B — Satellite Mode (Symbolic Link) - **Persona**: **TDD Master (Dev Persona — Tier A)** + **QA Red Team (QA Persona)**. - **Title**: `# Task 1: Synchronize Consumer Models, Adapters, and Fixtures with Upstream Contract (<domain>)` - **Files Allowed**: Satellite-internal files only — DTOs, serializers, API clients, mock fixtures, and test files (e.g. `src/models/<domain>/*`, `src/adapters/*`, `test/fixtures/*`). **STRICTLY EXCLUDES `shared-contracts/`** (symlink target) to prevent git pathspec errors. - **Decisions Already Made**: Mapping rules from upstream payload shapes to internal domain models, fallback defaults for legacy payloads. - **Verification**: Unit and deserialization tests validating backward and forward compatibility against the upstream contract definition. - **Pre-requisite / Dependency**: Canonical contract updated in Hub repo (via Upstream Contract Handoff or local cross-repo commit). #### Mandatory 3-Tier Testing Standard & 3-Level Test Scope Pyramid in Task Breakdown Every Epic breakdown MUST structure and scope all 3 testing tiers across the **3-Level Test Scope Pyramid** (`Level 1: Task-Scoped` -> `Level 2: Blast-Radius Scoped` -> `Level 3: Test All once on Merge to develop`) so `--replay`, per-task TDD, and Gate 4 run at maximum speed while guaranteeing 100% impact coverage: - **Level 1 — Task-Scoped (`Task 1 .. Task N-1` & `check_epic_readiness.py --replay`)**: - `RED`, `GREEN`, `TIER-B`, and `TIER-C` rows in `Task 1 .. Task N-1` MUST target **only the specific files in that task's `Allowed files`** (e.g. `uv run pytest tests/unit/test_foo.py::test_bar`, `uv run ruff check --select F821,F841,B007,B904 <allowed_py_files>`, `uv run mypy --strict <allowed_src_files>`). Never run whole-repo `ruff check src tests`, `mypy --strict src`, or `pytest` across all tests in intermediate tasks. - **Level 2 — Blast-Radius Scoped (`Task N` Final Integration Task, Gate 4, & Pre-Checks of `/cross-model-review`)**: - `Task N` and the HLD's `Integration results:` target **only the Epic's touched modules + Downstream Callers identified by `check_code_impact.py`**, paired with fast mechanical gates (< 5s total): Anti-Stub Enforcer (`check_anti_stub.py` / `audit_epic.py`), `.importlinter` package coverage (`verify_importlinter_coverage.py` + `lint-imports`), BDD Scenario Count Parity & Contract Watermark (`verify_bdd_coverage.py --verify-epic-parity --verify-contract-watermark`), and Pre-Review Self-Probe (`pre_review_self_probe.py`). - **Level 3 — Full Repository Suite (`Test All` — Once on Merge to `develop`)**: - Executing the full test suite across every unrelated module in the repository (`pytest`, `cargo test`, `melos test`, `./gradlew testDebugUnitTest`) is reserved for **Stage 4 (`finishing-a-development-branch`) at `Update onto Base` (after archiving tasks and rebasing onto `develop`, right before `integrate_branch.py land`)**. Every Epic breakdown MUST explicitly address all 3 testing tiers across the Tri-Persona system based on the target platform: ##### 💙 For Flutter Projects: - **Tier A (Unit / Package Tests)**: Tasks covering module/feature logic, BLoCs, UseCases, Repositories, Parsers with isolated unit tests (`fvm flutter test` or `melos test` using `bloc_test`, Mocktail). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling & Governance Tests)**: Tasks that touch feature packages or public APIs MUST verify module boundaries (`./scripts/check_module_boundaries.sh`), license headers (`./scripts/check_license_header.sh`), code formatting (`melos format`), and static analysis (`melos analyze`). - **Tier C (Acceptance & App Tests)**: Every Epic MUST include an explicit final integration task (e.g. `Task N: Host App Integration & Acceptance Tests`) verifying the Host composition root (`lib/` composition, `AppRoutes`, `AppEventBus`), full end-to-end user navigation flows, and running the automated acceptance/integration harness (`fvm flutter test integration_test` or `./scripts/testWithCoverage.sh`). Executed by the **System Integration Engineer (Integration Persona)**. ##### 🤖 For Android Native Projects: - **Tier A (Unit / Package Tests)**: Tasks covering module/feature logic, MVI ViewModels, UseCases, Repositories, Parsers with isolated unit tests (`./gradlew testDebugUnitTest` using JUnit, MockK, Turbine). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling & Governance Tests)**: Tasks that touch architectural rules, convention plugins, or public API signatures MUST include verification with Konsist rules K1–K10 (`./gradlew :konsist-test:test`) and BCV public ABI checks (`./gradlew apiCheck`), Detekt, and Spotless (`./gradlew check`). - **Tier C (Acceptance & App Tests)**: Every Epic MUST include an explicit final integration task verifying Host composition root (`:app` + `:shell`), full end-to-end user navigation flows, DFM on-demand splits, and running the automated acceptance harness (`./scripts/acceptance_check.sh`). Executed by the **System Integration Engineer (Integration Persona)**. ##### 🍎 For iOS Native Projects: - **Tier A (Unit / Package Tests)**: Tasks covering module/feature logic, MVI ViewModels, UseCases, Repositories, Parsers with isolated unit tests (`swift test --package-path <PackagePath>` using Swift Testing `@Test` or XCTest). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling & Governance Tests)**: Tasks that touch feature packages or public API contracts MUST verify module boundaries (`bash scripts/check_module_boundaries.sh`), AST architecture governance rules K1–K10 (`swift test --package-path ArchTests`), static analysis (`swiftlint lint --strict --config quality/.swiftlint.yml`), and code formatting (`swiftformat --config quality/.swiftformat . --lint`). - **Tier C (Acceptance & App Tests)**: Every Epic MUST include an explicit final integration task verifying Host composition root (`App/` + `Shell/`), `AppRoutes`, RouteProvider registration, end-to-end user navigation flows, and running the automated acceptance harness (`tuist generate --no-open && xcodebuild test ...`). Executed by the **System Integration Engineer (Integration Persona)**. ##### 🌐 For Web Applications & Frontend Projects: - **Tier A (Unit & State Tests)**: Tasks covering component logic, domain utilities, reactive stores, state machines, parsers, and reducers with isolated unit tests (`node --test`, Vitest, Jest). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling, Types & Governance Tests)**: Tasks touching components, pages, or shared modules MUST verify type soundness (`tsc --noEmit`), framework diagnostics (`astro check` or framework linter), code style/formatting (`prettier --check` / `eslint`), and module boundaries. - **Tier C (Acceptance, E2E & Live Browser Verification)**: Every Web Epic MUST include an explicit final integration task (e.g. `Task N: Integration & Live Browser Verification`) verifying application composition roots, router navigation flows, running the automated integration harness (`tests/e2e/*.test.ts`, Playwright, Cypress) **AND executing Live Web Browser Verification**. The agent MUST launch the local dev/preview server, navigate using `browser_subagent`, record a video session (`.webp`), capture screenshot artifacts, and assert real DOM states, user interactions, audio/video playback, and visual layout against analyzed use cases and edge cases. Executed by the **System Integration Engineer (Integration Persona)**. ##### 🐍 For Python Projects: - **Tier A (Unit Tests)**: Tasks covering module/domain logic, services, models, and parsers with isolated unit tests (`pytest tests/unit/` using `pytest-mock`, `unittest.mock`). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling & Governance Tests)**: Tasks touching modules or public APIs MUST verify code formatting and linting (`ruff check .`, `ruff format --check .`), strict type checking (`mypy --strict src`), and architectural layer boundaries (`lint-imports` or `import-linter` via `.importlinter`). - **Tier C (Acceptance & Integration Tests)**: Every Epic MUST include an explicit final integration task verifying service composition roots, API integrations, database workflows, and running automated integration/acceptance tests (`pytest tests/integration/` and `pytest tests/e2e/`). Executed by the **System Integration Engineer (Integration Persona)**. ##### 🦀 For Rust Core & Polyglot Backend Projects: - **Tier A (Unit / Crate Tests)**: Tasks covering core domain models, business logic, parsers, algorithms, and state machines with isolated unit tests (`cargo test --lib`). Executed by the **TDD Master (Dev Persona)**. - **Tier B (Tooling & Governance Tests)**: Tasks touching shared crates or public APIs MUST verify formatting (`just fmt` or `cargo fmt --check`), clippy warnings denied (`just lint` or `cargo clippy -D warnings`), dependency licensing/security (`cargo deny check`), and architecture boundaries (`cargo run -p xtask -- check-boundaries`). - **Tier C (Acceptance & App Tests)**: Every Epic MUST include an explicit final integration task verifying composition roots, WASM bindings (`just wasm-test`), FFI exports, and running end-to-end acceptance tests (`cargo test --test '*'` or `just acceptance`). Executed by the **System Integration Engineer (Integration Persona)**. ##### 🔗 Tier C — BDD Automation (All Platforms) - Every scenario in `bdd_scenarios.en.md` MUST be covered by **at least one automated integration test**, whatever its tier tag. One test may cover several scenarios. There are no waivers: a scenario that cannot be automated is rewritten before Gate 2. - The test carries the scenario identifier in its name, description or tag (`test_py_hp_01_...`, `func test_PY_HP_01_...()`, `testWidgets('[PY-HP-01] ...')`, ``@Test fun `PY-HP-01 ...`()``) and lives under one of the HLD's `Integration test roots`. - Each identifier is assigned to exactly one task through that task's `Covers:` line; two tasks never share an identifier. The final Tier C task takes every identifier no earlier task covers. - **Final Task Governance & Immutability (`Allowed files`)**: The final task of every epic (the Tier C integration/acceptance task running immediately before Phase 4 / Gate 4) MUST include `.agents/contract_sync.json` in its `Allowed files` (for recording `sync_contracts.py ack` watermark acknowledgements on Satellites) and, when path-scoped waivers are planned, `.agents/contract_map.json` in `Allowed files`. Updating these manifests inside the final task ensures that the repository commit SHA certified by Gate 4 remains completely immutable and reproducible. ```mermaid flowchart TD subgraph SPEC["Specification & Architecture (HLD)"] HLD["High-Level Design<br/>(Use Cases, Sequence & Integration Plan)"] end subgraph PHASE1["Phase 1: QA Red Team (Adversarial Decoupling)"] BDD["BDD Scenarios (Gherkin syntax)<br/>⚠️ Strictly Decoupled from Coding"] TAG{"Categorization & Contract Freeze"} end subgraph PARALLEL["Parallel Execution Tracks (dispatching-parallel-agents)"] direction LR subgraph TIER_A["Tier A: TDD Master (Dev Persona)"] UNIT_SCENARIOS["[Tier A - Unit] Scenarios"] RED["1. RED: Failing Unit Tests"] GREEN["2. GREEN: Minimal Feature Code"] REFACTOR["3. REFACTOR: Clean Code & Formatter"] VERIFY_A["Web: node --test / vitest<br/>Flutter: melos test<br/>Android: ./gradlew testDebugUnitTest<br/>iOS: swift test<br/>Python: pytest tests/unit<br/>Rust: cargo test --lib"] end subgraph TIER_C["Tier C: System Integration & E2E Engineer"] FLOW_SCENARIOS["[Tier C - Integration] Scenarios"] FLOW_TESTS["Host Integration Flow & E2E Tests<br/>(integration_test, *FlowTest.kt, tests/e2e)"] SYS_ASSERT["Assert DI, Navigation Stack, Lifecycle,<br/>Auth Gating Replay, Feature Seams"] BROWSER_VERIFY["Web: Live Browser Verification<br/>(browser_subagent + Video/Screenshots)"] FLOW_TESTS --> SYS_ASSERT --> BROWSER_VERIFY end end subgraph TIER_B["Tier B: Automated Governance Gates"] GATE["Web: tsc --noEmit + astro check<br/>Flutter: check_module_boundaries + melos analyze<br/>Android: Konsist K1-K10 + BCV apiCheck + detekt<br/>iOS: check_module_boundaries + ArchTests + swiftlint<br/>Python: ruff + mypy + lint-imports<br/>Rust: clippy -D warnings + xtask check-boundaries"] end subgraph SYNC["Sync Checkpoint & Acceptance Verification"] MERGE["Merge & Sync Checkpoint"] VERIFY_C["Web: tests/e2e + browser verification<br/>Flutter: ./scripts/testWithCoverage.sh<br/>Android: ./scripts/acceptance_check.sh<br/>iOS: tuist generate + xcodebuild test<br/>Python: pytest tests/integration<br/>Rust: just acceptance + wasm-test"] end HLD -->|100% Independent Derivation| BDD BDD --> TAG TAG -->|Track 1: Disjoint Feature Files| UNIT_SCENARIOS TAG -->|Track 2: Disjoint Host Test Files| FLOW_SCENARIOS UNIT_SCENARIOS --> RED --> GREEN --> REFACTOR --> VERIFY_A REFACTOR -.->|Code Changes Validated by| GATE VERIFY_A --> MERGE BROWSER_VERIFY --> MERGE GATE --> MERGE MERGE --> VERIFY_C ``` > [!IMPORTANT] > ### ⚡ PARALLEL EXECUTION RULES (TIER A & TIER C CONCURRENCY) > When executing via `dispatching-parallel-agents`, the Lead Agent may dispatch **Subagent 1 (Dev Persona — Tier A)** and **Subagent 2 (SDET Persona — Tier C)** concurrently, provided these 3 inviolable rules are satisfied: > > 1. **Rule 1: Strict Contract Freeze (Zero Contract Drift)**: > - All public interface contracts (`AppRoutes`, `AppEventBus`, DTOs, State/Action contracts) must be locked during Phase 1 BDD authoring. > - Neither agent is permitted to rename, alter types, or mutate public contract signatures during parallel execution without a synchronized pause. > > 2. **Rule 2: Disjoint File Sets (Zero Git Merge Conflicts)**: > - **Subagent 1 (Dev)**: Restricted strictly to feature/package sources (`apps/{app}/src/**` in Web; `features/{name}/**`, `packages/{package}/**` in Flutter; `:features:*`, `:packages:*` in Android; `Features/{Name}/**`, `Packages/{Name}/**` in iOS; `src/{package}/**` in Python; `src/{package}/**` in Python; `crates/{crate}/src/**` in Rust). > - **Subagent 2 (SDET)**: Restricted strictly to Host App integration testbeds (`tests/e2e/**` in Web; `integration_test/**` in Flutter; `app/src/test/**`, `shell/src/test/**` in Android; `App/Tests/**`, `Shell/Tests/**` in iOS; `tests/integration/**` in Python; `tests/integration/**` in Python; `tests/**` in Rust). > - **NEITHER agent** may modify shared root build or workspace files (`package.json`, `astro.config.*` in Web; `pubspec.yaml`, `melos.yaml` in Flutter; `settings.gradle.kts`, `buildSrc/**` in Android; `Project.swift`, `Workspace.swift`, `Tuist.swift` in iOS; `pyproject.toml` in Python; `pyproject.toml` in Python; root `Cargo.toml` in Rust) concurrently. > > 3. **Rule 3: ATDD Sync Checkpoint & Verification**: > - Subagent 2's integration flow tests initially act as **ATDD Red Tests** (failing while Subagent 1's code is in-flight). > - Once both subagents report completion, the Lead Agent performs the **Sync Checkpoint**: merges the branches, validates that the integration tests turn **GREEN**, and runs the Tier C acceptance check. Task files are English-only — do not generate a `.vi.md` variant for `task_*.md` and do not mix Vietnamese prose into their section headers or body. They are the sole language-pair exception in this workflow; the spec, Epic Overview, and BDD scenario documents remain bilingual. Each task file MUST adhere to this exact structure: 1. **YAML Frontmatter (LachyFS Kanban Markdown compatible)**: ```yaml --- id: "task_<number>_<name>" status: "todo" # one of: backlog | todo | in-progress | review | done — see Concurrent-Epic Backlog Rule above priority: "high" # one of: low | medium | high assignee: null epic: "<epic_name>" dueDate: null created: "<ISO-8601 timestamp, set once at creation>" modified: "<ISO-8601 timestamp, update on every edit>" completedAt: null # set to an ISO-8601 timestamp only when status becomes "done" labels: ["architecture", "feature"] order: "a<number>" --- ``` 2. **Title**: `# Task <number>: <Task Name>` 3. **Epic Reference**: A link back to the parent HLD, e.g. `Epic: [<epic_name>](../epic/<epic_name>/<epic_name>.en.md)`. This is the agent's entry point back to architecture/diagram context. 4. **Requirement Analysis**: Context and requirements specific to this task. 5. **Files**: A `## Files` section holding two lists. - `Allowed files:` lists the exact paths or globs (`*`, `?`, and `**` across directories) the task may create, change or delete. A path that does not exist yet carries `(new)`. Bare directories are not allowed. Changes under `.devtool/` (task status, mirrors, evidence) are never listed, except changes to a protected path. - `Read-only context:` lists the paths the task only reads, each with a note. It restricts nothing, and a path that another task creates may carry `(new)`. 6. **Design Rationale**: Architecture decisions or design patterns chosen. **Crucially, review the available skills in `.agents/skills/` and explicitly note applicable skills here**: - **For Web Tasks**: `browser_subagent` (live browser verification), Node.js `--test` / Vitest, Astro check, Playwright. - **For Python Tasks**: `python-quality-check`, `pytest`, `ruff`, `mypy`, `import-linter`. - **For Rust Tasks**: `rust-quality-check`, `xtask`, `wasm-pack`. - **For Flutter Tasks**: `flutter-ui-audit`, Mason bricks (`mason make pac_mvi_feature`), `build_runner`. - **For Android Tasks**: `android-ui-audit`, `android-api-integration`, `moshi_dto_generator`. - **For iOS Tasks**: `ios-ui-audit`, Tuist (`tuist generate`), `ArchTests`. 7. **Impact Analysis & Blast Radius**: Document predictive impact analysis for this specific task: - **Target Files & Symbols**: Classes, functions, and interfaces to be created or modified. - **Downstream Callers**: Known caller files that consume the target symbols. - **Cross-Platform Bridges**: Any `MethodChannel` or Native bridge contracts touched. - **Target Test Coverage Threshold**: Minimum line coverage threshold (100% for Security, $\ge 85\%$ for Domain UseCases, $\ge 80\%$ for UI/BLoC). 8. **BDD Scenarios & Acceptance Criteria (The QA Persona)**: Document this section under the markdown heading `### BDD SCENARIOS`. Directly under that heading, write the line `Covers: <ID>, <ID>` naming the epic scenario identifiers from `bdd_scenarios.en.md` whose integration tests this task writes. Omit the line only when the task covers no epic scenario, for example a Tier B tooling task. Copy the exact Gherkin scenario blocks (`Given - When - Then`) assigned to this task verbatim from `bdd_scenarios.en.md` (Rule `R3` in `check_epic_readiness.py` enforces byte-identical alignment between `bdd_scenarios.en.md` and `task_*.md`). **Strict Adversarial Independence & Edge-Case Mandate**: - The QA Persona MUST author BDD scenarios **completely decoupled from implementation code**. - Do NOT base scenarios on implementation ease or existing code internals. Base them **PURELY on the Epic's HLD specifications, Architecture & Feature Maintenance Map, and conditional Sequence Diagrams**. - The QA Persona's sole objective is to act as an adversarial quality gate: **catch the maximum number of unhandled edge cases, boundary violations, exceptions, race conditions, and system failure/rollback modes** before any coding begins. **Mandatory Self-Review**: Cross-check these scenarios directly against the Goals, Architecture, and Feature Maintenance Map defined in the Epic's HLD document (`<epic_name>.en.md`) to guarantee zero missing requirements. Exhaustively apply Boundary Value Analysis, Equivalence Partitioning, and Fault Injection across the 5 dimensions (prioritizing Dimensions 2–5): - **Happy Paths (`HP`)**: Baseline nominal data flow and standard successful outcomes. - **Edge Cases, Boundaries & Malformed Inputs (`EC`)**: Null/empty/whitespace inputs, unicode/encoding extremes, off-by-one and min/max numeric/collection bounds, malformed payloads/flags, and symlink/path edge cases. - **State Transitions & Invariant Guards (`ST`)**: Valid and invalid state transitions, out-of-order events, idempotency on duplicate requests, stale leases/tokens, and permission/precondition guards. - **Async, Concurrency & Race Conditions (`AR`)**: Rapid consecutive user interactions (debouncing, throttling, cancellation), timeout vs late response arrival, file/DB lock contention, and interrupted execution. - **Exceptions, Fault Injection & Atomic Rollback (`FR`)**: Network/IO errors (4xx/5xx, socket drop, timeouts), offline states, disk full / read-only paths, subprocess failures, corrupted storage/DB, and atomic rollback invariants (no partial state or orphan files left behind). **Tier Categorization Tagging & 100% Traceability Mandate**: - `[Tier A - Unit]`: Scenarios covering class/function level logic, BLoCs/ViewModels, UseCases, Repositories, Parsers, and Guards. Must be covered 100% by unit tests. - `[Tier C - Integration]`: Scenarios covering end-to-end user navigation, Host App lifecycle, Tab switching, Auth Gating & Replay, and multi-component seams (including media playback synchronization, live database states, and web route transitions). Must be covered 100% by integration tests. - **Zero Uncovered Scenarios Rule**: Every authored BDD scenario across all 5 dimensions MUST map to at least one automated test case. Unit tests with mocks do NOT substitute for Tier C integration tests. - **Grounded Assertions Mandate**: Under `### BDD SCENARIOS`, pin assertions to production observation points and exact inputs, outputs, boundary indices, attempt counts, timestamps, or canonical fixture anchors. Vague or weak assertions (`should be truthy`, `is valid`, `should work`, `returns non-empty`) are strictly forbidden and rejected by `check_task_contract.py --design`. 9. **Verification**: A `## Verification` section holding one table and nothing else to tick. Each row is a command the recorder (`run_task_checks.py`) runs and the done gate checks; nothing is ticked by hand. Per-platform example rows, and the command that produces each platform's test report, are in [`references/verification-rows.md`](references/verification-rows.md). Canonical table grammar rules, pipe escaping (`\|`), environment prefixing (`env VAR=val`), search pattern rules, and portable CLI usage are in [`references/verification-row-grammar.md`](references/verification-row-grammar.md). ```markdown | ID | Phase | Command | Expect | Needs | |----|-------|---------|--------|-------| | V1 | RED | `uv run pytest tests/unit/test_taxonomy.py` | exit 1; contains "ModuleNotFoundError" | — | | V2 | GREEN | `uv run pytest tests/unit/test_taxonomy.py` | exit 0; contains "passed" | — | | V3 | TIER-B | `uv run ruff check src tests` | exit 0 | — | | V4 | TIER-C | `uv run pytest tests/integration/test_taxonomy_bdd.py --junitxml=build/test-results/task_34.xml` | exit 0; results build/test-results/task_34.xml | TEST_DATABASE_URL | ``` - **Columns** are exactly `ID | Phase | Command | Expect | Needs`. IDs are `V1`, `V2`, … and unique within the task. - **Phase** is `RED` (run before implementation), `MEASURE` (benchmarking and heavy evaluation generating declared evidence files), `GREEN`, `TIER-B` (tooling and governance) or `TIER-C` (integration and acceptance). - **Command** is one inline code span, run as `bash -o pipefail -c '<command>'` from the worktree root. - **Measurement-to-Evidence Pattern**: Long-running measurement tasks (such as local model benchmarks or heavy perf evaluations) carry `Phase: MEASURE` Verification rows and declare `Evidence files:` in the task header (`Evidence files: - .devtool/epic/<epic_name>/evidence/<filename>.json`). The `MEASURE` phase executes before `GREEN` rows, writes non-empty evidence files to disk, and records SHA-256 digests in the task evidence JSON. `evaluate_done_gate()` and `audit_epic.py` enforce that `runs.measure.passed == true` and verify matching evidence file digests. - **Expect** follows this grammar; every `contains` text must appear in the combined stdout and stderr: ```text expect := exit-clause ( "; " clause )* exit-clause := "exit " DIGITS | "exit non-zero" clause := "contains \"" TEXT "\"" | "results " PATH ``` `results <path>` appears only on `TIER-C` rows, at most once per row, and names the JUnit or Dart JSON report the command writes. The path must be ignored by git. - **Needs** is `—` or a comma-separated list of environment variable names. An unset variable makes the row `BLOCKED` without running it. - A RED row names a real test function or method that is written first and fails through the platform's native assertion mechanism. - For pytest specifically, the command must use an exact node ID such as `path/test_file.py::test_name`, expect exit 1, and require positive collected-test failure output. Generic `-k` expressions without an exact node ID are rejected by `check_task_contract.py`. Other platforms use the repository's registered runner/provider command without imposing Python syntax on non-Python platforms. - A task with no new behaviour (a pure refactor, a config or tooling change) has no `RED` rows. Put the line `RED: n/a — <reason>` directly under the table instead, for example `RED: n/a — documentation only; no behaviour changes`. - The Tier A/B/C testing standard above decides which rows a task needs; the rows are the proof, not a checklist. Under the table, add `## Stop and Report If` with these five default bullets verbatim, then the bullets specific to this task: ```markdown ## Stop and Report If - A command, path, symbol or anchor named in this task does not match the repository. - A Verification row fails for a reason other than its Expect. - The work needs a change to a file outside Allowed files, or to a protected path. - The work needs a change to this task's Verification table, Definition of Done, Allowed files or Covers line. - A variable named in the Needs column is unset. ``` Then add `## Decisions Already Made`: the choices from the spec or HLD that the task must not revisit, copied inline so the receiver does not have to find them. State exact production signatures, parameter defaults, canonical constants, and the caller-to-callee chain when those facts are established by the HLD or grounded repository symbols. Label grounded existing contracts with their source path and symbol. Label planned interfaces as new frozen contracts. Never invent a signature merely to fill the task; unresolved contract facts stop Gate 2 and return to design clarification. When a task has executable changes (RED or GREEN rows), this section must not be empty or write `None`. Only tasks with no executable behavior (such as pure documentation tasks) may write `None` when there are genuinely no frozen technical choices. 10. **Definition of Done (DoD)**: Acceptance criteria (100% BDD scenario coverage across Tier A unit and Tier C integration tests with zero uncovered scenarios, passes Tier A/B/C verification, clean git status; for Web/UI deliverables: automated integration tests pass AND live browser verification artifacts are captured via `browser_subagent`). Every bullet ends with a parenthesised reference: the Verification rows that prove it, such as `(V2, V4)`, or `(Gate 5)` for an item only the developer can judge at Kanban review. The Gate 4 report lists `(Gate 5)` items; no script marks one met. 11. **Dependencies & Blockers**: Link to blocking/blocked task files as markdown links, each `Blocked by` clause on one line (e.g. `Blocked by [Task 1](task_1_create_package.md)`). 12. **References & Rollback**: Links to docs, APIs, and a rollback strategy if this specific task fails. ### Step 3: Finalize & Commit Before committing — and whether or not `auto_commit` is enabled — run `check_epic_readiness.py <epic_name>` (which internally executes `check_document.py`, `check_bdd_traceability.py plan`, and `check_task_contract.py --design` in a single pass; run the individual scripts below only when isolating a specific error). `SKILL_DIR` is the directory containing this `SKILL.md`: ```bash # Single-pass readiness check (covers R1-R8, check_bdd_traceability.py plan, and check_task_contract.py --design): python3 "$SKILL_DIR"/../dev-implementation/resources/scripts/check_epic_readiness.py <epic_name> [--baseline] # Targeted checks if isolating a failure: python3 "$SKILL_DIR"/../dev-implementation/resources/scripts/check_bdd_traceability.py plan \ --scenarios .devtool/epic/<epic_name>/bdd_scenarios.en.md \ --tasks .devtool/epic/<epic_name>/task_*.md python3 "$SKILL_DIR"/../dev-implementation/resources/scripts/check_task_contract.py --design \ --hld .devtool/epic/<epic_name>/<epic_name>.en.md \ --tasks .devtool/epic/<epic_name>/task_*.md ``` It must exit 0. Exit 1 names the unassigned, duplicated, unknown or malformed identifiers or contract issues: fix the task files or the scenario documents and run it again. To verify task text directives (`Create`, `Replace in`, `Insert in`) and all verification rows end-to-end inside an isolated scratch worktree without mutating the main tree, run: ```bash python3 "$SKILL_DIR"/../dev-implementation/resources/scripts/check_epic_readiness.py <epic_name> --replay ``` It must exit 0 as well; fix what it names and run checks again. All checks must exit 0 before the commit. Pass the epic directory's task mirrors, never `.devtool/features/task_*.md`, which can hold other epics' tasks. After the Epic Overview and all confirmed task files are written (or updated), commit them to git: - Read `.agents/config.json` — check the `auto_commit` setting. - If `auto_commit: true`: stage exactly the generated/modified paths (the epic's `.devtool/epic/<epic_name>/` directory and each new/modified `.devtool/features/task_*.md` file). Then commit: - New epic: `git commit -m "[<EPIC_NAME>] Generate epic and task breakdown" -m "- <task 1 title>\n- <task 2 title>"` - Update to an existing epic: `git commit -m "[<EPIC_NAME>] Add tasks to epic" -m "- <task title>"` Follow [Commit Message Format](../../rules/CRITICAL_RULES.md#commit-message-format) — bracketed scope, one-line title, one bullet per task written. No `Co-Authored-By` or other trailer. - If `auto_commit: false`: skip staging and committing entirely. Then automatically execute Gate 2 handoff packaging and `/save-context` without asking an intermediate "Package vs Continue" question first: 1. Record Gate 2 approval in the Gate Approval Ledger: ```bash python3 scripts/resume_context.py --gate 2 --epic <epic_slug> --approved "<approved task breakdown summary>" ``` (Query or verify Gate 2 status via `python3 scripts/resume_context.py --check-gate 2 --epic <epic_slug>`.) 2. Automatically package the epic for handoff (or revise an already packaged epic): ```bash python3 skills/dev-implementation/resources/scripts/package_epic.py <epic_dir> [--revise --reason "<text>"] ``` If `auto_commit: true`, commit the generated/updated `handoff.md` and `Packaged` status (`git commit -m "[<EPIC_NAME>] Package epic for handoff"`). 3. Automatically persist `/save-context` state and emit role handoff prompts: ```bash python3 scripts/resume_context.py --state --epic <epic_slug> --status "Stage 2: Packaged & Ready" python3 scripts/resume_context.py --emit-prompt principal-review --epic <epic_slug> python3 scripts/resume_context.py --emit-prompt implement --epic <epic_slug> ``` (This automatically updates the IDE window title to `<ICON> [<REPO>] [@<account_id>] <Vietnamese Epic Name> - Stage 2: Packaged & Ready`.) 4. Finally, stop calling tools and present the unified [Handoff Choice](../dev-lifecycle/SKILL.md#handoff-choice) in `dev-lifecycle`: ask the developer only whether to run `/principal-review` or proceed directly to `/dev-implementation` (or stop here with the packaged handoff). This skill never invokes `dev-implementation` or `principal-review` itself. ### Updating an Existing Epic When new requirements arrive for an epic already in progress, append new task files continuing the sequence, and append links to the Epic Overview's Kanban Tasks Breakdown section (in both `.en.md` and `.vi.md`). Update the Mermaid diagrams if architecture changes. If the epic's `bdd_scenarios.en.md` predates scenario identifiers, retrofit the whole epic first — identifiers, `Covers:` lines and the `Integration test roots:` line, as dev-implementation Phase 1 step 3 describes — before running the Step 3 `plan` check. ## Anti-Rationalization and Doubt-Driven Verification | Agent Rationalization | Enforced Counter-Rule | | :--- | :--- | | "A Node.js test is sufficient to prove this web UI feature works." | **REJECTED**: Node tests prove only pure data logic. 80% of web defects occur in DOM queries, event bubbling, and CSS rendering. Tier C requires headless Playwright execution with Zero-Console-And-Layout-Defect Watchdog. | | "This component is simple; hardcoding mock data in a stub is enough." | **REJECTED**: Method-level stubs bypass JSON deserialization and network interceptors. Wire-level fixtures from `shared-contracts/` are mandatory. | | "The red errors in the browser console are just harmless warnings." | **REJECTED**: The Zero-Console-Error rule fails Gate 4 on any browser console error or uncaught exception. | | "I cannot launch a mobile simulator, so I will write a unit test instead." | **REJECTED**: Mobile Tier C requires Subcutaneous Testing with real DI and in-memory persistence. Pure unit tests cannot be tagged as Tier C. | | "I ported the HTML structure and JS logic from the Visual Companion mockup, and the DOM selectors match in Playwright." | **REJECTED**: Porting HTML/JS without verifying computed CSS styles results in broken, unstyled layouts. Tier C2 tests for UI components MUST assert `getComputedStyle` and `getBoundingClientRect` properties (non-zero dimensions, layout display mode, and mutually exclusive state visibility, while respecting standard clipped `.sr-only` accessibility patterns) against the Visual Companion design. | ### Doubt-Driven Verification Protocol Apply the 4-phase doubt protocol: 1. **CLAIM**: State the architectural or test claim (e.g. "Scenario covered by Tier C test"). 2. **EXTRACT**: Inspect concrete evidence files (JUnit XML classnames, Playwright traces, network mocks). 3. **DOUBT**: Scrutinize whether mocks bypass the real bug or fake integration runner provenance. 4. **RECONCILE**: Verify against real production code paths, rejecting pure unit mocks for Tier C scenarios. ## Red Flags - STOP and Start Over - Designing cross-service features or payload changes without checking `shared-contracts/` first. - In Hub Mode, scheduling `shared-contracts/` updates at the end of the task list instead of `task_01` (blocking parallel execution in satellite repos). - In Satellite Mode, placing `shared-contracts/...` inside `Files Allowed` of a task, causing `fatal: pathspec is beyond a symbolic link` in git. - In Satellite Mode, designing cross-service payload changes without emitting an Upstream Contract Handoff Summary to the Hub repo. - Writing task files before the user has confirmed the task breakdown checkpoint. - Omitting the final Tier C (Acceptance & App Tests) task from the Epic breakdown. - Omitting Tier C integration tests that exercise analyzed use cases, edge cases, and boundary conditions. - Claiming a Web/UI Epic or task is complete without live browser verification (running preview/dev server and inspecting visual/DOM states with `browser_subagent`). - Using Android test commands (`./gradlew`) on a Flutter/iOS project, or Flutter test commands (`melos test`) on Android/iOS, or iOS test commands (`swift test`) on Flutter/Android. - Creating the Epic overview in the project root instead of `.devtool/epic/<epic_name>/`. - Defaulting new tasks to `status: "todo"` without checking for another epic's active tasks first. - Mixing languages within a single task file. - Using legacy Mermaid syntax (`graph TD`/`graph LR` instead of `flowchart TD`/`flowchart LR`), unquoted special-character labels, or malformed Graphviz (DOT) diagrams. - Violating markdown lint standards (e.g. untagged code blocks, heading skips, trailing whitespace). - Writing a scenario in `bdd_scenarios.*.md` without a bracketed identifier, or a task that writes integration tests without its `Covers:` line. - Committing the epic before `check_bdd_traceability.py plan` and `check_task_contract.py --design` both exit 0. - A Definition of Done item with neither a row reference nor `(Gate 5)`. - Task files whose paths or commands were not checked with `check_task_contract.py --design`. - Invoking `dev-implementation` after Step 3 instead of returning to the Handoff Choice.