Specification Writing
Governing Rule — NO PROCEDURAL REDUCTION
ABSOLUTE RULE: Never condense, summarize, shortcut, or skip detail when creating or updating specification files, PRDs, architecture docs, or any project artifact. Every rewrite must preserve ALL prior depth. Procedural reduction = loss of engineering knowledge = unacceptable.
When updating a spec file:
- Never replace detailed content with summaries
- Never collapse user stories into bullet-point descriptions
- Never remove Gherkin scenarios, edge cases, or error messages
- Never strip UI design system detail (spacing, elevation, radius, states, motion, accessibility)
- Never remove business rules, glossaries, or traceability matrices
- Add new decisions ON TOP of existing depth, not replacing it
Governing Rule — SKILL CONTENT SEPARATION
Hard-learned: 2026-07-26. The user rejected newly-created skills because their SKILL.md files mixed general patterns with project-specific audit data (mentioning Hermex, CarSah, Azdal by name). A skill that references specific projects cannot be reused by future projects.
ABSOLUTE RULE: SKILL.md is the universal pattern — it MUST remain project-agnostic. Project-specific context belongs ONLY in reference files, never in the skill body.
Separation contract:
| File |
Contains |
Must NOT contain |
SKILL.md |
Universal patterns, contracts, templates, anti-patterns |
Project names, file paths to specific repos, line numbers, DEC numbers from specific projects |
references/project-landscape.md |
Snapshot of current project state: exact file paths, line numbers, DEC entries, migration priorities |
Universal pattern definitions (those belong in SKILL.md) |
references/authoritative-sources.md |
Curated excerpts from Flutter/Dart official docs, library APIs, versioned references |
Project-specific observations |
When writing SKILL.md:
- Use "typical Flutter project" not "Hermex Android"
- Use "API-heavy app" not "Hermex pattern"
- Use "hundreds of debugPrint calls" not "483 debugPrint calls"
- Templates, examples, and code snippets must use generic class names
When a new project is audited:
- The universal pattern (SKILL.md) remains UNCHANGED
- Append a new section to
references/project-landscape.md
- If a pattern deficiency is found that applies universally, update SKILL.md generically
Governing Rule — EXTERNAL SOURCE GROUNDING
Established: 2026-07-26. Before finalizing any architectural skill, ground it in official Flutter/Dart documentation using find-docs (Context7 CLI).
Workflow:
- Use
npx ctx7@latest library to resolve relevant library IDs (dio, riverpod, go_router, logger, dart, flutter)
- Use
npx ctx7@latest docs to query official documentation for canonical patterns
- Curate findings into
references/authoritative-sources.md with library IDs, key evidence, and relevance summaries
- Cross-reference SKILL.md patterns against sources — flag any divergence
- If sources reveal a pattern is wrong or incomplete, fix SKILL.md BEFORE saving
Governing Rule — THE TWO-REIN RULE (Creativity vs Quality)
Established: 2026-07-30. Adopted from YC/Anthropic insights (Boris Cherny, Claude Code) and adapted through founder-led strategic discussion. The core insight: frontier models perform best with minimal scaffolding in creative domains, but still require strict guardrails in domains where errors are costly. The wisdom is knowing when to loosen and when to tighten.
The principle: Not all specification files are equal. Some require creative freedom; others require deterministic correctness. Applying the same governance level everywhere either suffocates innovation (all reins tight) or burns tokens on unverified output (all reins loose).
Three-Zone Classification
Every file in the Spec Pack falls into one of three zones:
| Zone |
Files |
Reins |
Governance |
| 🎨 Creative |
07 (User Flows), 08 (Design) |
Loose |
Human aesthetic judgment; minimal automated gates |
| ⚖️ Mixed |
09 (PRD), 12 (Architecture) |
Tight on logic, loose on UI |
Lint + review; template required |
| 🔒 Quality |
10 (Data), 11 (API), 13 (Security), 15 (DevOps), 17 (ACID), 18 (Backlog) |
Tight |
Automated verification gates (tests, lint, schema validation); skills enforced |
Stage 3: Dual Paths
Stage 3 is the ONLY stage with two execution paths. The founder chooses based on whether the design direction is already known:
| Path |
When |
Model Role |
Founder Role |
| 🐢 Normal |
App Mark exists (Canva), colors defined |
Claude generates derivative assets from App Mark |
Active: reviews, adjusts incrementally |
| ⚡ Fast |
No constraints — "surprise me" |
Claude reads Stage 1+2, autonomously produces BOTH 07+08 |
Passive: receives, judges (accept/reject/modify) |
Both paths produce files 07+08. The Normal Path is unchanged. Stage 3.5 is MANDATORY for both.
Governance Gradient
| Stage |
Writes |
Judges |
Reins |
| 1–2 (Idea & Feasibility) |
Founder + Model |
Founder |
Tight |
| 3 (Design) |
Model |
Founder (taste) |
Loose |
| 3.5 (Build Readiness) |
Model (founder's intent) |
Third party |
Tightest |
| 4+ (MVP & Production) |
Model (skills enforced) |
Auto tests + Founder |
Tight |
Key insight: Stage 3.5 is the governance bottleneck — model writes the build plan, third party reviews it adversarially, founder receives the verdict. Mirrors Bun (YC 2026): autonomous agents ran 11 days, adversarial review caught 3 critical bugs before merge.
Tooling — Premium Generator & Verifier
A paid/companion tooling suite exists for this skill (Spec Pack Premium, built 2026-08-03). Two scripts, both tested:
scripts/generate_spec_pack.py — generates the full 26-file pack (00–25) with mandatory headers + section skeletons into <project>/app-spec/. Usage: python3 scripts/generate_spec_pack.py /path/to/project PROJECT_NAME
scripts/verify_spec_pack.py — compliance gate (exit-code): checks file presence, header integrity, content markers, per-stage readiness. Usage: python3 scripts/verify_spec_pack.py /path/to/project (exit 0 = compliant, 1 = gaps).
The generator embeds the 4 mandatory architecture patterns (Hook System, Screen State Machine, Error Handler, Logger) with their verification checklists directly into File 12. The verifier is CI-usable. These were validated against a real project (correctly detected a legacy 22-slot structure as non-compliant with the 25-file system).
Trigger
Use this skill when:
Project Stages — Six Gates
Every project MUST pass through these 6 stages in order. A flaw in any stage affects all subsequent stages. No stage begins until the previous stage is fully complete.
| Stage |
Name |
Gate |
Rule |
| 1 🟢 |
الفكرة (Idea) |
IDEA_GATE |
Problem, personas, value prop, context. No code. |
| 2 🟡 |
دراسة الجدوى (Feasibility) |
FEASIBILITY_GATE |
Monetization, financials, risks. Prove viability before design. |
| 3 🟠 |
التصميم والهوية (Design) |
DESIGN_GATE |
User flows, design system, wireframes, prototype. No code before this closes. |
| 3.5 🟤 |
جاهزية البناء (Build Readiness) |
BUILD_READINESS_GATE |
Lock dependency graph + one build sequence (18) + technical-debt-vs-feature policy (16). No code until this closes. Deliberately lightweight — a dependency graph + one sequence + one policy, not Gantt/CPM. |
| 4 🔵 |
MVP |
MVP_GATE |
PRD, data model, architecture, security, testing, backlog. Build minimum. Requires DESIGN_GATE AND BUILD_READINESS_GATE both closed. |
| 5 🟣 |
التطوير والتحسين (Iteration) |
ITERATE_GATE |
Decision log, lessons learned, red team audit. Improve from real feedback. |
| 6 ⚫ |
النشر والإنتاج (Production) |
PRODUCTION_GATE |
Admin panel, support ops, capabilities inventory. Go live. |
Each stage has a status: ✅ Complete | 🔄 In Progress | ⏳ Blocked (waiting on previous stage) | 🚨 Missing (gap!)
Specification Pack Structure — 25 Files (Sequential 00–25)
Evolved from the 22-slot v2.0 system into a 6-stage, 25-file sequential structure. Every file is numbered by its position in the project lifecycle — open 00, read the index, follow the numbers.
🗺️ File 00 — The Map
00_project_stages.md is the FIRST file created and the FIRST file read by any agent. It contains:
- 📋 FILE INDEX — Complete table of all 25 files: number, filename, stage, purpose
- 🚦 STAGE STATUS — Which stages are complete, in progress, blocked, or missing
- Gates — What must be true before each stage can begin
Stage 1: الفكرة 🟢 — Files 01–03
| # |
File |
Purpose |
| 01 |
01_product_discovery.md |
Problem, personas, value proposition, MVP scope, feasibility, Go/No-Go decision |
| 02 |
02_project_context.md |
Tech stack, dependencies, environment, constraints, conventions, which persistence/backend stack this project uses |
| 03 |
03_project_overrides.md |
Deviations from standard spec pack, project-specific rules |
Stage 2: دراسة الجدوى 🟡 — Files 04–06
| # |
File |
Purpose |
| 04 |
04_monetization_entitlements.md |
Feature access matrix per tier, pricing, trial mechanism, paywall architecture, abuse protection |
| 05 |
05_financial_model.md |
Unit economics, LTV, CAC, break-even, founder targets, decision triggers |
| 06 |
06_assumptions_risks.md |
Categorized risks with IDs, severity, mitigation, product/technical/market assumptions |
Stage 3: التصميم والهوية 🟠 — Files 07–08
| # |
File |
Purpose |
| 07 |
07_user_flows_navigation.md |
Screen inventory with IDs, Mermaid navigation map, flow details, navigation rules |
| 08 |
08_design_prototype.md ✨ |
Everything design: Color tokens (hex), spacing (4dp MD3), elevation, radius, typography, component specs, states, motion, accessibility, RTL/LTR, wireframes, interactive prototype, user journey walkthrough, design testing notes |
Stage 3.5: جاهزية البناء 🟤 — Build Readiness (no new file numbers)
⚠️ MANDATORY for BOTH Stage 3 paths (Normal and Fast). This stage has NO standalone file. Its content lives inside two existing Stage 4 files — 16_ai_agent_contract.md and 18_implementation_backlog.md — but MUST be written and locked BEFORE any Stage 4 code begins. It cannot be completed before the design settles (Stage 3 must close first).
Governance for Stage 3.5:
- Who writes: The model — based on the founder's stated intent and the completed Stage 1-3 files
- Who judges: A third party (independent adversarial reviewer) — NOT the founder alone
- Why third party: This is the single highest-leverage quality gate. After creative freedom in Stage 3, the build plan must be challenged by an external reviewer. This mirrors the Bun case study (YC 2026): 64 agents ran autonomously for 11 days, but adversarial human review caught 3 critical bugs before merge
- Reins: Tightest in the entire governance gradient — external validation before any code
| Location |
Content |
18_implementation_backlog.md (new section) |
Dependency graph across all backlog items + one locked build sequence — deliberately one, not multi-variant. Once locked, the build order is NOT renegotiated feature-by-feature. |
16_ai_agent_contract.md (new section) |
Explicit technical-debt-vs-feature policy — when a mid-build choice arises between fixing debt or shipping a feature, the policy (not a live debate) decides. |
18_implementation_backlog.md (each step) |
Per-step HOW map — NARROWED form (one line per step, written at 3.5): the line carries ONLY what cannot be derived from elsewhere — (a) the files the step touches, (b) a POINTER to the governing section (e.g. "see 17 §3.1", "see DEC-004"), (c) step-specific pitfalls not derivable elsewhere (e.g. "stepNumber is 1-based"). NO rephrasing of spec content: the pointer cannot contradict its target, but a rephrased instruction can drift (measured: duplicated instructions are the project's most reliable defect generator — a line in 17 vs DEC-011, a line in 12 vs it, stale APK fingerprints). Full-form HOW lines were audited against 52 prior review findings and would NOT have prevented the logic/guard defect classes — those are caught by automated guards, not more prose. |
The locked sequence has two READ views — generate, never commit. A long
dependency-ordered table is hard to read from two angles at once (the build
story vs where each work-type lands). Provide two DERIVED views, generated ON
DEMAND from the locked table by a small script (one that parses the table +
the work-type/EPIC sections and prints both): (1) the sequence view — step |
BL | work-type | why — the build story; (2) the swimlane view — which work-type
lands where across the sequence, including deliberate splits (a privacy EPIC
may appear at step 28 and again at 37-38 because storage-before-UI outranks
category contiguity). NEVER commit a derived document: a committed derived
file drifts from the table and becomes a second, lying source of truth; a
script holds no data and cannot drift. The table stays the single source of
truth; the views are printed from it on demand (one command after any DEC).
Working generator (spec-pack convention, parse + both views + --html visual):
scripts/build_sequence_view.py.
Make the derived views LIVE, not static (validated 2026-08-10). The
founder's real need is "what is the NEXT step" — a static table does not
answer it. Have the generator also read the project's running STATE file
(done steps as numbers/ranges, next marked ⏭ — the listing may wrap across
several lines: join following lines until a blank line) and color the
swimlane accordingly: done ✅ / in-progress 🔄 (a dirty tree means the next
item is being edited) / next ⏭ (highlighted) / future (faded), with a
one-line "Next step: BL-XXX" header. The founder reads the whole build at a
glance — no re-reading the backlog to answer "where are we" (their own words:
"هذي المرة الوحيدة اللي أحس إني فيها فاهم — هذا ما كنت أحتاجه لأعرف ماهي
الخطوة التالية").
Work-type (EPIC) ids are audit-trail labels — freeze them mid-build.
Reviews, DECs, and handoff state all reference work-type ids; renumbering
mid-build manufactures label mismatches — the same failure class as a review
label contradicting the locked table. Confusing numbering (e.g. a
localization EPIC appearing before the data EPIC because localization is an
early dependency) is EXPLAINED by the derived views, not fixed by renumbering.
Renumber only at post-launch cleanup, with a mapping table.
Why this exists: Past build attempts hit repeated mid-build negotiation ("which feature first?", "fix this debt now or later?") despite having a spec pack — because the pack had priorities but no locked order and no debt policy. Stage 3.5 closes that gap once, before coding, instead of re-litigating it feature by feature. Deliberately lightweight (a dependency graph + one sequence + one policy) rather than formal construction-style scheduling (Gantt/CPM), which would reintroduce the process-overhead trap.
Stage 4: MVP 🔵 — Files 09–18
| # |
File |
Purpose |
| 09 |
09_prd.md |
User stories with Gherkin (Given/When/Then), business rules, edge cases, error messages (AR+EN), glossary, traceability matrix |
| 10 |
10_data_model_erd.md |
Entities, relationships, field justifications, schema |
| 11 |
11_api_contract.md |
OpenAPI/GraphQL spec, endpoints, request/response schemas, auth headers |
| 12 |
12_flutter_architecture.md |
Clean Architecture layers, provider/notifier graph, folder structure, routing, Hook System Architecture (§ mandatory), Screen State Machine (§ mandatory), Unified Error Handler (§ mandatory), Structured Logger (§ mandatory) |
Structured Logger — Depth Requirement (File 12)
Effective: 2026-07-26
Source: flutter-app-logger skill
Governance Rule: Every Flutter project MUST use AppLogger with at least 4 levels (debug, info, warn, error). Raw debugPrint for application logging is prohibited. LogBuffer must be accessible at runtime for debugging. Error/fatal levels must persist to file via LogPersister.
Verification Gate:
Cross-reference:
flutter-app-logger skill
flutter-error-handler skill — ErrorLogger.log() uses AppLogger.error() internally
Unified Error Handler — Depth Requirement (File 12)
Effective: 2026-07-26
Source: flutter-error-handler skill
Governance Rule: Every Flutter project MUST use ErrorHandler.show(context, error) as the single entry point for all user-facing errors. Raw ScaffoldMessenger.of(context).showSnackBar(SnackBar(...)) scattered across screens is prohibited. All errors must be classified through ErrorClassifier.classify() before display.
Verification Gate:
Cross-reference:
flutter-error-handler skill — the authoritative implementation reference
flutter-screen-state-machine skill — AppError widget pairs with ErrorHandler for full-screen errors
Screen State Machine — Depth Requirement (File 12)
Effective: 2026-07-26
Source: flutter-screen-state-machine skill
Governance Rule: Every Flutter project MUST use the unified ScreenState<T> widget pattern. Per-screen _buildLoadingState / _buildErrorState / _buildEmptyState methods are prohibited. The 5 standard widgets (AppLoading, AppError, AppEmpty, AppOffline, AppEmptySearch) must live in lib/core/ui/screen_states/.
Verification Gate:
Cross-reference:
flutter-screen-state-machine skill — the authoritative implementation reference
flutter-hook-architect skill — PostMutationInvalidationHook pairs with ScreenState for refresh
Hook System Architecture — Depth Requirement (File 12)
Effective: 2026-07-26
Source: flutter-hook-architect skill
Governance Rule: Every Flutter project MUST include a Hook System Architecture section in its architecture file (12 or project-overridden equivalent). Level 1 (Safety) hooks are non-negotiable before any code ships.
The Hook System Architecture section must address:
- 11 Hook Types — Which of the 11 hook types apply to this project (PreRequest, PostResponse, OnRequestError, RouteGuard, PreMutation, PostMutation, WidgetLifecycle, StreamTransform, InputSanitize, FileGuard, SessionGate)
- 4 Progression Levels — Current level for each hook type (Safety → Productivity → Intelligence → Orchestration)
- Configuration Structure —
hooks.yaml or equivalent configuration, registered with the HookChain orchestrator
- Security Chain — Veto order, injection patterns (14 patterns minimum), trusted tools skiplist
- Self-Healing Audit — Hook grading report (A-F) with auto-fix recommendations
- Project-Specific Template — Which of the 3 templates applies (API-heavy, Local-DB, LLM-powered) and any deviations
Verification Gate (Level 1 — Safety):
Cross-reference:
flutter-hook-architect skill — the authoritative implementation reference
hook-veto-protocol skill — security chain origin
19_decision_log.md — DEC entries for hook-related decisions
| 13 | 13_security_privacy.md | Auth strategy, data sensitivity classification, permissions, encryption, threat model |
| 14 | 14_testing_acceptance.md | Test pyramid, DoD, acceptance criteria, device targets |
| 15 | 15_devops_release.md | CI/CD pipelines, environments, signing, release checklist, observability |
| 16 | 16_ai_agent_contract.md | Agent rules, validation payload format, traceability, handoff protocols, boundaries |
| 17 | 17_data_architecture_acid.md | Transaction boundaries, consistency guarantees, migration strategy |
| 18 | 18_implementation_backlog.md | Prioritized feature queue, dependency chains, effort estimates |
Stage 5: التطوير والتحسين 🟣 — Files 19–21
| # |
File |
Purpose |
| 19 |
19_decision_log.md |
Structured ADR format (DEC-NNN), rationale, date, linked files, rejection reasons |
| 20 |
20_lessons_learned.md |
Sequential LL-NNN numbering, date discovered, stage, root cause, prevention rule, cross-reference to DEC |
| 21 |
21_zero_trust_red_team.md |
Attack vectors, penetration test results, security assumptions challenged |
Stage 6: النشر والإنتاج ⚫ — Files 22–25
| # |
File |
Purpose |
| 22 |
22_admin_panel.md |
Admin dashboard, moderation tools, analytics views, role-based access |
| 23 |
23_support_operations.md |
On-call procedures, incident response, escalation paths, FAQ maintenance |
| 24 |
24_active_capabilities.md |
Current feature status — the accurate, living inventory of what works. MUST include a plain-language App Completeness Checklist (§7): 20 yes/no questions a non-technical person answers by opening the app — navigation bar present, screens reachable, honesty rules visible. Checked before any release gate and after every 10 build steps (lesson 2026-08-12: 38 steps passed while the prototype-designed 3-tab navigation was never built — long spec files hide absences; a short checklist catches what long files hide). Full founder-validated doctrine in references/checklist-philosophy.md: four checklist types with distinct owners (pre-flight / completeness / compliance / release), the three-state answer model where N/A must cite a justifying decision or counts as NOT applied, project checklists born at 3.5, stable item IDs, and the checklist→gate→guard triad. |
Stage Gate Rules
Gate 3 (DESIGN_GATE) — The Critical One
This is the stage once discovered missing in a real project — the rule:
No executable code is written before DESIGN_GATE closes.
The design prototype (08_design_prototype.md) must exist and be approved. Colors, wireframes, user journey — all decided and documented. Code without design = rework.
PRECISION — what "no code" means (hard-learned): the gate forbids
APP SOURCE CODE (lib/, src/, app logic, behavior tests). It does NOT forbid
— and in fact REQUIRES — the design agent to write spec artifacts: reflecting
the design artifact onto 07_user_flows_navigation.md and
08_design_prototype.md, exporting visual references, element checklists,
and tokens into the repo. Refusing to touch spec files in the design phase on
the grounds of "stage 3.5 not complete" is a MISAPPLICATION of this gate: it
forces the founder to hand-copy design output, and every manual transfer loses
fidelity. The deciding question is only: does the change touch app source
code? No → design-stage artifact, write it. Yes → wait for the gates.
See File 08 §6 (Operational Pipeline) below for the full stage-3 execution
rules.
Gate 3.5 (BUILD_READINESS_GATE) — The Build Lock
This gate prevents the "which feature first?" negotiation that plagued past builds. It is MANDATORY for BOTH Stage 3 Normal and Fast paths.
No executable code is written before BUILD_READINESS_GATE closes.
After DESIGN_GATE closes, the next step is NOT writing code — it's locking the build order. The dependency graph + one build sequence (18) and the technical-debt-vs-feature policy (16) must be written by the model, then reviewed and approved by a third party (independent adversarial reviewer). The founder receives the reviewer's verdict and makes the final approval. Only then does MVP coding begin.
Why DESIGN_GATE alone isn't enough: A spec pack with priorities but no locked order still forces live mid-build negotiation on every feature boundary. Stage 3.5 eliminates that by making the build sequence a one-time decision (locked, not debated feature-by-feature) and the debt policy an explicit rule (not a recurring argument).
Why third-party review: The founder should not be the sole judge of the build plan. After creative freedom in Stage 3, an independent adversarial reviewer challenges the model's build plan — catching blind spots the founder and model both missed. This mirrors the Bun case study (YC 2026): autonomous agents produced code, but adversarial human review caught 3 critical bugs before merge.
Deliberately lightweight: This is a dependency graph + one sequence + one policy — NOT formal construction scheduling (Gantt charts, CPM, FF/FS/SF/SS dependencies). Heavy scheduling would reintroduce the governance-overhead trap.
Gate Rules for All Stages
- Each stage's files MUST exist in
app-spec/ before the stage begins — empty if not yet populated
- A stage CANNOT start until the previous stage's files are complete (not empty placeholders)
00_project_stages.md MUST be updated to reflect current stage status
- Create empty > Leave absent — an empty file signals intent; an absent file is a hidden assumption
Mid-Project Stage Audit
When receiving a project already in progress:
- Read
00_project_stages.md — if missing, create it and run a full audit
- Check each stage's files: present? populated?
- Flag any 🚨 gaps — especially missing DESIGN_GATE (Stage 3)
- Stop and fill gaps before writing new code — a mid-project design gap is still a gap
Pre-Proposal Code Audit (Fatabayyanu Gate)
Mandatory before adding any new architectural pattern, capability, or system design to app-spec. This gate prevents proposing something that already exists, and establishes an accurate baseline for the spec addition.
Workflow:
Read spec files first — check ALL relevant spec files across the project for existing mentions of the pattern (architecture, capabilities, decision log)
Search actual codebase — scan lib/ and all source directories for:
- The pattern name (e.g.
hook, interceptor, middleware, guard)
- Related class names, file names, and imports
- Any partial/primitive implementations that might be an informal version of the pattern
Cross-reference ALL projects the user maintains — the pattern may exist in one project but not others. Establish the full landscape:
- Which projects have it in spec? Which have it in code?
- Where is it partially implemented vs fully absent?
Report current state clearly before proposing changes — use a table format:
| Project | Spec | Code | Status |
|---------|------|------|--------|
| Example App A | ❌ Absent | ✅ Partial (HTTP interceptors only) | ❌ No formal pattern |
| Example App B | ❌ Absent | ❌ Absent | ❌ Not implemented |
Only then propose spec additions — grounded in the real gap, not an assumption
Rationale: This pattern was hard-learned when the user asked "تأكد اولا من الملفات كقراءة فقط هل هي منفذة ام لا" before agreeing to add Hook System architecture to app-spec. Proposing spec changes without code verification = proposing solutions to non-existent problems. Always verify the gap before filling it.
Depth Requirements Per File Type
PRD (File 09)
Must include:
- User stories with Gherkin-style acceptance criteria (Given/When/Then)
- Business rules with unique IDs
- Edge cases with expected behavior
- Error messages (AR + EN where applicable)
- Glossary of domain terms
- Feature traceability matrix (Feature ID → User Story → Screen → Business Rule → Test Case)
User Flows (File 07)
Must include:
- Screen inventory with IDs, tab/flow, MVP status, notes
- Single valid Mermaid navigation map inside ```mermaid fence
- Per-flow details with rules for each step
- Navigation rules with IDs
Design Prototype (File 08) ✨ — Unified Design File
This is the single most important file in Stage 3. It contains EVERYTHING design-related — no separate brand guide, no separate prototype spec. One file, one source of truth.
§1 Logo Architecture — Full Logo vs App Mark
A common pitfall is placing text-heavy full logos inside small app icon containers. The distinction:
| Asset |
Dimensions |
Usage |
| Full Combination Logo |
Horizontal/vertical lockup (variable) |
Landing pages, store listings, headers, invoices, PDF reports |
| App Mark (Standalone Symbol) |
1024×1024 px square canvas |
Master source for all system-generated icons |
App Mark Types (choose one):
- Symbol/Icon Mark — stylized graphic (e.g., car silhouette + checkmark for automotive apps)
- Monogram/Lettermark — abstracted letter from brand name (e.g., styled 'C' or 'S')
- Wordmark/Logotype — custom typographic logo. Note: full wordmarks are NEVER used directly as app icons; an extracted lettermark is used instead
§1.1 App Mark Generation Workflow (Canva → Claude)
The recommended non-designer workflow:
Step A: Generate App Mark in Canva
→ Use Canva's AI logo generator or manual design tools
→ Output: ONE 1024×1024 px App Mark (transparent PNG preferred)
Step B: Feed App Mark to Claude
→ Give Claude the App Mark + context about the brand
→ Claude produces derivative assets for all screen contexts:
• Full Combination Logo (for Auth, About, PDF headers)
• Splash screen variant (centered mark on brand background)
• Notification icons (monochrome white, per Android spec)
• Store listing feature graphics
Step C: Validate Platform Compliance
→ iOS: no transparency in final icon (system adds rounded corners)
→ Android: adaptive icon layers (foreground + background)
→ Notification icons: white/semi-transparent on transparent background
§2 Color Architecture (The 60-30-10 Rule)
Apply the standard color distribution rule to avoid visual clutter:
| Proportion |
Role |
Light Mode |
Dark Mode |
| 60% |
Neutral Surface/Background |
White or light off-grey |
Deep navy/slate |
| 30% |
Primary Brand Color |
Cards, headers, secondary navigation |
Same brand color, adjusted luminance |
| 10% |
Accent/CTA Color |
Primary action triggers (Save, Confirm, Inspect) |
Brighter accent for dark contrast |
System Status Colors (separate from brand): Green (success), Red (errors), Amber (warnings).
Color Exploration Tools:
| Tool |
Purpose |
| Realtime Colors (realtimecolors.com) |
Preview palettes on real mobile UI layouts, adjust distribution ratios |
| Coolors (coolors.co) |
Generate cohesive schemes, explore automotive-grade palettes |
| Adobe Color (color.adobe.com) |
Verify contrast ratios against WCAG accessibility standards |
| Material Theme Builder (material-foundation.github.io) |
Generate MD3 tonal palettes with 13 values per color, export as JSON |
§3 Platform-Specific System Asset Requirements
Modern mobile operating systems enforce strict guidelines for icons and splash screens:
App Launcher Icons:
| Platform |
Master Size |
Output Format |
Key Rule |
| iOS |
1024×1024 px |
PNG (no transparency) |
System applies rounded corners — do NOT pre-round |
| Android |
1024×1024 px |
Adaptive Icon (foreground + background layers) |
Foreground: 108dp safe zone inside 108dp; Background: fills 108dp |
Splash Screens:
| Platform |
Approach |
Implementation |
| iOS |
Storyboard-based |
Single centered image + solid background color |
| Android |
Native splash API (Android 12+) |
Window background + icon centered, no branding text |
Flutter Automation (eliminate manual resizing):
| Package |
Version |
Purpose |
flutter_launcher_icons |
^0.14.4 |
Ingest 1024×1024 master → generate all iOS + Android icon assets |
flutter_native_splash |
^2.4.8 |
Generate splash screens across all densities from config |
| IconKitchen (web) |
— |
Adaptive icon generation for Android |
| Android Asset Studio (web) |
— |
Monochrome notification icons |
Configuration snippet (pubspec.yaml):
dev_dependencies:
flutter_launcher_icons: ^0.14.4
flutter_native_splash: ^2.4.8
flutter_launcher_icons:
image_path: "assets/app_mark_1024.png"
android: true
ios: true
adaptive_icon_background: "#FFFFFF"
adaptive_icon_foreground: "assets/app_mark_foreground_1024.png"
flutter_native_splash:
color: "#1A73E8" # Primary brand color
image: "assets/splash_app_mark.png"
android: true
ios: true
§4 Screen-by-Screen Asset Placement Guide
To ensure consistent visual hierarchy throughout the user journey:
| Screen |
Asset |
Notes |
| Splash Screen |
Transparent App Mark centered on solid brand background |
No text, no slogan — mark only |
| Onboarding (3-4 screens) |
Vector illustrations + short benefit headlines + CTA buttons |
Brand colors in illustrations, not UI chrome |
| Authentication/Login |
Full Combination Logo (Symbol + Name + Slogan) at top header |
Maximum brand recognition at trust moment |
| Dashboard (Home) |
Clean header: user avatar, notifications, service cards, search |
App Mark small in header or nav bar only |
| About App Screen |
Full Combination Logo + build version + legal + support |
Official identity, not decorative |
| Exported PDF Reports |
Full Combination Logo in document header |
For vehicle inspection/maintenance reports or similar |
§5 Core Design Requirements (in addition to Stage 3 defaults)
Beyond the standard MD3 tokens, File 08 MUST include:
- Brand identity — color tokens with hex values and usage (light AND dark where defined)
- Spacing — based on 4dp MD3 grid
- Elevation — levels
- Border radius — tokens
- Typography — scale with all properties (include Arabic-first font choices like Cairo)
- Component specs — buttons, text fields, cards, state-specific layouts
- Empty/error state designs
- Motion specifications
- Accessibility requirements (WCAG contrast minimums)
- RTL/LTR rules — validate both states for every screen
- Wireframes — at minimum low-fidelity for every screen in the user journey
- Interactive prototype — Figma link or equivalent, showing full user journey
- User journey walkthrough — every tap, every transition, documented step by step
- Design testing notes — was it tested on someone? their feedback?
- Source/provenance labeling rules — which assets came from Canva, which from Claude, which are stock
§6 Operational Pipeline for Stage 3 (design agent behavior)
The design phase is not just content — it is an operational pipeline. These
rules prevent the two failure classes that cost real projects rework:
misclassification (refusing to write spec files) and shape loss (prose that
ten different implementations can all satisfy).
Visual references are the binding shape source:
- Export one screenshot per screen and COMMIT it into the repo next to the
spec. The spec stays the source of RULES (flows, data, logic); the reference
is the source of SHAPE (look, spacing, position).
- Write the conflict rule in the spec text: "on shape conflict, the reference
wins."
- Export state variants per screen (at least default + empty + error) — a
single happy-path screenshot leaves the other states to prose.
- No-build-without-reference: a screen is not buildable until its reference
exists; check completeness at Stage 3.5, not during build.
- The reference is the EXPORTED FILE (versioned artifact), never the agent's
memory or its re-description.
Element checklists, not paragraphs: for each screen provide a checkbox
list (brand icon present, back control at declared edge, empty/error/loading
states defined, fields match the data model). A gate can check a list; it
cannot audit a paragraph. Missing elements surface as unchecked boxes.
RTL-safe vocabulary: default to start/end (logical). "Left" is ambiguous
in RTL — physical left vs line start are different edges. If physical
left/right is truly intended, say "physical left, even in RTL" explicitly.
In Flutter mirror the vocabulary: AlignmentDirectional,
EdgeInsetsDirectional, never raw left/right for layout.
Declared tokens, never derived: every color/radius/spacing/typography
value is written explicitly; no seed-based generation (ColorScheme.fromSeed)
for final values — the seed silently produced a near-white tint where the spec
said white; all tests green, the eye can't tell. Stage 4 pins the declared
values with a theme/token test so drift fails CI, not the founder's eye.
Visual acceptance gate (mandatory): no screen is accepted on code review
alone. 1) device screenshot of the built screen; 2) the spec reference beside
it; 3) a numbered diff list; 4) the founder decides fix vs amend the spec —
never silently. Required step in the build pipeline, not a reviewer's favor.
Anti-patterns (all hit in the field):
| Anti-pattern |
Failure |
Fix |
| Design agent refuses spec-file writes before Stage 4 |
Founder hand-copies → fidelity loss |
Gate 3 precision: spec artifacts ARE stage 3 |
| Prose-only shape ("center the selector") |
Compliant but wrong layout (blank space, floating button) |
Visual references + no-build-without-reference |
| "left" in an RTL app |
Back control on wrong edge; lying comment |
start/end vocabulary |
| Derived palette from a seed |
Silent spec violation, invisible to tests |
Declared tokens + pinned test |
| "no deviations" without visual comparison |
Real deviations found later on device |
Visual acceptance gate + honest diff list |
| Manual re-transfer of design output |
Every transfer loses something |
Agent reflects its own artifact onto files |
Monetization (File 04)
Must include:
- Feature access matrix per tier
- Trial mechanism details
- Grace period rules
- Entitlement source of truth
- Paywall architecture with triggers
- Backend validation rules (if applicable)
- Analytics events
- Abuse protection
- Forward compatibility rules
Financial Model (File 05)
Must include:
- Unit economics per customer/transaction
- LTV calculation with assumptions
- CAC by channel
- Break-even analysis
- Revenue projections
- Decision triggers (when to pivot/kill/scale)
Risks (File 06)
Must include:
- Categorized risks with unique IDs
- Severity ratings
- Mitigation strategies
- References to governing files
- Product assumptions
- Technical assumptions
- Market assumptions
Lessons Learned (
…(truncated)
1---2name: specification-writing3description: Write and maintain product specification files following the AI-Agent App Build Specification Pack framework. Covers the 24-file, 6-stage sequential structure (00–24), mandatory file header template with Cross-Reference traceability, depth requirements (incl. dependency-health rule for library adoption decisions), and the NO PROCEDURAL REDUCTION rule. Use when creating or updating any app-spec file, writing PRDs, design systems, user flows, monetization specs, risk registers, financial models.4---56# Specification Writing78## Governing Rule — NO PROCEDURAL REDUCTION910**ABSOLUTE RULE:** Never condense, summarize, shortcut, or skip detail when creating or updating specification files, PRDs, architecture docs, or any project artifact. Every rewrite must preserve ALL prior depth. Procedural reduction = loss of engineering knowledge = unacceptable.1112When updating a spec file:13- Never replace detailed content with summaries14- Never collapse user stories into bullet-point descriptions15- Never remove Gherkin scenarios, edge cases, or error messages16- Never strip UI design system detail (spacing, elevation, radius, states, motion, accessibility)17- Never remove business rules, glossaries, or traceability matrices18- Add new decisions ON TOP of existing depth, not replacing it1920## Governing Rule — SKILL CONTENT SEPARATION2122> **Hard-learned:** 2026-07-26. The user rejected newly-created skills because their SKILL.md files mixed general patterns with project-specific audit data (mentioning Hermex, CarSah, Azdal by name). A skill that references specific projects cannot be reused by future projects.2324**ABSOLUTE RULE:** SKILL.md is the universal pattern — it MUST remain project-agnostic. Project-specific context belongs ONLY in reference files, never in the skill body.2526**Separation contract:**2728| File | Contains | Must NOT contain |29|------|----------|-----------------|30| `SKILL.md` | Universal patterns, contracts, templates, anti-patterns | Project names, file paths to specific repos, line numbers, DEC numbers from specific projects |31| `references/project-landscape.md` | Snapshot of current project state: exact file paths, line numbers, DEC entries, migration priorities | Universal pattern definitions (those belong in SKILL.md) |32| `references/authoritative-sources.md` | Curated excerpts from Flutter/Dart official docs, library APIs, versioned references | Project-specific observations |3334**When writing SKILL.md:**35- Use "typical Flutter project" not "Hermex Android"36- Use "API-heavy app" not "Hermex pattern"37- Use "hundreds of debugPrint calls" not "483 debugPrint calls"38- Templates, examples, and code snippets must use generic class names3940**When a new project is audited:**411. The universal pattern (SKILL.md) remains UNCHANGED422. Append a new section to `references/project-landscape.md`433. If a pattern deficiency is found that applies universally, update SKILL.md generically4445## Governing Rule — EXTERNAL SOURCE GROUNDING4647> **Established:** 2026-07-26. Before finalizing any architectural skill, ground it in official Flutter/Dart documentation using `find-docs` (Context7 CLI).4849**Workflow:**501. Use `npx ctx7@latest library` to resolve relevant library IDs (dio, riverpod, go_router, logger, dart, flutter)512. Use `npx ctx7@latest docs` to query official documentation for canonical patterns523. Curate findings into `references/authoritative-sources.md` with library IDs, key evidence, and relevance summaries534. Cross-reference SKILL.md patterns against sources — flag any divergence545. If sources reveal a pattern is wrong or incomplete, fix SKILL.md BEFORE saving5556## Governing Rule — THE TWO-REIN RULE (Creativity vs Quality)5758> **Established:** 2026-07-30. Adopted from YC/Anthropic insights (Boris Cherny, Claude Code) and adapted through founder-led strategic discussion. The core insight: frontier models perform best with minimal scaffolding in creative domains, but still require strict guardrails in domains where errors are costly. The wisdom is knowing when to loosen and when to tighten.5960**The principle:** Not all specification files are equal. Some require creative freedom; others require deterministic correctness. Applying the same governance level everywhere either suffocates innovation (all reins tight) or burns tokens on unverified output (all reins loose).6162### Three-Zone Classification6364Every file in the Spec Pack falls into one of three zones:6566| Zone | Files | Reins | Governance |67|:----:|:-----:|:-----:|------------|68| **🎨 Creative** | 07 (User Flows), 08 (Design) | **Loose** | Human aesthetic judgment; minimal automated gates |69| **⚖️ Mixed** | 09 (PRD), 12 (Architecture) | **Tight on logic, loose on UI** | Lint + review; template required |70| **🔒 Quality** | 10 (Data), 11 (API), 13 (Security), 15 (DevOps), 17 (ACID), 18 (Backlog) | **Tight** | Automated verification gates (tests, lint, schema validation); skills enforced |7172### Stage 3: Dual Paths7374Stage 3 is the ONLY stage with two execution paths. The founder chooses based on whether the design direction is already known:7576| Path | When | Model Role | Founder Role |77|:----:|------|------------|--------------|78| **🐢 Normal** | App Mark exists (Canva), colors defined | Claude generates derivative assets from App Mark | Active: reviews, adjusts incrementally |79| **⚡ Fast** | No constraints — "surprise me" | Claude reads Stage 1+2, autonomously produces BOTH 07+08 | Passive: receives, judges (accept/reject/modify) |8081**Both paths produce files 07+08. The Normal Path is unchanged. Stage 3.5 is MANDATORY for both.**8283### Governance Gradient8485| Stage | Writes | Judges | Reins |86|:-----:|--------|--------|:-----:|87| 1–2 (Idea & Feasibility) | Founder + Model | Founder | Tight |88| 3 (Design) | Model | Founder (taste) | **Loose** |89| 3.5 (Build Readiness) | Model (founder's intent) | **Third party** | **Tightest** |90| 4+ (MVP & Production) | Model (skills enforced) | Auto tests + Founder | Tight |9192**Key insight:** Stage 3.5 is the governance bottleneck — model writes the build plan, third party reviews it adversarially, founder receives the verdict. Mirrors Bun (YC 2026): autonomous agents ran 11 days, adversarial review caught 3 critical bugs before merge.9394## Tooling — Premium Generator & Verifier9596A paid/companion tooling suite exists for this skill (Spec Pack Premium, built 2026-08-03). Two scripts, both tested:9798- `scripts/generate_spec_pack.py` — generates the full 26-file pack (00–25) with mandatory headers + section skeletons into `<project>/app-spec/`. Usage: `python3 scripts/generate_spec_pack.py /path/to/project PROJECT_NAME`99- `scripts/verify_spec_pack.py` — compliance gate (exit-code): checks file presence, header integrity, content markers, per-stage readiness. Usage: `python3 scripts/verify_spec_pack.py /path/to/project` (exit 0 = compliant, 1 = gaps).100101The generator embeds the 4 mandatory architecture patterns (Hook System, Screen State Machine, Error Handler, Logger) with their verification checklists directly into File 12. The verifier is CI-usable. These were validated against a real project (correctly detected a legacy 22-slot structure as non-compliant with the 25-file system).102103## Trigger104105Use this skill when:106107---108109## Project Stages — Six Gates110111Every project MUST pass through these 6 stages in order. A flaw in any stage affects all subsequent stages. No stage begins until the previous stage is fully complete.112113| Stage | Name | Gate | Rule |114|:-----:|------|:----:|------|115| 1 🟢 | **الفكرة (Idea)** | IDEA_GATE | Problem, personas, value prop, context. No code. |116| 2 🟡 | **دراسة الجدوى (Feasibility)** | FEASIBILITY_GATE | Monetization, financials, risks. Prove viability before design. |117| 3 🟠 | **التصميم والهوية (Design)** | DESIGN_GATE | User flows, design system, wireframes, prototype. **No code before this closes.** |118| 3.5 🟤 | **جاهزية البناء (Build Readiness)** | BUILD_READINESS_GATE | Lock dependency graph + one build sequence (18) + technical-debt-vs-feature policy (16). **No code until this closes.** Deliberately lightweight — a dependency graph + one sequence + one policy, not Gantt/CPM. |119| 4 🔵 | **MVP** | MVP_GATE | PRD, data model, architecture, security, testing, backlog. Build minimum. **Requires DESIGN_GATE AND BUILD_READINESS_GATE both closed.** |120| 5 🟣 | **التطوير والتحسين (Iteration)** | ITERATE_GATE | Decision log, lessons learned, red team audit. Improve from real feedback. |121| 6 ⚫ | **النشر والإنتاج (Production)** | PRODUCTION_GATE | Admin panel, support ops, capabilities inventory. Go live. |122123Each stage has a status: ✅ Complete | 🔄 In Progress | ⏳ Blocked (waiting on previous stage) | 🚨 Missing (gap!)124125---126127## Specification Pack Structure — 25 Files (Sequential 00–25)128129Evolved from the 22-slot v2.0 system into a 6-stage, 25-file sequential structure. Every file is numbered by its position in the project lifecycle — open `00`, read the index, follow the numbers.130131### 🗺️ File 00 — The Map132133`00_project_stages.md` is the FIRST file created and the FIRST file read by any agent. It contains:1341351. **📋 FILE INDEX** — Complete table of all 25 files: number, filename, stage, purpose1362. **🚦 STAGE STATUS** — Which stages are complete, in progress, blocked, or missing1373. **Gates** — What must be true before each stage can begin138139### Stage 1: الفكرة 🟢 — Files 01–03140141| # | File | Purpose |142|---|------|---------|143| 01 | `01_product_discovery.md` | Problem, personas, value proposition, MVP scope, feasibility, Go/No-Go decision |144| 02 | `02_project_context.md` | Tech stack, dependencies, environment, constraints, conventions, **which persistence/backend stack this project uses** |145| 03 | `03_project_overrides.md` | Deviations from standard spec pack, project-specific rules |146147### Stage 2: دراسة الجدوى 🟡 — Files 04–06148149| # | File | Purpose |150|---|------|---------|151| 04 | `04_monetization_entitlements.md` | Feature access matrix per tier, pricing, trial mechanism, paywall architecture, abuse protection |152| 05 | `05_financial_model.md` | Unit economics, LTV, CAC, break-even, founder targets, decision triggers |153| 06 | `06_assumptions_risks.md` | Categorized risks with IDs, severity, mitigation, product/technical/market assumptions |154155### Stage 3: التصميم والهوية 🟠 — Files 07–08156157| # | File | Purpose |158|---|------|---------|159| 07 | `07_user_flows_navigation.md` | Screen inventory with IDs, Mermaid navigation map, flow details, navigation rules |160| 08 | `08_design_prototype.md` ✨ | **Everything design:** Color tokens (hex), spacing (4dp MD3), elevation, radius, typography, component specs, states, motion, accessibility, RTL/LTR, wireframes, interactive prototype, user journey walkthrough, design testing notes |161162### Stage 3.5: جاهزية البناء 🟤 — Build Readiness (no new file numbers)163164> **⚠️ MANDATORY for BOTH Stage 3 paths (Normal and Fast).** This stage has NO standalone file. Its content lives inside two existing Stage 4 files — `16_ai_agent_contract.md` and `18_implementation_backlog.md` — but MUST be written and locked BEFORE any Stage 4 code begins. It cannot be completed before the design settles (Stage 3 must close first).165166**Governance for Stage 3.5:**167- **Who writes:** The model — based on the founder's stated intent and the completed Stage 1-3 files168- **Who judges:** A **third party** (independent adversarial reviewer) — NOT the founder alone169- **Why third party:** This is the single highest-leverage quality gate. After creative freedom in Stage 3, the build plan must be challenged by an external reviewer. This mirrors the Bun case study (YC 2026): 64 agents ran autonomously for 11 days, but adversarial human review caught 3 critical bugs before merge170- **Reins:** Tightest in the entire governance gradient — external validation before any code171172| Location | Content |173|----------|---------|174| `18_implementation_backlog.md` (new section) | Dependency graph across all backlog items + **one locked build sequence** — deliberately one, not multi-variant. Once locked, the build order is NOT renegotiated feature-by-feature. |175| `16_ai_agent_contract.md` (new section) | Explicit technical-debt-vs-feature policy — when a mid-build choice arises between fixing debt or shipping a feature, the policy (not a live debate) decides. |176| `18_implementation_backlog.md` (each step) | **Per-step HOW map — NARROWED form (one line per step, written at 3.5):** the line carries ONLY what cannot be derived from elsewhere — (a) the files the step touches, (b) a POINTER to the governing section (e.g. "see 17 §3.1", "see DEC-004"), (c) step-specific pitfalls not derivable elsewhere (e.g. "stepNumber is 1-based"). NO rephrasing of spec content: the pointer cannot contradict its target, but a rephrased instruction can drift (measured: duplicated instructions are the project's most reliable defect generator — a line in 17 vs DEC-011, a line in 12 vs it, stale APK fingerprints). Full-form HOW lines were audited against 52 prior review findings and would NOT have prevented the logic/guard defect classes — those are caught by automated guards, not more prose. |177178**The locked sequence has two READ views — generate, never commit.** A long179dependency-ordered table is hard to read from two angles at once (the build180story vs where each work-type lands). Provide two DERIVED views, generated ON181DEMAND from the locked table by a small script (one that parses the table +182the work-type/EPIC sections and prints both): (1) the sequence view — step |183BL | work-type | why — the build story; (2) the swimlane view — which work-type184lands where across the sequence, including deliberate splits (a privacy EPIC185may appear at step 28 and again at 37-38 because storage-before-UI outranks186category contiguity). NEVER commit a derived document: a committed derived187file drifts from the table and becomes a second, lying source of truth; a188script holds no data and cannot drift. The table stays the single source of189truth; the views are printed from it on demand (one command after any DEC).190Working generator (spec-pack convention, parse + both views + `--html` visual):191`scripts/build_sequence_view.py`.192193**Make the derived views LIVE, not static (validated 2026-08-10).** The194founder's real need is "what is the NEXT step" — a static table does not195answer it. Have the generator also read the project's running STATE file196(done steps as numbers/ranges, next marked ⏭ — the listing may wrap across197several lines: join following lines until a blank line) and color the198swimlane accordingly: done ✅ / in-progress 🔄 (a dirty tree means the next199item is being edited) / next ⏭ (highlighted) / future (faded), with a200one-line "Next step: BL-XXX" header. The founder reads the whole build at a201glance — no re-reading the backlog to answer "where are we" (their own words:202"هذي المرة الوحيدة اللي أحس إني فيها فاهم — هذا ما كنت أحتاجه لأعرف ماهي203الخطوة التالية").204205**Work-type (EPIC) ids are audit-trail labels — freeze them mid-build.**206Reviews, DECs, and handoff state all reference work-type ids; renumbering207mid-build manufactures label mismatches — the same failure class as a review208label contradicting the locked table. Confusing numbering (e.g. a209localization EPIC appearing before the data EPIC because localization is an210early dependency) is EXPLAINED by the derived views, not fixed by renumbering.211Renumber only at post-launch cleanup, with a mapping table.212213**Why this exists:** Past build attempts hit repeated mid-build negotiation ("which feature first?", "fix this debt now or later?") despite having a spec pack — because the pack had priorities but no locked order and no debt policy. Stage 3.5 closes that gap once, before coding, instead of re-litigating it feature by feature. Deliberately lightweight (a dependency graph + one sequence + one policy) rather than formal construction-style scheduling (Gantt/CPM), which would reintroduce the process-overhead trap.214215### Stage 4: MVP 🔵 — Files 09–18216217| # | File | Purpose |218|---|------|---------|219| 09 | `09_prd.md` | User stories with Gherkin (Given/When/Then), business rules, edge cases, error messages (AR+EN), glossary, traceability matrix |220| 10 | `10_data_model_erd.md` | Entities, relationships, field justifications, schema |221| 11 | `11_api_contract.md` | OpenAPI/GraphQL spec, endpoints, request/response schemas, auth headers |222| 12 | `12_flutter_architecture.md` | Clean Architecture layers, provider/notifier graph, folder structure, routing, **Hook System Architecture** (§ mandatory), **Screen State Machine** (§ mandatory), **Unified Error Handler** (§ mandatory), **Structured Logger** (§ mandatory) |223224### Structured Logger — Depth Requirement (File 12)225226> **Effective:** 2026-07-26227> **Source:** `flutter-app-logger` skill228> **Governance Rule:** Every Flutter project MUST use `AppLogger` with at least 4 levels (debug, info, warn, error). Raw `debugPrint` for application logging is prohibited. `LogBuffer` must be accessible at runtime for debugging. Error/fatal levels must persist to file via `LogPersister`.229230**Verification Gate:**231- [ ] `AppLogger` replaces all `debugPrint` calls (hundreds across projects)232- [ ] Every class uses `AppLogger.of('Category')` — no manual prefixes233- [ ] At least 4 log levels in use: debug, info, warn, error234- [ ] `LogBuffer.query()` works at runtime — filterable by level and category235- [ ] `LogPersister` writes error+ entries to `app_log.txt`236237Cross-reference:238- `flutter-app-logger` skill239- `flutter-error-handler` skill — `ErrorLogger.log()` uses `AppLogger.error()` internally240241### Unified Error Handler — Depth Requirement (File 12)242243> **Effective:** 2026-07-26244> **Source:** `flutter-error-handler` skill245> **Governance Rule:** Every Flutter project MUST use `ErrorHandler.show(context, error)` as the single entry point for all user-facing errors. Raw `ScaffoldMessenger.of(context).showSnackBar(SnackBar(...))` scattered across screens is prohibited. All errors must be classified through `ErrorClassifier.classify()` before display.246247**Verification Gate:**248- [ ] `ErrorHandler.show()` is the ONLY way errors reach the user249- [ ] No raw `ScaffoldMessenger.of(context).showSnackBar()` for error display250- [ ] All 10 `ErrorType` values have AR + EN user messages in `ErrorMessageMapper`251- [ ] `ErrorLogger.log()` called on every error with stack trace252- [ ] `ErrorSeverity` matches display mechanism (success→green, error→red+retry, critical→dialog)253254Cross-reference:255- `flutter-error-handler` skill — the authoritative implementation reference256- `flutter-screen-state-machine` skill — `AppError` widget pairs with `ErrorHandler` for full-screen errors257258### Screen State Machine — Depth Requirement (File 12)259260> **Effective:** 2026-07-26261> **Source:** `flutter-screen-state-machine` skill262> **Governance Rule:** Every Flutter project MUST use the unified `ScreenState<T>` widget pattern. Per-screen `_buildLoadingState` / `_buildErrorState` / `_buildEmptyState` methods are prohibited. The 5 standard widgets (`AppLoading`, `AppError`, `AppEmpty`, `AppOffline`, `AppEmptySearch`) must live in `lib/core/ui/screen_states/`.263264**Verification Gate:**265- [ ] `ScreenState<T>` used in every screen that consumes `AsyncValue<T>`266- [ ] No per-screen `_buildLoadingState()` / `_buildErrorState()` / `_buildEmptyState()` methods exist267- [ ] All 5 standard widgets present in `lib/core/ui/screen_states/`268- [ ] `AppError` always has `onRetry` callback (no dead-end errors)269- [ ] `AppLoading` uses `skipLoadingOnRefresh` for pull-to-refresh screens270271Cross-reference:272- `flutter-screen-state-machine` skill — the authoritative implementation reference273- `flutter-hook-architect` skill — PostMutationInvalidationHook pairs with ScreenState for refresh274275### Hook System Architecture — Depth Requirement (File 12)276277> **Effective:** 2026-07-26278> **Source:** `flutter-hook-architect` skill279> **Governance Rule:** Every Flutter project MUST include a Hook System Architecture section in its architecture file (12 or project-overridden equivalent). Level 1 (Safety) hooks are non-negotiable before any code ships.280281The Hook System Architecture section must address:2822831. **11 Hook Types** — Which of the 11 hook types apply to this project (PreRequest, PostResponse, OnRequestError, RouteGuard, PreMutation, PostMutation, WidgetLifecycle, StreamTransform, InputSanitize, FileGuard, SessionGate)2842. **4 Progression Levels** — Current level for each hook type (Safety → Productivity → Intelligence → Orchestration)2853. **Configuration Structure** — `hooks.yaml` or equivalent configuration, registered with the HookChain orchestrator2864. **Security Chain** — Veto order, injection patterns (14 patterns minimum), trusted tools skiplist2875. **Self-Healing Audit** — Hook grading report (A-F) with auto-fix recommendations2886. **Project-Specific Template** — Which of the 3 templates applies (API-heavy, Local-DB, LLM-powered) and any deviations289290**Verification Gate (Level 1 — Safety):**291- [ ] Every user input passes through `InputSanitize` before any operation292- [ ] Every file path validated against `FileGuard.allowedPaths`293- [ ] Every HTTP request has Bearer token (for authenticated endpoints)294- [ ] Every 401 triggers token refresh + retry exactly once295- [ ] Every protected route has auth check via `RouteGuard`296297Cross-reference:298- `flutter-hook-architect` skill — the authoritative implementation reference299- `hook-veto-protocol` skill — security chain origin300- `19_decision_log.md` — DEC entries for hook-related decisions301| 13 | `13_security_privacy.md` | Auth strategy, data sensitivity classification, permissions, encryption, threat model |302| 14 | `14_testing_acceptance.md` | Test pyramid, DoD, acceptance criteria, device targets |303| 15 | `15_devops_release.md` | CI/CD pipelines, environments, signing, release checklist, observability |304| 16 | `16_ai_agent_contract.md` | Agent rules, validation payload format, traceability, handoff protocols, boundaries |305| 17 | `17_data_architecture_acid.md` | Transaction boundaries, consistency guarantees, migration strategy |306| 18 | `18_implementation_backlog.md` | Prioritized feature queue, dependency chains, effort estimates |307308### Stage 5: التطوير والتحسين 🟣 — Files 19–21309310| # | File | Purpose |311|---|------|---------|312| 19 | `19_decision_log.md` | Structured ADR format (DEC-NNN), rationale, date, linked files, rejection reasons |313| 20 | `20_lessons_learned.md` | Sequential LL-NNN numbering, date discovered, stage, root cause, prevention rule, cross-reference to DEC |314| 21 | `21_zero_trust_red_team.md` | Attack vectors, penetration test results, security assumptions challenged |315316### Stage 6: النشر والإنتاج ⚫ — Files 22–25317318| # | File | Purpose |319|---|------|---------|320| 22 | `22_admin_panel.md` | Admin dashboard, moderation tools, analytics views, role-based access |321| 23 | `23_support_operations.md` | On-call procedures, incident response, escalation paths, FAQ maintenance |322| 24 | `24_active_capabilities.md` | Current feature status — the accurate, living inventory of what works. **MUST include a plain-language App Completeness Checklist (§7): 20 yes/no questions a non-technical person answers by opening the app — navigation bar present, screens reachable, honesty rules visible. Checked before any release gate and after every 10 build steps (lesson 2026-08-12: 38 steps passed while the prototype-designed 3-tab navigation was never built — long spec files hide absences; a short checklist catches what long files hide).** Full founder-validated doctrine in `references/checklist-philosophy.md`: four checklist types with distinct owners (pre-flight / completeness / compliance / release), the three-state answer model where **N/A must cite a justifying decision or counts as NOT applied**, project checklists born at 3.5, stable item IDs, and the checklist→gate→guard triad. |323324---325326## Stage Gate Rules327328### Gate 3 (DESIGN_GATE) — The Critical One329330This is the stage once discovered missing in a real project — the rule:331332> **No executable code is written before DESIGN_GATE closes.**333> The design prototype (`08_design_prototype.md`) must exist and be approved. Colors, wireframes, user journey — all decided and documented. Code without design = rework.334335**PRECISION — what "no code" means (hard-learned):** the gate forbids336APP SOURCE CODE (lib/, src/, app logic, behavior tests). It does NOT forbid337— and in fact REQUIRES — the design agent to write spec artifacts: reflecting338the design artifact onto `07_user_flows_navigation.md` and339`08_design_prototype.md`, exporting visual references, element checklists,340and tokens into the repo. Refusing to touch spec files in the design phase on341the grounds of "stage 3.5 not complete" is a MISAPPLICATION of this gate: it342forces the founder to hand-copy design output, and every manual transfer loses343fidelity. The deciding question is only: does the change touch app source344code? No → design-stage artifact, write it. Yes → wait for the gates.345See File 08 §6 (Operational Pipeline) below for the full stage-3 execution346rules.347348### Gate 3.5 (BUILD_READINESS_GATE) — The Build Lock349350This gate prevents the "which feature first?" negotiation that plagued past builds. **It is MANDATORY for BOTH Stage 3 Normal and Fast paths.**351352> **No executable code is written before BUILD_READINESS_GATE closes.**353> After DESIGN_GATE closes, the next step is NOT writing code — it's locking the build order. The dependency graph + one build sequence (18) and the technical-debt-vs-feature policy (16) must be written by the model, then reviewed and approved by a third party (independent adversarial reviewer). The founder receives the reviewer's verdict and makes the final approval. Only then does MVP coding begin.354355**Why DESIGN_GATE alone isn't enough:** A spec pack with priorities but no locked order still forces live mid-build negotiation on every feature boundary. Stage 3.5 eliminates that by making the build sequence a one-time decision (locked, not debated feature-by-feature) and the debt policy an explicit rule (not a recurring argument).356357**Why third-party review:** The founder should not be the sole judge of the build plan. After creative freedom in Stage 3, an independent adversarial reviewer challenges the model's build plan — catching blind spots the founder and model both missed. This mirrors the Bun case study (YC 2026): autonomous agents produced code, but adversarial human review caught 3 critical bugs before merge.358359**Deliberately lightweight:** This is a dependency graph + one sequence + one policy — NOT formal construction scheduling (Gantt charts, CPM, FF/FS/SF/SS dependencies). Heavy scheduling would reintroduce the governance-overhead trap.360361### Gate Rules for All Stages3623631. Each stage's files MUST exist in `app-spec/` before the stage begins — empty if not yet populated3642. A stage CANNOT start until the previous stage's files are complete (not empty placeholders)3653. `00_project_stages.md` MUST be updated to reflect current stage status3664. **Create empty > Leave absent** — an empty file signals intent; an absent file is a hidden assumption367368### Mid-Project Stage Audit369370When receiving a project already in progress:3713721. Read `00_project_stages.md` — if missing, create it and run a full audit3732. Check each stage's files: present? populated?3743. Flag any 🚨 gaps — especially missing DESIGN_GATE (Stage 3)3754. **Stop and fill gaps before writing new code** — a mid-project design gap is still a gap376377### Pre-Proposal Code Audit (Fatabayyanu Gate)378379**Mandatory before adding any new architectural pattern, capability, or system design to app-spec.** This gate prevents proposing something that already exists, and establishes an accurate baseline for the spec addition.380381**Workflow:**3823831. **Read spec files first** — check ALL relevant spec files across the project for existing mentions of the pattern (architecture, capabilities, decision log)3842. **Search actual codebase** — scan `lib/` and all source directories for:385 - The pattern name (e.g. `hook`, `interceptor`, `middleware`, `guard`)386 - Related class names, file names, and imports387 - Any partial/primitive implementations that might be an informal version of the pattern3883. **Cross-reference ALL projects the user maintains** — the pattern may exist in one project but not others. Establish the full landscape:389 - Which projects have it in spec? Which have it in code?390 - Where is it partially implemented vs fully absent?3914. **Report current state clearly** before proposing changes — use a table format:392393 ```394 | Project | Spec | Code | Status |395 |---------|------|------|--------|396 | Example App A | ❌ Absent | ✅ Partial (HTTP interceptors only) | ❌ No formal pattern |397 | Example App B | ❌ Absent | ❌ Absent | ❌ Not implemented |398 ```3994005. **Only then propose spec additions** — grounded in the real gap, not an assumption401402**Rationale:** This pattern was hard-learned when the user asked "تأكد اولا من الملفات كقراءة فقط هل هي منفذة ام لا" before agreeing to add Hook System architecture to app-spec. Proposing spec changes without code verification = proposing solutions to non-existent problems. Always verify the gap before filling it.403404---405406## Depth Requirements Per File Type407408### PRD (File 09)409Must include:410- User stories with Gherkin-style acceptance criteria (Given/When/Then)411- Business rules with unique IDs412- Edge cases with expected behavior413- Error messages (AR + EN where applicable)414- Glossary of domain terms415- Feature traceability matrix (Feature ID → User Story → Screen → Business Rule → Test Case)416417### User Flows (File 07)418Must include:419- Screen inventory with IDs, tab/flow, MVP status, notes420- Single valid Mermaid navigation map inside ```mermaid fence421- Per-flow details with rules for each step422- Navigation rules with IDs423424### Design Prototype (File 08) ✨ — Unified Design File425426This is the single most important file in Stage 3. It contains EVERYTHING design-related — no separate brand guide, no separate prototype spec. One file, one source of truth.427428#### §1 Logo Architecture — Full Logo vs App Mark429430A common pitfall is placing text-heavy full logos inside small app icon containers. The distinction:431432| Asset | Dimensions | Usage |433|-------|-----------|-------|434| **Full Combination Logo** | Horizontal/vertical lockup (variable) | Landing pages, store listings, headers, invoices, PDF reports |435| **App Mark (Standalone Symbol)** | 1024×1024 px square canvas | Master source for all system-generated icons |436437**App Mark Types (choose one):**4381. **Symbol/Icon Mark** — stylized graphic (e.g., car silhouette + checkmark for automotive apps)4392. **Monogram/Lettermark** — abstracted letter from brand name (e.g., styled 'C' or 'S')4403. **Wordmark/Logotype** — custom typographic logo. Note: full wordmarks are NEVER used directly as app icons; an extracted lettermark is used instead441442**§1.1 App Mark Generation Workflow (Canva → Claude)**443444The recommended non-designer workflow:445446```447Step A: Generate App Mark in Canva448 → Use Canva's AI logo generator or manual design tools449 → Output: ONE 1024×1024 px App Mark (transparent PNG preferred)450451Step B: Feed App Mark to Claude452 → Give Claude the App Mark + context about the brand453 → Claude produces derivative assets for all screen contexts:454 • Full Combination Logo (for Auth, About, PDF headers)455 • Splash screen variant (centered mark on brand background)456 • Notification icons (monochrome white, per Android spec)457 • Store listing feature graphics458459Step C: Validate Platform Compliance460 → iOS: no transparency in final icon (system adds rounded corners)461 → Android: adaptive icon layers (foreground + background)462 → Notification icons: white/semi-transparent on transparent background463```464465#### §2 Color Architecture (The 60-30-10 Rule)466467Apply the standard color distribution rule to avoid visual clutter:468469| Proportion | Role | Light Mode | Dark Mode |470|:----------:|------|------------|-----------|471| **60%** | Neutral Surface/Background | White or light off-grey | Deep navy/slate |472| **30%** | Primary Brand Color | Cards, headers, secondary navigation | Same brand color, adjusted luminance |473| **10%** | Accent/CTA Color | Primary action triggers (Save, Confirm, Inspect) | Brighter accent for dark contrast |474475**System Status Colors** (separate from brand): Green (success), Red (errors), Amber (warnings).476477**Color Exploration Tools:**478| Tool | Purpose |479|------|---------|480| Realtime Colors (realtimecolors.com) | Preview palettes on real mobile UI layouts, adjust distribution ratios |481| Coolors (coolors.co) | Generate cohesive schemes, explore automotive-grade palettes |482| Adobe Color (color.adobe.com) | Verify contrast ratios against WCAG accessibility standards |483| Material Theme Builder (material-foundation.github.io) | Generate MD3 tonal palettes with 13 values per color, export as JSON |484485#### §3 Platform-Specific System Asset Requirements486487Modern mobile operating systems enforce strict guidelines for icons and splash screens:488489**App Launcher Icons:**490| Platform | Master Size | Output Format | Key Rule |491|----------|:----------:|---------------|----------|492| iOS | 1024×1024 px | PNG (no transparency) | System applies rounded corners — do NOT pre-round |493| Android | 1024×1024 px | Adaptive Icon (foreground + background layers) | Foreground: 108dp safe zone inside 108dp; Background: fills 108dp |494495**Splash Screens:**496| Platform | Approach | Implementation |497|----------|----------|---------------|498| iOS | Storyboard-based | Single centered image + solid background color |499| Android | Native splash API (Android 12+) | Window background + icon centered, no branding text |500501**Flutter Automation (eliminate manual resizing):**502| Package | Version | Purpose |503|---------|:-------:|---------|504| `flutter_launcher_icons` | ^0.14.4 | Ingest 1024×1024 master → generate all iOS + Android icon assets |505| `flutter_native_splash` | ^2.4.8 | Generate splash screens across all densities from config |506| IconKitchen (web) | — | Adaptive icon generation for Android |507| Android Asset Studio (web) | — | Monochrome notification icons |508509**Configuration snippet (`pubspec.yaml`):**510```yaml511dev_dependencies:512 flutter_launcher_icons: ^0.14.4513 flutter_native_splash: ^2.4.8514515flutter_launcher_icons:516 image_path: "assets/app_mark_1024.png"517 android: true518 ios: true519 adaptive_icon_background: "#FFFFFF"520 adaptive_icon_foreground: "assets/app_mark_foreground_1024.png"521522flutter_native_splash:523 color: "#1A73E8" # Primary brand color524 image: "assets/splash_app_mark.png"525 android: true526 ios: true527```528529#### §4 Screen-by-Screen Asset Placement Guide530531To ensure consistent visual hierarchy throughout the user journey:532533| Screen | Asset | Notes |534|--------|-------|-------|535| **Splash Screen** | Transparent App Mark centered on solid brand background | No text, no slogan — mark only |536| **Onboarding (3-4 screens)** | Vector illustrations + short benefit headlines + CTA buttons | Brand colors in illustrations, not UI chrome |537| **Authentication/Login** | Full Combination Logo (Symbol + Name + Slogan) at top header | Maximum brand recognition at trust moment |538| **Dashboard (Home)** | Clean header: user avatar, notifications, service cards, search | App Mark small in header or nav bar only |539| **About App Screen** | Full Combination Logo + build version + legal + support | Official identity, not decorative |540| **Exported PDF Reports** | Full Combination Logo in document header | For vehicle inspection/maintenance reports or similar |541542#### §5 Core Design Requirements (in addition to Stage 3 defaults)543544Beyond the standard MD3 tokens, File 08 MUST include:545- **Brand identity** — color tokens with hex values and usage (light AND dark where defined)546- **Spacing** — based on 4dp MD3 grid547- **Elevation** — levels548- **Border radius** — tokens549- **Typography** — scale with all properties (include Arabic-first font choices like Cairo)550- **Component specs** — buttons, text fields, cards, state-specific layouts551- **Empty/error state designs**552- **Motion specifications**553- **Accessibility requirements** (WCAG contrast minimums)554- **RTL/LTR rules** — validate both states for every screen555- **Wireframes** — at minimum low-fidelity for every screen in the user journey556- **Interactive prototype** — Figma link or equivalent, showing full user journey557- **User journey walkthrough** — every tap, every transition, documented step by step558- **Design testing notes** — was it tested on someone? their feedback?559- **Source/provenance labeling rules** — which assets came from Canva, which from Claude, which are stock560561#### §6 Operational Pipeline for Stage 3 (design agent behavior)562563The design phase is not just content — it is an operational pipeline. These564rules prevent the two failure classes that cost real projects rework:565misclassification (refusing to write spec files) and shape loss (prose that566ten different implementations can all satisfy).567568**Visual references are the binding shape source:**569- Export one screenshot per screen and COMMIT it into the repo next to the570 spec. The spec stays the source of RULES (flows, data, logic); the reference571 is the source of SHAPE (look, spacing, position).572- Write the conflict rule in the spec text: "on shape conflict, the reference573 wins."574- Export state variants per screen (at least default + empty + error) — a575 single happy-path screenshot leaves the other states to prose.576- No-build-without-reference: a screen is not buildable until its reference577 exists; check completeness at Stage 3.5, not during build.578- The reference is the EXPORTED FILE (versioned artifact), never the agent's579 memory or its re-description.580581**Element checklists, not paragraphs:** for each screen provide a checkbox582list (brand icon present, back control at declared edge, empty/error/loading583states defined, fields match the data model). A gate can check a list; it584cannot audit a paragraph. Missing elements surface as unchecked boxes.585586**RTL-safe vocabulary:** default to start/end (logical). "Left" is ambiguous587in RTL — physical left vs line start are different edges. If physical588left/right is truly intended, say "physical left, even in RTL" explicitly.589In Flutter mirror the vocabulary: `AlignmentDirectional`,590`EdgeInsetsDirectional`, never raw left/right for layout.591592**Declared tokens, never derived:** every color/radius/spacing/typography593value is written explicitly; no seed-based generation (`ColorScheme.fromSeed`)594for final values — the seed silently produced a near-white tint where the spec595said white; all tests green, the eye can't tell. Stage 4 pins the declared596values with a theme/token test so drift fails CI, not the founder's eye.597598**Visual acceptance gate (mandatory):** no screen is accepted on code review599alone. 1) device screenshot of the built screen; 2) the spec reference beside600it; 3) a numbered diff list; 4) the founder decides fix vs amend the spec —601never silently. Required step in the build pipeline, not a reviewer's favor.602603**Anti-patterns (all hit in the field):**604| Anti-pattern | Failure | Fix |605|---|---|---|606| Design agent refuses spec-file writes before Stage 4 | Founder hand-copies → fidelity loss | Gate 3 precision: spec artifacts ARE stage 3 |607| Prose-only shape ("center the selector") | Compliant but wrong layout (blank space, floating button) | Visual references + no-build-without-reference |608| "left" in an RTL app | Back control on wrong edge; lying comment | start/end vocabulary |609| Derived palette from a seed | Silent spec violation, invisible to tests | Declared tokens + pinned test |610| "no deviations" without visual comparison | Real deviations found later on device | Visual acceptance gate + honest diff list |611| Manual re-transfer of design output | Every transfer loses something | Agent reflects its own artifact onto files |612613### Monetization (File 04)614Must include:615- Feature access matrix per tier616- Trial mechanism details617- Grace period rules618- Entitlement source of truth619- Paywall architecture with triggers620- Backend validation rules (if applicable)621- Analytics events622- Abuse protection623- Forward compatibility rules624625### Financial Model (File 05)626Must include:627- Unit economics per customer/transaction628- LTV calculation with assumptions629- CAC by channel630- Break-even analysis631- Revenue projections632- Decision triggers (when to pivot/kill/scale)633634### Risks (File 06)635Must include:636- Categorized risks with unique IDs637- Severity ratings638- Mitigation strategies639- References to governing files640- Product assumptions641- Technical assumptions642- Market assumptions643644### Lessons Learned (645646…(truncated)