diff --git a/.github/workflows/adr-validate.yml b/.github/workflows/adr-validate.yml new file mode 100644 index 00000000..2c5a8740 --- /dev/null +++ b/.github/workflows/adr-validate.yml @@ -0,0 +1,67 @@ +name: ADR Validation + +# Validates Architecture Decision Records (ADRs) on every PR and push to main. +# Checks: +# 1. Naming convention: NNNN-title.md (4-digit number, kebab-case title) +# 2. Required front matter fields present and valid +# 3. Status values are from allowed enum +# 4. Date format is YYYY-MM-DD +# 5. Index.md table is consistent with actual ADR files +# 6. No duplicate ADR numbers + +on: + pull_request: + paths: + - 'docs/adr/**' + - '.github/workflows/adr-validate.yml' + push: + branches: [main] + paths: + - 'docs/adr/**' + - '.github/workflows/adr-validate.yml' + +permissions: + contents: read + +jobs: + validate-adrs: + name: Validate ADRs + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '24' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Run ADR validation script + run: node scripts/adr-validate.js + + validate-index: + name: Validate ADR Index + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '24' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Run index validation + run: node scripts/adr-index-validate.js \ No newline at end of file diff --git a/docs/adr/index.md b/docs/adr/index.md new file mode 100644 index 00000000..e4fe8424 --- /dev/null +++ b/docs/adr/index.md @@ -0,0 +1,50 @@ +# Architecture Decision Records (ADR) Index + +This directory contains Architecture Decision Records (ADRs) for the SubTrackr project. Each ADR documents a significant architectural decision, its context, considered options, and the chosen outcome. + +## ADR List + +| # | Title | Status | Date | Authors | Related | +|---|-------|--------|------|---------|---------| +| 0001 | [Example: Adopt TypeScript Strict Mode](0001-typescript-strict-mode.md) | Accepted | 2024-01-15 | @author1 | — | +| 0002 | [Example: Migrate to pnpm Workspaces](0002-pnpm-workspaces.md) | Accepted | 2024-02-20 | @author2 | 0001 | +| 0003 | [Example: Event-Driven Architecture for Notifications](0003-event-driven-notifications.md) | Proposed | 2024-03-10 | @author3 | — | + +> **Note:** Replace the example entries above with actual ADRs as they are created. The first real ADR should be numbered `0001`. + +## Status Definitions + +| Status | Meaning | +|--------|---------| +| **Proposed** | Under discussion, not yet approved | +| **Accepted** | Approved and being implemented / implemented | +| **Superseded** | Replaced by a newer ADR (link in Related column) | +| **Deprecated** | No longer relevant, but not replaced | + +## Creating a New ADR + +1. **Copy the template**: `cp docs/adr/template.md docs/adr/NNNN-title-of-decision.md` +2. **Choose the next number**: Check this index for the highest existing number and increment by 1. +3. **Fill in all sections** of the template. +4. **Add a row to this table** with the new ADR's metadata. +5. **Open a PR** for review. +6. **On merge**: Update the ADR's status to `Accepted`. + +## Validation + +ADRs are validated in CI by the `adr-validate.yml` workflow which checks: +- All ADR files follow the naming convention (`NNNN-title.md`) +- Required front matter fields are present +- Status is one of: Proposed, Accepted, Superseded, Deprecated +- Date format is YYYY-MM-DD +- Links in the index table are valid + +## Related Documentation + +- [ADR Template](template.md) — Use this template for new ADRs +- [Contributing Guide](../CONTRIBUTING.md) — General contribution guidelines +- [Architecture Overview](../architecture/README.md) — High-level system architecture + +--- + +*Last updated: 2024-11-24* \ No newline at end of file diff --git a/docs/adr/template.md b/docs/adr/template.md new file mode 100644 index 00000000..4f6b95de --- /dev/null +++ b/docs/adr/template.md @@ -0,0 +1,135 @@ +# ADR Template + +**Title:** [Short, descriptive title of the architectural decision] + +**Status:** [Proposed | Accepted | Superseded | Deprecated] + +**Date:** YYYY-MM-DD + +**Authors:** [Name(s) and GitHub handle(s)] + +## Context + +[Describe the architectural problem or decision that needs to be made. Include: +- What is the problem we're trying to solve? +- What are the constraints and requirements? +- What is the current state of the system? +- Why is this decision needed now?] + +## Decision Drivers + +- [Driver 1: e.g., Performance, scalability, cost, team familiarity] +- [Driver 2: e.g., Regulatory compliance, security, maintainability] +- [Driver 3: e.g., Time-to-market, technical debt reduction] + +## Considered Options + +### Option 1: [Name of option] + +**Description:** [Brief description of this option] + +**Pros:** +- [Pro 1] +- [Pro 2] + +**Cons:** +- [Con 1] +- [Con 2] + +**Estimated Effort:** [Low | Medium | High] +**Risk Level:** [Low | Medium | High] + +### Option 2: [Name of option] + +**Description:** [Brief description of this option] + +**Pros:** +- [Pro 1] +- [Pro 2] + +**Cons:** +- [Con 1] +- [Con 2] + +**Estimated Effort:** [Low | Medium | High] +**Risk Level:** [Low | Medium | High] + +### Option 3: [Name of option] (if applicable) + +**Description:** [Brief description of this option] + +**Pros:** +- [Pro 1] + +**Cons:** +- [Con 1] + +**Estimated Effort:** [Low | Medium | High] +**Risk Level:** [Low | Medium | High] + +## Decision Outcome + +**Chosen Option:** [Option X: Name] + +**Rationale:** [Explain why this option was chosen over the others. Reference the decision drivers and trade-offs.] + +## Consequences + +### Positive +- [Positive consequence 1] +- [Positive consequence 2] + +### Negative +- [Negative consequence 1] +- [Mitigation for negative consequence 1] + +### Neutral +- [Neutral consequence 1] + +## Implementation Plan + +1. [Step 1 with owner and timeline] +2. [Step 2 with owner and timeline] +3. [Step 3 with owner and timeline] + +## Validation Criteria + +- [ ] [Criterion 1: e.g., All existing tests pass] +- [ ] [Criterion 2: e.g., Performance benchmark meets threshold] +- [ ] [Criterion 3: e.g., No breaking changes to public API] + +## Related Decisions + +- [ADR-XXX: Title of related ADR] - [Brief description of relationship] + +## References + +- [Link to relevant documentation, RFC, or external resource] +- [Link to discussion thread (GitHub issue, PR, Slack, etc.)] + +--- + +## Template Usage Instructions + +1. **Copy this file** to `docs/adr/NNNN-title-of-decision.md` where `NNNN` is the next sequential number. +2. **Fill in all sections** - leave no placeholder text. +3. **Number sequentially** - check the [ADR Index](../adr/index.md) for the next number. +4. **Submit for review** - open a PR with the new ADR. +5. **On acceptance** - update status to "Accepted" and add to the index. +6. **If superseding** - update the old ADR's status to "Superseded" and link to the new one. + +## Metadata Format (Front Matter) + +```yaml +--- +adr: NNNN +title: [Title of decision] +status: [Proposed | Accepted | Superseded | Deprecated] +date: YYYY-MM-DD +authors: [Name1, Name2] +decision-drivers: [Driver1, Driver2] +options-considered: [Option1, Option2, Option3] +chosen-option: [Option X] +related-adrs: [ADR-XXX, ADR-YYY] +--- +``` \ No newline at end of file diff --git a/scripts/adr-index-validate.js b/scripts/adr-index-validate.js new file mode 100644 index 00000000..1cf09cd9 --- /dev/null +++ b/scripts/adr-index-validate.js @@ -0,0 +1,129 @@ +#!/usr/bin/env node +/** + * ADR Index Validation Script + * Validates that docs/adr/index.md is consistent with actual ADR files + */ + +const fs = require('fs'); +const path = require('path'); + +const ADR_DIR = path.join(__dirname, '..', 'docs', 'adr'); +const INDEX_FILE = path.join(ADR_DIR, 'index.md'); + +function extractFrontMatter(content) { + const match = content.match(/^---\n([\s\S]*?)\n---/); + if (!match) return null; + const fm = {}; + const lines = match[1].split('\n'); + for (const line of lines) { + const [key, ...valueParts] = line.split(':'); + if (key && valueParts.length > 0) { + fm[key.trim()] = valueParts.join(':').trim(); + } + } + return fm; +} + +function parseIndexTable(content) { + // Extract the markdown table from index.md + const tableMatch = content.match(/\| #.*?\n((?:\|.*\n)*)/); + if (!tableMatch) return []; + + const rows = tableMatch[1].trim().split('\n').filter(r => r.includes('|')); + const adrs = []; + + for (const row of rows) { + const cells = row.split('|').map(c => c.trim()).filter(Boolean); + if (cells.length >= 2) { + const numMatch = cells[0].match(/^(\d+)$/); + if (numMatch) { + const titleMatch = cells[1].match(/\[([^\]]+)\]\(([^)]+)\)/); + if (titleMatch) { + adrs.push({ + number: parseInt(numMatch[1], 10), + title: titleMatch[1], + file: titleMatch[2].replace('./', ''), + }); + } + } + } + } + return adrs; +} + +function main() { + console.log('🔍 Validating ADR Index...\n'); + + if (!fs.existsSync(INDEX_FILE)) { + console.error(`❌ Index file not found: ${INDEX_FILE}`); + process.exit(1); + } + + const indexContent = fs.readFileSync(INDEX_FILE, 'utf-8'); + const indexAdrs = parseIndexTable(indexContent); + + if (indexAdrs.length === 0) { + console.log('ℹ️ No ADR entries found in index table (may be template)'); + return; + } + + const files = fs.readdirSync(ADR_DIR) + .filter(f => f.endsWith('.md') && f !== 'template.md' && f !== 'index.md') + .sort(); + + const fileAdrs = []; + for (const file of files) { + const filePath = path.join(ADR_DIR, file); + const content = fs.readFileSync(filePath, 'utf-8'); + const fm = extractFrontMatter(content); + + if (fm && fm.adr) { + const fileMatch = file.match(/^(\d{4})-(.+)\.md$/); + if (fileMatch) { + fileAdrs.push({ + number: parseInt(fileMatch[1], 10), + title: fm.title || 'Untitled', + file: file, + status: fm.status || 'Unknown', + }); + } + } + } + + let hasErrors = false; + + // Check index entries exist as files + for (const idx of indexAdrs) { + const match = fileAdrs.find(f => f.number === idx.number); + if (!match) { + console.error(`❌ Index entry ADR-${String(idx.number).padStart(4, '0')} "${idx.title}" has no corresponding file`); + hasErrors = true; + } else if (match.title !== idx.title) { + console.warn(`⚠️ Title mismatch for ADR-${String(idx.number).padStart(4, '0')}: index="${idx.title}" file="${match.title}"`); + } + } + + // Check files have index entries + for (const file of fileAdrs) { + const match = indexAdrs.find(i => i.number === file.number); + if (!match) { + console.error(`❌ File ${file.file} (ADR-${String(file.number).padStart(4, '0')}: "${file.title}") missing from index`); + hasErrors = true; + } + } + + // Check for duplicate numbers in index + const indexNums = indexAdrs.map(a => a.number); + const dupIndex = indexNums.filter((n, i) => indexNums.indexOf(n) !== i); + if (dupIndex.length > 0) { + console.error(`❌ Duplicate ADR numbers in index: ${dupIndex.join(', ')}`); + hasErrors = true; + } + + console.log(`\n📋 Index entries: ${indexAdrs.length}`); + console.log(`📄 ADR files: ${fileAdrs.length}`); + console.log(`${hasErrors ? '❌ Index validation failed' : '✅ Index consistent'}`); + process.exit(hasErrors ? 1 : 0); +} + +main(); \ No newline at end of file diff --git a/scripts/adr-validate.js b/scripts/adr-validate.js new file mode 100644 index 00000000..4e2a1edc --- /dev/null +++ b/scripts/adr-validate.js @@ -0,0 +1,147 @@ +#!/usr/bin/env node +/** + * ADR Validation Script + * Validates Architecture Decision Records in docs/adr/ + */ + +const fs = require('fs'); +const path = require('path'); +const { execSync } = require('child_process'); + +const ADR_DIR = path.join(__dirname, '..', 'docs', 'adr'); +const VALID_STATUSES = ['Proposed', 'Accepted', 'Superseded', 'Deprecated']; +const FRONT_MATTER_REQUIRED = ['adr', 'title', 'status', 'date', 'authors']; + +function extractFrontMatter(content) { + const match = content.match(/^---\n([\s\S]*?)\n---/); + if (!match) return null; + + const fm = {}; + const lines = match[1].split('\n'); + for (const line of lines) { + const [key, ...valueParts] = line.split(':'); + if (key && valueParts.length > 0) { + fm[key.trim()] = valueParts.join(':').trim(); + } + } + return fm; +} + +function validateFilename(filename) { + // Should match NNNN-title.md format + const match = filename.match(/^(\d{4})-(.+)\.md$/); + if (!match) { + return { valid: false, error: `Filename "${filename}" does not match NNNN-title.md format` }; + } + const num = parseInt(match[1], 10); + if (num === 0) { + return { valid: false, error: `ADR number cannot be 0000` }; + } + return { valid: true, number: num, title: match[2] }; +} + +function validateFrontMatter(fm, filename, fileNumber) { + const errors = []; + + // Check required fields + for (const field of FRONT_MATTER_REQUIRED) { + if (!fm[field]) { + errors.push(`Missing required front matter field: ${field}`); + } + } + + // Validate adr number matches filename + if (fm.adr) { + const fmNum = parseInt(fm.adr, 10); + if (fmNum !== fileNumber) { + errors.push(`Front matter adr number (${fmNum}) does not match filename (${fileNumber})`); + } + } + + // Validate status + if (fm.status && !VALID_STATUSES.includes(fm.status)) { + errors.push(`Invalid status "${fm.status}". Must be one of: ${VALID_STATUSES.join(', ')}`); + } + + // Validate date format (YYYY-MM-DD) + if (fm.date && !/^\d{4}-\d{2}-\d{2}$/.test(fm.date)) { + errors.push(`Invalid date format "${fm.date}". Must be YYYY-MM-DD`); + } + + // Validate date is valid + if (fm.date) { + const date = new Date(fm.date); + if (isNaN(date.getTime())) { + errors.push(`Invalid date "${fm.date}"`); + } + } + + return errors; +} + +function main() { + console.log('🔍 Validating ADRs...\n'); + + if (!fs.existsSync(ADR_DIR)) { + console.error(`❌ ADR directory not found: ${ADR_DIR}`); + process.exit(1); + } + + const files = fs.readdirSync(ADR_DIR) + .filter(f => f.endsWith('.md') && f !== 'template.md' && f !== 'index.md') + .sort(); + + if (files.length === 0) { + console.log('ℹ️ No ADR files found (excluding template.md and index.md)'); + return; + } + + let hasErrors = false; + const adrNumbers = new Set(); + + for (const file of files) { + const filePath = path.join(ADR_DIR, file); + const content = fs.readFileSync(filePath, 'utf-8'); + + console.log(`📄 Checking ${file}...`); + + // Validate filename + const fileValidation = validateFilename(file); + if (!fileValidation.valid) { + console.error(` ❌ ${fileValidation.error}`); + hasErrors = true; + continue; + } + + // Extract and validate front matter + const fm = extractFrontMatter(content); + if (!fm) { + console.error(` ❌ No valid front matter found (expected --- front matter ---)`); + hasErrors = true; + continue; + } + + // Check for duplicate numbers + if (adrNumbers.has(fileValidation.number)) { + console.error(` ❌ Duplicate ADR number: ${fileValidation.number}`); + hasErrors = true; + } + adrNumbers.add(fileValidation.number); + + // Validate front matter + const fmErrors = validateFrontMatter(fm, file, fileValidation.number); + if (fmErrors.length > 0) { + for (const err of fmErrors) { + console.error(` ❌ ${err}`); + } + hasErrors = true; + } else { + console.log(` ✅ Valid (ADR-${String(fileValidation.number).padStart(4, '0')}: ${fm.title})`); + } + } + + console.log(`\n${hasErrors ? '❌ Validation failed' : '✅ All ADRs valid'}`); + process.exit(hasErrors ? 1 : 0); +} + +main(); \ No newline at end of file