Files
ASG_Framework/ASG_Framework.md
T
2026-09-04 08:44:04 +07:00

48 KiB

Agile + Spec Driven Development + GitOps Documentation Framework

This document defines the documentation framework for a software project. It establishes a structured approach to creating, maintaining, and evolving technical documentation in alignment with GitOps principles—ensuring that documentation is versioned, auditable, and continuously validated alongside the codebase.


The ASG Framework: Eight Pillars of Documentation

Document Purpose Primary Audience Format / Content Example (SaaS Context) Measurement (KPI)
Requirements Capture the business intent — why we're building this and what success looks like. Defines boundaries and user-visible outcomes. Stakeholders, Product Owners, Lead Developers User stories, PRDs, acceptance criteria, non-functional constraints. "System must process tabular data from Julia to SvelteKit UI with <200ms latency for 5-member teams." 95% of requests complete <200ms (synthetic monitoring).
Solution Design Translate requirements into an viable solution — how the system solves the user problem. Defines approach, components, and trade-offs before technical details. Product Owners, Architects, Developers Problem decomposition, solution approach, alternatives considered, high-level component diagram, decision rationale. "Problem: Users need to compare wines. Solution: Build a comparison table with filtering, sorting, and visual comparison. Components: Data layer (Wine API), UI layer (Table component), Logic layer (Filter/Sort engine)." 0 solution components without a requirement ID reference.
Walkthrough The end-to-end trace — maps the entire system flow from startup to cycle completion for each participant. Provides a "big picture" view that validates solution design before technical specification is locked. Product Owners, Architects, Developers, End Users Per-participant sections, sequence diagrams, state machine diagrams. Explicitly links to solution-design.md and requirements.md. "User logs in → selects wine → edits details → saves → backend validates against spec → UI updates with error states." 100% of user journeys traced across all layers before implementation starts.
Specification The technical contract — precise rules for inputs, outputs, and data shape. Ensures consistency across dev and test. Maps technical implementation to both what (requirements) and how (solution design). Developers, QA Engineers, CI/CD pipelines OpenAPI, Protobuf, AsyncAPI. Endpoint definitions, schemas, error codes. contract.yaml defining a NATS subject (solution-design SD-3.1) that accepts Arrow streams with snake_case headers (requirements FR-001). 100% of messages validated against spec (CI block rate).
UI Specification The design contract — precise rules for UI components, interactions, and visual patterns. Ensures consistency across design and implementation. Product Designers, Frontend Developers, QA Engineers Component libraries, style guides, interaction specs, design tokens. Atomic design system with Figma tokens synced to CSS variables. 100% of UI components match design spec (visual regression tests).
Validation The enforcer — defines tests before implementation begins to ensure spec compliance. Blocks drift and human error. QA Engineers, Developers, Automation servers Unit tests, integration tests, performance tests, penetration tests, contract tests, CI jobs, linting rules, schema validation. CI job rejects PR with camelCase field not allowed by YAML spec. <1% of PRs bypass validation gates.
Implementation Plan The execution roadmap — how implementation is organized, prioritized, and delivered. Maps code to validation tests and specification. Developers, Project Managers, Lead Developers Implementation plan, module breakdown, task list, delivery timeline, test strategy. Phase 1: Core API + data layer; Phase 2: UI components; Phase 3: Integration tests + E2E validation. 100% of validation tests covered by implementation tasks, <10% timeline drift.
Runbook The operational manual — how the system lives in production, scales, and recovers. Guides on-call engineers. DevOps, SREs, On-call Developers K8s manifests, Helm charts, Markdown guides. Deployment, scaling, backup/restore, troubleshooting. GitOps manifest ensuring 6 Julia replicas restart if memory >80%. MTTR <15 minutes for P1 incidents.

Detailed Document Descriptions

1. Requirements

1-requirements.md

Purpose: Capture the business intent — why we're building this and what success looks like. Defines boundaries and user-visible outcomes.

Why It Matters:

  • Aligns engineering efforts with business goals
  • Provides a north star for feature development
  • Establishes acceptance criteria before implementation begins
  • Creates a contract between product, engineering, security, and operations.

Content Guidelines:

  • User stories with clear acceptance criteria (As a X, I want Y so that Z)
  • Functional Requirements (FR): Testable features with clear IDs (e.g., FR-001, FR-101). Each functional requirement must be linked to a measurable KPI in the success metrics section.
  • Non-Functional Requirements (NFR): Qualities or constraints the system must have (performance, scalability, availability, reliability, security, privacy, observability). NFRs define what kind of system you need, not what it does.
    • Example NFR: "System shall support 10K TPS" (requirement)
    • Example KPI: "95th percentile latency <200ms" (measurable success metric)
  • Success Metrics & KPIs: Specific, measurable targets that validate whether requirements were met. KPIs are measured after deployment; NFRs are defined before implementation.
  • Boundary definitions that state what is in scope and out of scope.
  • Security requirements including threat model outcomes, authentication and authorization expectations, data classification, encryption requirements, and compliance controls.
  • Observability requirements specifying required telemetry, metrics, traces, logs, alerting thresholds, and retention policies.
  • Traceability Rule: Requirements must be self-contained (no cross-references to other docs as justification), but must include IDs (e.g., FR-001) so downstream artifacts (spec, UI spec, architecture) can trace back. All downstream documents MUST cite requirement IDs, but requirements themselves stand alone.

