Spec-Driven Development Workflow
A practical SOP for applying Spec-Driven Development across agency projects, organized around the 5 Ws and the required structure every spec must follow.
1. WHY — The Purpose of SDD
SDD exists because AI coding agents (Claude Code, Cursor, Copilot) can now turn a sufficiently precise spec into working code in minutes, which shifts the bottleneck from writing code to writing the spec well.
Core rationale:
The specification is the primary artifact, not the code.
It eliminates two failure modes: "vibe coding" (AI guessing from chat) and traditional agile vagueness (stories left intentionally open to interpretation).
A well-formed spec serves two audiences simultaneously: humans (PM, client, QA, devs) and AI coding agents — both need it unambiguous.
Ambiguity in a spec is treated as a defect, not a feature.
Practical test: if QA cannot write test cases directly from the spec without asking questions, the spec isn't ready.
2. WHO — Roles and Ownership
Role | Primary Responsibilities |
Project Manager (PM) | Owns PRD, TRD (if applicable), and the spec backlog. Decides at kickoff which stages the project needs. Drafts specs, iterates with Eng Lead, maintains the tracking doc. |
Engineering Lead | Reviews PRD for technical feasibility. Co-authors TRD sections involving data, calculations, and integrations. Writes and maintains implementation.md. Operates the AI coding agent. |
Designer | Maintains the design system (tokens, components). Delivers Figma per stage ahead of spec write-up. Flags missing design-system support. |
QA | Reviews each spec's Acceptance Criteria before "Ready" status. Has read access to PRD and TRD. Writes test cases per spec. |
Client | Signs off on initial PRD and TRD. Reviews end-of-stage demos. Source of truth for business-rule accuracy. Does not review individual specs by default. |
3. WHAT — Artifacts and Required Spec Structure
3.1 The Artifacts Pipeline
The pipeline is organized into three sequential loops, each with a defined team and a set of skills that drive the work.
3.1.1 Loop 1 — PRD Definition
Primary team: PM · PE · Designer
Create the PRD based on sales calls and client meeting notes.
Iterate on the PRD using the
sdd-prd-reasoningskill to identify gaps, ambiguities, and missing requirements.Repeat until the PRD is signed off by the client.
Source dependency: All downstream artifacts depend on the PRD as their source of truth. Never start Loop 2 without a signed-off PRD.
3.1.2 Loop 2 — TRD + Design System
Primary team: PM · Designer · Dev Lead
Create the TRD using the
sdd-trd-creationskill, derived from the signed PRD.Iterate on the TRD using the
sdd-trd-reasoningskill to find technical gaps, data model issues, API contract problems, and open questions.Create the Design System section inside the TRD using the
sdd-design-systemskill.Iterate on design decisions using the
sdd-design-system-reasoningskill.The team can input screenshots or actual HTML code exported from Figma to answer open design questions and enforce precise UI behavior inside the TRD.
Dev Lead signs off on technical feasibility. Client signs off on TRD scope.
Source dependency: All Loop 2 artifacts depend on the PRD. The Design System section depends on the Figma file delivered by the Designer.
3.1.3 Loop 3 — Stages & Specs
Primary team: PM · Dev Lead
Using the TRD as the source of truth, the dev lead set up the stages and specs for implementation.md prepared for AI to read
Based on the specs under implementation.md, the PM creates the humanly testable version using the
sdd-spec-writerskill — one spec per feature or flow within each stage.QA reviews Acceptance Criteria on every spec before it moves to "Ready."
Source dependencies: Stages depend on the TRD. Each spec depends on both the TRD and its parent Stage file.
3.1.4 Dev Execution
Once specs are ready, the Dev Lead:
Saves all artifacts to the project's source structure (see Section 4).
Operates the AI coding agent (e.g., Claude Code) via
implementation.mdas the table of contents — not via copy-pasted prompts.Communicates any implementation discoveries or necessary deviations to the PM immediately so both the codebase and the Google Drive doc stay in sync.
3.2 Required Structure for Every Spec
Every spec file must contain the following sections — this is the minimum:
# [Spec Name]
Stage: [N]
Status: Draft | Ready | In Progress | Done | Blocked
Depends on: [other spec names, or "none"]
Source:
§[X] of TRD
[Figma file link]
[PRD section]
## 1. Context
One paragraph. Who triggers this, why it exists, where it sits in the user journey.
## 2. Behavior
- UI behavior (referencing design tokens, not hex codes)
- State transitions
- Validation rules
- Error states and recovery
- Loading and empty states
## 3. Business Rules
The non-UI logic. Reference TRD section if repeating canonical content.
## 4. Permissions
Which roles can do what. Reference the TRD permission matrix.
## 5. Acceptance Criteria
A testable checklist. QA reads this to write test cases.
## 6. Open Questions
TBDs, deferred decisions, items to verify with the client.
3.3 The Four Mandatory Questions Every Spec Answers
If a spec does not explicitly answer all four, it is not ready for engineering:
What is this? (One paragraph: feature, user, trigger.)
What does it do? (UI behavior, business rules, formulas, validation, error states.)
What does it depend on? (Other specs, parameters, integrations, existing data.)
How do we know it works? (Testable acceptance criteria.)
4. WHERE — Location of Each Artifact
Artifact | Location | Format |
PRD | Project drive (Google Docs) | Markdown or Doc |
TRD | Project drive, then committed to repo as docs/TRD.md | Markdown |
Spec files | Repo under docs/specs/stage-N/spec-name.md | Markdown |
Repo root or docs/ | Markdown | |
Tracking Doc | External tool (Plutio) | Per-tool |
Design tokens / system | Figma + repo (tokens.json or Tailwind config) | Per-tool |
Rule: Specs do not embed pixel-level styling. They reference the design system. If a token doesn't exist, the spec logs it as a designer dependency rather than absorbing the hex code.
5. WHEN — Triggers and Cadence
5.1 When to Use SDD (and to What Depth)
The PM decides at kickoff and writes the decision into the tracking doc as a one-liner:
Project Profile | PRD | TRD | Stages | Specs |
|---|---|---|---|---|
Small — single-screen tool, internal demo, MVP landing page | Yes | Yes | 2-4 stages | Yes for every flow |
Medium — multi-screen app, standard CRUD, no complex calculations | Yes | Yes | 5-10 stages | Yes for every flow |
Large — many roles, calculations, integrations, regulatory considerations | Yes | Yes | Many, sequenced | Yes for every flow |
Existing project mid-flight | n/a | Don't retrofit | n/a | Add specs only for new work |
Test for whether a TRD is justified: "explicitly, you have to tell the AI like these plus this minus this divided into is what should give the result".
5.2 Cadence and Ceremonies
Sprint length: 1 week baseline;
Kickoff (once): decide artifact set, set up tracking doc.
Sprint planning (weekly): PM, Eng Lead, devs — what ships this week.
Sprint review (weekly): demo, status update, QA handoff.
Cross-project team retro: every 2 weeks.
Buffer: +20% on sprint estimates for projects with significant external integrations.
5.3 Status Lifecycle of a Spec
Draft → Ready → In Progress → Done (or Blocked). A spec moves to Ready only after QA confirms acceptance criteria are testable and the Eng Lead has reviewed the data/permissions sections.
6. Operational Rules (Non-Negotiables)
These rules apply to every project using SDD:
PMs draft specs in Claude on the web, never in Claude Code. Specs are documentation, reviewed and committed as Markdown.
No spec is AI-generated and immediately fed back to AI without a human review. PM (and Eng Lead for technical sections) reads every line.
Claude Code consumes specs via implementation.md, not via copy-pasted prompts. The repo is the context.
Tool choice is per-project, decided by the Engineering Lead at kickoff and written into the tracking doc.
No silent gaps in the TRD. Every TBD has an explicit Open Question with an owner and due date.
No retroactive artifact changes. If a project escalates, add the missing artifact going forward — never backfill.
7. PM "One-Stop-Shop" Checklist (Pinned to Every Tracking Doc)
Per sprint (weekly): sprint planning held, sprint review held, tracking doc updated, client check-in if scheduled, async client comms sent.
Per stage: stage demo to client, QA pass on previous stage before next starts, implementation.md status updated.
Per project (recurring): mid-project and end-of-project customer success micro-surveys, bi-weekly team review, Apple Dev account check if shipping to App Store.
Per project (one-time): PRD signed off, TRD signed off (if applicable), tech stack written into implementation.md, stages defined, tracking doc set up with stages and specs.
8. Assets
sdd-trd-reasoning
Description
Deep TRD analysis and validation skill for Spec-Driven Development (SDD) workflows. Use whenever a user provides a TRD and wants technical review, gap identification, inconsistency detection, or engineering readiness assessment. Trigger on: "review the TRD", "validate the TRD", "what's missing in the TRD", "check the technical spec", "find gaps in the TRD", "is this TRD ready for development?", "what did the tech lead miss?", "check these technical requirements", or whenever a TRD is shared and the user wants anything beyond a summary. Produces structured technical insight: architecture validation, data model completeness, API contract review, security gap analysis, integration risk assessment, open question prioritization, and implementation-blocking clarifying questions — grounded in the document's own logic and cross-referenced against its stated business rules.
Body
TRD Reasoning Skill
Purpose
This skill transforms a TRD into an engineering-ready validation report. Reading a TRD tells you how the system is supposed to be built. TRD reasoning tells you:
Whether the architecture decisions are internally consistent
What is underspecified, ambiguous, or outright missing
Where the technical spec contradicts itself or the business rules it references
What risks and tradeoffs the document glosses over or defers without justification
What decisions must be made before any implementation begins — and who owns them
Input
The user provides a TRD — as an uploaded file, pasted text, or a document shared in context. The TRD may reference a PRD (cross-references should be followed when available). Your job is to reason about it regardless of polish level.
Reasoning Process
Work through each of the six lenses below in order. For each lens, extract what the document specifies, what it implies, and what it leaves dangerously open. Then synthesize into a structured output and a targeted set of clarifying questions.
Lens 1 — Architecture & Infrastructure Consistency
Evaluate whether the stated architecture can actually deliver the stated requirements.
Check for:
Stack coherence: Does the chosen stack (languages, frameworks, cloud providers, DB engines) work together without hidden friction?
Scaling assumptions: Are the performance targets achievable with the described infrastructure? Are horizontal scaling claims backed by actual mechanisms?
Missing infrastructure components: Does the architecture description omit anything required by the feature specs (e.g., a queue mentioned in features but not in the stack)?
Environment parity gaps: Are staging/production environments specified with enough parity to catch production-only bugs?
Undefined TBDs that block architecture: Are there
[TBD]placeholders in architectural decisions that would change how the system is built (e.g., subdomain vs path routing, PDF engine choice)?Single points of failure: Are there integrations or components with no stated fallback?
Flag each issue as: Blocking (can't build without resolving), High (will cause rework), Medium (causes ambiguity), Low (polish/preference).
Lens 2 — Data Model Completeness & Integrity
Validate the data model against the feature specifications and business rules.
Check for:
Missing entities: Are there features described in § 8 (Feature Specs) that have no corresponding table or JSONB sub-schema?
Missing fields: Does each entity have the fields required to support every business rule that references it?
Missing constraints: Uniqueness, NOT NULL, foreign key ON DELETE behaviour — are they consistent with stated business rules?
Indexing gaps: Are high-read query patterns (filters, sorts, foreign key joins) covered by stated indexes?
RLS coverage: Is Row-Level Security (or equivalent multi-tenancy isolation) specified for every tenant-scoped table?
JSONB schema opacity: Are JSONB fields used for structured data without a documented sub-schema? This is a future maintenance risk.
Soft-delete consistency: Are entities that are "inactivated" (not deleted) handled consistently across all queries and API responses?
Cascade delete completeness: Are all child entities listed in ON DELETE CASCADE chains consistent with data retention policy?
Audit trail gaps: Are mutations to sensitive data (financial values, user roles, permissions) traceable via existing entities?
Lens 3 — API Contract & Business Rule Traceability
Verify that every business rule stated in § 8 (Feature Specs) and § 16 (General Business Rules) is traceable to an API endpoint, a DB constraint, or an explicit enforcement point.
Check for:
Orphaned business rules: Rules stated in feature specs with no corresponding endpoint, constraint, or validation path
Missing endpoints: Features described in § 8 that require CRUD operations not covered in § 5
Wrong HTTP semantics: Use of POST where PATCH is appropriate, missing idempotency on retryable actions
Incomplete error code coverage: Are all business-rule violations mapped to specific HTTP error codes?
Missing pagination/filtering specs: List endpoints without stated pagination behaviour
Rate limit gaps: Sensitive or expensive endpoints without rate limits
Webhook idempotency: Are webhook handlers specified as idempotent? Is the deduplication key defined?
Missing validation rules: Endpoints that accept structured input without stated field-level validation (type, length, enum, required)
Role enforcement consistency: Does every endpoint's stated
Auth Requiredvalue match the Permission Matrix in § 6?
Lens 4 — Security, Auth & Compliance Gaps
Evaluate whether the security model is complete and internally consistent.
Check for:
Token storage vulnerabilities: Access tokens in localStorage, refresh tokens not in HTTP-only cookies, tokens exposed to the browser that shouldn't be
Missing secret rotation policy: API keys, OAuth secrets, and webhook secrets without a rotation schedule
Unencrypted sensitive fields: OAuth refresh tokens, PII, or payment metadata stored without encryption-at-rest
PII exposure in logs/responses: Endpoints that could leak PII in error messages, query params, or audit trails
Missing CORS / CSP policy: Not mentioned or underspecified
Compliance mismatches: Features that imply compliance requirements (GDPR deletion, PCI DSS scope reduction, SOC 2 audit logs) that are marked TBD without a resolution path
Auth bypass risks: Endpoints reachable without JWT validation; RLS policies with gaps; client-side-only permission checks
Invitation/onboarding flow security: Magic link expiry, account enumeration risks, brute-force protection
Third-party data sharing: PII sent to integrations without stated consent or contractual basis
Lens 5 — Integration Risk & Third-Party Reliability
Assess the completeness of every third-party integration spec.
For each integration, check:
Auth flow completeness: Is the full OAuth flow (authorization, token exchange, refresh, revocation) specified for delegated auth integrations?
Error states: What happens when the integration is unavailable? Is the fallback behaviour specified?
Webhook security: Is the HMAC verification or equivalent specified? Is the shared secret rotation policy defined?
Idempotency: Can webhook events be safely replayed? Is the deduplication strategy stated?
Data contract: Are request/response schemas documented or linked?
Rate limits: Are the integration's own rate limits acknowledged and handled?
Sandbox vs production: Is there a testing/sandbox environment for each integration?
Vendor lock-in: Are any integrations tightly coupled in a way that would be expensive to replace?
Lens 6 — Open Questions & Implementation Blockers
Catalogue every [TBD], deferred decision, or implicit assumption in the document.
Classify each as:
Blocking: Cannot begin implementation of the affected feature without resolving this
High: Resolving after implementation begins will require rework
Medium: Can be decided during implementation without significant rework
Low: Can be decided post-launch
For each open item, identify: Who owns the decision, what the options are, and what the consequence of each option is.
Output Structure
Always produce output in this structure. Use markdown headers. Every finding must cite the specific TRD section, entity name, endpoint, or business rule it refers to — no generic commentary.
## TRD Reasoning Analysis: [Product / System Name] ### 1. Architecture Assessment[Coherence check on stack, scaling, environment strategy, and infrastructure TBDs][Each finding: Issue | TRD Reference | Severity | Recommendation] ### 2. Data Model Gaps[Missing entities, fields, constraints, indexes, RLS coverage, JSONB opacity][Each finding: Entity/Field | Issue | Business Rule Affected | Severity] ### 3. API & Business Rule Gaps[Orphaned rules, missing endpoints, semantic errors, validation gaps, role mismatches][Each finding: Endpoint or Rule | Issue | Severity] ### 4. Security & Compliance Gaps[Auth vulnerabilities, unencrypted fields, compliance TBDs without resolution paths][Each finding: Area | Issue | Risk Level | Recommended Resolution] ### 5. Integration Risks[Per-integration completeness check: auth flow, error states, webhooks, idempotency][Each finding: Integration | Gap | Risk Level] ### 6. Open Questions Register[All TBDs and deferred decisions, classified by blocking tier][Format: # | Question | Owner | Options | Consequence of deferral | Blocking Tier] ### 7. Clarifying Questions[Numbered list. Max 7 per round, ruthlessly prioritised by blocking tier.][Each question: grounded in a specific TRD section, not answerable by re-reading, single-focus, decision-relevant]
Clarifying Questions Protocol
After delivering the initial analysis, enter a dialogue loop:
Surface your top-priority clarifying questions (max 7 per round — prioritize Blocking > High > Medium).
Wait for answers.
Update the analysis and the Open Questions Register.
Surface any new gaps that the answers reveal (answers often close one gap and open another).
Repeat until one of these conditions is met:
All Blocking and High items are resolved or explicitly accepted as risks
The user confirms they've answered everything they can at this stage
Remaining open items are Medium/Low and won't affect the initial implementation sprint
When the TRD is sufficiently complete, signal:
"This TRD is ready for [next step — e.g., spec writing / implementation planning / developer handoff]. Here's a summary of what was resolved, what remains open by design, and what should be revisited before [milestone]."
Quality Standards
Every finding must cite a specific section, entity, endpoint, or rule from the document — never invent issues that aren't traceable to the document
Distinguish between: "the TRD doesn't specify" (a gap), "the TRD implies but doesn't confirm" (an inference), and "the TRD contradicts itself" (a conflict)
When two sections conflict, name both explicitly (e.g., "§ 6 says X, but § 8.3 says Y")
Never ask questions the TRD already answers
Never ask multiple questions in one question
Prioritise business-critical or security-critical gaps over cosmetic ones
For JSONB fields used for structured sub-schemas, always flag the missing schema definition as a maintenance risk even if not a launch blocker
Reference Patterns
See references/trd-gap-patterns.md for annotated examples of:
A well-formed data model gap entry
A business-rule orphan finding
An API semantic error
An integration risk entry with remediation path
A blocking open question with options and consequences
Load this file when you need concrete examples to calibrate tone, depth, and citation format.
sdd-prd-reasoning
Description
Deep PRD analysis and reasoning skill for Spec-Driven Development (SDD) workflows. Use this skill whenever a user provides a PRD (Product Requirements Document) and wants structured analysis, gap identification, technical translation, or clarifying questions — even if they don't use the word "PRD reasoning" explicitly. Trigger on phrases like "analyze this PRD", "review the PRD", "what's missing in this PRD", "help me understand the PRD", "find gaps in the PRD", "turn this PRD into specs", "PRD review", "what should I ask the client about", "what did the PM miss", "check the requirements", "read the PRD and give me your thoughts", or whenever a PRD document is shared and the user wants anything beyond a simple summary. This skill produces structured insight: intent inference, gap/ambiguity identification, technical implication mapping, prioritization reasoning, dependency mapping, and targeted clarifying questions — all grounded in the document's own logic.
Body
PRD Reasoning Skill
Purpose
This skill transforms a raw PRD into a structured, engineering-ready analysis. Simply reading a PRD tells you what to build. PRD reasoning tells you:
Whether it should be built that way
What's missing from the spec
How to translate it into actionable engineering or design work
What risks and tradeoffs the document glosses over
What questions to ask before a single line of code is written
Input
The user provides a PRD — as an uploaded file, pasted text, or a document shared in context. The PRD may be polished or rough. Your job is to reason about it regardless of format.
Reasoning Process
Work through each of the five lenses below in order. For each, extract what the document says, what it implies, and what it leaves open. Then synthesize everything into a structured output and a targeted set of clarifying questions.
Lens 1 — Intent Behind Requirements
Don't just read what is written. Ask: Why does this requirement exist?
What user problem does it solve?
What business goal does it serve?
What constraints or fears shaped it (legal, competitive, safety, operational)?
This lens prevents you from blindly implementing something that would fail its own purpose. A requirement like "biometric liveness check required for all sellers" exists not just for identity — it's a trust signal, a liability shield, and a brand promise simultaneously. Knowing that changes how you'd implement it and what tradeoffs are acceptable.
Lens 2 — Gaps and Ambiguities
A PRD rarely captures everything. Identify:
Unstated assumptions: things the author assumed were obvious but aren't
Edge cases not considered: what happens at the boundary of a rule?
Missing states: what happens when X hasn't happened yet, fails, or is undone?
Conflicting requirements: two requirements that can't both be true simultaneously
Undefined terms: words used as if they have a shared meaning but don't
Flag each gap with a severity: Critical (blocks implementation), High (causes rework if not resolved), Medium (causes confusion), Low (polish/preference).
Lens 3 — Technical Implications
PRDs are written in business language. Translate them into what they actually demand.
For each significant requirement or feature area, derive:
Data model implications: what entities, relationships, states, or fields are implied?
API / integration implications: what external services, webhooks, or internal endpoints are required?
UX flow implications: what screens, states, transitions, or conditional paths must exist?
Architectural implications: what system-level decisions does this require (e.g., real-time vs async, stateful vs stateless, edge vs server)?
Security / compliance implications: what data handling, encryption, retention, or consent flows are demanded?
Don't go deep on implementation — stay at the level of "this requirement demands a webhook handler", not "here's the code for the webhook handler."
Lens 4 — Prioritization Logic
Even when a PRD doesn't explicitly prioritize, you can reason about it:
Non-negotiable (Core): requirements tied directly to the product's core value proposition or legal compliance — removing them would make the product something else entirely
High Priority: requirements users will miss if absent on day one, but which don't define the product's identity
Nice-to-have / Phase-able: features that add value but whose absence won't break the core loop
Premature: requirements that are specified in detail for problems the product hasn't proven it has yet
Flag requirements that seem over-specified too early, or under-specified given their criticality.
Lens 5 — Dependency Mapping
Identify where requirement A implicitly depends on requirement B, or where a feature described in isolation actually touches multiple systems.
Express dependencies as chains:
Feature A→ requires →Feature B→ requires →Feature C
Flag circular dependencies (two features each requiring the other to be built first) and hidden dependencies (features that seem standalone but pull in infrastructure not mentioned in the PRD).
Output Structure
Always produce output in this structure. Use markdown headers. Keep each section focused and specific — reference actual content from the PRD, not generic advice.
## PRD Reasoning Analysis: [Product Name] ### 1. Intent Summary[2-3 sentences: the real problem this product is solving, the core hypothesis, and the primary constraints shaping the design decisions] ### 2. Gaps & Ambiguities[Organized by severity: Critical → High → Medium → Low][Each entry: Gap name | Description | Why it matters | Severity] ### 3. Technical Implications[Organized by domain: Data Model | APIs & Integrations | UX Flows | Architecture | Security & Compliance][Each entry: what the requirement demands technically] ### 4. Prioritization Assessment[What's non-negotiable, what's phase-able, what's premature. Reference specific features/sections.] ### 5. Dependency Map[Key dependency chains. Highlight circular or hidden dependencies.] ### 6. Clarifying Questions[Numbered list. Each question must be: - Grounded in specific PRD content (cite the section or feature) - Not answerable by re-reading the PRD - Focused on a single thing - Actionable: the answer would change a design or implementation decision]
Clarifying Questions Protocol
After delivering the initial analysis, enter a dialogue loop:
Ask your most critical clarifying questions (maximum 5 per round — prioritize ruthlessly).
Wait for the user's answers.
Update your analysis based on new information.
Identify any new gaps that the answers reveal.
Ask the next round of questions if any remain.
Repeat until one of these is true:
No gaps or ambiguities remain unresolved
The user explicitly says they've answered everything they can
The remaining questions are low-severity and won't affect implementation
When all critical and high-severity gaps are resolved, signal completion:
"The PRD is now sufficiently specified for [next step — e.g., TRD creation / spec writing / architecture planning]. Here's a summary of what was resolved and what remains open by design."
Quality Standards
Every gap, implication, or question must be traceable to something in the document — don't hallucinate requirements that aren't there
Prioritize substance over comprehensiveness — 5 sharp insights beat 20 generic ones
Never ask questions the PRD already answers
Never ask multiple questions in one question
When two requirements conflict, name both explicitly
Distinguish between "the PRD doesn't say" (a gap) and "the PRD implies" (an inference you're making explicit)
Reference: Worked Example Patterns
See references/example-patterns.md for annotated examples of:
A well-formed gap entry
A technical implication chain
A clarifying question grounded in document logic
A dependency map for a two-sided marketplace
Load this file if you need concrete examples to calibrate tone and depth.
sdd-design-system-reasoning
Description
Deep UI/UX gap analysis for TRDs with a design system section. Use whenever a user provides a TRD and wants to identify what is missing from the design spec that impacts the final user experience — even if they don't say "design system" or "UX gap". Trigger on: "what's missing in the design", "review the UI/UX spec", "find design gaps", "what did the designer miss", "check the UX behavior", "what should I ask the designer", "analyze the design tokens", "make the TRD ready for a UI dev to build with AI". Produces a structured UX Gap Report across 12 interaction categories: motion & animation tokens, skeleton loader behavior, toast & notification UX, modal & dialog patterns, input component states, table & data grid behavior, sidebar & navigation, drag & drop, charts & data visualization, z-index layer management, empty states, and miscellaneous component patterns — all grounded in the document's own spec and cross-referenced against feature requirements.
Body
Design System Reasoning Skill
Purpose
A TRD's design section typically defines what the visual tokens are (colors, spacing, typography). This skill finds everything that is not defined but is required to build the actual interface — the behavioral, interactive, and responsive layer that turns tokens into a living product.
Reading a design section tells you the paint colors. This skill tells you:
Which walls are missing blueprints
Which behaviors are assumed but never specified
Which interaction patterns will produce inconsistent results if each developer decides independently
What questions must be answered before an AI coding agent or developer begins component implementation
The output is structured as a UX Gap Report — a set of findings organized by interaction category, each with a gap description, the TRD section it references, the user-experience consequence if left unresolved, and a targeted question or recommendation for the design/product owner.
Input
The user provides a TRD — uploaded file, pasted text, or shared in conversation context. The TRD must contain at minimum a design system or UI tokens section (e.g., a § 18 — Design System or equivalent). Cross-reference against all feature specification sections (§ 8 equivalents) to understand which components are actually used in the product.
Reasoning Process
Work through each of the 12 UX Lenses below in order. For each lens:
Identify what the design section specifies for this category
Identify what the feature specs require from this category (which components, interactions, states appear in feature descriptions)
Flag every gap between what is specified and what is required
Classify gap severity: Blocking (will produce inconsistent or broken UX without resolution) · High (will cause rework or inconsistency across components) · Medium (produces minor inconsistency or ambiguity) · Low (optional enhancement)
Formulate a precise question or recommendation for each gap
Lens 1 — Motion & Animation Tokens
A design token system without motion tokens is incomplete. Every interactive element that transitions between states — sidebar expanding, modal appearing, toast sliding in, skeleton shimmer pulsing — requires duration and easing values. Without them, every developer picks their own, producing a jarring, inconsistent product.
Check for:
Are transition duration tokens defined? (e.g.,
--transition-fast,--transition-base,--transition-slow)Are easing/curve tokens defined? (e.g.,
--ease-in,--ease-out,--ease-spring)Is there a skeleton shimmer animation token (speed, direction, color delta)?
Are animation curves for modals, toasts, popovers, and drawers specified?
Is there a
prefers-reduced-motionpolicy stated?Are hover-state transitions specified (instant toggle vs. animated)?
Common gap: Design systems define colors and spacing exhaustively but ship with zero motion guidance, leaving animation as a per-developer decision.
Lens 2 — Skeleton Loader Behavior
The TRD's general business rules section may mention skeleton loaders as a loading pattern. Skeleton loaders require significantly more specification than a single line — each component type needs its own skeleton structure.
Check for:
Is a shimmer animation direction, speed, and color delta defined?
Are per-component-type skeleton shapes specified (tables, cards, charts, sidebar, notification feed)?
Is there guidance for partial loads (e.g., sidebar data loads before content area)?
Is the skeleton color derived from a token? (
--neutral-disabled? a new--skeleton-base/--skeleton-highlightpair?)What happens after 10 seconds if data never loads — is there a timeout empty/error state?
On re-fetch (SWR revalidation), does the component show skeletons again or retain stale data while loading?
Are chart skeletons specified? (Charts with no skeleton fallback typically flash an empty axis which looks broken)
Lens 3 — Toast & Notification UI Behavior
The TRD may specify toast rules (max count, auto-dismiss timing, color by type). Toasts require additional behavioral specification before they can be implemented consistently.
Check for:
Screen position: top-right? bottom-right? bottom-center? Per device?
Entry/exit animation: slide in from edge? Fade? Scale?
Stack direction: does a new toast push existing ones up or down?
Mobile behavior: full-width bottom-pinned? Same position as desktop?
Z-index layer: specified relative to modals, popovers, and sidebar?
Are action buttons inside toasts supported? (e.g., "Undo" after deletion, "View" after PDF generation)
Is there a progress indicator inside auto-dismiss toasts (visual timer bar)?
When 3 toasts are active and a 4th arrives, which is dismissed — oldest? Or the dismissed one becomes a "show more" count badge?
Is the in-app notification bell feed distinct from toast notifications, or do the same events appear in both simultaneously?
Lens 4 — Modal, Dialog & Drawer Patterns
Modals appear throughout feature specs (PDF config modal, confirmation dialogs, override popovers, scenario creation, goal creation overlay). Without a modal behavioral spec, every modal will be built differently.
Check for:
Modal size tokens: is there a size scale (sm / md / lg / xl / fullscreen)? Which features use which sizes?
Backdrop: color token? Opacity? Blur?
Entry/exit animation: fade? Scale from center? Slide from bottom (mobile)?
Close-on-backdrop-click: is this always allowed, or blocked for destructive confirmations?
Focus trap: is keyboard focus locked inside the modal while open?
Scroll behavior: does the page body scroll freeze when a modal is open? Does the modal body scroll independently?
Mobile behavior: full-screen on mobile? Bottom sheet pattern for action sheets?
Nested modals: is it possible to open a modal from within a modal? (e.g., Goal creation modal opens from 5-Uses History modal)
Are drawer/side-panel components distinct from modals? (e.g., notification details, step-level notes sidebar)
Lens 5 — Input Component States & Form Patterns
Every input field in the product passes through multiple visual states. The design token system may define colors but not how those colors apply to input states.
Check for:
Input states mapped to tokens: Default · Focus · Filled · Error · Disabled · Read-only — which token applies to border, background, text, and icon for each?
Focus ring: which token? Width? Offset? (e.g.,
2px solid var(--color-primary)at2pxoffset)Error state: does the border become
--danger-default? Is there an icon? Where is the error message positioned (below field? inline right)?Read-only vs disabled: are they visually distinguishable? (read-only = styled like text, not a dimmed input)
Blur-persist pattern (inline auto-save on blur): what is the visual indicator while saving? Is there an in-field spinner or inline "Saving…" text? What if it fails?
Inline edit "dirty" row state: which visual treatment indicates a row is in edit mode vs view mode? (highlight? border? background change?)
Are there defined input heights and internal padding beyond the spacing scale? (e.g., 40px height for standard inputs)
Text area: character count display? Auto-resize or fixed height with scroll?
Required field asterisk: which color? Is there a token?
Lens 6 — Dropdown, Select & Search Behavior
Dropdowns and selects appear extensively across the product (planning model, tax filing status, fund type, role selectors, etc.).
Check for:
Open direction: does the dropdown prefer to open downward, and flip upward when near the viewport bottom?
Max-height of the dropdown list: defined in tokens? Scrollable beyond that?
Searchable/filterable dropdowns: which selects support filtering by typing? Any type-ahead?
Multi-select dropdowns: are any fields multi-select? How are selections displayed (chips inside the field)?
"Other" option free-text reveal: how does the text field animate in? Is it inside the dropdown or below the closed select?
Keyboard navigation: arrow keys to navigate options, Enter to select, Escape to close — is this required?
Empty search state: if the user types and no options match, what is shown?
Disabled options within a dropdown: styling token?
Lens 7 — Table & Data Grid Behavior
Multiple features are built around tables with inline editing, reordering, and pagination (Step 1 data sheet — 7 tabs; transaction list; user list; household list).
Check for:
Row hover state: which token? (
--neutral-surface?--brand-surface?)Selected row state (if selectable): token?
Horizontal scroll on mobile: scrollable container? Card-stack transformation? Column hide?
Sticky column header on vertical scroll: required? Token for the sticky background?
Sort indicator: which icon and color for unsorted / asc / desc?
Empty table state: illustration? Message? CTA button? Layout spec?
Table skeleton: how many placeholder rows? What width variation per column to feel realistic?
Inline edit row: when a row enters edit mode, does it expand vertically? Change background?
Pagination component: numbered pages? Prev/Next only? Items per page selector? Behavior when current page empties after a deletion?
Column widths: are they fixed, proportional, or auto?
Lens 8 — Drag & Drop Behavior
Drag-to-reorder is specified for multiple features (Step 1 records, To-Do list). Without a visual spec, implementations will be inconsistent.
Check for:
Ghost/drag preview: opacity of the dragged element? Does it show a shadow/elevation?
Drop zone highlight: which token when a valid drop target is active? Border? Background tint?
Snap animation: does the list animate to close the gap as the user drags over?
Touch/mobile drag-and-drop: is it supported? (Touch drag requires separate implementation from mouse drag)
Drag handle: is the entire row draggable, or only the handle icon? What is the cursor style (
grab/grabbing)?Optimistic rollback visual: if the reorder API call fails, does the list visibly snap back to the original order? Any error toast?
Disabled state: can drag handles be hidden or locked for specific roles (read-only)?
Lens 9 — Sidebar & Navigation Behavior
The sidebar is a core structural element used in every authenticated view. Its behavior drives the entire layout experience.
Check for:
Collapse/expand animation: does the sidebar animate width? What duration/easing token?
Mobile behavior: at which breakpoint does the sidebar become a drawer (overlay) instead of a push? Is there a hamburger trigger?
Active nav item: which token for active state? (Is
--color-primaryused for background? Icon fill? Left border indicator?)Tooltip on collapsed icon: hover delay? Position (right of icon)? Using which tooltip component?
Sub-navigation: are there nested nav items? How do they expand (accordion? flyout)?
Overlay vs push: on tablet, does expanding the sidebar overlay the content or push it?
Portal token isolation:
--portal-backgroundand--portal-hoveredare defined — but are--portal-text-active,--portal-text-hover,--portal-bordertokens needed and missing?localStoragekey name for sidebar state: defined?
Lens 10 — Charts & Data Visualization
Multiple chart types appear in the product: donut (5 Uses of Money), bar (deduction comparison), projection cards (Near-Term Cash Flow), line (Historic Net Worth), and potentially others across plan steps.
Check for:
Chart color palette: are chart series colors defined as tokens? A 5-segment donut requires 5 distinct, accessible colors — are they in the design system?
Chart tooltip: which component pattern? Custom popover or native SVG tooltip? Token for background, border, text?
Chart empty/zero state: what renders when all values are $0? A grayed-out shape? A message overlay?
Chart skeleton: does the donut render as a gray ring placeholder? The bar chart as gray bars?
Chart accessibility: is there a screen-reader description pattern (e.g.,
aria-labelon the chart container with a text summary)?Responsive chart behavior: do charts reflow to a smaller size on tablet/mobile, or do they scroll horizontally?
Negative values: are negative bars / negative donut segments possible (e.g., net worth below zero)? What is the visual treatment?
Legend component: tokens for legend dot size, spacing, label style?
Lens 11 — Z-Index Scale & Layer Management
Toasts, modals, popovers, tooltips, sticky headers, and the sidebar overlay all require z-index management. Without a defined scale, components will randomly stack on top of each other.
Check for:
Is a z-index token scale defined? (e.g.,
--z-dropdown: 100,--z-sticky: 200,--z-modal-backdrop: 300,--z-modal: 400,--z-popover: 500,--z-toast: 600)Are toast z-index values guaranteed to be above modal z-index values (toasts should always be visible even when a modal is open)?
Is the sidebar overlay z-index specified on mobile?
Is the sticky table header z-index specified so dropdowns inside the table don't render behind it?
Lens 12 — Component-Level Behavioral Gaps (Miscellaneous)
Additional component-level gaps that don't fit a single lens but are equally important.
Subgroup A — Empty States
Are empty states designed for: Vault (no documents), Plans tab (no plans), Notifications feed (no notifications), Transaction list (no transactions), Household list (no households assigned)?
Do empty states have illustrations, a heading, a supporting message, and a CTA — or just a message?
Are empty state layouts specified (centered in the container? top-aligned?)?
Subgroup B — Status Badges & Chips
The system uses many status values:
active,inactive,pending,scheduled,completed,failed,expired,to_reschedule,cancelled,payment_pendingAre each of these mapped to a color token pair (background + text/icon)?
active→ success?failed→ danger?pending→ warning?expired→ neutral?Is there a badge size token (height, padding, border-radius, font-size)?
Subgroup C — File Upload Component
Used in Vault upload flow
Is there a drag-and-drop upload zone style (dashed border?
--brand-surfacebackground on drag-hover)?Upload progress: linear progress bar? Inline spinner? Which tokens?
Error state for invalid file (wrong type, over size limit): inline error below the zone? Toast only?
Is multi-file upload supported in one action, or one file at a time?
Subgroup D — Focus Management & Keyboard Navigation
Which token defines the focus ring? Width, offset, style?
After a modal closes, where does focus return? (should return to the trigger element)
After a row deletion, where does focus move? (next row? previous row? empty state message?)
Are skip-navigation links required for WCAG 2.1 AA compliance?
Subgroup E — Avatar & Profile Photo Fallback
When a user has no profile photo, what renders? Initials inside a circle? A generic person icon?
Which tokens define the avatar background (when showing initials)?
Is there a defined avatar size scale (xs / sm / md / lg)?
Subgroup F — Scroll Behavior
Does the page scroll to top on every route change?
Is scroll position restored when navigating back (browser back button)?
For long step pages (Step 1 has 7 tabs), is there a sticky tab bar defined?
Subgroup G — Print & Export Styles
Server-side PDFs are generated, but are web-view print styles (
@media print) required?If a user presses Cmd+P, should the layout adapt?
Output Structure
Produce the UX Gap Report in this structure. Every finding must cite the specific TRD section, design token name, or feature specification it references.
## UX Gap Report: [Product / System Name] ### Executive Summary[2–3 sentences: total gaps found, how many Blocking/High/Medium/Low, top 3 most impactful] ### 1. Motion & Animation [Blocking / High / Medium / Low count][Each finding: Gap | TRD Reference | UX Consequence | Severity | Recommendation / Question] ### 2. Skeleton Loaders [...][Same format] ### 3. Toast & Notification UX [...]### 4. Modal, Dialog & Drawer [...]### 5. Input States & Form Patterns [...]### 6. Dropdown & Select [...]### 7. Table & Data Grid [...]### 8. Drag & Drop [...]### 9. Sidebar & Navigation [...]### 10. Charts & Data Visualization [...]### 11. Z-Index Layer Management [...]### 12. Miscellaneous Component Gaps [...] - 12a. Empty States - 12b. Status Badges & Chips - 12c. File Upload - 12d. Focus & Keyboard - 12e. Avatar Fallback - 12f. Scroll Behavior - 12g. Print/Export Styles ### Priority Questions for the Designer/Product Owner[Numbered list. Max 10 per round, ranked by severity. Each grounded in a specific gap above.] ### Suggested Additional Token Groups[Token names the design system should add, with suggested values — formatted as CSS custom properties]
Question Protocol
After the initial report, enter a dialogue loop:
Surface your top-priority questions (max 10 per round — prioritize Blocking > High > Medium)
Wait for answers
Update the gap register and strike resolved items
Surface any new gaps that answers reveal
Repeat until all Blocking and High items are resolved or explicitly accepted as risk
When the design specification is sufficiently complete, signal:
"The design specification is ready for AI-assisted component development. Here is a summary of what was resolved, what was defined as out-of-scope, and what token additions are recommended before the first sprint begins."
Quality Standards
Every finding must cite a specific TRD section, token name, or feature description — no generic "you should add animations" commentary
Distinguish between: "not in the design section but implied by the feature spec" (a gap) vs "contradicts a stated token or rule" (a conflict)
When the design section and the general business rules section conflict (e.g., § 16 says skeletons, § 18 says nothing about skeleton tokens), name both sections
Never ask questions the TRD already answers
Never combine two questions into one
Prioritize UX consistency and developer clarity over aesthetic polish
When suggesting new tokens, use the established naming convention of the existing token system (match the
--category-variantpattern)
Reference
See references/ux-gap-patterns.md for annotated examples of:
A well-formed motion/animation gap entry
A table behavior gap with token recommendation
A z-index conflict finding
A status badge token mapping suggestion
An empty state gap with CTA recommendation
Load this file when calibrating the depth, tone, and citation format of findings.
sdd-design-system
Description
Reads a design-system.md file extracted from Figma and generates a canonical § 18 — Design System & UI Tokens section to be appended as the last topic of a TRD (Technical Requirements Document). Use this skill whenever the user provides a Figma design system export, a design-system.md file, or says things like "add the design system to the TRD", "generate the design system section", "attach the design tokens to the TRD", "create the UI tokens section", or "turn the Figma export into a TRD section". Also trigger when the user shares design tokens, typography specs, color palettes, spacing scales, or breakpoint tables and wants them formalized into a TRD-compatible document section. Always use this skill alongside sdd-trd-creation when a design system file is present, even if the user does not explicitly ask for § 18.
Body
SDD — Design System Skill
Reads a design-system.md exported from Figma and outputs a single, complete § 18 — Design System & UI Tokens section ready to be appended as the final section of a TRD produced by the sdd-trd-creation skill.
Inputs
Input | Required | Source |
|---|---|---|
| Yes | Uploaded file at |
Existing TRD | Optional | If provided, append § 18 directly and re-save the TRD file |
Product name | Optional | Inferred from the TRD or the design system file header |
Output
A complete
§ 18 — Design System & UI TokensMarkdown sectionIf a TRD file was provided: save the updated file to
/mnt/user-data/outputs/TRD_[ProductName].mdIf no TRD file was provided: save the section alone to
/mnt/user-data/outputs/DS_Section_[ProductName].mdPresent to user via
present_filestool when complete
Formatting Rules (Non-Negotiable)
These rules mirror the TRD formatting contract and must be applied throughout:
Tone: Engineering-precise. Reference tokens by their exact CSS custom property name (e.g.,
--color-primary). Never describe colours with vague adjectives ("nice blue") — always show the hex value.Tables: Use Markdown tables for ALL token groups. Never write token data as inline prose.
Code blocks: Wrap every CSS
:rootblock and utility class snippet in fenced```css ```blocks.Placeholders: If a token category is absent from the input file, write
[TBD — not defined in design system source]. Never skip a subsection.Footer: End the section with the horizontal rule and:
*Confidential — [Agency Name]*Cross-reference: Begin the section body with:
→ Cross-reference: Business PRD § 9 — Design GuidelinesLanguage: English throughout.
Pre-Generation Steps
Locate and read the design system source — check
/mnt/user-data/uploads/for any.mdfile that contains design token data; if not found, parse the inline/document content provided in the conversation.Identify the design system name from the file header (e.g.,
# Design System — White Coat). Use it as the system label throughout § 18.Scan for the following top-level categories and flag any that are absent:
Typography (font families, sizes, weights, line heights)
Colour — System tokens
Colour — Neutrals
Colour — Brand
Colour — Semantic (Success / Warning / Danger)
Colour — Specialised portals or dark surfaces
Spacing scale
Border radius scale
Breakpoints
CSS
:rootreference block (quick-reference tokens)
If an existing TRD
.mdfile is provided, read it last to confirm the numbering — § 18 follows whatever is the last existing section.
§ 18 — Design System & UI Tokens
Generate all subsections below in order. Do not omit any subsection — mark missing data [TBD — not defined in design system source].
18.0 — Overview
→ Cross-reference: Business PRD § 9 — Design Guidelines
Write 2–3 sentences stating:
The name of the design system
The source of truth (e.g., "Exported from Figma — [File Name]")
The intended usage contract: "All frontend components must consume values exclusively through the CSS custom properties defined in this section. Hard-coded hex values, pixel values, and font names are not permitted in production code."
Output this summary table:
Attribute | Value |
|---|---|
Design System Name | [from file header] |
Source | Figma — [file name from header] |
Export Date | [from file metadata or TBD] |
Token Format | CSS Custom Properties ( |
Font Delivery | Google Fonts / Self-hosted / [TBD] |
Figma Library Sync | [Yes — auto / Manual / TBD] |
18.1 — Typography
Font Families
Output as a table:
CSS Token | Font Family | Fallback Stack | Usage |
|---|---|---|---|
| [value] |
| H1–H3, display text |
| [value] |
| Body copy, UI labels, inputs |
Heading Sizes (Responsive)
CSS Token | Desktop | Mobile | Applies To |
|---|---|---|---|
| [value] | [value] | Page hero titles |
| [value] | [value] | Section headings |
| [value] | [value] | Card / panel headings |
Implementation note: Heading sizes use responsive values. Apply mobile values via
@media (max-width: var(--bp-mobile-sm)).
Body Sizes (Fixed)
CSS Token | Value | Usage |
|---|---|---|
| [value] | Large body / intro copy |
| [value] | Default body text |
| [value] | Secondary text, captions |
| [value] | Labels, tags, helper text |
| [value] | Legal text, footnotes |
Font Weights
CSS Token | Value | Usage |
|---|---|---|
| [value] | Body copy |
| [value] | Emphasized body, nav items |
| [value] | UI labels, button text |
| [value] | Headings, key metrics |
18.2 — Colour — System Tokens
These are the primary interface tokens that components must reference. Never bypass these in favour of raw Brand or Semantic tokens.
CSS Token | Hex | Usage |
|---|---|---|
| [value] | Primary actions, links, focus rings |
| [value] | Text/icons on primary backgrounds |
| [value] | Default text |
| [value] | Page / card surfaces |
| [value] | Root page background |
| [value] | Delete actions, error states |
| [value] | Confirmation, completed states |
| [value] | Warnings, advisory states |
18.3 — Colour — Neutrals
Scale
CSS Token | Hex | Semantic Use |
|---|---|---|
| [value] | Page / section backgrounds |
| [value] | Dividers, input borders |
| [value] | Disabled controls |
| [value] | Input placeholder text |
| [value] | Body text on light surfaces |
| [value] | Subtitles, secondary labels |
| [value] | Primary headings |
| [value] | Hover state on dark elements |
| [value] | Neutral button fill |
| [value] | Placeholder in disabled inputs |
18.4 — Colour — Brand
CSS Token | Hex | State |
|---|---|---|
| [value] | Light brand tint (badges, highlights) |
| [value] | Default brand colour |
| [value] | Hover on brand elements |
| [value] | Active / pressed brand state |
Usage rule: Use
--brand-defaultfor interactive elements. Use--brand-surfacefor non-interactive brand accents. Never use the raw Blue Scale tokens in components — use Brand tokens only.
18.5 — Colour — Semantic
Success
CSS Token | Hex | State |
|---|---|---|
| [value] | Background tint |
| [value] | Icon, text, border |
| [value] | Interactive hover |
| [value] | Active/pressed |
Warning
CSS Token | Hex | State |
|---|---|---|
| [value] | Background tint |
| [value] | Icon, text, border |
| [value] | Interactive hover |
| [value] | Active/pressed |
Danger
CSS Token | Hex | State |
|---|---|---|
| [value] | Background tint |
| [value] | Icon, text, border |
| [value] | Interactive hover |
| [value] | Active/pressed |
Usage rule: Semantic tokens map to toast notifications, inline validation messages, and status badges. Always pair
*-surfaceas the background with*-defaultas the foreground text/icon for accessible contrast.
18.6 — Colour — Specialised Surfaces
Generate this subsection only if the design system defines portal, dark-mode, or tenant-specific palettes. If none exist, write: N/A — no specialised surface palette defined.
CSS Token | Hex | Usage |
|---|---|---|
| [value] | Text on dark portal background |
| [value] | Portal / sidebar dark background |
| [value] | Hover state within portal |
Usage rule: Portal tokens apply exclusively to authenticated admin/student portal surfaces. They must not be used on public-facing pages.
18.7 — Spacing Scale
All layout spacing must use these tokens. Do not hard-code margin or padding pixel values in components.
CSS Token | Value | Common Uses |
|---|---|---|
| 0px | Reset |
| [value] | Inline icon gaps |
| [value] | Tight internal padding |
| [value] | Form field internal spacing |
| [value] | Default component internal padding |
| [value] | Card internal padding (compact) |
| [value] | Card internal padding (default) |
| [value] | Section gap (compact) |
| [value] | Section gap (default) |
| [value] | Block-level vertical rhythm |
| [value] | Page section padding |
| [value] | Hero section padding |
| [value] | Large layout gaps |
| [value] | Full-page vertical sections |
| [value] | Oversized hero / splash areas |
| [value] | Maximum layout spacing |
18.8 — Border Radius Scale
CSS Token | Value | Usage |
|---|---|---|
| 0px | Flush edges (tables, full-bleed banners) |
| [value] | Subtle rounding (badges, tags) |
| [value] | Small inputs, chips |
| [value] | Default input fields |
| [value] | Default cards, modals |
| [value] | Larger cards |
| [value] | Prominent cards, dialogs |
| [value] | Feature cards, drawers |
| [value] | Large modals |
| [value] | Hero panels |
| [value] | Pills, avatars, toggle switches |
18.9 — Breakpoints
All responsive layout rules must reference these tokens. Use min-width (mobile-first).
CSS Token | Value | Context |
|---|---|---|
| [value] | Smallest supported mobile viewport |
| [value] | Standard mobile (default base) |
| [value] | Small tablet / large phone landscape |
| [value] | Standard tablet |
| [value] | Tablet landscape |
| [value] | Standard desktop |
| [value] | Wide desktop / ultrawide |
Implementation contract:
All layouts must be built mobile-first: default styles target
--bp-mobile-sm(≥ [value])Each breakpoint upgrade layer is additive — never reset rules downward
Heading font sizes switch at
--bp-mobile-smper the values in § 18.1
18.10 — CSS Custom Properties Reference
Paste into the project's global stylesheet root to activate all tokens:
css
:root { /* ── TYPOGRAPHY ─────────────────────────────── */ /* [Generate full :root block verbatim from the "Tokens CSS (referência rápida)" section of the design system file, preserving all comments and groupings exactly as authored] */}
Source of truth: The
:rootblock above is the canonical token reference.
Any discrepancy between this block and the tables in §§ 18.1–18.9 must be resolved in favour of this block. File a design system issue if a discrepancy is found.
18.11 — Component Token Usage Rules
These rules are engineering constraints, not suggestions. All frontend engineers and AI coding agents must follow them:
No raw hex values — every colour reference in component code must use a
var(--token-name)expression.No raw pixel values for spacing or radius — always use
var(--spacing-*)andvar(--radius-*).No raw font strings — always use
var(--font-heading)orvar(--font-body).State hierarchy: For interactive elements, implement all four states in order — Default → Hover → Pressed → Disabled — using the appropriate
*-default,*-hovered,*-pressed, and--neutral-disabledtokens.Semantic-before-Brand: Prefer Semantic tokens (success, warning, danger) over Brand tokens for feedback states. Reserve Brand tokens for navigation, CTAs, and brand accent elements only.
Portal isolation: Portal tokens (
--portal-*) must be scoped to the authenticated portal layout component. They must not leak into public page components via global selectors.Responsive headings: Heading size tokens must be accompanied by their mobile counterpart via the
--bp-mobile-smmedia query breakpoint — never use heading tokens without the responsive override.Accessibility floor: Every colour pairing must meet WCAG 2.1 AA contrast ratio (≥ 4.5:1 for normal text, ≥ 3:1 for large text). The semantic
*-surface+*-defaultpairings in § 18.5 are pre-validated. Custom pairings require a contrast check before implementation.
Generation Procedure
Follow these steps in order:
Parse the design system source — extract every token category listed in the Pre-Generation Steps.
Fill all
[value]placeholders — replace each with the exact hex, pixel, or font string from the source. If a value is absent, use[TBD — not defined in design system source].Reproduce the
:rootblock verbatim in § 18.10 — copy it character-for-character from the source file's "CSS reference" or "Tokens CSS" section. Do not paraphrase or reformat.Append § 18 to the TRD — if a TRD
.mdfile was provided, insert the complete § 18 block after the last existing section (typically § 17). Preserve all existing TRD content.Run the Post-Generation Checklist before saving.
Post-Generation Checklist
Before saving the output file, verify:
All
[value]placeholders have been replaced with real token values (or[TBD])The
:rootblock in § 18.10 is copied verbatim from the source fileEvery subsection (18.0–18.11) is present
No raw hex values appear outside of the token tables
Section ends with
*Confidential — [Agency Name]*If a TRD was provided, all §§ 1–17 are intact and unmodified
Output is a valid, renderable Markdown file
File Output
When appending to an existing TRD:
/mnt/user-data/outputs/TRD_[ProductName].md
When generating the section standalone:
/mnt/user-data/outputs/DS_Section_[ProductName].md
Then call present_files with the output path.
sdd-trd-creation
Description
Generates a complete Technical Requirements Document (TRD) as a Markdown file (.md) from a provided Business PRD. Use this skill whenever the user wants to produce a TRD, technical spec, or engineering requirements document from a PRD. Trigger on phrases like "write the TRD", "create a technical spec", "generate the TRD from this PRD", "turn the PRD into a TRD", "draft the technical requirements", "I have the PRD now I need the TRD", or whenever a PRD file or PRD content is provided and the user needs an engineering-level counterpart document. Always use this skill even when the user says "technical document", "system spec", or "engineering doc" in the context of SDD workflows.
Body
SDD — TRD Creation Skill
Generates a complete, engineering-precise Technical Requirements Document (TRD) in Markdown format from a Business PRD input. Follows the canonical 17-section TRD structure defined in this skill.
Inputs
Required: A Business PRD — either as an uploaded file (
/mnt/user-data/uploads/) or pasted textOptional: Additional context provided by the user (tech stack preferences, compliance scope, team constraints)
Output
A single
.mdfile saved to/mnt/user-data/outputs/TRD_[ProductName].mdPresent to user via
present_filestool when complete
Formatting Rules (Non-Negotiable)
Apply these rules throughout the entire document without exception:
Tone: Engineering-precise. Use exact types, concrete numbers, and version pins where possible. Never use vague language ("fast", "scalable", "robust") — always replace with a measurable spec (e.g., "p95 < 200ms", "supports 5,000 concurrent users").
Tables: Use Markdown tables for ALL structured data. Never write tabular information as inline prose.
Bullets: Use for lists of rules, constraints, and checklist items only. Never nest beyond 2 levels.
Placeholders: When information cannot be derived from the PRD, always write
[TBD — pending engineering input]. Never leave a field blank or skip it.Footer: End every section with a horizontal rule and the footer line:
*Confidential — [Agency Name]*Cross-references: Begin every section body with a cross-reference line pointing to the companion PRD section, formatted as:
→ Cross-reference: Business PRD § [N] — [Section Name]No business justification: Describe how to build, never why to build. Omit market rationale, persona narratives, and sales language. Refer the reader to the PRD for those.
Scope discipline: For any feature or system not in beta scope, mark inline with
[Out of Scope — deferred to V1/V2]and do not spec it further.Language: English throughout.
Pre-Generation Steps
Read the PRD fully before writing any section.
Extract the following anchors from the PRD to use as cross-reference targets:
Product name, target platform, monetization model, tech stack choices, feature list, risk table
If the PRD is missing data needed to complete a TRD field, write
[TBD — pending engineering input]— do not invent values.Identify any features explicitly called out as post-beta / roadmap — mark those
[Out of Scope — deferred to V1/V2]in every section where they would appear.
TRD Structure
Generate all 17 sections below in order. Do not omit any section — mark it N/A — not applicable to this product only if truly irrelevant (e.g., § 12 File Handling for a product with no file uploads).
§ 1 — Executive Technical Summary
→ Cross-reference: Business PRD § 1 — Executive Summary
Write 2–3 paragraphs covering:
What is being built at a system level (not business level)
The architectural approach chosen and why (from PRD tech decisions if present)
Key constraints (compliance, integrations, scalability targets)
Then output this table, populated from PRD data:
Field | Value |
|---|---|
Product Name | [from PRD] |
Primary Platform | [from PRD] |
System Architecture | [Monolith / Microservices / Serverless / Hybrid] |
Primary Language(s) | [from PRD] |
Database Engine | [from PRD] |
Auth Provider | [from PRD] |
Hosting / Cloud | [from PRD] |
Compliance Scope | [from PRD] |
Target Uptime (Beta) | [from PRD or TBD] |
TRD Version | 0.1 — [generation date] |
§ 2 — System Architecture Overview
→ Cross-reference: Business PRD § 2 — About the Business
Cover:
Architecture Pattern: State the pattern (Monolith / Microservices / Serverless / Hybrid) and its rationale in 1–2 sentences
Component Diagram Description: Describe all major system components and how they communicate. Note that the actual diagram will be linked from the Architecture Diagram tool.
Data Flow Summary: How data moves from the user's device through the system and back — describe as a numbered sequence
Then output the Environment Strategy table:
Environment | Purpose | Infra | Auto-Deploy? |
|---|---|---|---|
Development | Local dev + unit tests | [e.g., Docker Compose] | N/A |
Staging | QA + client review | [TBD — pending engineering input] | Yes (on PR merge) |
Production | Live user traffic | [TBD — pending engineering input] | No (manual approval) |
§ 3 — Tech Stack & Infrastructure
→ Cross-reference: Business PRD § 3 — Discovery Process & Methodology
Output a complete, version-pinned technology table. Derive values from PRD tech decisions; use [TBD — pending engineering input] for any missing entry:
Layer | Technology | Version | Rationale |
|---|---|---|---|
Frontend | [from PRD] | [version] | [from PRD or TBD] |
State Management | [from PRD] | [version] | [TBD] |
Backend | [from PRD] | [version] | [from PRD or TBD] |
API Style | [REST / GraphQL] | — | [TBD] |
Primary DB | [from PRD] | [version] | [TBD] |
Cache | [from PRD or TBD] | [version] | [TBD] |
Queue | [from PRD or TBD] | [version] | [TBD] |
Search | [from PRD or TBD] | [version] | [TBD] |
File Storage | [from PRD or TBD] | — | [TBD] |
Auth | [from PRD] | — | [TBD] |
[from PRD or TBD] | — | [TBD] | |
CI/CD | [TBD] | — | [TBD] |
Monitoring | [TBD] | — | [TBD] |
Error Tracking | [TBD] | — | [TBD] |
Then describe the Infrastructure Topology covering:
Cloud provider and region(s)
Container orchestration approach (if any)
CDN strategy
DNS / load balancer approach
Backup and disaster recovery approach
§ 4 — Data Architecture & Models
→ Cross-reference: Business PRD § 6 — Feature Overview
For each core entity identified in the PRD feature list:
State the Entity Name and a one-sentence description
Output a Key Fields Table:
Field Name | Type | Constraints | Notes |
|---|---|---|---|
id | UUID | Primary Key, Not Null | Auto-generated |
created_at | TIMESTAMP | Not Null | UTC |
updated_at | TIMESTAMP | Not Null | UTC, auto-updated |
[field] | [type] | [constraints] | [notes] |
After all entities, output the Entity Relationship Summary Table:
Entity A | Relationship | Entity B | Notes |
|---|---|---|---|
[Entity] | has many / belongs to / many-to-many | [Entity] | [e.g., Soft-delete cascade] |
Output the Data Retention & Deletion Policy Table:
Data Type | Retention Period | Deletion Method | Compliance Trigger |
|---|---|---|---|
User PII | Account lifetime | Hard delete on request | GDPR right-to-erasure |
Audit Logs | 12 months | Archive → purge | SOC 2 |
[other] | [TBD] | [TBD] | [TBD] |
§ 5 — API Design & Contracts
→ Cross-reference: Business PRD § 6 — Feature Overview
Open with a 1–2 sentence description of the API design philosophy (REST / GraphQL / gRPC) and versioning strategy (e.g., URL path versioning /api/v1/).
For each major resource group, output an Endpoint Summary Table:
Method | Endpoint | Auth Required | Description | Rate Limit |
|---|---|---|---|---|
POST | /api/v1/auth/login | No | Authenticate user | 10/min per IP |
GET | /api/v1/users/:id | Yes (JWT) | Fetch user profile | 100/min |
[derive from PRD features] |
Then output:
Standard Response Envelope — describe the standard JSON shape for success and error responses as a code block.
Error Code Registry Table:
HTTP Status | Code | Message | When Used |
|---|---|---|---|
400 | INVALID_INPUT | Validation failed | Malformed request body |
401 | UNAUTHORIZED | Unauthorized action | Missing / invalid JWT |
403 | FORBIDDEN | Insufficient permissions | Role mismatch |
404 | NOT_FOUND | Resource not found | Missing entity |
429 | RATE_LIMITED | Too many requests | Rate limit exceeded |
500 | SERVER_ERROR | Internal server error | Uncaught exception |
Webhook Events Table (if the PRD includes webhooks or payment integrations):
Event Name | Trigger | Payload Summary |
|---|---|---|
[event] | [trigger condition] | { [fields] } |
§ 6 — Roles & Permission Matrix
→ Cross-reference: Business PRD § 5 — User Personas & Stories / § 8 — Monetization Strategy
List roles derived from the PRD (personas + tier definitions):
[Role Name]: [One-sentence description]
Then output the Permission Matrix table. Derive rows from PRD features; derive columns from roles:
Permission | [Role 1] | [Role 2] | [Role N] |
|---|---|---|---|
[Permission Name] | Yes / No / [condition] | Yes / No / [condition] | Yes / No / [condition] |
§ 7 — Authentication & Authorization
→ Cross-reference: Business PRD § 3 — Discovery Process (Key Decisions)
Describe the full auth model:
Auth Flow Description: Step-by-step numbered list for each flow (Login, Token Refresh, Logout)
Token Strategy Table:
Token Type | Storage Location | Expiry | Rotation Policy |
|---|---|---|---|
Access Token | Memory (JS) | 15 minutes | On every refresh |
Refresh Token | HTTP-only cookie | 7 days | Rotated on use |
API Key | Hashed in DB | Never (manual revoke) | Revocable by user |
Then provide a dedicated subsection for each auth flow found in the PRD:
Sign In
Sign Up
Logout
Reset Password
Any additional flows (SSO, MFA) — if out of beta scope, mark
[Out of Scope — deferred to V1/V2]
§ 8 — Feature Technical Specifications
→ Cross-reference: Business PRD § 6 — Feature Overview
For each feature listed in the PRD Feature Overview table, create a subsection:
[Feature Name]
Overview: 2–3 sentences describing what this feature does at a system level.
Business Rules: Bullet list of constraints, validations, and edge-case behaviors. Be precise — use exact values, types, and limits extracted from the PRD.
[Feature-Specific Sub-sections]: Add sub-sections relevant to the feature (e.g., for file upload: "Upload Flow", "Validation Rules", "Storage Path Convention"; for notifications: "Trigger Conditions", "Delivery Guarantees").
Acceptance Criteria:
[Criteria 1 — must be measurable, e.g., "List view loads in < 300ms with 1,000 items"]
[Criteria 2]
§ 9 — Third-Party Integrations
→ Cross-reference: Business PRD § 8 — Monetization Strategy
For each external integration identified in the PRD:
Integration Overview Table:
Integration | Purpose | SDK / API Version | Auth Method | Webhook Support | Fallback if Down |
|---|---|---|---|---|---|
[from PRD] | [purpose] | [TBD — pending engineering input] | [TBD] | Yes / No | [TBD] |
Data Shared per Integration Table:
Integration | Data Sent | Data Received | PII Involved | Stored Locally? |
|---|---|---|---|---|
[from PRD] | [fields] | [fields] | Yes (specify) / No | [what is stored] |
§ 10 — Performance, Scalability & Reliability
→ Cross-reference: Business PRD § 10 — Risks & Mitigation
Performance Targets Table:
Metric | Beta Target | V1 Target | Measurement Method |
|---|---|---|---|
API response time (p95) | < 300ms | < 200ms | [TBD — monitoring tool] |
Page load (LCP) | < 3s on 4G | < 2s on 4G | Lighthouse CI |
Time to Interactive (TTI) | < 4s | < 3s | Lighthouse CI |
Concurrent users | [from PRD or TBD] | [from PRD or TBD] | Load test (k6) |
Uptime SLA | 99.5% | 99.9% | [TBD — uptime monitor] |
Error rate (5xx) | < 1% | < 0.1% | [TBD — error tracker] |
DB query time (p95) | < 100ms | < 50ms | Slow query log |
Scalability Strategy — describe:
Horizontal scaling approach
Database indexing strategy for high-read entities
Caching strategy (what is cached, TTL values, invalidation triggers)
Queue-based offloading for heavy async jobs
Reliability & Disaster Recovery Table:
Scenario | RTO | RPO | Recovery Procedure |
|---|---|---|---|
Single instance failure | < 1 min | 0 | Auto-restart via orchestrator |
Database failure | < 5 min | < 5 min | Failover replica |
Full region outage | [Out of Scope — deferred to V1] | — | — |
Data corruption | < 2 hours | < 24 hours | Point-in-time restore |
§ 11 — Notifications & Communication
→ Cross-reference: Business PRD § 6 — Feature Overview (Notifications feature)
If the PRD includes a notifications feature, output:
Notification Types Table:
Notification Type | Trigger Event | Channel(s) | Provider | Template ID |
|---|---|---|---|---|
Welcome email | User registration | [from PRD] | [TBD] | |
Password reset | Reset requested | [from PRD] | [TBD] | |
[derive from PRD features] |
Notification Preference Model: Describe how users opt in/out and where preferences are stored (DB field, table).
Notification Menu (if in-app notifications are in scope): Describe the data model and display mechanism for the in-app notification feed.
If notifications are not in the PRD, mark this section: N/A — no notification system in beta scope.
§ 12 — File Handling & Media
→ Cross-reference: Business PRD § 6 — Feature Overview
If the product has file upload or media features, output:
Attribute | Spec |
|---|---|
Accepted File Types | [from PRD or TBD] |
Max File Size | [from PRD or TBD] |
Max Storage per User | [from PRD or TBD] |
Storage Provider | [from PRD or TBD] |
Delivery Method | [e.g., Pre-signed URLs, expiry = 1 hour] |
Virus Scanning | [Yes / No — provider if Yes] |
Image Processing | [TBD — pending engineering input] |
Backup Policy | [TBD — pending engineering input] |
If the product has no file upload/media features, mark this section: N/A — no file handling in scope.
§ 13 — Testing Strategy
→ Cross-reference: Business PRD § 10 — Risks & Mitigation
Testing Coverage Requirements Table:
Test Type | Coverage Target | Tooling | Runs On |
|---|---|---|---|
Unit Tests | ≥ 80% | [TBD] | Every PR |
Integration Tests | Critical paths | [TBD] | Every PR |
E2E Tests | Happy paths | [TBD] | Pre-deploy (staging) |
Load Tests | Launch traffic | k6 | Pre-production release |
Security Scan | OWASP Top 10 | [TBD] | Weekly + pre-release |
Accessibility | WCAG 2.1 AA | axe-core | Every PR (UI changes) |
Critical Test Scenarios — list the top 10 scenarios that must have automated coverage before beta launch. Derive from PRD features and user flows:
User can register, verify email, and log in
[Derive from PRD core feature flows]
[Derive from PRD monetization / subscription lifecycle if applicable]
[Derive from PRD file upload if applicable]
[Derive from PRD role/permission rules] 6–10.
[TBD — pending QA input]
§ 14 — DevOps, CI/CD & Release Strategy
→ Cross-reference: Business PRD § 12 — Deliverables & Documentation
CI/CD Pipeline Table:
Stage | Trigger | Actions | Gate to Next Stage |
|---|---|---|---|
Lint & Type Check | Every push | ESLint, TypeScript, Prettier | Must pass |
Unit Tests | Every push | [TBD], coverage report | ≥ 80% coverage |
Build | Every push | Docker image build + push to registry | Must succeed |
Integration Tests | PR to main | Spin up test DB, run API tests | Must pass |
Deploy to Staging | Merge to main | Automated deploy | Auto |
E2E Tests | Post-staging deploy | [TBD] suite | Must pass |
Deploy to Prod | Manual approval | Blue/green or rolling deploy | Human sign-off |
Feature Flag Strategy: Describe how new features are gated (e.g., flags stored in DB, env vars, or third-party tool). If not yet decided:
[TBD — pending engineering input]Rollback Procedure: Describe how a bad deploy is rolled back — time target and whether automated or manual.
Secrets Management: State how API keys, DB credentials, and tokens are stored and rotated.
§ 15 — Technical Risks & Mitigation
→ Cross-reference: Business PRD § 10 — Risks & Mitigation
Derive technical risks from the PRD's risk table and supplement with standard engineering risks. Minimum 8 rows:
# | Category | Risk Description | Likelihood | Impact | Mitigation Strategy |
|---|---|---|---|---|---|
1 | Technical | Third-party API introduces breaking change | Low | High | Pin SDK version; monitor changelog; integration tests |
2 | Performance | DB queries degrade at scale without indexing | Medium | High | Index all FK + filter columns; load test before launch |
3 | Security | JWT tokens leaked via XSS | Low | Critical | HttpOnly cookies for refresh; CSP headers; sanitize inputs |
4 | Scalability | Single-instance bottleneck at concurrent user peak | Medium | Medium | Horizontal scaling from day 1; load test pre-launch |
5 | Compliance | GDPR deletion request not fully propagated across services | Medium | High | Deletion cascade + audit trail; legal review |
6 | Operational | Missing monitoring causes silent failures in production | Medium | High | Full APM + alerting before beta; on-call runbook |
7 | Integration | Webhook delivery failure causes billing state mismatch | Medium | Critical | Idempotent handlers; retry queue; reconciliation job |
8 | [Derived from PRD] | [TBD — pending technical discovery] | [TBD] | [TBD] | [TBD] |
§ 16 — General Business Rules
→ Cross-reference: Business PRD § 6 — Feature Overview / § 9 — Design Guidelines
List all cross-cutting engineering rules that apply to every feature. Extract from PRD design guidelines and add standard engineering defaults:
All data-fetching UI states must show skeleton loaders while loading
All successful DB write operations must display a descriptive success toast notification
All DB or API errors must display a descriptive error toast notification with the error context
All pages and components must be fully responsive (mobile-first; breakpoints: 375px / 768px / 1280px)
All forms must validate client-side before submission and display field-level error messages
All destructive actions (delete, cancel subscription) must require a confirmation step
[Add further rules derived from PRD design guidelines and UX principles]
§ 17 — Open Technical Questions & Decisions Needed
→ Cross-reference: Business PRD § 11 — Open Questions & Decisions Needed
Group by area. Derive questions from PRD open questions plus standard TRD unknowns:
Architecture & Infrastructure
# | Question | Context / Options | Owner | Due |
|---|---|---|---|---|
1 | [e.g., Monolith vs. services split at launch?] | [Options from PRD or TBD] | Tech Lead | [TBD] |
Data & API
# | Question | Context / Options | Owner | Due |
|---|---|---|---|---|
1 | [e.g., REST vs GraphQL for client-facing API?] | [TBD] | Backend Lead | [TBD] |
Security & Compliance
# | Question | Context / Options | Owner | Due |
|---|---|---|---|---|
1 | [e.g., Is GDPR compliance required for beta?] | [from PRD compliance scope] | Tech Lead + Legal | [TBD] |
Out-of-Scope Technical Confirmations
The following are explicitly out of scope for beta and will not be engineered:
[Derive from PRD § 7 — Beyond Beta roadmap items]
[Derive from PRD § 11 — Out-of-Scope Confirmations]
Any item marked
[Out of Scope — deferred to V1/V2]elsewhere in this TRD
Post-Generation Checklist
Before saving the output file, verify:
Every section is present (§ 1–17)
Every table has at least one data row (no empty tables — use
[TBD]rows if needed)Every section starts with a
→ Cross-reference:lineEvery section ends with
*Confidential — [Agency Name]*No vague language remains (search for: "fast", "scalable", "robust", "easy", "simple")
All out-of-beta features are marked
[Out of Scope — deferred to V1/V2]No blank fields — every missing value uses
[TBD — pending engineering input]Output is a valid, renderable Markdown file
File Output
Save the final document to:
/mnt/user-data/outputs/TRD_[ProductName].md
Then call present_files with the output path.