Spec-Driven Development Approach
Specification-Driven Development (SDD) places a structured, machine-readable specification at the centre of your development process. When combined with AI coding tools, specs become the single source of truth that both humans and AI assistants use to generate, validate, and maintain code — drastically reducing ambiguity and rework.
1.1 — Why Spec-Driven Development
- Requirements live in verbal conversations, WhatsApp, and scattered notes
- AI tools generate generic code requiring heavy rework
- Business rules buried in legacy WinForms code
- Team members interpret requirements differently
- Testing is ad-hoc with no clear acceptance criteria
- Every feature has a structured spec before code is written
- AI receives specs as context — output is domain-aware and accurate
- Business rules are extracted, documented, and versioned
- All team members (and AI) work from the same specification
- Acceptance criteria are built-in — testing is deterministic
SDD doesn't mean writing specifications from scratch alone. You use AI to help draft specs from conversations with domain experts, then validate and refine. The spec feeds back into AI for code generation — creating a virtuous cycle.
1.2 — The SDD Lifecycle
Conduct structured interviews with domain experts (the existing team who built the WinForms app). Use AI to transcribe and summarize sessions. Capture business rules, workflows, edge cases, and the "why" behind each feature.
For the Memo module: "When a party returns stones, reconcile each by certificate number, recalculate lot-level averages, and adjust party outstanding."
Feed discovery notes + your spec template to an AI assistant. The AI generates a first draft that you refine with the domain expert — saving 60-70% of spec-writing time.
Team reviews for completeness, business rule accuracy, and edge case coverage. Use AI to cross-reference against the legacy WinForms codebase.
Use AI to decompose the spec into development tasks for Frontend (React, AG Grid) and Backend (.NET Core APIs, services, data models). Each task references specific spec sections.
Developers open the spec alongside their IDE. AI tools receive the spec as context, generating implementation code that aligns with the specification — not generic boilerplate.
Test cases derive directly from the spec's acceptance criteria. AI generates unit tests, integration tests, and e2e scripts from the documented scenarios.
When requirements change, the spec is updated first, then code follows. The spec remains the living single source of truth.
1.3 — Specification Template & Format
Every feature/module should follow this template. Store specs as Markdown in your repo under a /specs directory, version-controlled alongside code.
1.4 — Writing Specs with AI Assistance
Here is the recommended process for using AI tools to draft specifications quickly and accurately:
Method A: From Domain Expert Interview
## Prompt to AI (Claude, ChatGPT, Gemini) You are a senior business analyst specializing in diamond and jewellery inventory management software. I will provide interview notes about the "Diamond Purchase Entry" feature. Generate a complete feature specification using this template: [Paste your spec template here] Key context: - Modernization: WinForms + WCF → React + .NET Core - Frontend uses AG Grid for tabular data entry - Handles both loose diamonds and certified diamonds - Weights in carats (up to 3 decimal places) - Currency: INR with USD conversion rates - Party (supplier) master data already exists Interview Notes: """ Rajubhai explained the purchase entry process: - When broker brings diamonds, first we check the lot - Each stone has shape, size, color, clarity, cut - For certified stones, enter GIA/IGI certificate number - Rate can be per carat or per piece (for small sizes) - Making charges apply only to jewellery, not loose diamonds - Track broker commission (usually 0.5-1%) - Purchase can be "on memo" (approval) or "firm purchase" - GST: 0.25% on diamonds, 3% on gold jewellery - Party outstanding gets updated after saving - Need to print purchase voucher after saving """ Generate the complete specification with all fields filled in. Make sure business rules are numbered and testable.
Method B: From Legacy WinForms Code
## Prompt to AI I am modernizing a WinForms application to React + .NET Core. Below is legacy code for the Purchase Entry form and WCF service. Analyze and extract a complete feature specification: 1. Identify all business rules embedded in the code 2. Document the data model (fields, types, validations) 3. Map UI behaviors (grid columns, calculated fields, events) 4. List all edge cases handled in the code 5. Note hard-coded values that should become configurable Format using our spec template. Legacy Code: [Paste the relevant WinForms .cs file here]
Combine both methods. Extract the implicit spec from legacy code, then validate with domain expert interviews. The AI-generated spec becomes the starting point for structured review — not the final output.
1.5 — From Spec to Code: The AI-Accelerated Workflow
Once a spec is approved, here's how to systematically use it for AI-assisted code generation:
- Data Model → Entity classes, DTOs, EF Core configs
- Business Rules → Service/domain layer methods
- API Contract → Controllers, request/response models
- Validation → FluentValidation rules from field constraints
- Tests → xUnit tests from acceptance criteria
- Types → TypeScript interfaces from Data Model
- AG Grid → Column defs, cell renderers/editors
- Forms → React Hook Form + Zod schemas
- API Layer → API client functions from contract
- Components → React components from UI layout
## Prompt to your AI coding assistant (VS Code / Cursor) Based on the following spec section, generate AG Grid column definitions for the Diamond Purchase Entry grid. Requirements from spec: - Columns: Sr No (auto), Shape (dropdown), Size (text), Pcs (number), Carat (number, 3 decimals), Rate (number, 2 decimals), Amount (calculated: Carat × Rate), Certificate No (text, optional), Color, Clarity (dropdowns) - Amount auto-calculates when Rate or Carat changes - Shape, Color, Clarity use master data dropdowns - Certificate No: validate "GIA-XXXXXXXXXX" or "IGI-XXXXXXX" - Carat should not exceed 99.999 - Tab → next editable cell; Enter on last row → new row Generate ColDef[] with proper TypeScript types and AG Grid Enterprise features.
1.6 — Domain-Specific Spec Examples
Abbreviated examples showing how specs capture diamond & jewellery domain concepts:
## Business Rules BR-001: Purchase Entry Number auto-generated: "PUR-{BranchCode}-{YYMM}-{SeqNo}" (e.g., PUR-SUR-2605-0042) BR-002: Rate Type = "Per Carat": Amount = Carat × Rate Rate Type = "Per Piece": Amount = Pieces × Rate BR-003: Broker Commission: Commission Amount = Total Amount × (Commission% / 100) Default: 1.0%, Range: 0.00 to 5.00 BR-004: GST Calculation for diamonds: CGST = Net Amount × 0.125% SGST = Net Amount × 0.125% IGST = Net Amount × 0.25% (inter-state parties) Apply CGST+SGST if Party.State = Company.State, else IGST BR-005: Purchase Type = "Memo" (approval basis): - Do NOT update Party Outstanding - Do NOT update Stock ledger - Mark status as "Pending Approval" - Must convert within 15 days (configurable) BR-006: Certificate Number validation: - Must be unique across the system - Format: GIA + 10 digits, or IGI + 7 digits - Warn (not block) if certificate in another party's memo BR-007: Carat Weight Reconciliation: - Total (sum of items) must match Lot Total - Tolerance: ±0.005 carats - If mismatch exceeds tolerance → warning before save
## Acceptance Criteria AC-001: Full Return Given a Memo with 5 stones to Party "ABC Jewellers" When all 5 stones are selected for return Then Memo status → "Fully Returned" And Party Outstanding decreases by total memo amount And all 5 stones are available in stock again AC-002: Partial Return with Conversion Given a Memo with 5 stones When 3 stones returned, 2 converted to sale Then Memo status → "Closed" And 3 stones back in stock And 2 stones generate a Sale Entry linked to Memo And Party Outstanding adjusts accordingly AC-003: Return with Weight Discrepancy Given a Memo stone with recorded weight 1.520 ct When return weight entered as 1.515 ct (diff: 0.005) Then system shows "Weight discrepancy detected" And allows proceed with mandatory remark And logs discrepancy in audit trail
1.7 — Review, Validation & Governance
- Check for conflicting rules: "Do any of these rules contradict each other?"
- Check for missing edge cases: "What scenarios are not covered?"
- Check for data model gaps: "Any fields in rules missing from the model?"
- Cross-reference legacy code against the spec
- No code without a spec — PRs must reference a spec file
- Spec changes = pull requests — treat like code changes
- Version control — specs live in
/specsin Git - Status tracking — Draft → Review → Approved → Implemented → Verified
- Changelog — every spec tracks what changed and when
1.8 — Edge Cases & Business Rules in the Diamond Domain
The diamond and jewellery domain has unique characteristics that must be meticulously captured:
| Concept | Edge Case to Specify | Why It Matters |
|---|---|---|
| Carat Weight | 3 decimal places. Tolerance rules for weight matching across transactions. | 0.001ct diff on 5ct diamond at ₹5L/ct = ₹500 variance |
| Certificate Stones | Same stone in multiple memo entries. Track current holder. | Prevents duplicate sales, enables chain-of-custody |
| Memo / Approval | Time-bound consignment. Auto-reminders. Partial returns. Conversion to sale. | Core workflow — most transactions start as memo |
| Rate Fluctuations | USD/INR rate at entry vs. settlement. Rate locking rules. | Exchange rate changes impact P&L materially |
| Lot vs. Individual | Small diamonds as lots (100 pcs × 0.10ct). Large diamonds individually. | Different UI, validation, and pricing logic |
| Making Charges | Per gram, per piece, or percentage. Varies by item type. | Different calc modes coexist in same form |
| GST Complexity | Diamonds: 0.25%, Gold: 3%, Platinum: 3%, Making: 5%. HSN mapping. | Multiple tax rates in a single invoice |
Never assume AI understands your domain terminology. Terms like "Memo", "Jangad", "Packet", "Lot", "Rejection", and "Cutting" have specific meanings in the diamond trade. Always define a domain glossary in your specs and skill files.
Skills Setup & Concrete Approaches
A hands-on guide to configuring AI tools, creating custom skill files that embed domain knowledge, and establishing daily workflows that make AI a reliable development partner.
2.1 — AI Tool Selection & Configuration
| Tool | Purpose | IDE | Priority |
|---|---|---|---|
| GitHub Copilot | Inline completion, chat, code review | VS Code + Visual Studio | Essential |
| Cursor IDE | AI-first editor, multi-file context, codebase-aware chat | Cursor (VS Code fork) | Essential |
| Claude / ChatGPT / Gemini | Spec drafting, architecture decisions, documentation | Browser / API | Essential |
| Copilot for CLI | Terminal commands, dotnet CLI, git | Terminal | Recommended |
| AI Code Review Bots | Automated PR reviews (CodeRabbit, Copilot) | GitHub | Recommended |
| v0 / bolt.new | Rapid UI prototyping, component scaffolding | Browser | Prototyping |
GitHub Copilot Business (~₹1,600/user/month) is the best starting point — works in both VS Code and Visual Studio. Supplement with Cursor Pro (~₹1,700/user/month) for Frontend developers who need multi-file editing.
2.2 — VS Code Setup (Frontend — React + TypeScript + AG Grid)
Essential Extensions
Inline completions + Chat
Consistent formatting
Run tests in editor
Custom Instructions — .github/copilot-instructions.md
Create this file at your Frontend repo root. Copilot reads it automatically:
# Diamond & Jewellery Inventory — Frontend # React 18 + TypeScript 5 + AG Grid Enterprise ## Tech Stack - React 18 with functional components and hooks only - TypeScript strict mode — always provide explicit types - AG Grid Enterprise for all tabular data - React Hook Form + Zod for validation - TanStack Query for server state - Zustand for client state - Axios with interceptors for .NET Core backend ## Coding Standards - Named exports, not default exports - Component files: PascalCase (PurchaseEntryGrid.tsx) - Hooks: camelCase with "use" prefix (usePurchaseEntry.ts) - Never use `any` — use `unknown` + type guards - `const` assertions for AG Grid column definitions ## Domain Context - Memo / Jangad: Consignment/approval — stones on approval - Packet: Group of small diamonds traded as unit - Party: Business entity (supplier, customer, broker) - Carat: Weight unit — always 3 decimal places - 4C: Cut, Color, Clarity, Carat — grading params ## AG Grid Patterns - Always use ColDef<T> with generic type param - `valueGetter` for computed columns - Indian numbering for currency (₹1,23,456.78) - 3 decimal places for weight columns - Keyboard nav: Tab, Enter, Escape - Editable grids must support undo/redo ## File Structure src/ ├── features/ # Feature-based modules │ ├── purchase/ │ ├── sale/ │ ├── memo/ │ ├── stock/ │ └── masters/ ├── components/ # Shared components ├── hooks/ # Shared hooks ├── services/ # API layer ├── types/ # Shared TypeScript types └── utils/ # Utilities
2.3 — Visual Studio Setup (Backend — .NET Core)
Essential Extensions
Built into VS 2022+
Refactoring & analysis
Quality & security
# Diamond & Jewellery Inventory — Backend # .NET 8 (LTS) + EF Core + SQL Server ## Architecture - Clean Architecture: Domain → Application → Infrastructure → API - CQRS with MediatR for commands and queries - Repository pattern with Unit of Work over EF Core - FluentValidation for all command/query validation - AutoMapper for entity-to-DTO mapping ## Coding Standards - C# 12, nullable reference types enabled - `record` types for DTOs and value objects - `sealed` on classes not meant to be inherited - Async/await throughout — no `.Result` or `.Wait()` - `decimal` for monetary values & weights (never `double`) - API versioning: `/api/v1/` ## Domain Types - Carat Weight: `decimal(8,3)` in SQL, `decimal` in C# - Monetary amounts: `decimal(18,2)` - Exchange rates: `decimal(10,4)` - Primary keys: `Guid` not `int` ## Business Rules in Code - Rules live in Domain layer service classes - Name methods after rule: ApplyBR004_CalculateGST() - Include rule ID in XML doc comments - Throw DomainException for violations ## Project Structure src/ ├── DiamondJewel.Domain/ ├── DiamondJewel.Application/ ├── DiamondJewel.Infrastructure/ ├── DiamondJewel.API/ └── tests/ ├── DiamondJewel.Domain.Tests/ ├── DiamondJewel.Application.Tests/ └── DiamondJewel.API.Tests/
2.4 — Custom Instructions & AI Skills Files
Beyond Copilot instructions, create dedicated context files that you feed to AI assistants. These act as "skills" — concentrated domain knowledge that makes AI output dramatically more accurate.
Recommended Structure
Example: Domain Glossary
# Diamond & Jewellery Industry Glossary ## Transaction Types | Term | Local Term | Meaning | |----------------|---------------|--------------------------------------| | Purchase | Kharidi | Buying from a supplier | | Sale | Vechan | Selling to a customer | | Memo | Jangad | Stones sent on approval basis | | Memo Return | Jangad Parat | Getting back unsold stones | | Memo Convert | Jangad Sale | Converting memo to confirmed sale | | Rejection | Rejection | Returning stones due to quality | ## Diamond Grading (4C) | Param | Values | |-----------|-----------------------------------------------------| | Shape | Round, Princess, Oval, Cushion, Emerald, Pear, ... | | Color | D, E, F, G, H, I, J, K, L, M, N-Z | | Clarity | FL, IF, VVS1, VVS2, VS1, VS2, SI1, SI2, I1-I3 | | Cut | Ideal, Very Good, Good, Fair, Poor | ## Weight & Pricing - 1 Carat = 0.2 grams. Precision: 3 decimal places - Points: 1 carat = 100 points (50-pointer = 0.50ct) - Rapaport: Industry benchmark price list (USD/ct) - Discount%: Actual price as discount to Rapaport ## Tax (India GST) - Diamonds (rough & polished): 0.25% (HSN: 7102) - Gold Jewellery: 3% (HSN: 7113) - Making/Labour: 5% - Intra-state: split CGST + SGST. Inter-state: IGST
Example: AG Grid Patterns
# AG Grid Patterns — Diamond Inventory System ## Currency Column (Indian Format) ```typescript export const currencyColumn = ( field: string, header: string ): ColDef => ({ field, headerName: header, type: 'numericColumn', valueFormatter: (p) => p.value != null ? '₹' + new Intl.NumberFormat('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(p.value) : '', cellStyle: { textAlign: 'right' }, width: 140, }); ``` ## Carat Weight Column (3 Decimals) ```typescript export const caratColumn = ( field: string, header: string ): ColDef => ({ field, headerName: header, type: 'numericColumn', valueFormatter: (p) => p.value != null ? p.value.toFixed(3) : '', cellEditor: 'agNumberCellEditor', cellEditorParams: { precision: 3, min: 0, max: 99.999, step: 0.001, }, width: 110, }); ```
2.5 — Team Workflow Patterns with AI
How each role integrates AI into their daily work:
AI Usage: Record sessions → AI transcribes → AI drafts specs → Expert reviews → AI validates completeness
- Use Claude/ChatGPT for spec drafting
- Paste legacy code for rule extraction
- Ask AI to find gaps in acceptance criteria
AI Usage: Spec → TS types → AG Grid columns → Form components → API client → Tests
- Keep spec open in split pane while coding
- Cursor Composer for multi-file edits
- AI for cell renderers/editors
AI Usage: Spec → Entities & DTOs → MediatR handlers → FluentValidation → Migrations → xUnit tests
- Reference spec rule IDs in code comments
- AI chat for complex LINQ queries
- AI for stored procedures if needed
AI Usage: Review PRs against spec → Check rule coverage → Identify deviations → Architecture suggestions
- CodeRabbit for automatic PR reviews
- AI-generated review checklists
- AI for performance analysis
2.6 — Concrete Daily Workflow
Step-by-step: how a developer uses AI + specs to build a feature (e.g., "Memo Issue"):
Pull latest. Open specs/memo/memo-issue.md. Read business rules and acceptance criteria.
In Visual Studio Copilot Chat, paste the Data Model and Business Rules sections:
Based on this spec, generate: 1. MemoIssue entity in Domain layer 2. MemoIssueItem entity for line items 3. CreateMemoIssueCommand + MediatR handler 4. CreateMemoIssueCommandValidator (FluentValidation) 5. Follow architecture in copilot-instructions.md [Spec Data Model and Business Rules here]
Verify rules match spec (BR-001, BR-002…). Fix issues. Run tests. Commit: feat(memo): implement memo issue - refs specs/memo/memo-issue.md
In VS Code / Cursor, feed UI Behavior section to AI. Prompt for AG Grid columns, form layout, and API integration using the AG Grid skills file.
Copy AC-001, AC-002, etc. and prompt AI to generate test cases. Each criterion becomes one or more tests.
Update spec status. Create PR referencing the spec. AI code review bot validates implementation.
2.7 — Quality Gates & Guardrails
AI-generated code requires structured quality controls:
- TypeScript strict mode — no
any - ESLint / Roslyn analyzers: zero warnings
- Business rules reference spec rule IDs
- Unit tests cover all acceptance criteria
- PR references spec file & lists rules implemented
- AI code review validates coding standards
- Human reviewer checks domain logic
- No hardcoded values — all configurable
- Each AC (AC-001…) explicitly tested & signed off
- Edge cases from spec are tested
- Domain expert validates against real scenarios
- No hallucinated APIs — verify against actual endpoints
- No fabricated rules — every rule must exist in spec
- No phantom dependencies — verify all imports
- Security review — catch SQL injection, XSS
2.8 — Team Ramp-Up Plan
A practical 4-week plan to get proficient with AI-powered SDD:
| Week | Focus | Activities | Deliverables |
|---|---|---|---|
| Week 1 | Tool Setup | Install Copilot in VS Code & Visual Studio. Setup custom instructions. Prompt engineering workshop. | All IDEs configured. Instructions committed. Team trained. |
| Week 2 | Spec Writing | Pick 2-3 well-understood modules. Extract specs using AI + domain expert. Practice template. | 3 approved specs (Party Master, Purchase, Stock View) |
| Week 3 | Code Generation | Use approved specs to generate code for one module (Party Master). Practice prompt → generate → review cycle. | Party Master fully implemented from spec with AI. |
| Week 4 | Full Workflow | Execute full SDD lifecycle on complex module (Diamond Purchase). Discovery → spec → code → test → review. | Diamond Purchase WIP. Refined process documented. |
📊 Expected Outcomes After 4 Weeks
- 50-60% reduction in time from spec-to-code for CRUD modules
- 80% reduction in ambiguity-related rework
- Consistent code quality across the team via shared AI instructions
- Living documentation — specs stay current because they drive development
- Faster onboarding — new members read specs + skills files to understand the system
AI is a force multiplier, not a replacement for domain expertise. The team's deep knowledge of the diamond and jewellery trade is irreplaceable. AI helps express that knowledge in code faster, more consistently, and with better documentation. The spec is the bridge between domain expertise and code generation — invest heavily in getting specs right, and the code almost writes itself.