Best Practices:

  • Link each requirement to a measurable KPI — functional requirements should have explicit KPIs; non-functional requirements should have measurable thresholds
  • Keep requirements testable and verifiable
  • Maintain backward compatibility with existing requirements
  • Review and update requirements as business context changes

2. Solution Design

2-solution_design.md

Purpose: Translate requirements into an viable solution — how the system solves the user problem. Defines approach, components, and trade-offs before technical details.

Why It Matters:

  • Prevents technical-first thinking that skips design decisions
  • Ensures the solution addresses the actual user problem, not just requirements
  • Enables architects to evaluate alternatives before committing to technical details
  • Creates alignment between product, design, and engineering on the approach
  • Provides a reference for evaluating specification choices against intended solution

Content Guidelines:

  • Problem decomposition: Break down the user problem into smaller, solvable pieces
  • Solution approach: Describe the high-level approach (e.g., "Use event sourcing for audit trail", "Implement caching layer for performance")
  • Alternatives considered: Document at least 2-3 alternative approaches with rationale for why they were rejected
  • High-level component diagram: Show major components and their relationships (not technical details, just the big picture)
  • Decision rationale: Explain why each major decision was made (e.g., "Chose NATS over Kafka for simpler ops", "Used server-side rendering for SEO")
  • Risk assessment: Identify potential risks and how they will be mitigated
  • Traceability: Link each solution component to specific requirement ID(s) (e.g., FR-001, NFR-201) that it addresses
  • Decision IDs: Assign unique IDs to major decisions using the format SD-XXX (e.g., SD-001 for "Use NATS for async messaging") to enable specification traceability

Best Practices:

  • Write solution design from the user's perspective first, then justify technical choices
  • Keep it high-level—avoid technical specifics (API endpoints, data schemas, etc.)
  • Use diagrams that are easy to update (Mermaid.js)
  • Document trade-off decisions explicitly
  • Review solution design against requirements to verify completeness
  • Get sign-off from product, architecture, and engineering before creating walkthroughs

Gap-Check Question: Does the Solution Design clearly explain how the system solves the user problem, not just what it does?

Example Gap: Requirements say "users can compare wines", but solution design only mentions "wine comparison API" without explaining how users will actually use the comparison feature.


3. Walkthrough

3-walkthrough.md

Primary Audience: Product Owners, Architects, Developers, End Users

Purpose: The end-to-end trace — each section maps one system participant's complete journey from their own POV, from session start to task completion. Provides a "big picture" view that validates solution design before technical specification is locked. Each section is standalone: described entirely from that participant's perspective, with cross-references to other participants' sections where their workflows intersect.

Per-Participant Walkthroughs The walkthrough is organized as one document with a dedicated section per system participant, each tracing the complete journey from that participant's perspective:

Walkthrough Section System Participant What It Shows
Participant A Section Primary system user (e.g., wine retailer customer) End-to-end journey: browse → interact → complete task → receive outcome
Participant B Section Secondary system user (e.g., wine retailer admin) End-to-end journey: manage → configure → review → reconcile
Participant C Section Tertiary system user (e.g., system administrator) End-to-end journey: configure → monitor → handle incidents → audit

Each section:

  • Traces the complete flow from that participant's login/session start to task completion and logout
  • Explicitly references steps where other participants' actions are triggered (e.g., "Customer places order → see Retailer section step 4.2")
  • Shows error paths, edge cases, and recovery from that participant's perspective
  • Uses sequence diagrams to illustrate interactions across participants

Why It Matters:

  • Each section is written entirely from one participant's POV — what they see, do, and achieve
  • Each participant sees their complete end-to-end journey in a standalone walkthrough section
  • Participants understand how their actions trigger or depend on other participants' workflows
  • Validates that all components (UI, API, backend logic) work together cohesively before implementation begins
  • Exposes solution design gaps and integration risks between participant workflows early in the design phase
  • Provides a reference for verifying implementation against intended behavior and for tracing requirements through to architecture

Content Guidelines:

  • One section per system participant, starting from their login/session start to task completion
  • End-to-end flow: what the participant sees, does, and achieves at each step
  • Cross-references to other participants' sections where workflows intersect (e.g., "Customer order placed → see Retailer section step 4.2")
  • External interactions (user actions, API calls, third-party integrations)
  • Internal flow (state transitions, business logic, data transformations) triggered by the participant's actions
  • Error paths and edge cases specific to that participant's journey
  • Sequence diagrams showing request/response patterns across participants for complex multi-user flows
  • State machine diagrams for workflows that span multiple participants
  • Each major walkthrough step must cite the exact Solution Design decision ID(s) (e.g., SD-001, SD-002) from solution-design.md and/or Requirement ID(s) from requirements.md that it implements or depends on.

Best Practices:

  • Write each section from one participant's perspective, then cross-reference other participants' sections
  • Include concrete examples with realistic data values for each participant's typical usage
  • Link each step to its corresponding Solution Design decision (SD-XXX IDs) and requirement IDs
  • Map cross-participant interactions explicitly (e.g., "Customer action X → Retailer notification Y")
  • Document failure modes and recovery paths from each participant's perspective
  • Keep walkthroughs updated as requirements and participant roles evolve
  • Review walkthroughs against the solution design to verify completeness across all participants

4. Specification

4-specification.md Purpose: The technical contract — precise rules for inputs, outputs, and data shape. Ensures consistency across dev and test. Maps technical implementation to both what (requirements) and how (solution design).

Why It Matters:

  • Prevents implementation drift between components
  • Enables contract testing in CI/CD pipelines
  • Provides a single source of truth for data structures
  • Facilitates integration between teams
  • Enables traceability from business requirements to technical implementation

Content Guidelines:

  • API endpoint definitions (methods, paths, parameters)
  • Request/response schemas (JSON, XML, Protobuf, AsyncAPI)
  • Error codes and their meanings
  • Data validation rules and constraints
  • Rate limiting and quota definitions
  • Each specification item must cite:
    • Requirement ID(s) from requirements.md (e.g., FR-001, NFR-201) — defines what the system must do
    • Solution Design reference(s) from solution-design.md (e.g., SD-2.1, SD-3.3) — defines how and why this technical approach was chosen
    • Link each endpoint, schema, validation rule, error case, etc to the exact requirement(s) and solution design decision(s) it implements or satisfies.

Best Practices:

  • Use formal specification languages (OpenAPI 3.0+, AsyncAPI)
  • Version specifications alongside code
  • Generate client SDKs from specifications
  • Block CI on specification violations
  • Document edge cases and error scenarios

5. UI Specification

5-ui_specification.md

Purpose: The design contract — precise rules for UI components, interactions, and visual patterns. Ensures consistency across design and implementation.

Why It Matters:

  • Prevents visual inconsistency across the application
  • Enables design system scalability and maintainability
  • Provides a single source of truth for UI components and interactions
  • Facilitates collaboration between designers and developers
  • Enables traceability from business requirements to UI implementation

Content Guidelines:

  • Component specifications (atomic design principles)
  • Style guide (colors, typography, spacing, icons)
  • Interaction patterns (animations, transitions, states)
  • Design tokens (CSS variables, Figma tokens)
  • Accessibility standards (WCAG compliance)
  • Responsive design breakpoints and layouts
  • Each UI specification artifact must cite the specific requirement ID(s) from requirements.md (for example FR-001, NFR-201) and/or the exact specification ID(s) or spec path(s) from specification.md that it implements or depends on.

Best Practices:

  • Use design systems with versioned component libraries
  • Sync design tokens from Figma to CSS variables automatically
  • Document component states (normal, hover, disabled, error)
  • Include accessibility requirements for each component
  • Create visual regression tests for critical UI flows
  • Version UI specifications alongside code

6. Validation

6-validation.md

Purpose: The enforcer — defines tests before implementation begins to ensure spec compliance. Blocks drift and human error.

Why It Matters:

  • Ensures tests are written before implementation, so code can be tested as it's built
  • Prevents breaking changes from reaching production
  • Catches specification violations early in the CI pipeline
  • Maintains data integrity and API consistency
  • Reduces manual QA effort through automation
  • Provides immediate feedback to developers during implementation
  • Validates performance NFRs (latency, throughput) against measurable KPIs before deployment
  • Validates security requirements through adversarial testing before production

Content Guidelines:

  • Unit tests — atomic tests for each specification rule, data schema field, and UI component state (cites specification.md sections, ui-specification.md component specs)
  • Integration tests — end-to-end flow validation covering workflows defined in 3-walkthrough.md (cites specification.md endpoint chains, 3-walkthrough.md participant sections)
  • Performance tests — load tests, stress tests, and benchmarking against NFR thresholds (cites requirements.md NFRs, solution-design.md performance decisions)
  • Penetration tests — adversarial testing of security requirements and auth flows (cites requirements.md security NFRs, specification.md auth endpoints)
  • Contract testing scripts (mapped to specification.md sections)
  • Linting rules and configurations (enforcing style guides from ui-specification.md)
  • Schema validation jobs (validating data shapes from specification.md)
  • Visual regression tests (verifying UI matches ui-specification.md)
  • Security scanning and audit jobs (SAST, dependency vulnerability checks)
  • CI/CD pipeline configurations for automated test execution
  • Each validation test must include explicit references to:
    • specification.md (spec IDs or paths — API contracts, data schemas, e.g., /api/v1/endpoint or #/components/schemas/Request)
    • ui-specification.md (components, interactions, visual states, e.g., ## Wine Table or ### Sort States)
    • requirements.md (e.g., FR-001, NFR-101, NFR-201) — business intent and NFR thresholds being validated
    • solution-design.md (e.g., SD-2.1, SD-3.3) — architectural decisions being tested

Best Practices:

  • Define tests before writing implementation code
  • Fail CI on specification violations
  • Run validation jobs on every commit and PR
  • Use automated code review tools
  • Maintain validation job health dashboard
  • Document validation failure remediation steps

Specification-to-Test Execution Trace

Every specification rule must have a runnable, verifiable test. This trace maps each spec item to its corresponding test file, test function, and CI gate — proving that every requirement was tested, not just claimed.

Trace Format:

Requirement ID Source Path Unit Test File Unit Test Function Additional Test File(s) CI Gate Status
FR-001 specification.md:3.2.1 tests/unit/schema-validation.test.ts test_rejects_camelCase_headers — ci/contract-validation.yaml Pass
FR-002 specification.md:4.1 tests/unit/api-routes.test.ts test_post_wine_returns_201 tests/integration/wine-flow.test.ts ci/contract-validation.yaml Pass
FR-003 specification.md:3.2.3 — — tests/integration/error-handling.test.ts ci/contract-validation.yaml Pass
NFR-101 requirements.md:4.1 — — tests/performance/load.test.ts ci/performance.yaml Pass
SD-001 solution-design.md:5.1 — — tests/integration/nats-async.test.ts ci/integration.yaml Pass
UI-15.3.2 ui-specification.md:15.3.2 tests/unit/wine-table.test.tsx test_sort_by_name tests/visual/wine-table.spec.js ci/visual-regression.yaml Pass

Additional Test File(s) column covers: integration tests (participant section flows), performance tests (NFR benchmarks), penetration tests (security NFRs), and visual regression tests (UI component states).

Trace Rules:

  • Every specification section with a concrete rule (endpoint, schema field, validation constraint, error code) must have at least one unit test
  • Every participant section journey must have at least one integration test
  • Every performance NFR must have at least one performance test (load/stress/benchmark)
  • Every security NFR must have at least one penetration test scenario
  • Every UI component state must have at least one unit test (behavior) and one visual regression test (appearance)
  • A test may cover multiple spec items, but each spec item must be covered by at least one test
  • Status is tracked via CI gate results (Pass/Fail/Skipped) — not manual checks

How to Maintain:

  1. When writing a new spec rule, add a trace row before implementation
  2. When writing the test, fill in the test file and function
  3. CI gate auto-updates Status from pipeline results
  4. Gap-Check step 6 (Validation Review) verifies 100% row coverage — no spec rule without a test

Tooling (optional):

  • Use YAML or JSON files (e.g., validation/test-trace.yaml) as machine-readable trace data
  • Generate CI reports that auto-populate the Status column from pipeline results
  • Use tools like cypress open for E2E traces, k6 for performance traces, owasp-zap for pen test traces
  • Integrate trace data into PR descriptions so reviewers can verify coverage before merge

7. Implementation Plan

7-implementation-plan.md

Why It Matters:

  • Converts specification into executable code with clear ownership and timeline
  • Enables parallel development across teams by defining module boundaries
  • Provides visibility into progress and blockers for stakeholders
  • Ensures all validation tests are covered by implementation tasks

Content Guidelines:

  • Implementation phases and timeline (e.g., Phase 1: Core API + data layer; Phase 2: UI components; Phase 3: Integration tests + E2E validation)
  • Module/component breakdown with responsibilities and dependencies
  • Task list with assignees, priorities, and estimated effort
  • Test coverage: which validation tests each implementation task satisfies
  • Build and deployment preparation (CI/CD setup, environment configuration)
  • Risk mitigation: known blockers and mitigation steps

Best Practices:

  • Break implementation into small, testable increments (1-3 day sprints)
  • Map each implementation task to specific validation tests (not just specification sections)
  • Define clear ownership for each module or component
  • Include test coverage targets for each phase
  • Document dependencies between modules to avoid blocking work
  • Review implementation plan against validation tests to ensure complete coverage

8. Runbook

8-runbook.md

Purpose: The operational manual — how the system lives in production, scales, and recovers. Guides on-call engineers.

Why It Matters:

  • Reduces Mean Time To Recovery (MTTR) for incidents
  • Provides step-by-step guidance for common issues
  • Documents scaling and deployment procedures
  • Ensures operational knowledge is not siloed

Content Guidelines:

  • Deployment procedures (manual and automated)
  • Scaling instructions (horizontal/vertical)
  • Backup and restore procedures
  • Troubleshooting guides for common issues
  • Runbook entries for specific error codes
  • Contact information and escalation paths
  • Explicit references to specification.md (API contracts, data schemas, specific endpoint sections)
  • Explicit references to ui-specification.md (components, interactions, visual states, specific component sections)

Best Practices:

  • Write runbooks for every P1/P2 incident
  • Include exact commands and configuration snippets
  • Test runbooks periodically (chaos engineering)
  • Link runbook entries to relevant documentation
  • Keep runbooks updated when system changes

How to Use This Approach Effectively

1. Start with Requirements

Before writing any code or documentation, establish clear requirements. Ask:

  • What business problem are we solving?
  • How will we measure success?
  • What are the non-negotiable constraints?

Action: Create a docs/requirements/ directory and start with PRD.md and KPIs.md.

2. Define Solution Design

Once requirements are stable, translate them into an viable solution. This ensures the technical approach solves the user problem, not just requirements.

Action: Create docs/solution-design/ with solution-design.md, problem decomposition, alternatives considered, high-level component diagram, and decision rationale.

3. Create Walkthroughs Early

As soon as the solution design is defined, create walkthroughs — one document with a section per system participant. This helps identify gaps in each participant's flow and provides onboarding material. Each section traces the complete journey from that participant's perspective and cross-references other participants' workflows. The walkthrough should explicitly link to solution-design.md (SD-XXX IDs) and requirements.md.

Action: Create docs/walkthrough/ with 3-walkthrough.md containing one section per participant (e.g., Customer, Retailer, Admin), sequence diagrams, and cross-references to solution design decisions and requirements.

4. Define the Specification

With walkthrough in place, define the technical specification. This becomes the contract for implementation. Each specification item must trace to both:

  • Requirements (WHAT - business intent)
  • Solution Design (HOW/WHY - architectural decisions)

Action: Create docs/specification/ with contract.yaml (or appropriate format), error-codes.md, and traceability mappings to requirements.md, solution-design.md, and 3-walkthrough.md.

5. Define UI Specification Early

Create UI specifications before implementing frontend components. This ensures design consistency and provides a contract for implementation.

Action: Create docs/ui-specification/ with component-library.md, style-guide.md, and design-tokens.json.

6. Define Validation Tests Before Implementation

Write validation tests before implementation begins. This ensures every specification rule and UI state has a corresponding test that defines success. Tests should reference specification.md, ui-specification.md, requirements.md (NFR thresholds), and solution-design.md (performance decisions). Create a specification-to-test execution trace that maps every spec item to its test file, test function, and CI gate.

Action: Create docs/validation/ with unit-tests/ (spec rules, schema fields, component states), integration-tests/ (end-to-end flows from each participant walkthrough section), performance-tests/ (NFR benchmarks: latency, TPS), penetration-tests/ (security NFRs, auth flows), contract-tests/, ci-pipeline.yaml, lint-rules/, and test-trace.yaml (specification-to-test execution trace mapping every spec path to its test file, test function, and CI gate).

7. Create Implementation Plan

With validation tests defined, create the implementation plan. Map each implementation task to specific validation tests that it must satisfy.

Action: Create docs/implementation-plan/ with phases, module breakdown, task list with assignees, and test coverage targets.

8. Document Operations from Day One

Create runbook entries as soon as deployment procedures are established. Update them when incidents occur.

Action: Create docs/runbook/ with entries for deployment, scaling, and common issues.


The Gap-Check Process

Since all docs defined in the ASG Framework are living documents that evolve throughout the project lifecycle, this Gap-Check process ensures each documentation stage validates the previous one before moving forward.

Stage Transition Goal Gap-Check Question Example Gap Result
Requirements → Solution Design Turn a "Wish" into a "Solution" Does the Solution Design clearly explain how the system solves the user problem, not just what it does? Requirements say "users can compare wines", but solution design only mentions "wine comparison API" without explaining how users will actually use the comparison feature Add UI flow and user interaction patterns to the solution design
Solution Design → Walkthrough Turn a "Solution" into a "Story" Does every participant section trace the complete flow the Solution Design describes, including all SD-XXX decisions? Is there a section for each system participant? Solution design says "use NATS for async messaging", but Participant A section doesn't trace the async flow or reference SD-001 Add the async messaging flow with SD-001 reference to Participant A section
Walkthrough → Specification Turn the "Story" into "Rules" Does the Specification cover all the behaviors defined in every participant section? Participant A section shows 10 interaction steps, but Specification only defines 2 REST endpoints Add the missing endpoint definitions to Specification
Specification → UI Specification Turn a "Rule" into a "Button" Does the UI Specification expose all the data and states defined in the Specification? Specification says device must "Handshake" within 5 seconds, but UI Specification has no connection status indicator Add a Connection Status component to UI Specification
UI Specification → Validation Turn "Design" into "Tests" Do the Validation tests cover all specification rules, UI states, performance NFRs, and security requirements? UI Spec defines 15 component states but Validation only has 5 unit tests; NFR-101 latency threshold has no performance test Add unit tests for all component states, performance benchmarks for NFR thresholds, and pen test scenarios for security NFRs
Validation → Implementation Plan Turn "Tests" into "Tasks" Does the Implementation Plan satisfy all validation tests with clear ownership? Validation defines 30 test cases but Implementation Plan only has tasks for 20 Add implementation tasks for remaining test cases with assignees and timelines

Why Gap-Checks Matter

  • Prevent rework: Catch missing requirements before coding begins
  • Ensure completeness: Verify all scenarios are covered across all layers
  • Validate feasibility: Confirm technical approach supports the intended user flow
  • Maintain alignment: Keep all stakeholders (product, design, dev) on the same page

How to Run Gap-Checks

  1. Requirements Review: After writing requirements, ask "What happens if X?" for each user story
  2. Solution Design Review: After writing solution design, verify every requirement is addressed by at least one solution component with a corresponding requirement ID reference
  3. Walkthrough Review: After writing walkthrough, verify every SD-XXX decision and requirement is traced in every participant section with error paths included, and that each system participant has a dedicated section
  4. Specification Review: After writing the spec, verify every spec item has:
    • At least one requirement ID reference (WHAT)
    • At least one solution design reference (HOW/WHY)
    • Coverage for all behaviors defined in each participant section
  5. UI Specification Review: After writing UI Specification, verify every spec rule has at least one UI representation with a corresponding requirement ID reference
  6. Validation Review: After writing Validation, verify every specification section and UI state has at least one corresponding unit/integration test case; every performance NFR has a benchmark test; every security NFR has a penetration test scenario — each with explicit references to specification.md, ui-specification.md, and/or requirements.md
  7. Implementation Plan Review: After writing the plan, verify every validation test is covered by at least one implementation task with an assignee and timeline

The Pre-Code Debugging Habit

This habit ensures that each documentation stage is complete and validated before moving forward. These checklists serve as mental guards against building features that don't meet the requirements or architecture.

Stage Debug Checklist Why It Matters
Requirements If I can't state the Value, I'm building a feature nobody needs. Clarifies the business impact before technical discussion begins
Solution Design If I can't Imagine the solution, I'm building without a compass. Ensures the technical approach solves the user problem before spec writing
Walkthrough If I can't Trace every participant's full flow, the system has 'broken bridges'. Identifies gaps between components and validates the solution design end-to-end for each system participant
Specification If I can't write a Rule with a requirement ID reference AND/OR solution design reference, I haven't thought the logic through. Ensures traceability from technical rules to both business requirements (what) and architectural decisions (how/why)
UI Specification If I can't See it with a requirement ID reference, the user has no way to trigger the logic. Ensures traceability from UI elements to business requirements
Validation If I can't Write a Test for every spec rule, UI state, NFR threshold, and security requirement, implementation is untestable. Ensures code can be tested from day one — unit, integration, performance, and pen tests define success before implementation begins

How to Use This Habit:

  1. Before writing each doc, run through the checklist for that stage
  2. Before moving to the next doc, run through the checklist for the current stage
  3. When reviewing docs, use the checklist to verify completeness

This habit turns documentation into a self-validating process—each stage catches gaps from the previous one before they become bugs in production.


GitOps Integration

This documentation framework aligns with GitOps principles:

GitOps Principle Documentation Alignment
Versioned All documentation lives in git, with history and audit trail
Declarative Specifications and architecture are declarative contracts
Automated Validation jobs automate spec compliance checks
Self-Service Walkthroughs and runbooks enable self-service onboarding and operations
Observability KPIs and metrics are defined for each documentation artifact

Metrics and Continuous Improvement

Each documentation artifact has associated KPIs. Track these to ensure quality:

Document KPI Target
Requirements Requirement coverage 100% of features have associated requirements
Solution Design Solution completeness 0 solution components without a requirement ID reference
Specification Specification compliance rate 100% of messages validate against spec
UI Specification UI spec compliance 100% of components match design spec (visual regression tests)
Walkthrough New dev time-to-first-PR <2 days from onboarding to first contribution
Implementation Test coverage >80% unit test coverage
Validation Bypass rate <1% of PRs bypass validation gates
Runbook MTTR <15 minutes for P1 incidents

Review Cadence:

  • Weekly: Review KPI dashboards and documentation gaps
  • Monthly: Update documentation based on incident learnings
  • Quarterly: Full framework review and improvement

Deployment Decision Rules

These rules define the critical gates that must be passed before and after deployment:

  • Acceptance Condition NOT met → Don't deploy (buggy/broken)
  • KPI NOT met after deployment → Deployed feature is failing business goals (need fix/optimization)

Acceptance Conditions are verified before deployment through testing and validation. They determine whether the implementation matches the specification and is ready for production.

KPIs are measured after deployment to validate whether the feature is achieving its business goals. If KPIs are not met, the feature may be deployed but is failing its intended purpose and requires immediate attention (fixes or optimization).

These rules serve as a binary decision framework:

  • Acceptance Conditions = Quality Gate (deploy or block)
  • KPIs = Business Health Monitor (deploy but fix if failing)

Template Examples

Requirements Template

# PRD: Feature Name

## 1. Business Context & Success Metrics

### Business Goal
[Clear statement of the business problem being solved and why]

### User Stories
- **US-XXX**: [User story with clear action and value]
- *Example: US-001 - As a wine retailer customer, I want to access the sommpanion chat so that I can get wine-related help quickly*

### KPIs & Targets
- **KPI-XXX**: [Measurable target with validation reference]
- *Example: KPI-001 - 95% of chat messages receive responses within 3 seconds (validates FR-001)*

## 2. Technical Boundaries

### In Scope
[List features and capabilities included in this release]

### Out of Scope
[List features explicitly excluded from this release]

### Dependencies
[List external services, APIs, or systems this feature depends on]

### Deployment Constraints
- **NFR-XXX**: [Deployment-specific requirement]
- *Example: NFR-501 - System shall be deployed to MicroK8s cluster with relative URL support*

## 3. Functional Requirements (FR)

### FR-XXX: [Requirement Title]
[Detailed description of what the system shall do]
- [Specific behavior 1]
- [Specific behavior 2]
- [Specific behavior 3]

**Traceability**: US-XXX, US-XXX

### FR-XXX: [Requirement Title]
[Detailed description of what the system shall do]
- [Specific behavior 1]

**Traceability**: US-XXX

## 4. Non-Functional Requirements (NFRs)

### 4.1 Performance & Scalability
- **NFR-XXX**: [Performance requirement with measurable threshold]
- *Example: NFR-101 - Support page shall load in <1 second on 3G networks*

### 4.2 Availability & Reliability
- **NFR-XXX**: [Reliability requirement]
- *Example: NFR-201 - Chat functionality shall have 99.9% monthly uptime*

### 4.3 Privacy & Security
- **Data Classification**: [e.g., PII, PHI, commercial data]
- **Encryption**: [e.g., TLS 1.3+, AES-256 at rest]
- **Authentication**: [e.g., Session-based, OAuth2, API keys]
- **Compliance**: [e.g., GDPR Art. 32, SOC2 Type II, HIPAA]

### 4.4 Observability & Telemetry
- **Required Logs**: [e.g., `session_id`, `user_id`, `message_id`, `event_type`, `timestamp`, `latency_ms`]
- **Critical Metrics**:
  - `metric_name_1`
  - `metric_name_2`
- **Tracing**: [e.g., Zipkin/B3 propagation, 10% sampling]
- **Alerting**: [e.g., `chat_delivery_rate < 95%` triggers PagerDuty]
- **Retention**: [e.g., Logs: 30 days, Metrics: 1 year]

## 5. Acceptance Conditions

- [ ] **FR-XXX**: [Verifiable acceptance condition]
- [ ] **FR-XXX**: [Verifiable acceptance condition]
- [ ] **NFR-XXX**: [Verifiable acceptance condition]
- *Example: [ ] FR-001: Sommpanion landing page renders with all required elements*

## 6. Requirements Traceability Matrix

| Requirement ID | Description | Implementation File | Test File |
|----------------|-------------|---------------------|-----------|
| FR-XXX | [Brief description] | `path/to/file.ext` | `tests/file.spec.js` |
| NFR-XXX | [Brief description] | `path/to/file.ext` | `tests/file.spec.js` |

**Notes**:
- Functional Requirements (FR) define what the system shall do
- Non-Functional Requirements (NFR) define system qualities (performance, availability, security, etc.)
- KPIs are measurable targets that validate whether requirements were met post-deployment
- Each requirement must include a clear requirement ID for traceability
- All acceptance conditions must be verifiable through testing or manual inspection

Solution Design Template

# Solution Design: Feature Name

## 1. Problem Decomposition

Break down the user problem into smaller, solvable pieces.

| Problem | Description | User Impact |
|---------|-------------|-------------|
| [Problem ID] | Brief description of the problem | How this affects the user |

**Example**: 
- **P-001**: Users cannot compare multiple wines side-by-side → They must navigate between wine pages, losing context and making comparisons difficult

## 2. Solution Approach

Describe the high-level approach to solving the problem.

**Approach**: [e.g., "Implement a comparison table with filtering, sorting, and visual comparison features"]

**Key Principles**:
- [e.g., "Keep comparison data in memory for instant updates"]
- [e.g., "Use server-side rendering for SEO"]
- [e.g., "Support unlimited wine comparisons for power users"]

## 3. Alternatives Considered

Document at least 2-3 alternative approaches with rationale.

| Alternative | Pros | Cons | Decision |
|-------------|------|------|----------|
| Client-side comparison | Fast updates, no server load | Memory-intensive, no sharing | Rejected - memory constraints on mobile |
| Server-side comparison | Centralized, scalable | Latency, complex state sync | Accepted - matches performance requirements |
| Hybrid approach | Best of both worlds | Complex, hard to maintain | Rejected - over-engineering |

## 4. High-Level Component Diagram

```mermaid
%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#3b82f6'}}}%%
flowchart TD
    A[User] --> B[Comparison UI]
    B --> C[Comparison State]
    B --> D[Wine API]
    C --> D

Component Descriptions:

  • [Component Name]: [Brief description of responsibilities and how it solves part of the problem]
    • Links to requirements: FR-001, NFR-201

5. Decision Rationale

Explain why each major decision was made.

Decision ID Decision Rationale Alternatives Rejected
SD-001 Use NATS for async messaging Required for real-time messaging with low overhead Kafka - too complex for current scale
SD-002 Use WebSockets for real-time updates Required for <100ms feedback REST polling - too slow, too many requests
SD-003 Store comparison list in localStorage Allows offline comparison editing Redux - overkill for this feature
SD-004 Server-side rendering for comparison export SEO for shared comparisons Client-side rendering - no SEO benefit

6. Risk Assessment

Identify potential risks and mitigation strategies.

Risk Impact Probability Mitigation
Performance degradation with >5 wines High Medium Implement performance profiling, limit to 10 wines max
Race conditions in real-time updates Medium Low Use optimistic updates with rollback
Memory leaks from comparison state Medium Medium Implement cleanup on unmount, use weak references

7. Requirements Traceability

Link each solution component to specific requirements and assign Solution Design IDs for specification traceability.

Solution Component Requirement ID Decision ID Description
Comparison table UI FR-101 SD-001 Display wines in table format (uses NATS messaging)
Filtering FR-102 SD-002 Filter wines by criteria (uses WebSocket updates)
Sorting FR-103 SD-003 Sort wines by any column (stored in localStorage)
Real-time updates NFR-201 SD-002 Updates appear within 100ms (uses WebSocket)
Export comparison FR-201 SD-004 Export comparison to PDF/CSV (uses server-side rendering)

Specification Template

# contract.yaml
openapi: 3.0.0
info:
  title: NATSBridge API
  version: 1.0.0
  description: Technical specification with requirements and solution design traceability
paths:
  /api/v1/endpoint:
    post:
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Request'
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Response'
      x-requirement-id: FR-001    # Reference to Requirements document (WHAT)
      x-solution-design-ref: SD-3.1  # Reference to Solution Design decision (HOW/WHY)
components:
  schemas:
    Request:
      type: object
      properties:
        data:
          type: string
          x-requirement-id: FR-002    # Reference to Requirements document (WHAT)
          x-solution-design-ref: SD-3.2  # Reference to Solution Design decision (HOW/WHY)
    Response:
      type: object
      properties:
        status:
          type: string
          x-requirement-id: FR-003    # Reference to Requirements document (WHAT)
          x-solution-design-ref: SD-3.1  # Reference to Solution Design decision (HOW/WHY)

UI Specification Template

# UI Specification: Component Name

## Component Overview
**Name**: [Component Name]
**Status**: [Draft/Approved/Deprecated]
**Version**: 1.0.0

## Requirements Traceability
| UI Element | Requirement ID | Solution Design Ref | Description |
|------------|----------------|---------------------|-------------|
| Login form | FR-001 | SD-2.1 | Username/password authentication |
| Sidebar menu | NFR-202 | Collapsible sidebar for usability |
| Wine table | FR-101 | Sortable, searchable inventory table |

## Design Tokens
- **Color**: `--color-primary`
- **Typography**: `--font-body`
- **Spacing**: `--spacing-md`

## Component States
| State | Description | Example | Requirement ID |
|-------|-------------|---------|----------------|
| Default | Normal state | `<Button />` | FR-001 |
| Hover | Mouse over | `<Button hover />` | NFR-201 |
| Disabled | Disabled state | `<Button disabled />` | NFR-203 |
| Error | Error state | `<Button error />` | EH-004 |

## Accessibility
- [ ] WCAG 2.1 AA compliant
- [ ] Keyboard navigation support
- [ ] Screen reader compatible

## Implementation
- Component file: `src/components/[Component].svelte`
- Test file: `src/components/[Component].test.js`
- Visual regression test: `tests/visual/[Component].spec.js`

## References
- Figma: [Link to design file]
- Storybook: [Link to component story]
- Requirements: [`docs/requirements.md`](../requirements.md)

Architecture Template

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#3b82f6'}}}%%
flowchart TD
    A[Client] --> B[Caddy]
    B --> C[Node.js API]
    C --> D[Julia Worker]
    D --> E[NATS Cluster]
    E --> F[Storage]
    
    style A fill:#f9f9f9,stroke:#333
    style E fill:#e0e7ff,stroke:#3b82f6

Specification Traceability:

Architecture Component Solution Design Ref Specification Section UI Specification Section Requirement ID
NATS Bridge (smartsend) SD-3.1 specification.md:3.1 - FR-301, NFR-201
Login Form SD-2.1 specification.md:10.1 ui-specification.md:15.2.1 FR-001, NFR-201
Wine Inventory Table SD-2.2 specification.md:4.2 ui-specification.md:15.3.3 FR-101, NFR-205
Sidebar Menu SD-2.3 specification.md:11.1 ui-specification.md:15.3.2 NFR-202

Component Details:

  • Caddy: Static file serving (specification.md:2.2, ui-specification.md:15.1, solution-design.md:SD-1.1)
  • Node.js API: NATS bridge client (specification.md:3.1, solution-design.md:SD-3.1)
  • Julia Worker: Backend processing (specification.md:4.1, solution-design.md:SD-4.1)
  • NATS Cluster: Message bus (specification.md:3.3, solution-design.md:SD-3.3)
  • Storage: Data persistence (specification.md:5.1, solution-design.md:SD-5.1)

Runbook Template

# Runbook: Service Restart

**Severity**: P2
**Estimated Time**: 5 minutes

## Symptoms
- Service is unresponsive
- Health checks are failing

## Steps
1. SSH to the host
2. Run: `kubectl rollout restart deployment/natsbridge`
3. Monitor: `kubectl get pods -l app=natsbridge -w`

## Rollback
- Run: `kubectl rollout undo deployment/natsbridge`

## Post-Incident
- [ ] Review logs for root cause
- [ ] Update runbook if needed

Conclusion

This ASG Documentation Framework ensures that documentation is:

  • Structured: Eight distinct artifacts with clear purposes
  • Automated: Validation and CI/CD integration
  • Versioned: All documentation in git with history
  • Measurable: KPIs for quality and effectiveness
  • Actionable: Practical templates and examples

Use this framework as a living document—update it as your team's needs evolve.