Initial commit: Clean DSS implementation
Migrated from design-system-swarm with fresh git history.
Old project history preserved in /home/overbits/apps/design-system-swarm
Core components:
- MCP Server (Python FastAPI with mcp 1.23.1)
- Claude Plugin (agents, commands, skills, strategies, hooks, core)
- DSS Backend (dss-mvp1 - token translation, Figma sync)
- Admin UI (Node.js/React)
- Server (Node.js/Express)
- Storybook integration (dss-mvp1/.storybook)
Self-contained configuration:
- All paths relative or use DSS_BASE_PATH=/home/overbits/dss
- PYTHONPATH configured for dss-mvp1 and dss-claude-plugin
- .env file with all configuration
- Claude plugin uses ${CLAUDE_PLUGIN_ROOT} for portability
Migration completed: $(date)
🤖 Clean migration with full functionality preserved
This commit is contained in:
410
docs/01_core/ADMIN_PRINCIPLES.md
Normal file
410
docs/01_core/ADMIN_PRINCIPLES.md
Normal file
@@ -0,0 +1,410 @@
|
||||
# Admin Principles & Operational Standards
|
||||
|
||||
**Version 2.0.0** | Status: Production | Context: Extension of [PRINCIPLES.md](./PRINCIPLES.md)
|
||||
|
||||
This document defines the architectural and operational standards for the Design System Swarm (DSS) Administration Layer. While `PRINCIPLES.md` governs the system as a whole, these principles specifically constrain how privileged operations, monitoring, and governance are implemented.
|
||||
|
||||
The 6 Admin Principles extend the core DSS principles with **role-based governance**, **configuration hierarchy**, and **team-specific operational modes**. They enable different teams (Admin, UI, UX, QA) to work within the same system without duplicating configuration or losing governance auditability.
|
||||
|
||||
---
|
||||
|
||||
## 1. Admin Visibility (The Glass Box)
|
||||
|
||||
### Core Concept
|
||||
The Admin layer must provide total transparency into the system's state. There are no "hidden" processes. If the system does it, the Admin sees it. This is not just about logs; it is about semantic understanding of system health, user activity, and resource state.
|
||||
|
||||
### Why It Matters
|
||||
- **Trust**: You cannot govern what you cannot see. Hidden failures erode trust in the swarm.
|
||||
- **Velocity**: Debugging time is inversely proportional to visibility. Opaque systems require hours to debug; transparent systems require minutes.
|
||||
- **Proactive Maintenance**: Visibility allows admins to spot trends (e.g., rising error rates) before they become outages.
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. Semantic Dashboards, Not Just Logs
|
||||
Don't just stream text logs. Aggregate state into meaningful views.
|
||||
- **Bad**: A log stream showing "User X updated Token Y".
|
||||
- **Good**: A "Recent Token Activity" widget showing a heatmap of updates by user and component.
|
||||
|
||||
#### 2. Real-Time State Reflection
|
||||
Admin UIs must subscribe to state changes, not poll for them.
|
||||
- Use WebSockets or Server-Sent Events (SSE) to push updates.
|
||||
- If a deployment status changes, the Admin UI updates immediately.
|
||||
|
||||
#### 3. Correlated Telemetry
|
||||
Every error visible in the Admin UI must link directly to:
|
||||
- The Trace ID.
|
||||
- The User ID involved.
|
||||
- The exact System State version at that moment.
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **Unified Logging**: All services emit structured JSON logs to a central aggregator accessible by Admin tools.
|
||||
- [ ] **State Inspection Tools**: MCP tools exist to query the raw state of any component (`get_component_state`, `inspect_queue`).
|
||||
- [ ] **Deployment Observability**: Admins can see the exact step-by-step progress of any active deployment.
|
||||
- [ ] **Error aggregation**: Repeated errors are grouped, counted, and ranked by severity on the dashboard.
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **SSH Debugging**: If an admin has to SSH into a container to check a log file, Visibility has failed.
|
||||
- **"It works on my machine"**: Admin views differ from actual system state due to caching or separate data paths.
|
||||
- **Opaque Queues**: Background jobs are processing, but the Admin UI shows no indication of queue depth or latency.
|
||||
- **Silent Failures**: A process fails but reports "Success" to the UI because the API call technically succeeded (even if the job failed).
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **Linting**: CI checks reject code that uses `console.log` instead of the structured logger.
|
||||
- **Contract Testing**: Every MCP tool must return a standard `telemetry` object containing trace IDs.
|
||||
- **Chaos Testing**: Deliberately break a service in staging; verify the Admin UI accurately reports the *specific* error within <5 seconds.
|
||||
|
||||
### Success Metrics
|
||||
- **MTTD (Mean Time To Detect)**: < 1 minute for critical failures.
|
||||
- **UI Latency**: Admin dashboard reflects system state changes within 500ms.
|
||||
- **Coverage**: 100% of background processes have visible status indicators in the Admin UI.
|
||||
|
||||
---
|
||||
|
||||
## 2. Admin Authority (Guardrails, Not God Mode)
|
||||
|
||||
### Core Concept
|
||||
Admins have high privileges, but they are **not** above the law. The "law" is defined by the immutable contracts (`API_CONTRACTS.md`, `ARCHITECTURE.md`). Admin tools are powerful agents of the system, but they cannot force the system into an invalid state or override versioned constraints without a formal schema change.
|
||||
|
||||
### Why It Matters
|
||||
- **Integrity**: If admins can bypass validation logic, data corruption is inevitable.
|
||||
- **Consistency**: The system behaves predictably only if rules apply to everyone, including admins.
|
||||
- **Safety**: Preventing "God Mode" prevents accidental catastrophic deletion or misconfiguration.
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. Validated Mutations Only
|
||||
Admin actions go through the exact same API validation pipes as user actions.
|
||||
- **Do not** write directly to the database.
|
||||
- **Do** call the `SystemMutation` API which enforces schemas.
|
||||
|
||||
#### 2. Immutable Contract Protection
|
||||
Admin UIs cannot modify Tier 1 documents directly.
|
||||
- To change a contract, an Admin must trigger a **Proposal Workflow** (which creates a PR/Version Bump).
|
||||
- Admins approve/merge changes; they do not "edit" them in a WYSIWYG editor.
|
||||
|
||||
#### 3. Bounded Scope
|
||||
Admin tokens have scopes. A "User Admin" cannot modify "System Architecture". A "Deployment Admin" cannot "Delete Users".
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **No Direct DB Access**: Admin API endpoints use the core service layer, never raw SQL.
|
||||
- [ ] **Contract Validation**: Every admin input is validated against the Zod schemas defined in `API_CONTRACTS.md`.
|
||||
- [ ] **Immutable File Locks**: The file system prevents the Admin process from writing to `docs/01_core/` except via specific versioning tools.
|
||||
- [ ] **Role Scopes**: JWT tokens for admins contain specific scopes (`admin:users`, `admin:deploy`, `admin:full`).
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **"Force" Flags**: API parameters like `?force=true` that bypass validation logic.
|
||||
- **Direct SQL Tools**: An admin panel that is just a GUI over a raw SQL query.
|
||||
- **Contract Overrides**: Admin tools that allow changing a Design Token's type from "color" to "spacing" without a major version bump.
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **Middleware**: API middleware explicitly checks for "Immutable" targets and rejects modifications.
|
||||
- **Code Review**: Any PR introducing a "bypass validation" function is automatically flagged for architectural review.
|
||||
- **Penetration Testing**: Attempt to use Admin API to inject invalid data; system must reject it with 400 Bad Request.
|
||||
|
||||
### Success Metrics
|
||||
- **Contract Violations**: 0 successful admin actions that violate a defined schema.
|
||||
- **Drift**: 0 discrepancies between the file-system contracts and the runtime database state.
|
||||
|
||||
---
|
||||
|
||||
## 3. Admin Accountability (The Audit Trail)
|
||||
|
||||
### Core Concept
|
||||
Every action taken by an admin is a signed, timestamped, and immutable record. There is no concept of an "anonymous admin" or "system action" without attribution. Accountability is non-repudiation.
|
||||
|
||||
### Why It Matters
|
||||
- **Security**: In the event of a breach, we must know exactly which account was compromised and what they did.
|
||||
- **Compliance**: Many regulatory standards (SOC2, HIPAA) require strict access logging.
|
||||
- **Rollback**: To undo a mistake, you must know exactly what the mistake was and the state before it happened.
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. The 5 Ws of Logging
|
||||
Every Audit Log entry must contain:
|
||||
- **Who**: User ID + IP Address + Session ID.
|
||||
- **What**: The specific operation (Tool Name + Arguments).
|
||||
- **Where**: The resource ID affected.
|
||||
- **When**: ISO 8601 Timestamp (UTC).
|
||||
- **Why**: (Optional) A "Reason" field for sensitive actions (e.g., "Deleting user X per GDPR request").
|
||||
|
||||
#### 2. Immutable Audit Store
|
||||
Audit logs are write-only.
|
||||
- Admin tools cannot delete or modify audit logs.
|
||||
- Ideally, ship logs immediately to an external secure storage (S3 Object Lock, Datadog, etc.).
|
||||
|
||||
#### 3. Session Context
|
||||
If an Admin assumes another user's identity (Impersonation), the log must reflect:
|
||||
`Actor: Admin_Alice acting_as User_Bob`.
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **Audit Middleware**: Global interceptor on all `/admin/*` routes that records the request/response.
|
||||
- [ ] **Reason Prompts**: UI modals that force admins to type a reason before performing destructive actions (Delete, Ban, Force Deploy).
|
||||
- [ ] **Read-Only Audit UI**: A dedicated page in the Admin panel to search/filter audit logs (no delete button).
|
||||
- [ ] **Export Capability**: Ability to export logs for external compliance review.
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **Shared Credentials**: "admin@company.com" used by 5 different people.
|
||||
- **Generic "System" Logs**: Changes attributed to "System" when they were actually triggered by a human button press.
|
||||
- **Missing Context**: A log saying "Updated Config" without showing *what* changed (diff).
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **Database Triggers**: Prevent `UPDATE` or `DELETE` operations on the `audit_logs` table.
|
||||
- **Schema Validation**: Ensure `actor_id` is a required field in the AuditEvent schema.
|
||||
- **Regular Audits**: Automated weekly report sending a summary of Admin actions to the CTO/Lead.
|
||||
|
||||
### Success Metrics
|
||||
- **Attribution Rate**: 100% of state-changing operations have a linked human Actor ID.
|
||||
- **Audit Lag**: Time from Action -> Audit Log availability < 1 second.
|
||||
|
||||
---
|
||||
|
||||
## 4. Admin-Developer Partnership
|
||||
|
||||
### Core Concept
|
||||
Clear separation of concerns strengthens the system. Developers propose and implement; Admins approve, monitor, and enforce. Admins do not write code in production; Developers do not restart production services manually.
|
||||
|
||||
### Why It Matters
|
||||
- **Stability**: Prevents "hot fixes" that bypass CI/CD and review processes.
|
||||
- **Focus**: Developers focus on feature velocity; Admins focus on system reliability and governance.
|
||||
- **Checks and Balances**: Requires two distinct approvals for major changes (Code Review + Deployment Approval).
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. Promotion Workflows
|
||||
Developers push to `staging`. Admin tools control the gate from `staging` -> `production`.
|
||||
- The Admin UI shows "Pending Changes" (diffs).
|
||||
- The Admin clicks "Promote" to execute the deployment.
|
||||
|
||||
#### 2. Feedback Loops
|
||||
Admin tools provide feedback to developers.
|
||||
- If a deployment fails, the Admin tool generates a report linked to the Developer's commit.
|
||||
- Developers consume "Admin" metrics (performance, errors) via their own views/tools.
|
||||
|
||||
#### 3. Configuration Management
|
||||
Developers define "Default Config" in code. Admins manage "Environment Config" (secrets, scaling limits) in the platform.
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **Deployment Gates**: Production deployments require an explicit Admin approval signal (API call or UI click).
|
||||
- [ ] **Environment Isolation**: Developers have full access to Dev/Staging; Read-only access to Production.
|
||||
- [ ] **Service Catalog**: Admin UI lists all services with their "Owner" (Developer Team) clearly contactable.
|
||||
- [ ] **Incident Routing**: Admin tools automatically route alerts to the specific developer/team who owns the failing component.
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **Hot-Patching**: Admins editing script files directly on the server to fix a bug.
|
||||
- **Cowboy Deploys**: Developers bypassing the Admin gate to push directly to production.
|
||||
- **Vague Ownership**: A service crashes and Admins don't know which Developer to page.
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **CI/CD Pipelines**: Pipeline explicitly halts at `Staging` and waits for an `AdminApproval` signal.
|
||||
- **RBAC**: Developer accounts have `READ` permission on Prod; Admin accounts have `DEPLOY` permission.
|
||||
|
||||
### Success Metrics
|
||||
- **Change Failure Rate**: < 1% of promotions to production result in rollback.
|
||||
- **MTTR (Mean Time To Recovery)**: Reduced by clear ownership routing.
|
||||
|
||||
---
|
||||
|
||||
## 5. Admin Isolation (The Lifeboat Principle)
|
||||
|
||||
### Core Concept
|
||||
The Admin Plane is distinct from the Data Plane. If the user-facing application crashes, is under DDoS attack, or the database is locked, the Admin tools **must still function**. You cannot fix a broken system if the tool you use to fix it is also broken.
|
||||
|
||||
### Why It Matters
|
||||
- **Resilience**: The admin panel is the lifeboat. It must float when the ship sinks.
|
||||
- **Security**: Isolating admin traffic prevents vectoring attacks from public endpoints to admin tools.
|
||||
- **Resource Contention**: Heavy user load shouldn't make the Admin dashboard sluggish.
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. Separate Infrastructure
|
||||
Ideally, run Admin tools on separate containers/pods or even a separate cluster/network.
|
||||
- Separate subdomains (`admin.internal` vs `app.com`).
|
||||
- Separate ingress controllers to prevent bandwidth starvation.
|
||||
|
||||
#### 2. Dedicated Resources
|
||||
Admin API limits are distinct from User API limits.
|
||||
- If users are rate-limited, Admins are not.
|
||||
- Reserve compute/memory specifically for Admin operations.
|
||||
|
||||
#### 3. Out-of-Band Access
|
||||
Maintain a "break-glass" mechanism.
|
||||
- If the API is totally unresponsive, have a CLI tool or direct operational port that bypasses the main load balancer.
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **Separate Build**: Admin App is a separate build artifact from the User App.
|
||||
- [ ] **Connection Pooling**: Admin tools use a dedicated database connection pool (so user load doesn't starve admin access).
|
||||
- [ ] **External Monitoring**: Admin uptime is monitored from an external location (e.g., UptimeRobot) distinct from user monitoring.
|
||||
- [ ] **Failover Testing**: Simulate a 100% CPU load on the User App; verify Admin App loads instantly.
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **Monolith Integration**: Admin routes (`/admin`) served by the exact same Express/FastAPI instance as user traffic.
|
||||
- **Shared Rate Limits**: Admin gets 429 Too Many Requests because users are spamming the API.
|
||||
- **Single Point of Failure**: The Auth service goes down, locking Admins out of the system they need to fix.
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **Infrastructure as Code**: Terraform/Docker Compose defines explicit resource reservations for `admin-service`.
|
||||
- **Load Testing**: Load tests specifically target the user plane while simultaneously measuring admin plane latency.
|
||||
|
||||
### Success Metrics
|
||||
- **Admin Availability**: > 99.99% (higher than User Availability).
|
||||
- **Latency during Incident**: Admin latency increases < 10% during high-severity user-facing incidents.
|
||||
|
||||
---
|
||||
|
||||
## 6. Role-Based Configuration & Visibility (The One-Click Pattern)
|
||||
|
||||
### Core Concept
|
||||
Admin configures the system **once** (immutable, versioned). All teams access **only their relevant features** via role-based access control (RBAC). Operations flow from admin configuration without requiring teams to re-enter information. Components are automatically discovered (not manually imported via URLs). Configuration hierarchy flows: System Settings (Admin) → Project Settings (Admin/Team) → User Secrets (Encrypted per-user).
|
||||
|
||||
### Why It Matters
|
||||
- **Velocity**: Teams don't spend time reconfiguring Figma URLs, Storybook paths, or Jira credentials. Admin sets once, everyone uses.
|
||||
- **Consistency**: System-wide configuration ensures all teams operate with identical understanding of component locations, credentials, and settings.
|
||||
- **Governance**: Single source of truth for configuration means auditing, compliance, and rollback are straightforward.
|
||||
- **Autonomy**: Each team sees only the features they need—no cognitive overload, no accidental admin access.
|
||||
|
||||
### How to Apply
|
||||
|
||||
#### 1. Configuration Hierarchy (Immutable Contracts)
|
||||
Create a three-tier configuration model:
|
||||
|
||||
**Tier 1: System Configuration** (Immutable, Admin-only)
|
||||
```
|
||||
{
|
||||
"system_id": "dss-v2",
|
||||
"version": "2.1.0",
|
||||
"figma_api_base": "https://api.figma.com",
|
||||
"atlassian_api_base": "https://api.atlassian.cloud",
|
||||
"storybook_base_url": "https://storybook.designsystem.internal",
|
||||
"component_registry_update_interval": "5m",
|
||||
"audit_retention_days": 365
|
||||
}
|
||||
```
|
||||
|
||||
**Tier 2: Project Configuration** (Versioned, Admin/Team-settable)
|
||||
```
|
||||
{
|
||||
"project_id": "tokens-library",
|
||||
"figma_file_id": "abc123xyz",
|
||||
"figma_team_id": "team456",
|
||||
"storybook_project_path": "/projects/tokens",
|
||||
"jira_project_key": "TOKENS",
|
||||
"slack_channel": "#tokens-alerts",
|
||||
"skin_selection": ["material", "ios"],
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Tier 3: User Secrets** (Encrypted, Per-user)
|
||||
```
|
||||
{
|
||||
"user_id": "alice@company.com",
|
||||
"figma_api_key": "[encrypted]",
|
||||
"atlassian_api_token": "[encrypted]",
|
||||
"slack_bot_token": "[encrypted]"
|
||||
}
|
||||
```
|
||||
|
||||
Each tier is versioned separately. Changes to Tier 2 trigger a MINOR version bump (per Principle 2). Changes require audit trail logging.
|
||||
|
||||
#### 2. Component Registry (Automatic Discovery)
|
||||
Don't ask admins for component URLs. Instead:
|
||||
- Admin enables "Component Indexing" once
|
||||
- System polls/watches component sources (Figma, Git, Storybook) on configurable interval
|
||||
- All components automatically registered with metadata (name, path, Figma ID, Storybook URL, owner)
|
||||
- Teams query registry by name, project, or tag
|
||||
|
||||
```
|
||||
Component Registry Entry:
|
||||
{
|
||||
"name": "Button",
|
||||
"project": "tokens-library",
|
||||
"figma_component_id": "comp:123",
|
||||
"figma_url": "https://figma.com/file/...",
|
||||
"storybook_url": "https://storybook/...",
|
||||
"last_indexed": "2025-12-08T14:23:00Z",
|
||||
"owner": "UI Team"
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Team-Specific Dashboards (Role-Based Views)
|
||||
Each team sees a customized portal:
|
||||
|
||||
**Admin Dashboard:**
|
||||
- System settings (configuration, version management)
|
||||
- Project creation & onboarding
|
||||
- User management & key rotation
|
||||
- Audit logs & compliance reports
|
||||
- Team role assignments
|
||||
|
||||
**UI Team Dashboard:**
|
||||
- Figma extract (one-click sync with change detection)
|
||||
- QuickWins analysis (non-breaking improvements)
|
||||
- Regression tool (full style migration to DSS)
|
||||
- Metrics & performance trends
|
||||
|
||||
**UX Team Dashboard:**
|
||||
- Component listing (filterable, linked to Storybook + Figma)
|
||||
- Token listing (with update/export options)
|
||||
- Icon listing (with usage counts)
|
||||
- Figma plugin customization & download
|
||||
- Metrics dashboard
|
||||
|
||||
**QA Team Dashboard:**
|
||||
- Metrics dashboard
|
||||
- Component listing (with comparison links)
|
||||
- ESRE text area (testing)
|
||||
- Component screenshot comparison (create issues)
|
||||
- Jira issues list (assignable, linked)
|
||||
|
||||
**All Teams:**
|
||||
- Metrics frontpage (error rate, deployment health, sync status)
|
||||
- AI chat sidebar (collapsable, for design questions/suggestions)
|
||||
- Jira integration (view & create issues)
|
||||
|
||||
#### 4. One-Click Operations Pattern
|
||||
Once admin configures Figma URL, Storybook path, and Jira project:
|
||||
- UI team clicks "Extract from Figma" → system uses pre-configured Figma ID + credentials
|
||||
- UX team clicks "Component Comparison" → system loads Storybook + Figma automatically
|
||||
- QA team clicks "Create Issue" → system pre-fills with component metadata
|
||||
- No re-prompts, no manual URL entry
|
||||
|
||||
### Implementation Checklist
|
||||
- [ ] **Configuration Schema**: Define Tier 1 (system), Tier 2 (project), Tier 3 (user) schemas in TypeScript
|
||||
- [ ] **Configuration Versioning**: Track version history, enable rollback to previous config
|
||||
- [ ] **Component Registry**: Implement indexer that scans Figma, Git, Storybook on interval
|
||||
- [ ] **RBAC Middleware**: Middleware that filters dashboard features based on user role
|
||||
- [ ] **Dashboard Routing**: Separate Next.js routes for /admin, /ui-team, /ux-team, /qa-team
|
||||
- [ ] **Encrypted Secrets**: Use libsodium or similar for Tier 3 user secrets
|
||||
- [ ] **Config API Endpoints**: GET /api/config/system, GET /api/config/project/{id}, POST /api/config/validate
|
||||
- [ ] **Team Feature Flags**: Runtime flags for which teams see which features
|
||||
- [ ] **One-Click Tests**: Verify each team's quick-action buttons work with pre-configured values
|
||||
|
||||
### Red Flags (Anti-Patterns)
|
||||
- **Hardcoded Credentials**: Team code contains hardcoded Figma tokens or API keys
|
||||
- **Manual Configuration Prompts**: Team operations prompt for URLs ("Enter Figma URL...") instead of using config
|
||||
- **Config Duplication**: Same Figma URL stored in multiple places (settings file, env vars, database)
|
||||
- **No Registry**: Admins manually track which components exist; teams ask for component URLs
|
||||
- **Shared Dashboards**: All teams see all features, including admin-only config screens
|
||||
- **Stale Configuration**: Config doesn't update when projects move or credentials rotate
|
||||
|
||||
### Enforcement Mechanisms
|
||||
- **Pre-commit Hooks**: Reject code commits containing Figma API keys or URLs
|
||||
- **Secrets Scanning**: Automated detection of leaked credentials in logs
|
||||
- **Config Validation**: Every config change is schema-validated before persisting
|
||||
- **RBAC Testing**: Jest tests verify each role sees only their features
|
||||
- **Integration Tests**: "One-click" operations tested end-to-end with real Figma/Storybook calls
|
||||
- **Audit Logging**: Every config access/change logged with actor, timestamp, diff
|
||||
|
||||
### Success Metrics
|
||||
- **Configuration Centralization**: 100% of credentials and URLs stored in config, 0 in code
|
||||
- **Component Discovery**: 100% of components auto-indexed, admin never manually registers
|
||||
- **Team Independence**: Each team can complete their tasks without asking admin for URLs
|
||||
- **One-Click Success Rate**: > 95% of team quick-actions complete without additional input
|
||||
- **Configuration Drift**: < 2% discrepancy between config and runtime state
|
||||
- **Credential Rotation**: User can rotate API keys in < 2 minutes with no team disruption
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-09
|
||||
**Version**: 2.0.0 (Added Principle 6: Role-Based Configuration & Visibility)
|
||||
**Status**: PRODUCTION - All 6 principles active and enforced
|
||||
737
docs/01_core/ANTI_PATTERNS_AND_LEARNINGS.md
Normal file
737
docs/01_core/ANTI_PATTERNS_AND_LEARNINGS.md
Normal file
@@ -0,0 +1,737 @@
|
||||
# Anti-Patterns & Learnings from DSS Implementation
|
||||
|
||||
**Version 1.0.0** | Last Updated: 2025-12-08 | Status: Production
|
||||
|
||||
This document catalogs **what not to do** and lessons learned from DSS implementation. When you see these patterns, they're usually violations of one or more core principles.
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 1: Shadow Config
|
||||
|
||||
**What It Is**: Configuration that lives in multiple places (code comments, README, config file) with different values.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 3** (Single Source of Truth). Developers don't know which is the actual value.
|
||||
|
||||
### Example
|
||||
|
||||
```python
|
||||
# Code comment in middleware.py
|
||||
timeout = 30 # Timeout is 30 seconds
|
||||
|
||||
# docs/README.md
|
||||
"Configure timeout (default 60 seconds)"
|
||||
|
||||
# config.json
|
||||
{
|
||||
"timeout": 90
|
||||
}
|
||||
|
||||
# Which is right? 🤔
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Find hardcoded values in code
|
||||
grep -r "timeout" code/src/ | grep -v config
|
||||
|
||||
# Compare with actual config values
|
||||
grep "timeout" config.json
|
||||
|
||||
# Check README for contradictions
|
||||
grep -i "timeout" README.md
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Identify the source of truth**
|
||||
- Where should this value live? (config file, environment variable, database)
|
||||
- This is now the ONLY place
|
||||
|
||||
2. **Update everywhere else to reference it**
|
||||
```python
|
||||
# WRONG:
|
||||
timeout = 30
|
||||
|
||||
# RIGHT:
|
||||
timeout = config.get("timeout", default=30)
|
||||
|
||||
# README:
|
||||
"See config.json for timeout (default 30 seconds)"
|
||||
```
|
||||
|
||||
3. **Remove copies**
|
||||
- Delete hardcoded values from code
|
||||
- Delete from comments
|
||||
- Leave only reference
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] Identify canonical config location (config file, env, DB)
|
||||
- [ ] Code loads from canonical location
|
||||
- [ ] Comments reference canonical source
|
||||
- [ ] README points to config file, not duplicate values
|
||||
- [ ] No hardcoded values elsewhere
|
||||
- [ ] CI check: Detect hardcoded values (grep patterns)
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 2: Lying Docstring
|
||||
|
||||
**What It Is**: Documentation that doesn't match implementation.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 2** (Contracts are Immutable). Code is the real contract; docstring is a lie.
|
||||
|
||||
### Example
|
||||
|
||||
```python
|
||||
def sync_tokens():
|
||||
"""Syncs Figma tokens to project (synchronous operation)"""
|
||||
|
||||
# Actually async now, but docstring wasn't updated
|
||||
async def _sync():
|
||||
await figma_api.fetch(...)
|
||||
|
||||
asyncio.create_task(_sync()) # Non-blocking, returns immediately
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Check function signatures vs docstrings
|
||||
# Look for mismatches:
|
||||
# - Says synchronous but returns Promise/Task
|
||||
# - Says required but marked optional
|
||||
# - Says returns X but actually returns Y
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Update docstring to match code**
|
||||
```python
|
||||
def sync_tokens():
|
||||
"""Syncs Figma tokens to project (async operation).
|
||||
|
||||
Returns:
|
||||
asyncio.Task - Handle to running sync operation
|
||||
"""
|
||||
```
|
||||
|
||||
OR
|
||||
|
||||
2. **Update code to match docstring**
|
||||
```python
|
||||
def sync_tokens(): # If contract says synchronous
|
||||
"""Syncs Figma tokens to project (synchronous operation)."""
|
||||
result = asyncio.run(_sync()) # Block until done
|
||||
return result
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] Docstring describes actual behavior
|
||||
- [ ] Parameter types match signature
|
||||
- [ ] Return type matches what's returned
|
||||
- [ ] Exceptions match what's thrown
|
||||
- [ ] Usage examples work as-is
|
||||
- [ ] CI check: Parse docstrings and compare with signature
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 3: Ghost Script
|
||||
|
||||
**What It Is**: Old deployment/setup script that nobody maintains but everyone fears deleting.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 3** (Single Source of Truth). Unclear if it's still used, causing confusion and maintenance burden.
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
repo/
|
||||
├── deploy_v1.sh (2023, obsolete)
|
||||
├── deploy_v2.sh (2024, semi-used)
|
||||
├── deploy_v3.sh (2025, current)
|
||||
└── deploy_test.sh (unknown origin)
|
||||
|
||||
Question: Which one do we use? Nobody knows for sure.
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Find all deployment scripts
|
||||
find . -name "*deploy*" -type f
|
||||
|
||||
# Check git history: when was it last modified?
|
||||
git log --oneline -- deploy_v1.sh | head -5
|
||||
|
||||
# Check: is it referenced in docs?
|
||||
grep -r "deploy_v1" docs/
|
||||
|
||||
# Check: does CI/CD use it?
|
||||
grep -r "deploy_v1" .github/workflows/
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
**Option 1: Archive It**
|
||||
```bash
|
||||
mkdir -p archived/scripts/deployment
|
||||
mv deploy_v1.sh archived/scripts/deployment/2025-12-08_deploy_v1.sh
|
||||
|
||||
# Add README explaining why archived
|
||||
cat > archived/scripts/deployment/README.md <<EOF
|
||||
# Archived Deployment Scripts
|
||||
|
||||
## deploy_v1.sh
|
||||
Archived: 2025-12-08
|
||||
Reason: Replaced by deploy_v3.sh (supports containers, faster rollback)
|
||||
Reference: See DEPLOYMENT_GUIDE.md for current process
|
||||
EOF
|
||||
```
|
||||
|
||||
**Option 2: Delete It**
|
||||
```bash
|
||||
# If truly unused:
|
||||
git rm deploy_v1.sh
|
||||
git commit -m "remove: Delete obsolete deploy_v1.sh (replaced by v3)"
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] Audit all deployment scripts
|
||||
- [ ] Identify which are actively used
|
||||
- [ ] Delete unused scripts OR archive with reason
|
||||
- [ ] Document which script is current in DEPLOYMENT_GUIDE.md
|
||||
- [ ] Update CI/CD to use only current version
|
||||
- [ ] Prevent committing ghost scripts: CI check for script age
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 4: Wiki Rot
|
||||
|
||||
**What It Is**: Markdown files that were never updated after creation. Over time they become stale, misleading documentation.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 3** (Current State Transparency). Readers follow outdated advice.
|
||||
|
||||
### Example
|
||||
|
||||
```markdown
|
||||
# DEPLOYMENT_GUIDE_2024.md
|
||||
|
||||
Last Updated: 2024-01-15
|
||||
|
||||
To deploy:
|
||||
1. SSH into prod-server-old
|
||||
2. Run `node deploy.js`
|
||||
3. Wait 30 minutes
|
||||
4. Check http://old-dashboard.com/status
|
||||
|
||||
<!-- This guide is now completely wrong -->
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Find markdown files not updated in 60+ days
|
||||
find . -name "*.md" -type f -mtime +60 | head -20
|
||||
|
||||
# Check git log: when was it last changed?
|
||||
git log -1 --format="%ai" -- DEPLOYMENT_GUIDE.md
|
||||
|
||||
# Look for "Last Updated" field
|
||||
grep -r "Last Updated" docs/ | awk -F: '{print $NF}' | sort
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Review and Update**
|
||||
```bash
|
||||
# For each stale doc:
|
||||
1. Read it thoroughly
|
||||
2. Check if process still accurate
|
||||
3. Update with current reality
|
||||
4. Change "Last Updated" date
|
||||
5. Commit with "docs: Update GUIDE.md for 2025"
|
||||
```
|
||||
|
||||
2. **Or Archive It**
|
||||
```bash
|
||||
mkdir -p docs/archive/2024
|
||||
mv DEPLOYMENT_GUIDE_2024.md docs/archive/2024/
|
||||
|
||||
# Create new one for current year
|
||||
cp DEPLOYMENT_GUIDE_TEMPLATE.md DEPLOYMENT_GUIDE.md
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] All active docs have "Last Updated" field
|
||||
- [ ] Timestamp is within last 30 days
|
||||
- [ ] Docs reviewed regularly (monthly audit)
|
||||
- [ ] Stale docs archived immediately
|
||||
- [ ] CI check: Fail if doc older than 90 days
|
||||
- [ ] Process: Every PR that changes process updates related docs
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 5: Sprint Spec
|
||||
|
||||
**What It Is**: Technical specification written during sprint planning, never consolidated into permanent documentation.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 3** (Single Source of Truth). Knowledge lost when sprint ends. Phases become documentation.
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
Phase 5D - Token Merge System
|
||||
│
|
||||
├── SPRINT_15_TECH_SPEC.md (contains API design details)
|
||||
├── PHASE_5D_PLANNING.md (implementation approach)
|
||||
├── PHASE_5D_FINAL_REPORT.md (what was actually built)
|
||||
│
|
||||
└── docs/01_core/API_CONTRACTS.md (empty—didn't update this!)
|
||||
```
|
||||
|
||||
Problem: If someone asks "what API does token merge use?" the answer is scattered across 3 phase docs, not in the canonical API_CONTRACTS.md.
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Find phase-named files
|
||||
find . -maxdepth 1 -name "*PHASE*" -o -name "*SPRINT*" -o -name "*WEEK*"
|
||||
|
||||
# Check: Are these in root or in archive?
|
||||
ls -la | grep -i "phase\|sprint\|week"
|
||||
|
||||
# Scan for technical specs in phase files
|
||||
grep -l "endpoint\|API\|schema" PHASE_*.md
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Extract Technical Content**
|
||||
```
|
||||
OLD (scattered):
|
||||
SPRINT_15_TECH_SPEC.md has API design
|
||||
ARCHITECTURE.md is generic
|
||||
|
||||
NEW (consolidated):
|
||||
ARCHITECTURE.md updated with token merge design
|
||||
API_CONTRACTS.md has full endpoint specs
|
||||
SPRINT_15_TECH_SPEC.md archived (reference only)
|
||||
```
|
||||
|
||||
2. **Extract Decision Rationale**
|
||||
```
|
||||
OLD (in phase report):
|
||||
"We chose token merge because Figma + CSS coexist"
|
||||
|
||||
NEW (in ADR):
|
||||
.knowledge/adrs/ADR-001-token-merge.md
|
||||
Context: Why this matters
|
||||
Decision: Token merge approach
|
||||
Alternatives: What we considered
|
||||
Consequences: Trade-offs
|
||||
```
|
||||
|
||||
3. **Archive Phase Documents**
|
||||
```bash
|
||||
mkdir -p docs/archive/phases/phase-5d
|
||||
mv PHASE_5D_PLANNING.md docs/archive/phases/phase-5d/
|
||||
mv SPRINT_15_TECH_SPEC.md docs/archive/phases/phase-5d/
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] All technical specs extracted to Tier 1 (API_CONTRACTS.md, ARCHITECTURE.md)
|
||||
- [ ] All decision rationale extracted to ADRs
|
||||
- [ ] All status updates consolidated to PROJECT_STATUS.md
|
||||
- [ ] Phase docs archived immediately (not left in root)
|
||||
- [ ] API_CONTRACTS.md updated with all new endpoints
|
||||
- [ ] CI check: Fail if *PHASE_*.md, *SPRINT_*.md found in root
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 6: Version Chaos
|
||||
|
||||
**What It Is**: Files change without corresponding version bumps, or versions are bumped arbitrarily.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 2** (Contracts are Immutable and Versioned). External systems can't pin to stable versions.
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
API_CONTRACTS.md:
|
||||
v1.0.0 (2025-11-01): Initial version
|
||||
|
||||
2025-11-05: "Added timeout to GET /sync" (no version bump!)
|
||||
2025-11-10: "Changed response schema" (no version bump!)
|
||||
2025-12-01: "Version 1.5.0" (what changed? no changelog!)
|
||||
|
||||
Consumer can't trust version numbers or stable APIs.
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Check if version matches commit history
|
||||
git log --all --oneline -- API_CONTRACTS.md | head -20
|
||||
|
||||
# Count changes without version bumps
|
||||
git diff v1.0.0..HEAD -- API_CONTRACTS.md | wc -l
|
||||
|
||||
# Find missing changelogs
|
||||
ls -la docs/*CHANGELOG* docs/*VERSION*
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Establish Versioning Discipline**
|
||||
```
|
||||
Every change to Tier 1 files:
|
||||
1. Decide: MAJOR, MINOR, or PATCH
|
||||
2. Update version in file
|
||||
3. Add changelog entry (what, why, migration path)
|
||||
4. Commit with message: "v1.2.0: Add new endpoint"
|
||||
5. Tag commit: git tag v1.2.0
|
||||
```
|
||||
|
||||
2. **Create Changelog**
|
||||
```markdown
|
||||
# API_CONTRACTS.md Changelog
|
||||
|
||||
## v1.2.0 (2025-12-08)
|
||||
|
||||
### Added
|
||||
- GET /api/tokens/resolve endpoint (per-project token lookup)
|
||||
|
||||
### Changed
|
||||
- POST /api/tokens/merge now supports PREFER_SPECIFIC strategy
|
||||
|
||||
### Deprecated
|
||||
- GET /api/v1/projects/{id} (use v2 endpoint instead)
|
||||
|
||||
### Migration
|
||||
See MIGRATION_GUIDE.md for upgrading from v1.1.0
|
||||
```
|
||||
|
||||
3. **Establish Review Process**
|
||||
```
|
||||
PR template asks:
|
||||
- [ ] Version bumped?
|
||||
- [ ] Changelog entry?
|
||||
- [ ] Breaking changes documented?
|
||||
- [ ] Migration path provided?
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] All Tier 1 files have version numbers
|
||||
- [ ] Version follows semver (MAJOR.MINOR.PATCH)
|
||||
- [ ] Every change bumps version
|
||||
- [ ] Changelog entries for each version
|
||||
- [ ] Git tags for each release
|
||||
- [ ] Breaking changes clearly marked
|
||||
- [ ] Migration guides for breaking changes
|
||||
- [ ] CI check: Fail if file changed but version didn't
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 7: Dead Documentation
|
||||
|
||||
**What It Is**: Documentation files that reference each other but neither is updated, creating a closed loop of outdated information.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 3** (Single Source of Truth). Difficult to know which is the source.
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
README.md says:
|
||||
"For full details see DEPLOYMENT_GUIDE.md"
|
||||
|
||||
DEPLOYMENT_GUIDE.md says:
|
||||
"For overview see README.md"
|
||||
|
||||
Both are outdated (last updated 2024-06):
|
||||
Neither is maintained
|
||||
Both reference each other in circles
|
||||
Neither is authoritative
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Find cross-references between docs
|
||||
grep -h "See.*\.md\|For.*see" docs/*.md | sort | uniq -c
|
||||
|
||||
# Check which docs are circular references
|
||||
# (if A links to B, B links to A, probably one is dead)
|
||||
|
||||
# Check update frequency
|
||||
git log --all --pretty=format:"%h %ar %s" -- docs/README.md docs/DEPLOYMENT_GUIDE.md
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Establish Single Authority**
|
||||
```
|
||||
Choose: Which document is the source of truth?
|
||||
|
||||
Option A: README.md is overview (entry point)
|
||||
DEPLOYMENT_GUIDE.md is detailed (reference)
|
||||
|
||||
Option B: DEPLOYMENT_GUIDE.md is source
|
||||
README.md just links to it
|
||||
```
|
||||
|
||||
2. **Remove Circular References**
|
||||
```markdown
|
||||
# Good structure:
|
||||
|
||||
README.md:
|
||||
"To deploy: See DEPLOYMENT_GUIDE.md"
|
||||
(just one link, no attempt to explain deployment)
|
||||
|
||||
DEPLOYMENT_GUIDE.md:
|
||||
Full deployment instructions
|
||||
(no need to reference README)
|
||||
```
|
||||
|
||||
3. **Update Ownership**
|
||||
```bash
|
||||
# In CODEOWNERS or project docs:
|
||||
|
||||
README.md: @team-leads
|
||||
DEPLOYMENT_GUIDE.md: @devops-team
|
||||
|
||||
Schedule monthly reviews
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] Identify which doc is authoritative
|
||||
- [ ] Remove redundant explanations
|
||||
- [ ] Use one-way links (source → dependent)
|
||||
- [ ] Establish ownership for each doc
|
||||
- [ ] Schedule regular reviews (monthly)
|
||||
- [ ] Update timestamp on every review (even if no changes)
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern 8: Implicit Contracts
|
||||
|
||||
**What It Is**: Component or API behavior that's "understood" but never documented.
|
||||
|
||||
**Why It's Bad**: Breaks **Principle 4** (Decisions are Explicit and Traceable). When someone asks "why does it work this way?" there's no answer.
|
||||
|
||||
### Example
|
||||
|
||||
```typescript
|
||||
// Button component
|
||||
export function Button({ variant, disabled, onClick }) {
|
||||
// What happens if someone clicks a disabled button?
|
||||
// Click handler fires? Doesn't fire? Returns early?
|
||||
// There's no documentation, so developers guess.
|
||||
}
|
||||
```
|
||||
|
||||
### Detection
|
||||
|
||||
```bash
|
||||
# Look for undocumented behavior
|
||||
grep -r "TODO\|FIXME\|XXX" code/src/ | grep -i "undocumented\|behavior\|need to"
|
||||
|
||||
# Check component files for missing JSDoc
|
||||
find packages/components -name "*.tsx" -exec grep -L "@param\|@return" {} \;
|
||||
|
||||
# Check for implicit assumptions in tests
|
||||
grep "it should" tests/*.test.ts | grep -v "it should.*{" | head -5
|
||||
```
|
||||
|
||||
### How to Fix
|
||||
|
||||
1. **Document Component Contract**
|
||||
```typescript
|
||||
/**
|
||||
* Button component
|
||||
*
|
||||
* @param variant - Button style (primary, secondary, ghost)
|
||||
* @param disabled - If true, button is not interactive (click ignored)
|
||||
* @param onClick - Called when button clicked (not called if disabled)
|
||||
*
|
||||
* Behavior:
|
||||
* - Disabled button: visual change (opacity 50%), click handler NOT invoked
|
||||
* - Icon + text: text displayed, icon as prefix
|
||||
*/
|
||||
export function Button({ variant, disabled, onClick }) { ... }
|
||||
```
|
||||
|
||||
2. **Document API Behavior**
|
||||
```markdown
|
||||
# GET /api/tokens/{token_id}
|
||||
|
||||
Returns token definition by ID.
|
||||
|
||||
**Response (200):**
|
||||
{ id: string, name: string, value: string }
|
||||
|
||||
**Behavior:**
|
||||
- If token inherited from base theme, includes `inherits_from` field
|
||||
- If token has been overridden, includes `overridden_at` timestamp
|
||||
- Deleted tokens return 404
|
||||
|
||||
**Not documented:** Old behavior returned 200 with deleted_at field
|
||||
Deprecated in v1.3.0, removed in v2.0.0
|
||||
```
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] Every component has JSDoc with @param, @return
|
||||
- [ ] Every API endpoint documents behavior
|
||||
- [ ] Error cases documented
|
||||
- [ ] Edge cases documented
|
||||
- [ ] Assumptions documented
|
||||
- [ ] Links to related ADR if behavioral decision
|
||||
|
||||
---
|
||||
|
||||
## Learnings & Practices
|
||||
|
||||
### Learning 1: Versions Must Be Intentional
|
||||
|
||||
**The Hard Way:**
|
||||
```
|
||||
Team member updates API contract without bumping version.
|
||||
External consumer pins to "latest" without specifying version.
|
||||
Breaks. Consumer blames us. Trust eroded.
|
||||
```
|
||||
|
||||
**The Right Way:**
|
||||
```
|
||||
Establish: Version bumps are code reviews (never silent)
|
||||
External consumers: Always pin major version (>=1.0.0,<2.0.0)
|
||||
Breaking changes: Announced 6 months before removal
|
||||
```
|
||||
|
||||
### Learning 2: Duplicate Information Is a Technical Debt
|
||||
|
||||
**The Hard Way:**
|
||||
```
|
||||
API endpoint spec in 3 places:
|
||||
- API_CONTRACTS.md
|
||||
- README.md
|
||||
- Integration guide
|
||||
|
||||
Someone fixes bug in one place.
|
||||
Others become incorrect.
|
||||
Different consumers see different specs.
|
||||
```
|
||||
|
||||
**The Right Way:**
|
||||
```
|
||||
Spec lives in ONE place (API_CONTRACTS.md).
|
||||
Other docs link to it.
|
||||
Update once, everywhere is correct.
|
||||
```
|
||||
|
||||
### Learning 3: Status Stales Quickly
|
||||
|
||||
**The Hard Way:**
|
||||
```
|
||||
"Last Updated: 2025-10-01"
|
||||
It's now 2025-12-08 (2+ months old)
|
||||
Is it still accurate?
|
||||
Team doesn't know.
|
||||
```
|
||||
|
||||
**The Right Way:**
|
||||
```
|
||||
Weekly status review (every Friday)
|
||||
Automated reminders if stale
|
||||
CI/CD fails if status older than 7 days
|
||||
Before production deploy
|
||||
```
|
||||
|
||||
### Learning 4: ADRs Aren't Just for Major Decisions
|
||||
|
||||
**The Hard Way:**
|
||||
```
|
||||
Year later: "Why do we cache tokens this way?"
|
||||
Look at git history: "Cache tokens"
|
||||
No context. No alternatives considered. No rationale.
|
||||
Have to reverse-engineer decision.
|
||||
```
|
||||
|
||||
**The Right Way:**
|
||||
```
|
||||
Even medium decisions get ADRs:
|
||||
- Why caching (vs fetching each time)?
|
||||
- Cache TTL strategy?
|
||||
- What to do on cache miss?
|
||||
|
||||
Year later: Check ADR-NNN. All context there.
|
||||
```
|
||||
|
||||
### Learning 5: Tools Are Better Than Endpoints for Agents
|
||||
|
||||
**The Hard Way:**
|
||||
```
|
||||
Agent has to:
|
||||
1. Call HTTP endpoint (slow)
|
||||
2. Parse HTTP response
|
||||
3. Handle HTTP errors
|
||||
4. Implement retry logic
|
||||
|
||||
Result: Agent can't work autonomously.
|
||||
```
|
||||
|
||||
**The Right Way:**
|
||||
```
|
||||
Agent calls MCP tool directly:
|
||||
1. Input validation built-in
|
||||
2. Error handling built-in
|
||||
3. Audit trail automatic
|
||||
4. Agent can reason about operations directly
|
||||
|
||||
Result: Agent can work independently.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## When to Create ADRs vs Just Documenting
|
||||
|
||||
| Situation | ADR | Just Docs | Reason |
|
||||
|-----------|-----|----------|--------|
|
||||
| New endpoint added | Maybe | Yes (API_CONTRACTS.md) | Doc requirement, ADR only if trade-offs |
|
||||
| Component design | Maybe | Yes (ARCHITECTURE.md) | Doc requirement, ADR if design pattern |
|
||||
| Caching strategy | **Yes** | Plus docs | Affects performance, needs rationale |
|
||||
| Bug fix | No | Maybe (PROJECT_STATUS.md) | Just update status if impactful |
|
||||
| Token merge approach | **Yes** | Plus docs | Core architecture decision |
|
||||
| Color palette | No | Yes (tokens/) | Design choice, not architectural |
|
||||
| Authentication method | **Yes** | Plus docs | Security, backwards compatibility |
|
||||
| URL structure | Maybe | Yes (API_CONTRACTS.md) | ADR only if non-obvious choice |
|
||||
|
||||
---
|
||||
|
||||
## Red Flags Checklist
|
||||
|
||||
When reviewing code, docs, or PRs, watch for:
|
||||
|
||||
- [ ] Hardcoded values (should be in config)
|
||||
- [ ] Docstrings that contradict code
|
||||
- [ ] Ghost scripts (unused but feared)
|
||||
- [ ] Markdown files older than 30 days
|
||||
- [ ] Technical specs in phase reports
|
||||
- [ ] Version numbers that didn't change
|
||||
- [ ] Circular documentation (A→B, B→A)
|
||||
- [ ] Undocumented behavior
|
||||
- [ ] "I think this is what it does" in comments
|
||||
- [ ] PHASE_*.md files in root directory
|
||||
- [ ] Different information in different docs
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-08
|
||||
**Version**: 1.0.0 (extracted and expanded from PRINCIPLES.md)
|
||||
**Status**: PRODUCTION
|
||||
705
docs/01_core/API_CONTRACTS.md
Normal file
705
docs/01_core/API_CONTRACTS.md
Normal file
@@ -0,0 +1,705 @@
|
||||
# Design System Swarm - API Specification (IMMUTABLE)
|
||||
|
||||
**Document Version:** 1.0-IMMUTABLE
|
||||
**Created:** 2025-12-08
|
||||
**Status:** Immutable Reference Document
|
||||
**Lock Date:** 2025-12-08
|
||||
**Authority:** Project Technical Specification
|
||||
|
||||
---
|
||||
|
||||
## 🔒 IMMUTABILITY NOTICE
|
||||
|
||||
This document defines the complete API specification for the Design System Swarm platform. Once committed, this specification becomes the source of truth and should not be modified without version bump and full audit trail.
|
||||
|
||||
**All changes to this specification MUST:**
|
||||
1. Create new version (e.g., 1.1-IMMUTABLE)
|
||||
2. Document reason for change in changelog
|
||||
3. Include migration path for existing consumers
|
||||
4. Be reviewed and approved by technical lead
|
||||
5. Trigger client library updates
|
||||
|
||||
---
|
||||
|
||||
## API OVERVIEW
|
||||
|
||||
**API Base URL:** `https://dss.overbits.luz.uy/api` (Production)
|
||||
**Development Base URL:** `http://localhost:3001/api`
|
||||
**API Version:** 1.0
|
||||
**Response Format:** JSON
|
||||
**Authentication:** JWT Bearer Token
|
||||
**Rate Limit:** 100 requests per 15 minutes per user
|
||||
|
||||
---
|
||||
|
||||
## AUTHENTICATION
|
||||
|
||||
### Login Endpoint
|
||||
```
|
||||
POST /auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
Request:
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"password": "password"
|
||||
}
|
||||
|
||||
Response (200):
|
||||
{
|
||||
"status": "success",
|
||||
"code": "LOGIN_SUCCESS",
|
||||
"message": "Login successful",
|
||||
"data": {
|
||||
"user": {
|
||||
"id": "uuid",
|
||||
"email": "user@example.com",
|
||||
"name": "User Name",
|
||||
"role": "admin|editor|viewer"
|
||||
},
|
||||
"tokens": {
|
||||
"accessToken": "jwt_token",
|
||||
"refreshToken": "jwt_token"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Authorization Header
|
||||
```
|
||||
Authorization: Bearer <accessToken>
|
||||
```
|
||||
|
||||
Token expiry: 1 hour (3600 seconds)
|
||||
Refresh token expiry: 30 days
|
||||
|
||||
---
|
||||
|
||||
## STANDARD RESPONSE FORMAT
|
||||
|
||||
### Success Response
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"code": "OPERATION_CODE",
|
||||
"message": "Human readable description",
|
||||
"data": {
|
||||
// Response-specific data
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
HTTP Status: 200, 201, 202, 204
|
||||
|
||||
### Error Response
|
||||
```json
|
||||
{
|
||||
"status": "error",
|
||||
"code": "ERROR_CODE",
|
||||
"message": "Error description",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
HTTP Status: 400, 401, 403, 404, 409, 500, 503
|
||||
|
||||
---
|
||||
|
||||
## HTTP STATUS CODES
|
||||
|
||||
| Code | Meaning | Use Case |
|
||||
|------|---------|----------|
|
||||
| 200 | OK | Successful GET/PUT request |
|
||||
| 201 | Created | Resource created successfully (POST) |
|
||||
| 202 | Accepted | Async operation queued |
|
||||
| 204 | No Content | Successful DELETE |
|
||||
| 400 | Bad Request | Invalid input/validation error |
|
||||
| 401 | Unauthorized | Missing or invalid JWT token |
|
||||
| 403 | Forbidden | Valid token but insufficient permissions |
|
||||
| 404 | Not Found | Resource does not exist |
|
||||
| 409 | Conflict | Resource already exists (duplicate) |
|
||||
| 500 | Internal Server Error | Unexpected server error |
|
||||
| 503 | Service Unavailable | Server at capacity/maintenance |
|
||||
|
||||
---
|
||||
|
||||
## PHASE 1 ENDPOINTS (IMMUTABLE)
|
||||
|
||||
### Configuration
|
||||
```
|
||||
GET /config
|
||||
Auth: None
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "CONFIG_RETRIEVED",
|
||||
"data": {
|
||||
"app": { "name": "Design System Swarm", "version": "1.0.0" },
|
||||
"features": { /* feature flags */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Server Logging
|
||||
```
|
||||
POST /logs
|
||||
Auth: JWT (Required)
|
||||
Request: { "level": "log|warn|error|info|debug", "message": "string", "context": {} }
|
||||
Response: 201 Created
|
||||
{
|
||||
"status": "success",
|
||||
"code": "LOG_CREATED",
|
||||
"data": { "logId": "uuid", "timestamp": "iso-string" }
|
||||
}
|
||||
```
|
||||
|
||||
### Browser Logging
|
||||
```
|
||||
POST /logs/browser
|
||||
Auth: JWT (Required)
|
||||
Request: { "level": "string", "message": "string", "url": "string", "userAgent": "string" }
|
||||
Response: 201 Created
|
||||
```
|
||||
|
||||
### Retrieve Logs
|
||||
```
|
||||
GET /logs?level=error&source=browser&limit=100&offset=0
|
||||
Auth: JWT (Required)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "LOGS_RETRIEVED",
|
||||
"data": {
|
||||
"total": 150,
|
||||
"limit": 100,
|
||||
"offset": 0,
|
||||
"logs": [{ "id": "uuid", "level": "string", "message": "string", "timestamp": "iso-string" }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PHASE 2 ENDPOINTS (IMMUTABLE)
|
||||
|
||||
### Notifications (Server-Sent Events)
|
||||
```
|
||||
GET /notifications/events
|
||||
Auth: JWT (Required)
|
||||
Type: SSE (Server-Sent Events)
|
||||
Response: 200 OK (persistent connection)
|
||||
|
||||
Events format:
|
||||
data: {"type": "connection:established|notification", "timestamp": "iso-string", "data": {}}
|
||||
|
||||
Example notification:
|
||||
data: {"type": "project:created", "timestamp": "2025-12-08T20:35:15.972Z", "data": {"projectId": "uuid"}}
|
||||
```
|
||||
|
||||
### Notification Statistics
|
||||
```
|
||||
GET /notifications/stats
|
||||
Auth: JWT (Required, Admin only)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "NOTIFICATION_STATS",
|
||||
"data": {
|
||||
"totalSubscribers": 5,
|
||||
"userCount": 3,
|
||||
"byUser": { "user-id": 2, "user-id-2": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Test Notification
|
||||
```
|
||||
POST /notifications/test
|
||||
Auth: JWT (Required)
|
||||
Request: { "message": "string" }
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEST_NOTIFICATION_SENT",
|
||||
"data": { "timestamp": "iso-string" }
|
||||
}
|
||||
```
|
||||
|
||||
### List MCP Tools
|
||||
```
|
||||
GET /mcp/tools
|
||||
Auth: JWT (Required)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "MCP_TOOLS_LIST",
|
||||
"data": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "dss-analyze-project",
|
||||
"description": "Analyze codebase for design patterns",
|
||||
"params": { "projectPath": "string", "depth": "number" }
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Execute MCP Tool
|
||||
```
|
||||
POST /mcp/tools/:name/execute
|
||||
Auth: JWT (Required)
|
||||
Request: { "projectPath": "string", "depth": 2 }
|
||||
Response: 202 Accepted
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TOOL_EXECUTION_QUEUED",
|
||||
"data": { "estimatedDuration": "30-60 seconds" }
|
||||
}
|
||||
```
|
||||
|
||||
### Discover Project
|
||||
```
|
||||
POST /mcp/discover_project
|
||||
Auth: JWT (Required)
|
||||
Request: { "projectId": "uuid", "path": "string", "depth": 2 }
|
||||
Response: 202 Accepted
|
||||
{
|
||||
"status": "success",
|
||||
"code": "DISCOVERY_QUEUED",
|
||||
"data": {
|
||||
"discoveryId": "string",
|
||||
"estimatedTime": "2-5 minutes",
|
||||
"pollEndpoint": "/api/discovery/activity"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Get Quick Wins
|
||||
```
|
||||
POST /mcp/get_quick_wins
|
||||
Auth: JWT (Required)
|
||||
Request: { "projectId": "uuid", "path": "string" }
|
||||
Response: 202 Accepted
|
||||
{
|
||||
"status": "success",
|
||||
"code": "QUICK_WINS_ANALYSIS_QUEUED",
|
||||
"data": {
|
||||
"analysisId": "string",
|
||||
"expectedWins": ["string"],
|
||||
"estimatedTime": "1-3 minutes"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Callback (Webhook)
|
||||
```
|
||||
POST /mcp/callback
|
||||
Auth: None
|
||||
Request: { "toolName": "string", "status": "completed|failed", "data": {}, "projectId": "uuid" }
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "CALLBACK_ACKNOWLEDGED",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PHASE 3 ENDPOINTS (IMMUTABLE - DESIGNED, NOT YET IMPLEMENTED)
|
||||
|
||||
### Team Operations
|
||||
|
||||
#### List Teams
|
||||
```
|
||||
GET /teams
|
||||
Auth: JWT (Required)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAMS_RETRIEVED",
|
||||
"data": {
|
||||
"teams": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"name": "Design System",
|
||||
"description": "string",
|
||||
"ownerId": "uuid",
|
||||
"settings": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Create Team
|
||||
```
|
||||
POST /teams
|
||||
Auth: JWT (Required)
|
||||
Request: { "name": "string (required)", "description": "string (optional)" }
|
||||
Response: 201 Created
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_CREATED",
|
||||
"data": { "team": { "id": "uuid", "name": "string", "ownerId": "uuid" } }
|
||||
}
|
||||
```
|
||||
|
||||
#### Get Team
|
||||
```
|
||||
GET /teams/:id
|
||||
Auth: JWT (Required, must be team member)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_RETRIEVED",
|
||||
"data": { "team": { /* team object */ } }
|
||||
}
|
||||
```
|
||||
|
||||
#### Update Team
|
||||
```
|
||||
PUT /teams/:id
|
||||
Auth: JWT (Required, admin only)
|
||||
Request: { "name": "string", "description": "string" }
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_UPDATED",
|
||||
"data": { "team": { /* updated team */ } }
|
||||
}
|
||||
```
|
||||
|
||||
#### Delete Team
|
||||
```
|
||||
DELETE /teams/:id
|
||||
Auth: JWT (Required, owner only)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_DELETED",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
### Team Member Management
|
||||
|
||||
#### List Members
|
||||
```
|
||||
GET /teams/:id/members
|
||||
Auth: JWT (Required, team member)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_MEMBERS_RETRIEVED",
|
||||
"data": {
|
||||
"members": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"teamId": "uuid",
|
||||
"userId": "uuid",
|
||||
"role": "admin|editor|viewer",
|
||||
"joinedAt": "iso-string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Add Member
|
||||
```
|
||||
POST /teams/:id/members
|
||||
Auth: JWT (Required, admin only)
|
||||
Request: { "userId": "uuid (required)", "role": "viewer|editor|admin" }
|
||||
Response: 201 Created
|
||||
{
|
||||
"status": "success",
|
||||
"code": "MEMBER_ADDED",
|
||||
"data": { "member": { /* member object */ } }
|
||||
}
|
||||
```
|
||||
|
||||
#### Update Member Role
|
||||
```
|
||||
PUT /teams/:id/members/:memberId
|
||||
Auth: JWT (Required, admin only)
|
||||
Request: { "role": "admin|editor|viewer" }
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "MEMBER_UPDATED",
|
||||
"data": { "member": { /* updated member */ } }
|
||||
}
|
||||
```
|
||||
|
||||
#### Remove Member
|
||||
```
|
||||
DELETE /teams/:id/members/:memberId
|
||||
Auth: JWT (Required, admin only)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "MEMBER_REMOVED",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
### Team Settings
|
||||
|
||||
#### Get Settings
|
||||
```
|
||||
GET /teams/:id/settings
|
||||
Auth: JWT (Required, team member)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_SETTINGS_RETRIEVED",
|
||||
"data": {
|
||||
"settings": {
|
||||
"teamId": "uuid",
|
||||
"allowMemberInvites": boolean,
|
||||
"requireApprovalForProjects": boolean,
|
||||
"defaultRole": "viewer",
|
||||
"features": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Update Settings
|
||||
```
|
||||
PUT /teams/:id/settings
|
||||
Auth: JWT (Required, admin only)
|
||||
Request: { "allowMemberInvites": boolean, "defaultRole": "string" }
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_SETTINGS_UPDATED",
|
||||
"data": { "settings": { /* updated settings */ } }
|
||||
}
|
||||
```
|
||||
|
||||
### Team Dashboard
|
||||
|
||||
#### Get Dashboard
|
||||
```
|
||||
GET /teams/:id/dashboard
|
||||
Auth: JWT (Required, team member)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "TEAM_DASHBOARD_RETRIEVED",
|
||||
"data": {
|
||||
"dashboard": {
|
||||
"teamId": "uuid",
|
||||
"memberCount": 5,
|
||||
"activeMembers": 4,
|
||||
"stats": {
|
||||
"projectsCreatedThisMonth": 3,
|
||||
"componentsCreatedThisMonth": 12,
|
||||
"tokensUpdatedThisMonth": 47
|
||||
},
|
||||
"recentActivity": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PHASE 4 ENDPOINTS (IMMUTABLE - DESIGNED, NOT YET IMPLEMENTED)
|
||||
|
||||
### Discovery & Analysis
|
||||
|
||||
#### Start Discovery Scan
|
||||
```
|
||||
POST /discovery/scan
|
||||
Auth: JWT (Required)
|
||||
Request: { "projectId": "uuid (required)", "type": "project-analysis|quick-wins|component-audit|token-extraction" }
|
||||
Response: 202 Accepted
|
||||
{
|
||||
"status": "success",
|
||||
"code": "DISCOVERY_SCAN_STARTED",
|
||||
"data": {
|
||||
"discoveryId": "uuid",
|
||||
"status": "queued",
|
||||
"estimatedTime": "2-5 minutes"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Get Discovery Activity
|
||||
```
|
||||
GET /discovery/activity?projectId=uuid&limit=50&offset=0
|
||||
Auth: JWT (Required)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "DISCOVERY_ACTIVITY_RETRIEVED",
|
||||
"data": {
|
||||
"total": 100,
|
||||
"limit": 50,
|
||||
"offset": 0,
|
||||
"activities": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"projectId": "uuid",
|
||||
"type": "project-analysis",
|
||||
"status": "completed",
|
||||
"progress": 100,
|
||||
"startedAt": "iso-string",
|
||||
"completedAt": "iso-string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Get Discovery Statistics
|
||||
```
|
||||
GET /discovery/stats
|
||||
Auth: JWT (Required)
|
||||
Response: 200 OK
|
||||
{
|
||||
"status": "success",
|
||||
"code": "DISCOVERY_STATS_RETRIEVED",
|
||||
"data": {
|
||||
"stats": {
|
||||
"total": 50,
|
||||
"byType": { "project-analysis": 30, "quick-wins": 15, "component-audit": 5 },
|
||||
"byStatus": { "completed": 45, "running": 3, "failed": 2 },
|
||||
"recentCompleted": { /* discovery object */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PHASE 5 ENDPOINTS (IMMUTABLE - ROADMAP)
|
||||
|
||||
### 5A: Figma Integration (9 endpoints)
|
||||
1. `GET /figma/health` - API health check
|
||||
2. `POST /figma/extract-variables` - Extract Figma variables
|
||||
3. `POST /figma/extract-components` - Extract components
|
||||
4. `POST /figma/extract-styles` - Extract design tokens
|
||||
5. `POST /figma/sync-tokens` - Bidirectional sync
|
||||
6. `POST /figma/visual-diff` - Visual comparison
|
||||
7. `POST /figma/validate-components` - Validate compliance
|
||||
8. `POST /figma/generate-code` - Generate code
|
||||
9. `POST /figma/export-assets` - Export assets
|
||||
|
||||
### 5B: QA/Testing (2 endpoints)
|
||||
1. `POST /qa/screenshot-compare` - Visual regression
|
||||
2. `POST /test/run` - Execute tests
|
||||
|
||||
### 5C: Services (6+ endpoints)
|
||||
1. `POST /claude/chat` - Claude AI chat
|
||||
2. `POST /ai/chat` - Generic AI chat
|
||||
3. `POST /dss/save-tokens` - Save design tokens
|
||||
4. `POST /navigation/generate` - Generate navigation
|
||||
5. `POST /system/reset` - Admin reset (DANGEROUS)
|
||||
6. `GET /assets/list` - List design assets
|
||||
|
||||
---
|
||||
|
||||
## ERROR CODES REFERENCE
|
||||
|
||||
| Code | HTTP | Meaning |
|
||||
|------|------|---------|
|
||||
| VALIDATION_ERROR | 400 | Invalid input validation |
|
||||
| UNAUTHORIZED | 401 | Missing/invalid JWT |
|
||||
| FORBIDDEN | 403 | Insufficient permissions |
|
||||
| NOT_FOUND | 404 | Resource doesn't exist |
|
||||
| DUPLICATE_KEY | 409 | Resource already exists |
|
||||
| TEAM_NOT_FOUND | 404 | Team doesn't exist |
|
||||
| MEMBER_NOT_FOUND | 404 | Team member doesn't exist |
|
||||
| PROJECT_NOT_FOUND | 404 | Project doesn't exist |
|
||||
| TOOL_NOT_FOUND | 404 | MCP tool not found |
|
||||
| TOOL_EXECUTION_QUEUED | 202 | Tool queued successfully |
|
||||
| DISCOVERY_QUEUED | 202 | Discovery queued |
|
||||
| INTERNAL_SERVER_ERROR | 500 | Unexpected error |
|
||||
| SERVICE_UNAVAILABLE | 503 | Server at capacity |
|
||||
|
||||
---
|
||||
|
||||
## ROLE-BASED ACCESS CONTROL (RBAC)
|
||||
|
||||
### Role Definitions
|
||||
- **Admin** - Full control, can manage team, members, settings
|
||||
- **Editor** - Can create/edit projects, components, tokens
|
||||
- **Viewer** - Read-only access, cannot modify anything
|
||||
|
||||
### Permission Matrix
|
||||
| Action | Admin | Editor | Viewer |
|
||||
|--------|-------|--------|--------|
|
||||
| Create Team | ✓ | ✗ | ✗ |
|
||||
| Update Team | ✓ | ✗ | ✗ |
|
||||
| Delete Team | ✓ (owner) | ✗ | ✗ |
|
||||
| Manage Members | ✓ | ✗ | ✗ |
|
||||
| Create Project | ✓ | ✓ | ✗ |
|
||||
| Edit Project | ✓ | ✓ | ✗ |
|
||||
| View Project | ✓ | ✓ | ✓ |
|
||||
| Delete Project | ✓ | ✓ (owner) | ✗ |
|
||||
|
||||
---
|
||||
|
||||
## VERSIONING & CHANGELOG
|
||||
|
||||
### Version History
|
||||
- **1.0-IMMUTABLE** (2025-12-08) - Initial API specification
|
||||
- Phase 1-2: 12 endpoints implemented
|
||||
- Phase 3-4: 15 endpoints designed
|
||||
- Phase 5: 17+ endpoints planned
|
||||
|
||||
### Change Process
|
||||
All changes to this specification require:
|
||||
1. Version number increment
|
||||
2. Detailed change documentation
|
||||
3. Migration guide for clients
|
||||
4. Technical lead approval
|
||||
5. Client notification period (minimum 30 days for breaking changes)
|
||||
|
||||
---
|
||||
|
||||
## DEPLOYMENT CHECKLIST
|
||||
|
||||
### Before Deploying
|
||||
- [ ] All endpoints tested locally with curl
|
||||
- [ ] Database migrations prepared and tested
|
||||
- [ ] Error handling implemented for all cases
|
||||
- [ ] RBAC verified on protected endpoints
|
||||
- [ ] Rate limiting configured
|
||||
- [ ] Logging configured
|
||||
- [ ] Monitoring alerts set up
|
||||
|
||||
### Rollback Plan
|
||||
- [ ] Database rollback scripts prepared
|
||||
- [ ] Code rollback procedure documented
|
||||
- [ ] Backup of production data taken
|
||||
- [ ] Team notified of deployment
|
||||
|
||||
### Post-Deployment
|
||||
- [ ] Verify all endpoints responding
|
||||
- [ ] Monitor error logs
|
||||
- [ ] Check performance metrics
|
||||
- [ ] Verify database persistence
|
||||
- [ ] Test RBAC in production
|
||||
|
||||
---
|
||||
|
||||
## SUPPORT & DOCUMENTATION
|
||||
|
||||
**API Documentation:** This specification
|
||||
**Implementation Guide:** `/PHASE_3_4_5_IMPLEMENTATION.md`
|
||||
**Error Handling:** See ERROR CODES REFERENCE section
|
||||
**Authentication:** See AUTHENTICATION section
|
||||
**Rate Limiting:** 100 requests per 15 minutes per user
|
||||
|
||||
---
|
||||
|
||||
**Status:** 🔒 IMMUTABLE - DO NOT MODIFY WITHOUT VERSION BUMP
|
||||
**Last Updated:** 2025-12-08
|
||||
**Next Review:** After Phase 3 implementation
|
||||
**Maintained By:** Technical Lead
|
||||
318
docs/01_core/ARCHITECTURE.md
Normal file
318
docs/01_core/ARCHITECTURE.md
Normal file
@@ -0,0 +1,318 @@
|
||||
# DSS Enterprise Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
Design System Swarm v0.8.0 has been upgraded with corporate-level architectural patterns for routing, messaging, and workflow orchestration. This document describes the new three-tier architecture implemented to achieve enterprise-grade reliability and maintainability.
|
||||
|
||||
## Architecture Summary
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ DSS Application │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Router │───▶│ Messaging │───▶│ Workflows │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ Centralized │ │ Structured │ │ State │ │
|
||||
│ │ Routes │ │ Notifications│ │ Machines │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └─────────────────────┴────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌────────▼────────┐ │
|
||||
│ │ Store (State) │ │
|
||||
│ └─────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## New Modules
|
||||
|
||||
### 1. **Messaging System** (`admin-ui/js/core/messaging.js`)
|
||||
|
||||
**Purpose**: Centralized notification system with structured error taxonomy and correlation IDs.
|
||||
|
||||
**Features**:
|
||||
- ✅ Event bus using CustomEvent API
|
||||
- ✅ Structured message format with correlation IDs
|
||||
- ✅ Error taxonomy (E1xxx-E5xxx for errors, S1xxx for success)
|
||||
- ✅ Message persistence via localStorage
|
||||
- ✅ Helper functions: `notifySuccess()`, `notifyError()`, `notifyWarning()`, `notifyInfo()`
|
||||
- ✅ Message history and debugging capabilities
|
||||
|
||||
**Error Code Taxonomy**:
|
||||
- `E1xxx` - User errors (invalid input, forbidden actions)
|
||||
- `E2xxx` - Validation errors (missing fields, invalid formats)
|
||||
- `E3xxx` - API errors (request failed, timeout, unauthorized)
|
||||
- `E4xxx` - System errors (unexpected, network, storage)
|
||||
- `E5xxx` - Integration errors (Figma connection, API errors)
|
||||
- `S1xxx` - Success codes (operation complete, created, updated, deleted)
|
||||
|
||||
**Example Usage**:
|
||||
```javascript
|
||||
import { notifySuccess, notifyError, ErrorCode } from './messaging.js';
|
||||
|
||||
// Success notification
|
||||
notifySuccess('Project created successfully!', ErrorCode.SUCCESS_CREATED, {
|
||||
projectId: 'demo-ds'
|
||||
});
|
||||
|
||||
// Error notification
|
||||
notifyError('Failed to connect to Figma', ErrorCode.FIGMA_CONNECTION_FAILED, {
|
||||
fileKey: 'abc123',
|
||||
endpoint: '/figma/file'
|
||||
});
|
||||
```
|
||||
|
||||
**Message Structure**:
|
||||
```javascript
|
||||
{
|
||||
id: 'uuid-v4',
|
||||
message: 'User-facing message',
|
||||
type: 'success|error|warning|info',
|
||||
code: 'E3001',
|
||||
metadata: { /* context */ },
|
||||
correlationId: 'uuid-v4',
|
||||
timestamp: '2025-12-05T19:00:00.000Z',
|
||||
duration: 5000
|
||||
}
|
||||
```
|
||||
|
||||
### 2. **Router** (`admin-ui/js/core/router.js`)
|
||||
|
||||
**Purpose**: Centralized hash-based routing with guards and lifecycle hooks.
|
||||
|
||||
**Features**:
|
||||
- ✅ Centralized route registry
|
||||
- ✅ Route guards (`beforeEnter`, `afterEnter`, `onLeave`)
|
||||
- ✅ History management
|
||||
- ✅ Programmatic navigation
|
||||
- ✅ Route metadata support
|
||||
- ✅ Common guards (requireAuth, requireProject)
|
||||
|
||||
**Registered Routes** (12 total):
|
||||
1. `dashboard` - Main dashboard
|
||||
2. `projects` - Project management
|
||||
3. `tokens` - Design tokens
|
||||
4. `components` - Component library
|
||||
5. `figma` - Figma integration settings
|
||||
6. `docs` - Documentation
|
||||
7. `teams` - Team management
|
||||
8. `audit` - Audit log
|
||||
9. `settings` - Application settings
|
||||
10. `services` - Service configuration
|
||||
11. `quick-wins` - Quick wins analyzer
|
||||
12. `chat` - AI chat interface
|
||||
|
||||
**Example Usage**:
|
||||
```javascript
|
||||
import router, { guards } from './router.js';
|
||||
|
||||
// Register a route with guards
|
||||
router.register({
|
||||
path: 'admin',
|
||||
name: 'admin-panel',
|
||||
handler: ({ route, params }) => {
|
||||
// Handle route
|
||||
},
|
||||
beforeEnter: guards.requireAuth,
|
||||
afterEnter: ({ route }) => {
|
||||
console.log('Entered:', route.name);
|
||||
},
|
||||
meta: { requiresAuth: true }
|
||||
});
|
||||
|
||||
// Navigate programmatically
|
||||
router.navigate('projects');
|
||||
router.navigateByName('admin-panel');
|
||||
```
|
||||
|
||||
**Route Lifecycle**:
|
||||
```
|
||||
1. User clicks navigation
|
||||
2. Router calls previous route's onLeave hook
|
||||
3. Router calls new route's beforeEnter guard
|
||||
└─▶ If guard returns false, navigation aborted
|
||||
4. Router calls route handler
|
||||
5. Router calls afterEnter hook
|
||||
6. Router emits 'route-changed' event
|
||||
```
|
||||
|
||||
### 3. **Workflow State Machines** (`admin-ui/js/core/workflows.js`)
|
||||
|
||||
**Purpose**: Orchestrate multi-step user workflows with state machines.
|
||||
|
||||
**Features**:
|
||||
- ✅ Base StateMachine class
|
||||
- ✅ CreateProjectWorkflow (Create → Configure → Extract → Success)
|
||||
- ✅ TokenExtractionWorkflow (Connect → Select → Extract → Sync)
|
||||
- ✅ Progress tracking
|
||||
- ✅ State transition guards
|
||||
- ✅ Side effects via actions
|
||||
- ✅ Event emission for UI updates
|
||||
|
||||
**CreateProjectWorkflow States**:
|
||||
```
|
||||
init ──CREATE_PROJECT──> creating
|
||||
│
|
||||
├──PROJECT_CREATED──> created
|
||||
│ │
|
||||
│ ├──CONFIGURE_SETTINGS──> configuring
|
||||
│ │ │
|
||||
│ │ └──SETTINGS_SAVED──> ready
|
||||
│ │
|
||||
│ └──SKIP_CONFIG──> ready
|
||||
│ │
|
||||
│ └──EXTRACT_TOKENS──> extracting
|
||||
│ │
|
||||
│ ├──EXTRACTION_SUCCESS──> complete
|
||||
│ │
|
||||
│ └──EXTRACTION_FAILED──> ready
|
||||
│
|
||||
└──CREATE_FAILED──> init
|
||||
```
|
||||
|
||||
**Example Usage**:
|
||||
```javascript
|
||||
import { createProjectWorkflow } from './workflows.js';
|
||||
|
||||
const workflow = createProjectWorkflow({
|
||||
onProgress: (state, progress) => {
|
||||
console.log(`Progress: ${progress.percentage}%`);
|
||||
},
|
||||
onComplete: (machine) => {
|
||||
console.log('Workflow complete!', machine.context);
|
||||
}
|
||||
});
|
||||
|
||||
// Start workflow
|
||||
await workflow.start({ projectName: 'My Design System' });
|
||||
|
||||
// Advance workflow
|
||||
await workflow.send('PROJECT_CREATED', { projectId: 'my-ds' });
|
||||
await workflow.send('CONFIGURE_SETTINGS');
|
||||
```
|
||||
|
||||
## Integration with Existing App
|
||||
|
||||
### Changes to `app.js`
|
||||
|
||||
1. **Imports Added** (Lines 18-21):
|
||||
```javascript
|
||||
import router from './router.js';
|
||||
import { subscribe as subscribeToNotifications, notifySuccess, notifyError, notifyInfo, ErrorCode } from './messaging.js';
|
||||
import { createProjectWorkflow } from './workflows.js';
|
||||
```
|
||||
|
||||
2. **Initialization** (Lines 35-42):
|
||||
```javascript
|
||||
async init() {
|
||||
logger.info('App', 'Initializing application...');
|
||||
|
||||
// Initialize enterprise messaging system
|
||||
this.initializeMessaging();
|
||||
|
||||
// Initialize router with route definitions
|
||||
this.initializeRouter();
|
||||
|
||||
// ... rest of initialization
|
||||
}
|
||||
```
|
||||
|
||||
3. **New Methods**:
|
||||
- `initializeMessaging()` - Sets up notification subscription
|
||||
- `initializeRouter()` - Registers all 12 application routes
|
||||
|
||||
## Industry Standards Applied
|
||||
|
||||
1. ✅ **Separation of Concerns** - Router, Messaging, Workflows are independent modules
|
||||
2. ✅ **Single Responsibility Principle** - Each module has one clear purpose
|
||||
3. ✅ **Dependency Injection** - Workflows receive dependencies via options
|
||||
4. ✅ **Observer Pattern** - Pub/sub for messaging and route changes
|
||||
5. ✅ **State Machine Pattern** - Workflow orchestration
|
||||
6. ✅ **Command Pattern** - Route handlers as commands
|
||||
7. ✅ **Strategy Pattern** - Different workflow strategies
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### Before Architecture Upgrade
|
||||
- ❌ No centralized routing
|
||||
- ❌ Inconsistent messaging (simple strings)
|
||||
- ❌ No workflow orchestration
|
||||
- ❌ No error taxonomy
|
||||
- ❌ No correlation IDs
|
||||
- ❌ Manual state management
|
||||
|
||||
### After Architecture Upgrade
|
||||
- ✅ 12 routes centrally managed
|
||||
- ✅ 100% structured messaging with error codes
|
||||
- ✅ 2 workflow state machines implemented
|
||||
- ✅ Full error taxonomy (E1xxx-E5xxx, S1xxx)
|
||||
- ✅ UUID v4 correlation IDs for all messages
|
||||
- ✅ Automated state transitions with guards
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
admin-ui/js/core/
|
||||
├── messaging.js # Enterprise notification system (NEW)
|
||||
├── router.js # Centralized routing (NEW)
|
||||
├── workflows.js # State machine workflows (NEW)
|
||||
├── app.js # Main app (UPDATED)
|
||||
├── logger.js # Existing logger
|
||||
├── theme.js # Existing theme manager
|
||||
└── team-dashboards.js # Existing dashboards
|
||||
```
|
||||
|
||||
## Performance Impact
|
||||
|
||||
- **Bundle Size**: +15KB (minified) for all three modules
|
||||
- **Initialization Time**: +50ms for router and messaging setup
|
||||
- **Memory**: +~1MB for message queue (50 messages in localStorage)
|
||||
- **Network**: No additional requests (all modules loaded from same origin)
|
||||
|
||||
## Testing Status
|
||||
|
||||
✅ All JavaScript files validated with `node -c`
|
||||
✅ Server running on `http://localhost:3456`
|
||||
✅ All modules served with HTTP 200
|
||||
✅ Admin UI loads successfully
|
||||
✅ No syntax errors
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Immediate (Optional)
|
||||
1. Migrate existing `this.store.notify()` calls to use new messaging system
|
||||
2. Add route guards for protected pages (admin, settings)
|
||||
3. Implement CreateProjectWorkflow in Projects page
|
||||
4. Add progress indicators for workflows
|
||||
|
||||
### Future Enhancements
|
||||
1. Add route parameters support (e.g., `/projects/:id`)
|
||||
2. Implement breadcrumb navigation from route metadata
|
||||
3. Add workflow persistence (resume workflows after page reload)
|
||||
4. Create visual workflow builder/debugger
|
||||
5. Add A/B testing support via router metadata
|
||||
6. Implement role-based access control (RBAC) guards
|
||||
|
||||
## Documentation
|
||||
|
||||
- **Messaging API**: See JSDoc comments in `messaging.js`
|
||||
- **Router API**: See JSDoc comments in `router.js`
|
||||
- **Workflows API**: See JSDoc comments in `workflows.js`
|
||||
- **Integration Guide**: This document
|
||||
|
||||
## Support
|
||||
|
||||
For questions or issues:
|
||||
1. Check existing documentation at `http://localhost:3456/admin-ui/index.html#docs`
|
||||
2. Review code comments in source files
|
||||
3. Check browser console for detailed error messages with correlation IDs
|
||||
4. Use `getRecentErrors()` from messaging.js for debugging
|
||||
|
||||
---
|
||||
|
||||
**Architecture Version**: 1.0
|
||||
**DSS Version**: 0.8.0
|
||||
**Date**: 2025-12-05
|
||||
**Status**: ✅ Deployed and Tested
|
||||
755
docs/01_core/BEST_PRACTICES.md
Normal file
755
docs/01_core/BEST_PRACTICES.md
Normal file
@@ -0,0 +1,755 @@
|
||||
# DSS Best Practices & Implementation Guide
|
||||
|
||||
**Version 1.0.0** | Last Updated: 2025-12-08 | Status: Production
|
||||
|
||||
This document explains **how to apply** the 5 core principles in daily work. See PRINCIPLES.md for what the principles are; this document shows how to implement them.
|
||||
|
||||
---
|
||||
|
||||
## Principle 1: Design is an Architectural Concern
|
||||
|
||||
### How to Apply
|
||||
|
||||
**1.1 Treat Design Tokens as Code Dependencies**
|
||||
|
||||
Design tokens (colors, spacing, typography) are not styling suggestions—they're contracts that code depends on.
|
||||
|
||||
```
|
||||
❌ WRONG:
|
||||
<!-- Using hex values directly -->
|
||||
<Button style={{ background: "#007AFF" }} />
|
||||
|
||||
✅ RIGHT:
|
||||
<!-- Using design token from contract -->
|
||||
<Button background={tokens.color.primary[500]} />
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] All color values come from token definitions
|
||||
- [ ] All spacing values come from token definitions
|
||||
- [ ] All typography values come from token definitions
|
||||
- [ ] Components reference tokens, not hardcoded values
|
||||
- [ ] Token schema documented in tokens/ directory
|
||||
- [ ] Tokens versioned with semantic versioning
|
||||
|
||||
**Enforcement:**
|
||||
```bash
|
||||
# Pre-commit check: No hardcoded hex colors in component code
|
||||
grep -r "#[0-9A-F]{6}" packages/components/ && exit 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**1.2 Design Changes Follow Same Review as API Changes**
|
||||
|
||||
A design change that affects components requires the same rigor as an API change.
|
||||
|
||||
```
|
||||
Component Update Example:
|
||||
Old Contract: Button[variant=primary] uses color.primary[500]
|
||||
New Contract: Button[variant=primary] uses color.primary[600]
|
||||
|
||||
Requires:
|
||||
✅ Version bump in component spec
|
||||
✅ Migration guide for consumers
|
||||
✅ Changelog entry
|
||||
✅ 6-month deprecation notice for old version
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Design change documented in ARCHITECTURE.md
|
||||
- [ ] Component contract updated with version
|
||||
- [ ] Migration path provided if breaking
|
||||
- [ ] Changelog entry created
|
||||
- [ ] Deprecation timeline documented
|
||||
|
||||
---
|
||||
|
||||
**1.3 Make Visual Decisions Explicit**
|
||||
|
||||
Every design decision should be traceable back to why (not "looks good").
|
||||
|
||||
```
|
||||
❌ "Changed button color to blue"
|
||||
✅ "Changed button color from color.primary[500] to color.primary[600]
|
||||
for improved contrast on light backgrounds (WCAG AA compliance)"
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Design decisions documented in ADR
|
||||
- [ ] Visual change rationale explained
|
||||
- [ ] Alternatives considered documented
|
||||
- [ ] Impact assessment done
|
||||
- [ ] Accessibility implications checked
|
||||
|
||||
---
|
||||
|
||||
### Red Flags
|
||||
|
||||
```
|
||||
❌ "Let me just tweak this spacing"
|
||||
→ Is it breaking a contract? Document the change
|
||||
|
||||
❌ Figma file has one value, component has another
|
||||
→ Single source of truth violation; reconcile immediately
|
||||
|
||||
❌ "Designers will use Figma, developers will use tokens"
|
||||
→ Should be the same source (tokens in Figma, imported to code)
|
||||
|
||||
❌ Visual change not documented in ARCHITECTURE.md
|
||||
→ Architectural decisions should be explicit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Principle 2: Contracts are Immutable and Versioned
|
||||
|
||||
### How to Apply
|
||||
|
||||
**2.1 Understand Semantic Versioning**
|
||||
|
||||
```
|
||||
MAJOR.MINOR.PATCH (e.g., 1.2.3)
|
||||
|
||||
PATCH (1.2.3 → 1.2.4):
|
||||
- Documentation fixes
|
||||
- Bug fixes
|
||||
- Non-breaking improvements
|
||||
- Examples: typo fix, clarity improvement
|
||||
|
||||
MINOR (1.2.3 → 1.3.0):
|
||||
- New features/endpoints
|
||||
- New optional fields
|
||||
- Backwards compatible additions
|
||||
- Examples: new Button variant, new optional parameter
|
||||
|
||||
MAJOR (1.2.3 → 2.0.0):
|
||||
- Breaking changes only (rare)
|
||||
- Removed endpoints
|
||||
- Changed schemas
|
||||
- Changed behavior
|
||||
- Examples: remove deprecated endpoint, change auth scheme
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] All Tier 1 files have version numbers (API_CONTRACTS.md, ARCHITECTURE.md)
|
||||
- [ ] Version follows semver (MAJOR.MINOR.PATCH)
|
||||
- [ ] Every change bumps appropriate version level
|
||||
- [ ] Changelog entry created for each version
|
||||
- [ ] Breaking changes documented in migration guide
|
||||
- [ ] Deprecation timeline provided (6+ months notice)
|
||||
|
||||
---
|
||||
|
||||
**2.2 Version Control Workflow**
|
||||
|
||||
```
|
||||
Step 1: Make change to contract
|
||||
↓
|
||||
Step 2: Bump version in file header
|
||||
↓
|
||||
Step 3: Add changelog entry (what changed, why, migration path)
|
||||
↓
|
||||
Step 4: Open PR with version change
|
||||
↓
|
||||
Step 5: PR reviewed (breaking changes require extra scrutiny)
|
||||
↓
|
||||
Step 6: Merge and tag with version (git tag v1.3.0)
|
||||
↓
|
||||
Step 7: Update dependent systems
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Version bumped BEFORE merge (not after)
|
||||
- [ ] Changelog file updated with new version
|
||||
- [ ] Git tag created (git tag v1.2.4)
|
||||
- [ ] Dependent projects notified of breaking changes
|
||||
- [ ] Migration guide provided if needed
|
||||
- [ ] Old version archived in docs/archive/versions/
|
||||
|
||||
---
|
||||
|
||||
**2.3 Deprecation Pattern**
|
||||
|
||||
```
|
||||
When you need to remove something:
|
||||
|
||||
v1.2.0: Introduce deprecation notice
|
||||
"Endpoint GET /api/v1/projects/{id} deprecated as of v1.2.0"
|
||||
"Will remove in v2.0.0 (projected Q2 2026)"
|
||||
"Migration: See MIGRATION_GUIDE.md"
|
||||
|
||||
v1.3.0 - v1.9.9: Endpoint still works, warning on use
|
||||
Agents can query mcp_tool_usage table and see deprecation warnings
|
||||
|
||||
v2.0.0: Remove deprecated endpoint
|
||||
Removed entirely (breaking change, MAJOR bump)
|
||||
Old version documented in docs/archive/versions/v1.9.9/
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Deprecation notice added to contract
|
||||
- [ ] Sunset date documented (minimum 6 months)
|
||||
- [ ] Migration guide provided
|
||||
- [ ] Warning emitted when deprecated feature used
|
||||
- [ ] Period passed before removal
|
||||
- [ ] Removal is major version bump
|
||||
|
||||
---
|
||||
|
||||
### Red Flags
|
||||
|
||||
```
|
||||
❌ API_CONTRACTS.md changed but version didn't change
|
||||
→ Every change = version bump required
|
||||
|
||||
❌ "We'll update the version after release"
|
||||
→ Version should be updated before merge
|
||||
|
||||
❌ Endpoint removed without deprecation period
|
||||
→ Breaks contract immutability; should have been deprecated first
|
||||
|
||||
❌ Breaking change in a minor version
|
||||
→ Only non-breaking changes in MINOR bumps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Principle 3: The System is the Single Source of Truth
|
||||
|
||||
### How to Apply
|
||||
|
||||
**3.1 One Canonical Location Rule**
|
||||
|
||||
```
|
||||
Information Type | Canonical Location
|
||||
------------------------|----------------------------------
|
||||
API endpoint specs | API_CONTRACTS.md (Tier 1)
|
||||
Architecture decisions | ARCHITECTURE.md (Tier 1)
|
||||
Project status | PROJECT_STATUS.md (Tier 2)
|
||||
Feature inventory | IMPLEMENTATION_SUMMARY.md (Tier 2)
|
||||
Implementation guides | docs/03_reference/GUIDES/ (Tier 3)
|
||||
Historical snapshots | docs/archive/ (Tier 4)
|
||||
Why decisions were made | .knowledge/adrs/ (Decision records)
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Each piece of info has ONE canonical location
|
||||
- [ ] No duplicate specs in multiple files
|
||||
- [ ] Other docs link to canonical source, not copy content
|
||||
- [ ] Tier 1 files are immutable (semver only)
|
||||
- [ ] Tier 2 files updated weekly
|
||||
- [ ] Tier 3 docs reference Tier 1 (not duplicate)
|
||||
|
||||
---
|
||||
|
||||
**3.2 Link Instead of Copy**
|
||||
|
||||
```
|
||||
❌ WRONG (duplication):
|
||||
README.md:
|
||||
"Supported auth methods: OAuth, JWT, API Key"
|
||||
|
||||
ARCHITECTURE.md:
|
||||
"Supported auth methods: OAuth, JWT, API Key"
|
||||
|
||||
✅ RIGHT (single source):
|
||||
README.md:
|
||||
"See ARCHITECTURE.md for supported auth methods"
|
||||
|
||||
ARCHITECTURE.md:
|
||||
"Supported auth methods: OAuth, JWT, API Key"
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Never copy-paste specifications between files
|
||||
- [ ] Use markdown links when referencing specs
|
||||
- [ ] Links updated when target moves
|
||||
- [ ] Broken links detected by CI/CD (link-rot check)
|
||||
|
||||
---
|
||||
|
||||
**3.3 Conflict Resolution: Find the Real Source**
|
||||
|
||||
When two docs say different things:
|
||||
|
||||
```
|
||||
Step 1: Identify conflict
|
||||
"Status says Figma sync works (PROJECT_STATUS.md)"
|
||||
"API_CONTRACTS.md says GET /sync has 30s timeout"
|
||||
|
||||
Step 2: Find canonical source
|
||||
Tier 1 (ARCHITECTURE.md) is more authoritative than Tier 2
|
||||
Real truth is in the code
|
||||
|
||||
Step 3: Fix the summary
|
||||
PROJECT_STATUS.md should say:
|
||||
"Figma sync works (30s timeout limit)"
|
||||
|
||||
Step 4: Update both sources
|
||||
Summary = simplified truth
|
||||
Spec = full truth
|
||||
They must align
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Identify which source is authoritative (Tier level)
|
||||
- [ ] Update all copies to match truth
|
||||
- [ ] Add cross-reference explaining difference
|
||||
- [ ] Document conflict resolution in ADR
|
||||
|
||||
---
|
||||
|
||||
### Red Flags
|
||||
|
||||
```
|
||||
❌ "Also see DEPLOYMENT_GUIDE.md for full endpoint spec"
|
||||
→ Spec should be ONLY in API_CONTRACTS.md
|
||||
|
||||
❌ Three different status files: MVP_STATUS, PHASE_5_REPORT, PROJECT_STATUS
|
||||
→ Keep PROJECT_STATUS.md only; archive others
|
||||
|
||||
❌ README.md repeats API endpoints from API_CONTRACTS.md
|
||||
→ README links to API_CONTRACTS.md instead
|
||||
|
||||
❌ Component spec in Figma file AND Storybook AND Component.md
|
||||
→ Single source: Storybook is canonical; Figma links to it
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Principle 4: Decisions are Explicit and Traceable
|
||||
|
||||
### How to Apply
|
||||
|
||||
**4.1 Create Architecture Decision Records (ADRs)**
|
||||
|
||||
Every significant architectural decision should have an ADR in `.knowledge/adrs/`.
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: 001
|
||||
title: Token Merge System as Core DSS Feature
|
||||
date: 2025-12-05
|
||||
author(s): Team Name
|
||||
status: Accepted
|
||||
principles: [Design is Architectural, Contracts Immutable, Single Source of Truth]
|
||||
related:
|
||||
- doc: docs/01_core/ARCHITECTURE.md#token-merge
|
||||
- adr: ADR-002-MCP-first-architecture
|
||||
- ticket: DSS-PR-101
|
||||
---
|
||||
|
||||
## Context
|
||||
Multiple projects needed to ingest tokens from Figma, CSS, SCSS...
|
||||
|
||||
## Decision
|
||||
Implement TokenMerger class with pluggable merge strategies...
|
||||
|
||||
## Alternatives Considered
|
||||
1. Manual token mapping → Doesn't scale
|
||||
2. Single canonical strategy → Too rigid
|
||||
|
||||
## Consequences
|
||||
**Positive:**
|
||||
- Flexible: Teams choose their strategy
|
||||
- Non-destructive: Conflict reports
|
||||
|
||||
**Negative:**
|
||||
- More complex than single strategy
|
||||
- Developers must understand each strategy
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] ADR created for significant decisions
|
||||
- [ ] Context section explains why decision matters
|
||||
- [ ] Alternatives section documents what was considered
|
||||
- [ ] Consequences section lists pros and cons
|
||||
- [ ] Related links connect to docs and code
|
||||
- [ ] Status is Proposed → Accepted → (Deprecated/Superseded)
|
||||
- [ ] Linked from PR that implements decision
|
||||
|
||||
---
|
||||
|
||||
**4.2 Link Code to Decisions**
|
||||
|
||||
In commit messages and PRs, reference the ADR:
|
||||
|
||||
```
|
||||
Bad:
|
||||
commit: "Add token merge strategies"
|
||||
|
||||
Good:
|
||||
commit: "feat: Add token merge strategies (implements ADR-001)
|
||||
|
||||
TokenMerger class supports FIRST, LAST, PREFER_FIGMA,
|
||||
PREFER_CODE, PREFER_SPECIFIC strategies.
|
||||
|
||||
See ADR-001 for rationale and alternatives."
|
||||
|
||||
PR Description:
|
||||
"## ADR Link
|
||||
Implements decision in ADR-001
|
||||
|
||||
## Principle Alignment
|
||||
- Principle 1: Design decisions are architectural
|
||||
- Principle 3: Token merge is Single Source of Truth
|
||||
- Principle 4: Decision recorded for traceability"
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Commit messages reference ADR (if architectural change)
|
||||
- [ ] PR description includes ADR link
|
||||
- [ ] Code comments point to ADR for rationale
|
||||
- [ ] ADR status updated (Proposed → Accepted)
|
||||
- [ ] Decision traceable: PR → ADR → Code
|
||||
|
||||
---
|
||||
|
||||
**4.3 Query Decisions**
|
||||
|
||||
```bash
|
||||
# Find all decisions about token handling
|
||||
grep -r "token" .knowledge/adrs/ --include="*.md"
|
||||
|
||||
# Find all decisions made by a specific author
|
||||
grep -r "author.*Alice" .knowledge/adrs/
|
||||
|
||||
# Find deprecated decisions
|
||||
grep -r "status.*Deprecated" .knowledge/adrs/
|
||||
|
||||
# Find decisions related to a principle
|
||||
grep -r "principle.*Design is Architectural" .knowledge/adrs/
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] ADRs organized in `.knowledge/adrs/`
|
||||
- [ ] Easy to search and query ADRs
|
||||
- [ ] ADRs linked from related code/docs
|
||||
- [ ] When reconsidering decision, old ADR shows previous reasoning
|
||||
|
||||
---
|
||||
|
||||
### Red Flags
|
||||
|
||||
```
|
||||
❌ "We decided to use JWT for auth" (no ADR)
|
||||
→ Should be documented: why JWT? what alternatives?
|
||||
|
||||
❌ Design decision only in commit message
|
||||
→ Lost when history is cleaned up; should be in ADR
|
||||
|
||||
❌ Component contract changed without ADR
|
||||
→ Architectural decision needs documentation
|
||||
|
||||
❌ "Why did we do this?" requires reading git logs
|
||||
→ Indicates decision wasn't documented in ADR
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Principle 5: Operations are Exposed as Standardized Tools
|
||||
|
||||
### How to Apply
|
||||
|
||||
**5.1 Tool-First Architecture**
|
||||
|
||||
```
|
||||
WRONG (REST-first):
|
||||
Agent → MCP tool wrapper → REST endpoint → Database
|
||||
Problem: Extra layer, agent waits for HTTP
|
||||
|
||||
RIGHT (Tool-first):
|
||||
Agent → MCP tool → Database
|
||||
Human UI → MCP tool → Database
|
||||
(REST endpoint wraps tool, just a thin layer)
|
||||
|
||||
Key difference:
|
||||
- Tools are primary (agents use directly)
|
||||
- REST is secondary (UI convenience layer)
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] All major operations have MCP tool equivalents
|
||||
- [ ] Tools are primary implementation (not wrappers)
|
||||
- [ ] REST endpoints wrap tools (thin layer)
|
||||
- [ ] Tool input/output documented in JSON Schema
|
||||
- [ ] Tools versioned (match API_CONTRACTS.md version)
|
||||
- [ ] All tool calls logged in audit trail
|
||||
- [ ] Agents can discover tools via introspection
|
||||
|
||||
---
|
||||
|
||||
**5.2 Design MCP Tool Correctly**
|
||||
|
||||
```python
|
||||
# WRONG: Tool calls REST endpoint
|
||||
class ProjectTools:
|
||||
async def dss_create_project(self, name, root_path):
|
||||
# Calls REST endpoint, extra hop
|
||||
response = await http.post("/api/projects", {...})
|
||||
return response.json()
|
||||
|
||||
# RIGHT: Tool does the work, REST wraps tool
|
||||
class ProjectTools:
|
||||
async def dss_create_project(self, name, root_path):
|
||||
# Tool does work directly
|
||||
project = await db.insert_project(name, root_path)
|
||||
await log_mcp_tool_usage("dss_create_project", {...})
|
||||
return project
|
||||
|
||||
# REST endpoint wraps tool
|
||||
@app.post("/api/projects")
|
||||
async def create_project(request):
|
||||
return await tools.dss_create_project(
|
||||
request.json["name"],
|
||||
request.json["root_path"]
|
||||
)
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Tool implementation is the primary logic
|
||||
- [ ] Tool directly accesses data layer (database, files)
|
||||
- [ ] Tool includes input validation
|
||||
- [ ] Tool logs usage to audit trail
|
||||
- [ ] Tool returns structured response (not HTTP wrapper)
|
||||
- [ ] REST endpoint wraps tool (simple delegation)
|
||||
|
||||
---
|
||||
|
||||
**5.3 Tool Versioning**
|
||||
|
||||
```
|
||||
Tool versions must match API_CONTRACTS.md version:
|
||||
|
||||
When API_CONTRACTS.md says v1.2.0:
|
||||
All tools must be v1.2.0
|
||||
Tool schema matches API schema
|
||||
Breaking changes in tools = breaking API changes
|
||||
|
||||
Tool versioning rules:
|
||||
MAJOR: Remove parameter, change behavior
|
||||
MINOR: Add optional parameter, new tool
|
||||
PATCH: Fix bug, improve error message
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Tool version in code matches API_CONTRACTS.md
|
||||
- [ ] Tool schema matches API schema
|
||||
- [ ] Breaking tool changes = breaking API changes (major bump)
|
||||
- [ ] Tool changelog entries for each version
|
||||
- [ ] Deprecation path documented for tool changes
|
||||
|
||||
---
|
||||
|
||||
**5.4 Tool Audit Trail**
|
||||
|
||||
```
|
||||
Every tool call logged with:
|
||||
- Tool name (dss_create_project)
|
||||
- Timestamp (2025-12-08T10:30:45Z)
|
||||
- Caller (agent name, user ID, or "anonymous")
|
||||
- Input parameters (name: "my-project", ...)
|
||||
- Output (project_id: 123, success: true)
|
||||
- Errors (if any)
|
||||
|
||||
Example table:
|
||||
CREATE TABLE mcp_tool_usage (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tool_name VARCHAR(255),
|
||||
timestamp TIMESTAMP,
|
||||
caller_type VARCHAR(50), -- "agent", "user", "system"
|
||||
caller_id VARCHAR(255),
|
||||
input_json JSONB,
|
||||
output_json JSONB,
|
||||
error_message TEXT,
|
||||
duration_ms INT
|
||||
);
|
||||
```
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Tool call audit table exists
|
||||
- [ ] Every tool call logged with parameters
|
||||
- [ ] Audit trail queryable (who used what, when)
|
||||
- [ ] Errors captured in audit trail
|
||||
- [ ] Tool performance tracked (duration)
|
||||
|
||||
---
|
||||
|
||||
### Red Flags
|
||||
|
||||
```
|
||||
❌ "Just POST /api/projects directly"
|
||||
→ Should use dss_create_project tool
|
||||
|
||||
❌ Tool only wraps REST endpoint
|
||||
→ Tool should be primary; endpoint wraps tool
|
||||
|
||||
❌ Tool implementation scattered across 3 files
|
||||
→ Tools should be in tools/ directory, organized
|
||||
|
||||
❌ New feature added to REST API but not as MCP tool
|
||||
→ Every operation MUST be a tool first
|
||||
|
||||
❌ Tool calls not logged to audit trail
|
||||
→ All tool usage must be auditable
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cross-Principle Patterns
|
||||
|
||||
### Pattern: Adding a New Feature
|
||||
|
||||
```
|
||||
1. Design the feature (Principle 1: Design is Architectural)
|
||||
↓
|
||||
2. Document in ARCHITECTURE.md with version (Principle 2: Contracts)
|
||||
↓
|
||||
3. Update Single Source of Truth (Principle 3: Single Source)
|
||||
API_CONTRACTS.md gets new endpoint spec
|
||||
↓
|
||||
4. Record why in ADR (Principle 4: Decisions Traceable)
|
||||
.knowledge/adrs/ADR-NNN.md explains rationale
|
||||
↓
|
||||
5. Create MCP Tool (Principle 5: Operations as Tools)
|
||||
dss_new_feature tool is primary
|
||||
↓
|
||||
6. REST endpoint wraps tool
|
||||
POST /api/new-feature calls tool
|
||||
|
||||
Timeline: Design → Docs → ADR → Tool → Endpoint
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pattern: Changing a Contract
|
||||
|
||||
```
|
||||
1. Is this breaking? (Principle 2: Contracts)
|
||||
- YES → MAJOR version bump (v1.2.0 → v2.0.0)
|
||||
- NO → MINOR version bump (v1.2.0 → v1.3.0)
|
||||
|
||||
2. Update Single Source (Principle 3: Single Source)
|
||||
Update API_CONTRACTS.md with new version
|
||||
|
||||
3. Deprecate old if breaking (Principle 2: Contracts)
|
||||
Old endpoint: "Deprecated in v1.3.0, remove in v2.0.0"
|
||||
New endpoint: "Introduced in v1.3.0"
|
||||
|
||||
4. Record decision (Principle 4: Decisions)
|
||||
ADR: "Why did we change the contract?"
|
||||
|
||||
5. Update tool (Principle 5: Operations)
|
||||
Tool version must match new contract version
|
||||
|
||||
Timeline: Identify change → Determine version → Update docs → Update tool
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pattern: Handling Decision Conflicts
|
||||
|
||||
```
|
||||
When principles conflict, use priority order:
|
||||
|
||||
1. Contracts are Immutable (highest)
|
||||
"This tool would break the API contract"
|
||||
→ Keep contract, deprecate old tool, introduce new one
|
||||
|
||||
2. Single Source of Truth
|
||||
"Two files have different info"
|
||||
→ Find source of truth, delete copy, add link
|
||||
|
||||
3. Operations as Tools
|
||||
"Tool implementation is complex"
|
||||
→ Break into multiple tools, each focused
|
||||
|
||||
4. Decisions Traceable
|
||||
"Should we have an ADR for this?"
|
||||
→ If significant and recurring, yes
|
||||
|
||||
5. Design is Architectural (lowest)
|
||||
"Visual tweak seems simple"
|
||||
→ Still document if it affects component contracts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Enforcement & Automation
|
||||
|
||||
### Pre-Commit Hooks
|
||||
|
||||
```bash
|
||||
# Hook 1: Detect duplicate documentation
|
||||
check-link-rot.py → Fails if same content in 2+ files
|
||||
|
||||
# Hook 2: Ensure version bumped
|
||||
schema-diff.py → Fails if file changed but version didn't
|
||||
|
||||
# Hook 3: Detect phase-named files
|
||||
detect-phase-names.py → Fails if *PHASE*, *DEPLOYMENT*, *WEEK* files
|
||||
|
||||
# Hook 4: Validate knowledge graph
|
||||
knowledge-graph-validator.py → Validates .knowledge/*.json schema
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CI/CD Checks
|
||||
|
||||
```yaml
|
||||
# Check 1: Version sync
|
||||
version-bump-validator:
|
||||
- For any Tier 1 file change: requires version bump
|
||||
- Updates VERSIONING.md map
|
||||
- Validates semver format
|
||||
|
||||
# Check 2: Documentation consistency
|
||||
doc-coverage:
|
||||
- Every API endpoint in code appears in API_CONTRACTS.md
|
||||
- Feature code doesn't define its own spec (references Tier 1)
|
||||
- All open bugs in code correspond to PROJECT_STATUS.md
|
||||
|
||||
# Check 3: Tool API alignment
|
||||
tool-api-alignment:
|
||||
- Tool schema matches API_CONTRACTS.md schema
|
||||
- Tool version matches contract version
|
||||
- All tools have input/output schema
|
||||
|
||||
# Check 4: Link validation
|
||||
link-validation:
|
||||
- All markdown links are valid
|
||||
- References to ADRs use correct format
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
✅ **Implementation Success:**
|
||||
- No duplicate documentation (use links instead)
|
||||
- All API endpoints documented once with version
|
||||
- All major decisions in .knowledge/adrs/ (with rationale)
|
||||
- No PHASE_*_REPORT.md, DEPLOYMENT_*.md in root
|
||||
- All operations have MCP tools (no REST-only endpoints)
|
||||
- Tier 1 files change only via semantic versioning
|
||||
- PROJECT_STATUS.md updated weekly (within 7 days)
|
||||
|
||||
✅ **Team Adoption:**
|
||||
- New developer reads PRINCIPLES.md → starts coding (30 min)
|
||||
- Team asks "which principle?" before PRs
|
||||
- Developers cite principles in code reviews
|
||||
- ADRs referenced in commit messages
|
||||
|
||||
✅ **Organizational Value:**
|
||||
- Stakeholders can check status without asking
|
||||
- Decision rationale preserved for future teams
|
||||
- Agents can work autonomously via MCP tools
|
||||
- Design changes tracked with same rigor as code
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-08
|
||||
**Version**: 1.0.0 (extracted from PRINCIPLES.md)
|
||||
**Status**: PRODUCTION
|
||||
437
docs/01_core/DOCUMENTATION_GUIDE.md
Normal file
437
docs/01_core/DOCUMENTATION_GUIDE.md
Normal file
@@ -0,0 +1,437 @@
|
||||
# DSS Documentation Guide
|
||||
|
||||
**Version 1.0.0** | Last Updated: 2025-12-08 | Status: Production
|
||||
|
||||
This guide helps you find the right documentation for your task. Start here, find your scenario, and jump to the right doc.
|
||||
|
||||
---
|
||||
|
||||
## I'm New to DSS
|
||||
|
||||
**Goal**: Understand what DSS is and get started
|
||||
|
||||
**Read In This Order:**
|
||||
1. **PRINCIPLES.md** (5 min) - What DSS believes
|
||||
2. **README.md** (5 min) - Project overview
|
||||
3. **QUICK_REFERENCE.md** (5 min) - Key links and commands
|
||||
4. This guide (you're reading it!)
|
||||
|
||||
**Then Choose Your Path:**
|
||||
- Integrating DSS into your project? → INTEGRATION_GUIDE.md
|
||||
- Contributing to DSS? → CONTRIBUTION_GUIDE.md
|
||||
- Setting up for development? → DEVELOPMENT_SETUP.md
|
||||
|
||||
---
|
||||
|
||||
## I Need to Do Something Specific
|
||||
|
||||
### I'm Making a Structural Decision
|
||||
|
||||
**Question**: Will this affect how components, tokens, or APIs work?
|
||||
|
||||
**Read:**
|
||||
- **PRINCIPLES.md** (understand the 5 core principles)
|
||||
- **BEST_PRACTICES.md** (how to apply principles)
|
||||
- **.knowledge/adrs/** (how similar decisions were made)
|
||||
|
||||
**Then:**
|
||||
- Create an ADR documenting your decision
|
||||
- Open PR referencing the ADR
|
||||
|
||||
---
|
||||
|
||||
### I'm Writing Code
|
||||
|
||||
**Question**: What's the contract I need to follow?
|
||||
|
||||
**Read:**
|
||||
- **ARCHITECTURE.md** (system structure and design)
|
||||
- **API_CONTRACTS.md** (endpoint specifications)
|
||||
- **BEST_PRACTICES.md** (implementation patterns for your principle)
|
||||
|
||||
**Then:**
|
||||
- Follow the patterns in ARCHITECTURE.md
|
||||
- Respect the contracts in API_CONTRACTS.md
|
||||
- Link to BEST_PRACTICES.md in your PR if needed
|
||||
|
||||
---
|
||||
|
||||
### I'm Adding an API Endpoint or MCP Tool
|
||||
|
||||
**Read:**
|
||||
- **API_CONTRACTS.md** (existing endpoints)
|
||||
- **BEST_PRACTICES.md** § Principle 5 (tool-first architecture)
|
||||
- **docs/03_reference/MCP_TOOLS_SPEC.md** (how to design tools)
|
||||
|
||||
**Then:**
|
||||
1. Design MCP tool (primary)
|
||||
2. Implement tool
|
||||
3. REST endpoint wraps tool
|
||||
4. Document in API_CONTRACTS.md with new version
|
||||
5. Create ADR for architectural decision
|
||||
|
||||
---
|
||||
|
||||
### I'm Integrating DSS into My Project
|
||||
|
||||
**Read:**
|
||||
- **QUICK_REFERENCE.md** (overview)
|
||||
- **INTEGRATION_GUIDE.md** (step-by-step integration)
|
||||
- **API_CONTRACTS.md** (endpoints you'll use)
|
||||
- **docs/03_reference/MCP_TOOLS_SPEC.md** (available tools)
|
||||
|
||||
**Questions?**
|
||||
- "How do I do X?" → Search INTEGRATION_GUIDE.md
|
||||
- "What endpoints are available?" → See API_CONTRACTS.md
|
||||
- "How do tokens work?" → See docs/03_reference/TOKEN_SYSTEM.md
|
||||
|
||||
---
|
||||
|
||||
### I'm Deploying DSS
|
||||
|
||||
**Read:**
|
||||
- **PROJECT_STATUS.md** (current deployment status)
|
||||
- **DEPLOYMENT_GUIDE.md** (step-by-step deployment)
|
||||
- **PRODUCTION_READINESS.md** (checklist before deploy)
|
||||
- **TROUBLESHOOTING.md** (when things go wrong)
|
||||
|
||||
**Then:**
|
||||
- Check PRODUCTION_READINESS.md checklist
|
||||
- Follow DEPLOYMENT_GUIDE.md steps
|
||||
- Update PROJECT_STATUS.md after successful deploy
|
||||
|
||||
---
|
||||
|
||||
### I'm Debugging Something
|
||||
|
||||
**Read:**
|
||||
- **PROJECT_STATUS.md** (known issues section)
|
||||
- **TROUBLESHOOTING.md** (common problems)
|
||||
- **ARCHITECTURE.md** (understand component interactions)
|
||||
- Log files in **logs/** directory
|
||||
|
||||
**Still stuck?**
|
||||
- Check .knowledge/adrs/ for related decisions
|
||||
- Review ANTI_PATTERNS_AND_LEARNINGS.md for common mistakes
|
||||
- Ask team in Slack with reference to docs you read
|
||||
|
||||
---
|
||||
|
||||
### I'm Reviewing a PR
|
||||
|
||||
**Checklist:**
|
||||
- [ ] Does this violate any principles? → See PRINCIPLES.md
|
||||
- [ ] Did they follow best practices? → See BEST_PRACTICES.md
|
||||
- [ ] Should this be documented? → Where should it go?
|
||||
- [ ] Is this an architectural change? → ADR needed?
|
||||
- [ ] Version numbers updated? → See BEST_PRACTICES.md § Principle 2
|
||||
|
||||
**Look for anti-patterns:**
|
||||
See ANTI_PATTERNS_AND_LEARNINGS.md for common mistakes
|
||||
|
||||
---
|
||||
|
||||
## Documentation by Tier
|
||||
|
||||
### Tier 1: Constitutional Documents (Immutable, Versioned)
|
||||
|
||||
These change only through semantic versioning. They define the system.
|
||||
|
||||
| Document | Purpose | Read When |
|
||||
|----------|---------|-----------|
|
||||
| **PRINCIPLES.md** | Core values (5 principles) | Onboarding, making decisions |
|
||||
| **API_CONTRACTS.md** | API endpoint specifications | Building integrations, implementing endpoints |
|
||||
| **ARCHITECTURE.md** | System design, structure | Understanding system, making changes |
|
||||
|
||||
**Update Process:**
|
||||
1. Change file
|
||||
2. Bump version (MAJOR.MINOR.PATCH)
|
||||
3. Add changelog entry
|
||||
4. Open PR
|
||||
5. Merge and tag (git tag v1.2.0)
|
||||
|
||||
---
|
||||
|
||||
### Tier 2: Current State Documents (Living, Weekly Updates)
|
||||
|
||||
These reflect production reality. Updated at least weekly.
|
||||
|
||||
| Document | Purpose | Read When |
|
||||
|----------|---------|-----------|
|
||||
| **PROJECT_STATUS.md** | Current deployment, bugs, roadmap | Weekly reviews, planning, status checks |
|
||||
| **IMPLEMENTATION_SUMMARY.md** | Feature inventory by phase | Understanding what's shipped |
|
||||
| **README.md** | Project overview, quick links | First time visiting repo |
|
||||
|
||||
**Update Process:**
|
||||
1. Every Friday: Review and update
|
||||
2. Mark "Last Updated" with current date
|
||||
3. Update bugs, roadmap, deployment status
|
||||
4. Commit to main branch
|
||||
|
||||
---
|
||||
|
||||
### Tier 3: How-To Guides (Reference Documents)
|
||||
|
||||
Detailed guidance on specific tasks. Updated as needed.
|
||||
|
||||
| Document | Purpose | Read When |
|
||||
|----------|---------|-----------|
|
||||
| **QUICK_REFERENCE.md** | Cheat sheet, commands, quick links | Need to find something fast |
|
||||
| **INTEGRATION_GUIDE.md** | How to integrate DSS into your project | Using DSS in your own project |
|
||||
| **DEPLOYMENT_GUIDE.md** | Step-by-step deployment process | Deploying to production |
|
||||
| **MIGRATION_GUIDE.md** | How to upgrade between versions | Upgrading DSS version |
|
||||
| **MCP_TOOLS_SPEC.md** | Available MCP tools and how to use them | Using MCP tools in automation |
|
||||
| **CONTRIBUTION_GUIDE.md** | How to contribute to DSS | Contributing code changes |
|
||||
| **DEVELOPMENT_SETUP.md** | Local development environment | Setting up to develop DSS |
|
||||
| **PRODUCTION_READINESS.md** | Pre-deployment checklist | Before deploying to production |
|
||||
| **TROUBLESHOOTING.md** | Common problems and solutions | Debugging issues |
|
||||
|
||||
**Update Process:**
|
||||
1. Update when procedures change
|
||||
2. Mark "Last Updated" date
|
||||
3. Review monthly for staleness
|
||||
4. Archive if superseded by new guide
|
||||
|
||||
---
|
||||
|
||||
### Tier 4: Knowledge Archive
|
||||
|
||||
Historical records, old versions, archived docs.
|
||||
|
||||
| Document Type | Purpose | Read When |
|
||||
|---------|---------|-----------|
|
||||
| **.knowledge/adrs/** | Architecture Decision Records | Understanding why decisions were made |
|
||||
| **docs/archive/versions/** | Old API/Architecture versions | Integrating with old systems |
|
||||
| **docs/archive/** | Historical documents | Research, understanding evolution |
|
||||
|
||||
---
|
||||
|
||||
## Documentation Structure
|
||||
|
||||
```
|
||||
docs/
|
||||
├── 01_core/
|
||||
│ ├── PRINCIPLES.md # Tier 1: What we believe
|
||||
│ ├── BEST_PRACTICES.md # How to apply principles
|
||||
│ ├── API_CONTRACTS.md # Tier 1: API spec
|
||||
│ ├── ARCHITECTURE.md # Tier 1: System design
|
||||
│ ├── ANTI_PATTERNS_AND_LEARNINGS.md # What not to do
|
||||
│ └── DOCUMENTATION_GUIDE.md # This file
|
||||
│
|
||||
├── 02_status/
|
||||
│ ├── PROJECT_STATUS.md # Tier 2: Current state
|
||||
│ ├── IMPLEMENTATION_SUMMARY.md # Tier 2: Feature inventory
|
||||
│ └── CHANGELOG.md # Version history
|
||||
│
|
||||
├── 03_reference/
|
||||
│ ├── QUICK_REFERENCE.md # Tier 3: Cheat sheet
|
||||
│ ├── INTEGRATION_GUIDE.md # Tier 3: How to integrate
|
||||
│ ├── DEPLOYMENT_GUIDE.md # Tier 3: How to deploy
|
||||
│ ├── MIGRATION_GUIDE.md # Tier 3: Version upgrades
|
||||
│ ├── MCP_TOOLS_SPEC.md # Tier 3: Tool reference
|
||||
│ ├── TOKEN_SYSTEM.md # Tier 3: Token guide
|
||||
│ ├── PRODUCTION_READINESS.md # Tier 3: Deploy checklist
|
||||
│ ├── TROUBLESHOOTING.md # Tier 3: Common problems
|
||||
│ ├── CONTRIBUTION_GUIDE.md # Tier 3: How to contribute
|
||||
│ └── DEVELOPMENT_SETUP.md # Tier 3: Dev environment
|
||||
│
|
||||
├── archive/
|
||||
│ ├── versions/
|
||||
│ │ ├── v1.0.0/
|
||||
│ │ │ ├── API_CONTRACTS.md
|
||||
│ │ │ └── ARCHITECTURE.md
|
||||
│ │ └── v1.1.0/
|
||||
│ │ └── ...
|
||||
│ ├── phases/
|
||||
│ └── 2024/
|
||||
│
|
||||
└── README.md # Repo overview
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## How to Find Information
|
||||
|
||||
### By Task
|
||||
|
||||
| I Want To... | Start Here |
|
||||
|-------------|-----------|
|
||||
| Understand DSS | PRINCIPLES.md |
|
||||
| Integrate DSS | INTEGRATION_GUIDE.md |
|
||||
| Deploy DSS | DEPLOYMENT_GUIDE.md |
|
||||
| Contribute code | CONTRIBUTION_GUIDE.md |
|
||||
| Write an endpoint | API_CONTRACTS.md + BEST_PRACTICES.md |
|
||||
| Use MCP tools | MCP_TOOLS_SPEC.md |
|
||||
| Debug something | TROUBLESHOOTING.md |
|
||||
| Check status | PROJECT_STATUS.md |
|
||||
| Upgrade version | MIGRATION_GUIDE.md |
|
||||
| Understand a decision | .knowledge/adrs/ |
|
||||
|
||||
### By Role
|
||||
|
||||
| I'm A... | Read These |
|
||||
|---------|-----------|
|
||||
| **New Developer** | PRINCIPLES.md → README.md → QUICK_REFERENCE.md |
|
||||
| **Product Manager** | PROJECT_STATUS.md → IMPLEMENTATION_SUMMARY.md |
|
||||
| **DevOps Engineer** | DEPLOYMENT_GUIDE.md → PRODUCTION_READINESS.md |
|
||||
| **API Consumer** | API_CONTRACTS.md + INTEGRATION_GUIDE.md |
|
||||
| **System Architect** | ARCHITECTURE.md + ANTI_PATTERNS_AND_LEARNINGS.md |
|
||||
| **PR Reviewer** | PRINCIPLES.md + BEST_PRACTICES.md |
|
||||
|
||||
### By Principle
|
||||
|
||||
| Principle | Learn More In |
|
||||
|-----------|--------------|
|
||||
| Design is Architectural | PRINCIPLES.md § 1, ARCHITECTURE.md |
|
||||
| Contracts are Immutable | BEST_PRACTICES.md § Principle 2, API_CONTRACTS.md |
|
||||
| Single Source of Truth | BEST_PRACTICES.md § Principle 3, ANTI_PATTERNS_AND_LEARNINGS.md |
|
||||
| Decisions Traceable | BEST_PRACTICES.md § Principle 4, .knowledge/adrs/ |
|
||||
| Operations as Tools | BEST_PRACTICES.md § Principle 5, MCP_TOOLS_SPEC.md |
|
||||
|
||||
---
|
||||
|
||||
## Reading Paths
|
||||
|
||||
### Path 1: Onboarding (30 minutes)
|
||||
```
|
||||
1. PRINCIPLES.md (5 min)
|
||||
↓
|
||||
2. README.md (5 min)
|
||||
↓
|
||||
3. QUICK_REFERENCE.md (5 min)
|
||||
↓
|
||||
4. Start with relevant Tier 3 guide for your task (15 min)
|
||||
```
|
||||
|
||||
### Path 2: Making a Decision (45 minutes)
|
||||
```
|
||||
1. PRINCIPLES.md (5 min)
|
||||
↓
|
||||
2. BEST_PRACTICES.md for relevant principle (15 min)
|
||||
↓
|
||||
3. .knowledge/adrs/ - similar decisions (15 min)
|
||||
↓
|
||||
4. ANTI_PATTERNS_AND_LEARNINGS.md (10 min)
|
||||
↓
|
||||
5. Create ADR for your decision
|
||||
```
|
||||
|
||||
### Path 3: Architectural Change (1 hour)
|
||||
```
|
||||
1. ARCHITECTURE.md (20 min)
|
||||
↓
|
||||
2. BEST_PRACTICES.md (15 min)
|
||||
↓
|
||||
3. ANTI_PATTERNS_AND_LEARNINGS.md (10 min)
|
||||
↓
|
||||
4. .knowledge/adrs/ for similar decisions (15 min)
|
||||
↓
|
||||
5. Design change, create ADR, open PR
|
||||
```
|
||||
|
||||
### Path 4: Integration (2 hours)
|
||||
```
|
||||
1. INTEGRATION_GUIDE.md (30 min)
|
||||
↓
|
||||
2. API_CONTRACTS.md (30 min)
|
||||
↓
|
||||
3. QUICK_REFERENCE.md (10 min)
|
||||
↓
|
||||
4. Implement integration, reference docs
|
||||
↓
|
||||
5. TROUBLESHOOTING.md if issues (20 min)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Docs That Reference Each Other
|
||||
|
||||
**Single Source of Truth Flow:**
|
||||
```
|
||||
PRINCIPLES.md (what we believe)
|
||||
↓
|
||||
BEST_PRACTICES.md (how to implement)
|
||||
↓
|
||||
API_CONTRACTS.md, ARCHITECTURE.md (actual specs)
|
||||
↓
|
||||
IMPLEMENTATION_GUIDE.md, DEPLOYMENT_GUIDE.md (how-to guides)
|
||||
↓
|
||||
Actual code implementation
|
||||
```
|
||||
|
||||
**Decision Flow:**
|
||||
```
|
||||
BEST_PRACTICES.md (decision criteria)
|
||||
↓
|
||||
.knowledge/adrs/ (record decision)
|
||||
↓
|
||||
PR links to ADR (traceability)
|
||||
↓
|
||||
Code implements decision
|
||||
↓
|
||||
ARCHITECTURE.md or API_CONTRACTS.md (documents result)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Keeping Docs Current
|
||||
|
||||
### Weekly (Every Friday)
|
||||
- [ ] Update PROJECT_STATUS.md
|
||||
- Mark "Last Updated"
|
||||
- Update bugs list
|
||||
- Update roadmap
|
||||
- Update deployment status
|
||||
|
||||
### Monthly (First Friday)
|
||||
- [ ] Audit all Tier 3 docs for staleness
|
||||
- Any docs older than 30 days?
|
||||
- Still accurate?
|
||||
- Update or archive?
|
||||
|
||||
### Per Release
|
||||
- [ ] Update API_CONTRACTS.md version
|
||||
- [ ] Add CHANGELOG entry
|
||||
- [ ] Update MIGRATION_GUIDE.md if breaking changes
|
||||
- [ ] Update IMPLEMENTATION_SUMMARY.md with new features
|
||||
- [ ] Create tag (git tag vX.Y.Z)
|
||||
|
||||
### When Making Major Changes
|
||||
- [ ] Create or update ADR
|
||||
- [ ] Update relevant Tier 1 docs
|
||||
- [ ] Link PR to ADR
|
||||
- [ ] Update related Tier 3 guides
|
||||
|
||||
---
|
||||
|
||||
## FAQ: Finding Documentation
|
||||
|
||||
**Q: Where are API endpoints documented?**
|
||||
A: API_CONTRACTS.md (Tier 1, immutable)
|
||||
|
||||
**Q: Why did we choose this architecture?**
|
||||
A: Check ARCHITECTURE.md or .knowledge/adrs/ (decision records)
|
||||
|
||||
**Q: What's currently deployed?**
|
||||
A: PROJECT_STATUS.md (Tier 2, updated weekly)
|
||||
|
||||
**Q: How do I integrate DSS?**
|
||||
A: INTEGRATION_GUIDE.md (Tier 3, reference guide)
|
||||
|
||||
**Q: How do I deploy changes?**
|
||||
A: DEPLOYMENT_GUIDE.md (Tier 3, step-by-step)
|
||||
|
||||
**Q: What's the status of feature X?**
|
||||
A: IMPLEMENTATION_SUMMARY.md or PROJECT_STATUS.md
|
||||
|
||||
**Q: What changed between versions?**
|
||||
A: CHANGELOG.md or MIGRATION_GUIDE.md
|
||||
|
||||
**Q: Is this documented?**
|
||||
A: Yes! (probably) → Use this guide to find it
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-08
|
||||
**Version**: 1.0.0 (new navigation guide)
|
||||
**Status**: PRODUCTION
|
||||
207
docs/01_core/PRINCIPLES.md
Normal file
207
docs/01_core/PRINCIPLES.md
Normal file
@@ -0,0 +1,207 @@
|
||||
# DSS Core Principles
|
||||
|
||||
**Version 2.1.0** | Last Updated: 2025-12-09 | Status: Production
|
||||
|
||||
The Design System Swarm (DSS) treats design as a core architectural concern, equal to code and infrastructure. By codifying design decisions into version-controlled, immutable contracts and exposing all operations via standardized tooling, we deliver consistent, high-quality user experiences with greater velocity and traceability.
|
||||
|
||||
---
|
||||
|
||||
## The 5 Core Principles
|
||||
|
||||
### 1. Design is an Architectural Concern
|
||||
|
||||
Design decisions shape system structure, not just aesthetics. Every color, spacing, and component is a **contract** that other parts of the system depend on.
|
||||
|
||||
**What this means:**
|
||||
- Design tokens are code-level dependencies, not styling suggestions
|
||||
- Component specifications are immutable contracts (API_CONTRACTS.md)
|
||||
- Design changes go through the same versioning and review as API changes
|
||||
|
||||
**Decision criteria:**
|
||||
- Does this design change affect component contracts? → Version it
|
||||
- Is this a visual tweak or structural change? → Structural = architectural
|
||||
|
||||
---
|
||||
|
||||
### 2. Contracts are Immutable and Versioned
|
||||
|
||||
Tier 1 files (API_CONTRACTS.md, ARCHITECTURE.md, PRINCIPLES.md) are the constitution. They change only through semantic versioning.
|
||||
|
||||
**What this means:**
|
||||
- Breaking changes require MAJOR version bump (v1.0.0 → v2.0.0)
|
||||
- Non-breaking additions require MINOR bump (v1.0.0 → v1.1.0)
|
||||
- Documentation fixes require PATCH bump (v1.0.0 → v1.0.1)
|
||||
- Every change includes a changelog entry
|
||||
|
||||
**Decision criteria:**
|
||||
- Will external systems break if I change this? → Don't change it (bump version first)
|
||||
- Can I add new fields without breaking old code? → Minor bump, backwards compatible
|
||||
|
||||
---
|
||||
|
||||
### 3. The System is the Single Source of Truth
|
||||
|
||||
Every piece of information exists in exactly ONE canonical location. No duplicates, no "also documented in...".
|
||||
|
||||
**What this means:**
|
||||
- API endpoints documented ONCE in API_CONTRACTS.md (not repeated in README)
|
||||
- Architecture decisions documented ONCE in ARCHITECTURE.md (not in project guides)
|
||||
- Project status documented ONCE in PROJECT_STATUS.md (not in weekly reports)
|
||||
- Use links instead of copy-paste for cross-references
|
||||
|
||||
**Decision criteria:**
|
||||
- Does this information already exist somewhere? → Link to it, don't duplicate
|
||||
- Is there conflicting information in two places? → Find the canonical source and delete the copy
|
||||
|
||||
---
|
||||
|
||||
### 4. Decisions are Explicit and Traceable
|
||||
|
||||
Why did we choose this? → Check the Architecture Decision Record (ADR).
|
||||
|
||||
**What this means:**
|
||||
- Significant architectural decisions documented in `.knowledge/adrs/`
|
||||
- Every ADR includes: context, decision, alternatives considered, consequences
|
||||
- Code changes link to ADRs (`Implements ADR-002`)
|
||||
- Decision rationale is preserved, not lost in commit messages
|
||||
|
||||
**Decision criteria:**
|
||||
- Will someone ask "why did we do this?" in 6 months? → Document it as an ADR
|
||||
- Is this a one-off technical choice or a pattern? → If pattern, it's an ADR
|
||||
|
||||
---
|
||||
|
||||
### 5. Operations are Exposed as Standardized Tools
|
||||
|
||||
Model Context Protocol (MCP) tools are first-class. REST endpoints wrap tools, not the reverse. Agents interact via tools; humans use tools through UIs.
|
||||
|
||||
**What this means:**
|
||||
- Every operation (create project, sync tokens, etc.) is an MCP tool
|
||||
- REST endpoints wrap tools, not standalone logic
|
||||
- Agents have full autonomy via tools
|
||||
- All operations logged in audit trail
|
||||
|
||||
**Decision criteria:**
|
||||
- Is this a new capability? → Create as MCP tool first, then REST endpoint wraps it
|
||||
- Should humans or agents do this? → Humans use tool through UI, agents use directly
|
||||
|
||||
---
|
||||
|
||||
## How These Principles Work Together
|
||||
|
||||
```
|
||||
Design Decisions (Principle 1)
|
||||
↓
|
||||
Version in Contracts (Principle 2)
|
||||
↓
|
||||
Document in Single Location (Principle 3)
|
||||
↓
|
||||
Record Why in ADR (Principle 4)
|
||||
↓
|
||||
Expose as MCP Tool (Principle 5)
|
||||
↓
|
||||
Governed by Admin Standards (Admin Principles)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Admin & Operational Standards
|
||||
|
||||
The administration of the DSS is governed by a specific set of operational standards that extend these core principles.
|
||||
|
||||
**See [ADMIN_PRINCIPLES.md](./ADMIN_PRINCIPLES.md) for the detailed specification.**
|
||||
|
||||
**Key Admin Principles:**
|
||||
1. **Visibility**: Transparent system state (Glass Box).
|
||||
2. **Authority**: Decisions bounded by contracts (No God Mode).
|
||||
3. **Accountability**: All actions audited and attributed.
|
||||
4. **Partnership**: Distinct roles for Developers and Admins.
|
||||
5. **Isolation**: Admin plane survives User plane failures.
|
||||
|
||||
---
|
||||
|
||||
## What to Do When Principles Conflict
|
||||
|
||||
Use this hierarchy:
|
||||
|
||||
1. **Contracts are Immutable** (highest priority)
|
||||
2. **Single Source of Truth**
|
||||
3. **Operations as Tools**
|
||||
4. **Decisions Traceable**
|
||||
5. **Design is Architecture** (lowest priority)
|
||||
|
||||
**Example**: If MCP tooling would break an API contract → Keep the contract, deprecate the old tool, introduce new one in next major version.
|
||||
|
||||
---
|
||||
|
||||
## For Different Audiences
|
||||
|
||||
**New Developer:**
|
||||
1. Read this file (5 min)
|
||||
2. Read DOCUMENTATION_GUIDE.md (10 min)
|
||||
3. Start with QUICK_REFERENCE.md for your task
|
||||
|
||||
**Making a Decision:**
|
||||
1. Will this break a contract? (Principle 2)
|
||||
2. Will this duplicate existing info? (Principle 3)
|
||||
3. Should this be an MCP tool? (Principle 5)
|
||||
4. Document in an ADR if significant (Principle 4)
|
||||
|
||||
**Doing Code Review:**
|
||||
- Does this create duplicate documentation? ✗
|
||||
- Is the version updated? ✓
|
||||
- Should this be an MCP tool? ✓
|
||||
- Is there an ADR for this decision? (if major change) ✓
|
||||
|
||||
---
|
||||
|
||||
## Key Documents
|
||||
|
||||
- **API_CONTRACTS.md**: Endpoint specifications (immutable, versioned)
|
||||
- **ARCHITECTURE.md**: System design and structure (immutable, versioned)
|
||||
- **ADMIN_PRINCIPLES.md**: Operational standards and admin governance
|
||||
- **PROJECT_STATUS.md**: Current state (updated weekly, not immutable)
|
||||
- **IMPLEMENTATION_SUMMARY.md**: Feature inventory by phase
|
||||
- **.knowledge/adrs/**: Decision records (why we chose this way)
|
||||
- **DOCUMENTATION_GUIDE.md**: Map of all documentation (where to find what)
|
||||
- **BEST_PRACTICES.md**: How to apply principles (implementation patterns)
|
||||
- **ANTI_PATTERNS_AND_LEARNINGS.md**: What not to do (and why)
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
- ✅ No duplicate documentation (links used instead)
|
||||
- ✅ All major decisions in `.knowledge/adrs/`
|
||||
- ✅ Tier 1 files (contracts) never change without version bump
|
||||
- ✅ PROJECT_STATUS.md updated weekly
|
||||
- ✅ All operations have MCP tools (REST wraps tools)
|
||||
- ✅ New developer can start coding in 30 min (read QUICK_REFERENCE → DOCUMENTATION_GUIDE → relevant guide)
|
||||
- ✅ Team asks "which principle applies here?" before PRs
|
||||
|
||||
---
|
||||
|
||||
## Evolution Path
|
||||
|
||||
**Year 1 (Now)**: Manual enforcement
|
||||
- Team follows principles consciously
|
||||
- Pre-commit hooks catch violations
|
||||
- CI/CD validates consistency
|
||||
|
||||
**Year 2**: Automation
|
||||
- Generate semver from change detection
|
||||
- Auto-generate changelogs
|
||||
- Tools self-discover from API schema
|
||||
|
||||
**Year 3**: Code-from-Graph
|
||||
- ARCHITECTURE.md generates TypeScript types
|
||||
- API_CONTRACTS.md generates OpenAPI + SDK types
|
||||
- ADRs generate test suites
|
||||
- Rules become executable code
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-09
|
||||
**Version**: 2.2.0 (Integrated 6-principle Admin framework)
|
||||
**Previous Version**: 2.1.0
|
||||
**Status**: PRODUCTION - All principles active and enforced
|
||||
999
docs/01_core/PRINCIPLES_DEEP.md
Normal file
999
docs/01_core/PRINCIPLES_DEEP.md
Normal file
@@ -0,0 +1,999 @@
|
||||
# DSS Principles Deep Dive (v1.2.0 - Archived Reference)
|
||||
|
||||
**Version 1.2.0** | Last Updated: 2025-12-08 | Status: Archived Reference Only
|
||||
|
||||
This document contains the full elaboration of DSS principles from **Version 1.2.0**, archived for reference when you need deep understanding of individual principles.
|
||||
|
||||
**See PRINCIPLES.md for the current concise version (2.0.0).**
|
||||
|
||||
---
|
||||
|
||||
## When to Use This Document
|
||||
|
||||
You're reading the right document if:
|
||||
- You need detailed explanation of a principle
|
||||
- You want to understand the "why" behind enforcement mechanisms
|
||||
- You're implementing pre-commit hooks or CI/CD checks
|
||||
- You want to see all the red flags and success metrics
|
||||
|
||||
You should read **PRINCIPLES.md** if:
|
||||
- You're new to DSS (quick overview)
|
||||
- You're making a decision
|
||||
- You want decision-making criteria
|
||||
- You have 5-10 minutes
|
||||
|
||||
---
|
||||
|
||||
## Structure of This Document
|
||||
|
||||
This document covers the same 5 core principles as PRINCIPLES.md (v2.0.0) but with full elaboration:
|
||||
|
||||
### For Each Principle:
|
||||
- **Core Concept**: What it means
|
||||
- **Why It Matters**: Business/technical rationale
|
||||
- **How to Apply**: Step-by-step implementation
|
||||
- **Implementation Checklist**: Verification items
|
||||
- **Red Flags**: Anti-patterns to watch for
|
||||
- **Enforcement Mechanism**: Pre-commit hooks and CI checks
|
||||
- **Success Metrics**: How to measure implementation
|
||||
|
||||
---
|
||||
|
||||
## The 5 Principles (Detailed)
|
||||
|
||||
### Principle 1: Design is an Architectural Concern
|
||||
|
||||
**Core Concept**
|
||||
|
||||
Design decisions shape system structure, not just aesthetics. Every color, spacing, and component is a **contract** that other parts of the system depend on.
|
||||
|
||||
**Why It Matters**
|
||||
|
||||
- **Consistency**: Design tokens are dependencies; inconsistency breaks contracts
|
||||
- **Testability**: Component specs are testable contracts
|
||||
- **Evolution**: Design changes tracked with same rigor as API changes
|
||||
- **Autonomy**: Teams can work independently if contracts are clear
|
||||
|
||||
**How to Apply**
|
||||
|
||||
1. **Treat Design Tokens as Code Dependencies**
|
||||
|
||||
Design tokens (colors, spacing, typography) are not styling suggestions—they're contracts that code depends on.
|
||||
|
||||
```
|
||||
❌ WRONG:
|
||||
<!-- Using hex values directly -->
|
||||
<Button style={{ background: "#007AFF" }} />
|
||||
|
||||
✅ RIGHT:
|
||||
<!-- Using design token from contract -->
|
||||
<Button background={tokens.color.primary[500]} />
|
||||
```
|
||||
|
||||
Checklist:
|
||||
- [ ] All color values come from token definitions
|
||||
- [ ] All spacing values come from token definitions
|
||||
- [ ] All typography values come from token definitions
|
||||
- [ ] Components reference tokens, not hardcoded values
|
||||
- [ ] Token schema documented in tokens/ directory
|
||||
- [ ] Tokens versioned with semantic versioning
|
||||
|
||||
Enforcement:
|
||||
```bash
|
||||
# Pre-commit check: No hardcoded hex colors in component code
|
||||
grep -r "#[0-9A-F]{6}" packages/components/ && exit 1
|
||||
```
|
||||
|
||||
2. **Design Changes Follow Same Review as API Changes**
|
||||
|
||||
A design change that affects components requires the same rigor as an API change.
|
||||
|
||||
```
|
||||
Component Update Example:
|
||||
Old Contract: Button[variant=primary] uses color.primary[500]
|
||||
New Contract: Button[variant=primary] uses color.primary[600]
|
||||
|
||||
Requires:
|
||||
✅ Version bump in component spec
|
||||
✅ Migration guide for consumers
|
||||
✅ Changelog entry
|
||||
✅ 6-month deprecation notice for old version
|
||||
```
|
||||
|
||||
Checklist:
|
||||
- [ ] Design change documented in ARCHITECTURE.md
|
||||
- [ ] Component contract updated with version
|
||||
- [ ] Migration path provided if breaking
|
||||
- [ ] Changelog entry created
|
||||
- [ ] Deprecation timeline documented
|
||||
|
||||
3. **Make Visual Decisions Explicit**
|
||||
|
||||
Every design decision should be traceable back to why (not "looks good").
|
||||
|
||||
```
|
||||
❌ "Changed button color to blue"
|
||||
✅ "Changed button color from color.primary[500] to color.primary[600]
|
||||
for improved contrast on light backgrounds (WCAG AA compliance)"
|
||||
```
|
||||
|
||||
Checklist:
|
||||
- [ ] Design decisions documented in ADR
|
||||
- [ ] Visual change rationale explained
|
||||
- [ ] Alternatives considered documented
|
||||
- [ ] Impact assessment done
|
||||
- [ ] Accessibility implications checked
|
||||
|
||||
**Red Flags**
|
||||
|
||||
```
|
||||
❌ "Let me just tweak this spacing"
|
||||
→ Is it breaking a contract? Document the change
|
||||
|
||||
❌ Figma file has one value, component has another
|
||||
→ Single source of truth violation; reconcile immediately
|
||||
|
||||
❌ "Designers will use Figma, developers will use tokens"
|
||||
→ Should be the same source (tokens in Figma, imported to code)
|
||||
|
||||
❌ Visual change not documented in ARCHITECTURE.md
|
||||
→ Architectural decisions should be explicit
|
||||
```
|
||||
|
||||
**Enforcement Mechanism**
|
||||
|
||||
Pre-commit hook: `check-design-tokens.py`
|
||||
```python
|
||||
# Validates all hardcoded colors are in token definitions
|
||||
# Fails if: component uses non-token color value
|
||||
# Exception: Comments explaining legacy colors (documented)
|
||||
```
|
||||
|
||||
CI Check: `design-consistency`
|
||||
```yaml
|
||||
# Compares Figma tokens against code tokens
|
||||
# Fails if: values diverge (SSoT violation)
|
||||
# Validates component specs match contracts
|
||||
```
|
||||
|
||||
**Success Metrics**
|
||||
|
||||
- All components use design tokens (zero hardcoded values)
|
||||
- Figma and code tokens always in sync
|
||||
- Design changes versioned like API changes
|
||||
- Component contracts documented in ARCHITECTURE.md
|
||||
- Developers can cite design decisions in PRs
|
||||
|
||||
---
|
||||
|
||||
### Principle 2: Contracts are Immutable and Versioned
|
||||
|
||||
**Core Concept**
|
||||
|
||||
Tier 1 files (API_CONTRACTS.md, ARCHITECTURE.md, PRINCIPLES.md) are the constitution. They change only through semantic versioning.
|
||||
|
||||
**Why It Matters**
|
||||
|
||||
- **Backwards Compatibility**: Consumers rely on these specs not changing randomly
|
||||
- **Trust**: External systems can pin to a version and stay stable
|
||||
- **Intentionality**: Every API change is deliberate, not accidental
|
||||
- **Governance**: Breaking changes require explicit version bump, not silent updates
|
||||
|
||||
**How to Apply**
|
||||
|
||||
1. **Immutable Until Version Bump**
|
||||
|
||||
```
|
||||
docs/01_core/API_CONTRACTS.md
|
||||
Version 1.2.3 ← This is THE contract
|
||||
|
||||
Changes allowed:
|
||||
✅ Add new endpoints (1.3.0 - minor bump)
|
||||
✅ Extend with optional fields (1.2.4 - patch bump)
|
||||
✅ Fix documentation clarity (1.2.4 - patch bump)
|
||||
✅ Deprecate endpoint (add note, bump to 1.4.0)
|
||||
|
||||
Breaking changes FORBIDDEN until major bump:
|
||||
❌ Remove endpoint
|
||||
❌ Change auth scheme
|
||||
❌ Change response schema (breaking)
|
||||
❌ Change error codes
|
||||
```
|
||||
|
||||
2. **Clear Deprecation Path**
|
||||
|
||||
```
|
||||
## Endpoint: GET /api/v1/projects/{id}
|
||||
|
||||
**Status**: Active (v1.2.0+)
|
||||
**Deprecation**: Will remove in v3.0.0 (projected Q2 2026)
|
||||
**Migration**: See MIGRATION_GUIDE.md for upgrade path
|
||||
|
||||
Request: {...}
|
||||
Response: {...}
|
||||
```
|
||||
|
||||
3. **Version Everything**
|
||||
|
||||
- API contracts include version (e.g., "endpoints as of v1.2.3")
|
||||
- Architecture versioning tracks major design shifts (e.g., "Token merge system v2.1")
|
||||
- Principles versioning tracks philosophy evolution (rare)
|
||||
|
||||
4. **Never Silent Changes**
|
||||
|
||||
- Every change to Tier 1 triggers a version bump AND changelog
|
||||
- Changelog entry: what changed, why, migration path
|
||||
- Old versions archived in `docs/archive/versions/`
|
||||
|
||||
**Implementation Checklist**
|
||||
|
||||
- [ ] All Tier 1 files include version number at top (Version X.Y.Z)
|
||||
- [ ] Versioning follows semantic versioning (MAJOR.minor.patch)
|
||||
- [ ] Changelog entries for every Tier 1 change
|
||||
- [ ] Deprecated endpoints marked with sunset date
|
||||
- [ ] Breaking changes bump MAJOR version (very rare)
|
||||
- [ ] Non-breaking additions bump minor version
|
||||
- [ ] Documentation fixes bump patch version
|
||||
- [ ] Old API versions archived with `VERSIONING.md` map
|
||||
|
||||
**Conflict Resolution: Contracts vs MCP First**
|
||||
|
||||
When a new MCP tool would require breaking the API contract:
|
||||
```
|
||||
Hierarchy: Foundational Contracts > MCP First
|
||||
|
||||
Action:
|
||||
1. Add new MCP tool (doesn't violate contract)
|
||||
2. Keep legacy API endpoint working
|
||||
3. Mark legacy as deprecated, suggest MCP alternative
|
||||
4. Plan sunset in next major version
|
||||
|
||||
Example:
|
||||
OLD API (v1.2.0):
|
||||
POST /api/projects/figma/link
|
||||
|
||||
NEW MCP TOOL (v1.2.0+):
|
||||
dss_add_figma_file (MCP-first approach)
|
||||
|
||||
Migration Path:
|
||||
• 1.2.0: Both work (API deprecated in docs)
|
||||
• 2.0.0: API removed, MCP tool is SSoT
|
||||
```
|
||||
|
||||
**Red Flags**
|
||||
|
||||
```
|
||||
❌ API_CONTRACTS.md updated without version bump
|
||||
→ Version should change with EVERY update
|
||||
|
||||
❌ Endpoint removed, no deprecation notice
|
||||
→ Should have been deprecated for 6+ months first
|
||||
|
||||
❌ No changelog for API changes
|
||||
→ Every version bump needs "What changed" entry
|
||||
|
||||
❌ Architecture changes silently reflected in code
|
||||
→ Changes must be explicit in ARCHITECTURE.md with rationale
|
||||
```
|
||||
|
||||
**Enforcement Mechanism**
|
||||
|
||||
Pre-commit hook: `schema-diff.py`
|
||||
```python
|
||||
# Compares API spec version in file against git history
|
||||
# Fails if: file changed but version number didn't change
|
||||
# Exception: Version file itself (PR metadata only)
|
||||
```
|
||||
|
||||
CI Check: `version-bump-validator`
|
||||
```yaml
|
||||
# For any change to Tier 1 files:
|
||||
# - Requires version bump
|
||||
# - Requires changelog entry
|
||||
# - Validates semver format
|
||||
# - Updates VERSIONING.md map
|
||||
```
|
||||
|
||||
**Success Metrics**
|
||||
|
||||
- No file mirrors content from another (use links instead)
|
||||
- Each API endpoint documented once with version number
|
||||
- No "draft" or "TODO" versions of specs floating around
|
||||
- Git history shows updates to core docs, not creation of new ones
|
||||
- Breaking changes properly sunset (6+ months deprecation period)
|
||||
|
||||
---
|
||||
|
||||
### Principle 3: The System is the Single Source of Truth
|
||||
|
||||
**Core Concept**
|
||||
|
||||
Tier 2 files (PROJECT_STATUS.md, IMPLEMENTATION_SUMMARY.md, README.md) always reflect production reality. They are living documents updated at least weekly.
|
||||
|
||||
**Why It Matters**
|
||||
|
||||
- **No Hallucination**: Agents read what's actually deployed, not aspirational state
|
||||
- **Trust**: Stakeholders can check status without asking
|
||||
- **Incident Response**: Current state is documented for quick triage
|
||||
- **History**: Changes are logged for retrospectives
|
||||
|
||||
**How to Apply**
|
||||
|
||||
1. **PROJECT_STATUS.md Is The Source**
|
||||
|
||||
```markdown
|
||||
# Project Status
|
||||
|
||||
Last Updated: 2025-12-08
|
||||
Current Phase: Phase 5D - Production Hardening
|
||||
|
||||
## Deployment Status
|
||||
- Production: v1.2.3 (deployed 2025-12-05)
|
||||
- Staging: v1.3.0-rc.1 (testing new features)
|
||||
- Current Focus: MCP tool stabilization
|
||||
|
||||
## Open Bugs (prioritized)
|
||||
1. CRITICAL: Figma token sync timeout (affects 3 projects)
|
||||
2. HIGH: Pre-commit hook slow on large repos
|
||||
3. MEDIUM: Typo in INTEGRATION_GUIDE.md
|
||||
|
||||
## Roadmap
|
||||
- Week of 12/8: Fix token sync timeout
|
||||
- Week of 12/15: Release v1.2.4 (bug fixes)
|
||||
- Q1 2026: MCP tool ecosystem expansion
|
||||
```
|
||||
|
||||
2. **Update Weekly (Not Monthly)**
|
||||
|
||||
- Every Friday: Review bugs, deployment status, roadmap changes
|
||||
- Update "Last Updated" timestamp
|
||||
- Use past tense for completed work: "Fixed token timeout (12/8)"
|
||||
|
||||
3. **What Goes in PROJECT_STATUS.md**
|
||||
|
||||
- Current deployment version in production
|
||||
- Current phase/sprint (if relevant)
|
||||
- Open bugs (prioritized)
|
||||
- In-progress features
|
||||
- Upcoming roadmap (next 4 weeks visible)
|
||||
- Known limitations
|
||||
- Maintenance windows
|
||||
|
||||
4. **IMPLEMENTATION_SUMMARY.md**
|
||||
|
||||
- Complete inventory of features by phase
|
||||
- Phase 1: User authentication, project creation
|
||||
- Phase 2: Figma integration, token management
|
||||
- Phase 3: Component sync, design tokens
|
||||
- etc.
|
||||
|
||||
**Implementation Checklist**
|
||||
|
||||
- [ ] PROJECT_STATUS.md updated every Friday
|
||||
- [ ] "Last Updated" timestamp current (within 7 days)
|
||||
- [ ] Production version matches git tags
|
||||
- [ ] All open bugs tracked with priority
|
||||
- [ ] Roadmap looks 4 weeks ahead (not vague)
|
||||
- [ ] Completed work removed from todo lists
|
||||
- [ ] Deployment changes logged with dates
|
||||
- [ ] Incident post-mortems update "Known Limitations"
|
||||
|
||||
**Red Flags**
|
||||
|
||||
```
|
||||
❌ "Last Updated: 2025-11-15" (older than 7 days)
|
||||
→ Is this stale? Update it this week
|
||||
|
||||
❌ "Phase: TBD" or "Roadmap: TBD"
|
||||
→ Status should be concrete, not vague
|
||||
|
||||
❌ "See MVP_FINAL_REPORT.md for details"
|
||||
→ Archive the report; put summary in PROJECT_STATUS
|
||||
|
||||
❌ "Fixed: Token sync issue (date unknown)"
|
||||
→ Always date stamp: "Fixed 2025-12-05"
|
||||
```
|
||||
|
||||
**Enforcement Mechanism**
|
||||
|
||||
Git hook: `status-staleness-check.py`
|
||||
```python
|
||||
# Runs before push to production
|
||||
# Checks: PROJECT_STATUS.md "Last Updated" is within 7 days
|
||||
# Fails if stale (prevents deploying with old status)
|
||||
```
|
||||
|
||||
CI Check: `version-sync`
|
||||
```yaml
|
||||
# Validates PROJECT_STATUS.md version matches git tag
|
||||
# Validates IMPLEMENTATION_SUMMARY.md references match features in code
|
||||
# Fails if status doesn't match deployed code
|
||||
```
|
||||
|
||||
GitHub Actions: `weekly-status-reminder`
|
||||
```yaml
|
||||
# Every Friday at 5pm: Opens PR with PROJECT_STATUS.md template
|
||||
# Reminder to team: Update status before weekend
|
||||
# Cannot be merged; just a CTA
|
||||
```
|
||||
|
||||
**Success Metrics**
|
||||
|
||||
- PROJECT_STATUS.md updated every 7 days max
|
||||
- Production version in status matches deployed code
|
||||
- Bugs filed have corresponding entries in status
|
||||
- Completed features removed from in-progress list
|
||||
- Roadmap always 4+ weeks visible
|
||||
- Team consensus: "This is the one source of project truth"
|
||||
|
||||
---
|
||||
|
||||
### Principle 4: Decisions are Explicit and Traceable
|
||||
|
||||
**Core Concept**
|
||||
|
||||
Architecture decisions, design rationales, and system history live in a structured knowledge graph (`.knowledge/`), not scattered across markdown files. The graph is queryable and executable.
|
||||
|
||||
**Why It Matters**
|
||||
|
||||
- **Rationale**: Why was this decision made? Check the graph.
|
||||
- **Traceability**: Who decided this? When? What alternatives?
|
||||
- **Evolution**: Track how decisions evolved over time
|
||||
- **Executability**: Graph can generate code (Year 3 vision)
|
||||
- **Machine-Readable**: Agents can reason about decisions systematically
|
||||
|
||||
**How to Apply**
|
||||
|
||||
1. **ADR (Architecture Decision Record) Pattern**
|
||||
|
||||
File: `.knowledge/decisions/ADR-0001.md`
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: ADR-0001
|
||||
title: Token Merge System as Core DSS Feature
|
||||
date: 2025-12-05
|
||||
author(s): Team Name
|
||||
status: Accepted
|
||||
principles: [Design is Architectural, Contracts Immutable, Single Source of Truth]
|
||||
related:
|
||||
- doc: docs/01_core/ARCHITECTURE.md#token-merge
|
||||
- adr: ADR-0002-MCP-first-architecture
|
||||
- ticket: DSS-PR-101
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Multiple projects needed to ingest tokens from Figma, CSS, SCSS. Without normalization, incompatible systems couldn't coexist.
|
||||
|
||||
## Decision
|
||||
|
||||
Implement TokenMerger class with pluggable merge strategies (FIRST, LAST, PREFER_FIGMA, PREFER_CODE, PREFER_SPECIFIC, MERGE_METADATA).
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
1. **Manual token mapping**
|
||||
- Reason rejected: Doesn't scale; requires human review per project
|
||||
|
||||
2. **Single canonical merge strategy**
|
||||
- Reason rejected: Too rigid; different projects have different workflows
|
||||
|
||||
## Consequences
|
||||
|
||||
**Positive:**
|
||||
- Supports multiple UI libraries (flexibly)
|
||||
- Non-breaking integration (each project chooses strategy)
|
||||
- Auditable (all merges logged)
|
||||
|
||||
**Negative:**
|
||||
- More complex than single strategy
|
||||
- Developers must understand each strategy
|
||||
- Potential for misconfiguration
|
||||
```
|
||||
|
||||
2. **Design Patterns Library**
|
||||
|
||||
File: `.knowledge/patterns/pattern-optional-auth.md`
|
||||
|
||||
```markdown
|
||||
# Optional Authentication Middleware
|
||||
|
||||
## Problem
|
||||
|
||||
Some endpoints work anonymous (GET /projects) but also work authenticated (same endpoint with per-user filtering).
|
||||
|
||||
## Solution
|
||||
|
||||
Optional auth middleware that validates token IF present, but doesn't require it.
|
||||
|
||||
## Implementation
|
||||
|
||||
See docs/01_core/ARCHITECTURE.md#optional-auth-middleware
|
||||
|
||||
## Use Cases
|
||||
|
||||
- GET /projects (public → all, authenticated → user's projects)
|
||||
- GET /api/health (always works, no auth needed)
|
||||
|
||||
## Trade-offs
|
||||
|
||||
- More complex than required auth
|
||||
- Security: Never trust unauthenticated requests
|
||||
```
|
||||
|
||||
3. **Component Contract Graph**
|
||||
|
||||
File: `.knowledge/components/Button.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "Button",
|
||||
"canonical_path": "packages/components/Button/Button.tsx",
|
||||
"contract_version": "1.2.0",
|
||||
"interface": {
|
||||
"variant": ["primary", "secondary", "ghost"],
|
||||
"size": ["sm", "md", "lg"],
|
||||
"disabled": "boolean"
|
||||
},
|
||||
"story_path": "packages/components/Button/Button.stories.tsx",
|
||||
"api_endpoint": "GET /api/components/button",
|
||||
"figma_file_id": "figd_abc123",
|
||||
"figma_component_name": "Button",
|
||||
"design_tokens": [
|
||||
"color.primary.500",
|
||||
"color.primary.600",
|
||||
"spacing.md",
|
||||
"radius.sm"
|
||||
],
|
||||
"accessibility": {
|
||||
"wcag_level": "AA",
|
||||
"tested": true,
|
||||
"issues": []
|
||||
},
|
||||
"related_components": ["Input", "Modal"],
|
||||
"status": "stable"
|
||||
}
|
||||
```
|
||||
|
||||
4. **Integration Points**
|
||||
|
||||
File: `.knowledge/integrations/figma-sync.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "figma-sync",
|
||||
"name": "Figma ↔ DSS Token Sync",
|
||||
"status": "active",
|
||||
"flow": {
|
||||
"source": "Figma file (figma.json manifest)",
|
||||
"processor": "dss_sync_figma (MCP tool)",
|
||||
"target": "Local project tokens",
|
||||
"frequency": "On-demand (manual trigger via MCP)"
|
||||
},
|
||||
"reliability": {
|
||||
"failures_per_week": 0,
|
||||
"timeout_seconds": 30,
|
||||
"retry_strategy": "exponential-backoff"
|
||||
},
|
||||
"related_tools": [
|
||||
"dss_add_figma_file",
|
||||
"dss_discover_figma_files",
|
||||
"dss_get_project_manifest"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Implementation Checklist**
|
||||
|
||||
- [ ] Create `.knowledge/` directory structure
|
||||
- [ ] Document core ADRs (Decision #1 in ADR-0001, etc.)
|
||||
- [ ] Create pattern library for reusable designs
|
||||
- [ ] Map component contracts in graph format
|
||||
- [ ] Record integration points and reliability metrics
|
||||
- [ ] Link markdown files to related knowledge entries
|
||||
- [ ] Enable querying: `query_knowledge("token merge")` returns ADRs + patterns
|
||||
- [ ] Set up graph visualization (D3.js or similar)
|
||||
|
||||
**Graph Structure**
|
||||
|
||||
```
|
||||
.knowledge/
|
||||
├── decisions/ # Architecture Decision Records
|
||||
│ ├── ADR-0001.md # Token merge system
|
||||
│ ├── ADR-0002.md # MCP-first architecture
|
||||
│ ├── ADR-0003.md # Knowledge graph as SSoT
|
||||
│ └── ...
|
||||
├── patterns/ # Design patterns library
|
||||
│ ├── pattern-optional-auth.md
|
||||
│ ├── pattern-translation-dictionary.md
|
||||
│ ├── pattern-component-extension.md
|
||||
│ └── ...
|
||||
├── components/ # Component contracts
|
||||
│ ├── Button.json
|
||||
│ ├── Input.json
|
||||
│ ├── Card.json
|
||||
│ └── ...
|
||||
├── integrations/ # External system integrations
|
||||
│ ├── figma-sync.json
|
||||
│ ├── shadcn-migration.json
|
||||
│ ├── heroui-migration.json
|
||||
│ └── ...
|
||||
├── graph.json # Full knowledge graph (generated)
|
||||
└── graph.schema.json # JSON Schema for validation
|
||||
```
|
||||
|
||||
**Conflict Resolution: Knowledge Persistence vs Foundational Contracts**
|
||||
|
||||
When a decision conflicts with documented contract:
|
||||
```
|
||||
Hierarchy: Foundational Contracts > Knowledge Persistence
|
||||
|
||||
Action:
|
||||
1. If decision is old, update ADR to "superseded"
|
||||
2. Create new ADR explaining contract change
|
||||
3. Update API_CONTRACTS.md version number
|
||||
4. Link new ADR from contract file
|
||||
|
||||
Example:
|
||||
Old ADR: "Auth is required on all endpoints"
|
||||
Current API: "Auth is optional (pattern-optional-auth)"
|
||||
Fix: ADR → superseded, new ADR → current pattern
|
||||
```
|
||||
|
||||
**Red Flags**
|
||||
|
||||
```
|
||||
❌ "Design decision" explained only in a commit message
|
||||
→ Should be in .knowledge/decisions/ as ADR
|
||||
|
||||
❌ "Component contract is in Figma notes"
|
||||
→ Should be in .knowledge/components/ComponentName.json
|
||||
|
||||
❌ Multiple integration patterns documented in markdown
|
||||
→ Should be in .knowledge/patterns/
|
||||
|
||||
❌ No link between markdown and knowledge graph entries
|
||||
→ Each should reference the other
|
||||
```
|
||||
|
||||
**Enforcement Mechanism**
|
||||
|
||||
Pre-commit hook: `knowledge-graph-validator.py`
|
||||
```python
|
||||
# Validates .knowledge/*.json against schema
|
||||
# Ensures all ADRs are properly formatted
|
||||
# Warns if decision made in code without ADR
|
||||
```
|
||||
|
||||
CI Check: `orphaned-knowledge`
|
||||
```yaml
|
||||
# Finds ADRs/patterns not referenced in any markdown
|
||||
# Finds markdown decisions not in knowledge graph
|
||||
# Flags for review: "Knowledge graph is out of sync"
|
||||
```
|
||||
|
||||
**Success Metrics**
|
||||
|
||||
- Every major decision has an ADR (with rationale, alternatives, consequences)
|
||||
- Every design pattern documented in pattern library
|
||||
- Every component contract defined in graph
|
||||
- Markdown links to graph entries (and vice versa)
|
||||
- Developers can query knowledge: "Why did we choose MCP-first?"
|
||||
- Year 3: Graph generates TypeScript types (executable specs)
|
||||
|
||||
---
|
||||
|
||||
### Principle 5: Operations are Exposed as Standardized Tools
|
||||
|
||||
**Core Concept**
|
||||
|
||||
Model Context Protocol (MCP) tools are first-class citizens for all operations. REST endpoints are secondary (for human access). Agents interact via MCP tools; humans use the tools OR web UI (which uses the tools).
|
||||
|
||||
**Why It Matters**
|
||||
|
||||
- **Agent Autonomy**: Agents don't wait for UI; they use tools directly
|
||||
- **Consistency**: All operations (human or agent) go through same tools
|
||||
- **Auditability**: Every operation logged in mcp_tool_usage
|
||||
- **Extensibility**: Adding new capability = adding MCP tool (not API endpoint)
|
||||
- **Future-Proof**: Year 3 vision: All work done via agents, tools are primary interface
|
||||
|
||||
**How to Apply**
|
||||
|
||||
1. **Tool-First Architecture**
|
||||
|
||||
```
|
||||
WRONG ❌ (REST-first, tools secondary)
|
||||
───────────────────────────────────
|
||||
Operation: Create new project
|
||||
|
||||
Primary: POST /api/projects
|
||||
Secondary: dss_create_project MCP tool (calls REST endpoint)
|
||||
|
||||
Flow: Agent → MCP tool → REST API → Database
|
||||
Problem: Extra layer, still tied to HTTP API
|
||||
|
||||
RIGHT ✅ (MCP-first, REST is UI only)
|
||||
──────────────────────────────────
|
||||
Operation: Create new project
|
||||
|
||||
Primary: dss_create_project MCP tool (direct to database)
|
||||
Secondary: REST endpoint POST /api/projects (uses MCP tool internally)
|
||||
|
||||
Flow Agent: Agent → MCP tool → Database
|
||||
Flow (Human via UI): UI button → MCP tool → Database
|
||||
|
||||
Result: Single source of truth (tool), REST is thin wrapper
|
||||
```
|
||||
|
||||
2. **Current MCP Tool Inventory**
|
||||
|
||||
**Project Management** (docs/03_reference/MCP_TOOLS_SPEC.md):
|
||||
- `dss_create_project` - Create new project with figma.json manifest
|
||||
- `dss_setup_figma_credentials` - Store user's Figma API token (encrypted)
|
||||
- `dss_get_project_manifest` - Read project's figma.json
|
||||
- `dss_add_figma_file` - Link Figma file to project
|
||||
- `dss_discover_figma_files` - List available Figma files
|
||||
- `dss_list_project_figma_files` - List linked files
|
||||
|
||||
**Token Extraction & Merging**:
|
||||
- `dss_extract_tokens` - Extract from CSS, SCSS, Tailwind, JSON
|
||||
- `dss_merge_tokens` - Merge multiple sources with strategies
|
||||
- `dss_resolve_token` - Look up token through cascade
|
||||
|
||||
**Design System Operations**:
|
||||
- `dss_sync_figma` - Sync tokens from Figma file
|
||||
- `dss_transform_tokens` - Convert between token formats
|
||||
- `dss_generate_theme` - Generate theme output files
|
||||
|
||||
**Analysis & Auditing**:
|
||||
- `dss_analyze_project` - Analyze codebase for patterns
|
||||
- `dss_audit_components` - Audit component adoption
|
||||
- `dss_find_quick_wins` - Identify easy improvements
|
||||
|
||||
3. **Tool Design Pattern**
|
||||
|
||||
```python
|
||||
# In tools/dss_mcp/tools/project_tools.py
|
||||
|
||||
class ProjectTools:
|
||||
"""All project operations as MCP tools (primary interface)"""
|
||||
|
||||
async def dss_create_project(
|
||||
self,
|
||||
name: str,
|
||||
root_path: str,
|
||||
description: str = ""
|
||||
) -> Dict:
|
||||
"""Create new project (primary: MCP tool, not REST API)"""
|
||||
# 1. Validate input
|
||||
# 2. Insert into database
|
||||
# 3. Create figma.json manifest
|
||||
# 4. Log to mcp_tool_usage table
|
||||
# 5. Emit event
|
||||
# 6. Return result
|
||||
|
||||
# REST endpoint just wraps this
|
||||
# @app.post("/api/projects")
|
||||
# async def create_project_rest(request):
|
||||
# return await self.dss_create_project(...)
|
||||
```
|
||||
|
||||
4. **Tool Versioning & Documentation**
|
||||
|
||||
```
|
||||
MCP Tool versioning mirrors API versioning:
|
||||
|
||||
Tool: dss_create_project
|
||||
Version: 1.2.0 (matches API_CONTRACTS.md v1.2.0)
|
||||
|
||||
Input Schema: JSON Schema (immutable until version change)
|
||||
Output Schema: JSON Schema (immutable until version change)
|
||||
|
||||
Deprecation: If tool signature changes
|
||||
- 1.2.0 → 1.3.0: New optional parameter (backwards compatible)
|
||||
- 1.3.0 → 2.0.0: Required parameter change (breaking)
|
||||
```
|
||||
|
||||
5. **Tool Evolution**
|
||||
|
||||
```
|
||||
Year 1 (Now):
|
||||
- All major operations exposed as MCP tools
|
||||
- REST endpoints wrap tools (not standalone)
|
||||
- Agents have full autonomy via tools
|
||||
|
||||
Year 2:
|
||||
- Tool auto-discovery from API schema
|
||||
- Agents suggest new tools based on gaps
|
||||
- Tool testing automated (schema + behavior)
|
||||
|
||||
Year 3:
|
||||
- Tools generate code (tool params become types)
|
||||
- Graph-driven: Architecture.md generates tool specs
|
||||
- Agents create new tools via ADRs + execution
|
||||
```
|
||||
|
||||
**Implementation Checklist**
|
||||
|
||||
- [ ] All major operations have MCP tool equivalents
|
||||
- [ ] REST endpoints wrap tools (not standalone logic)
|
||||
- [ ] Tool input/output documented in JSON Schema
|
||||
- [ ] Tool versions tracked and versioned
|
||||
- [ ] All tool calls logged in mcp_tool_usage table
|
||||
- [ ] Tool errors include context (which tool, which parameters)
|
||||
- [ ] Deprecation path documented for tool changes
|
||||
- [ ] Agent can discover available tools via introspection
|
||||
|
||||
**Current Tool Implementation Status**
|
||||
|
||||
✅ Implemented (production-ready):
|
||||
- dss_create_project
|
||||
- dss_setup_figma_credentials
|
||||
- dss_get_project_manifest
|
||||
- dss_add_figma_file
|
||||
- dss_discover_figma_files
|
||||
- dss_list_project_figma_files
|
||||
- dss_extract_tokens
|
||||
- dss_merge_tokens
|
||||
- dss_transform_tokens
|
||||
- dss_analyze_project
|
||||
- dss_audit_components
|
||||
- dss_find_quick_wins
|
||||
|
||||
🔄 In Progress:
|
||||
- dss_sync_figma (complex Figma API integration)
|
||||
|
||||
⏱️ Planned:
|
||||
- dss_generate_theme (using style-dictionary)
|
||||
- dss_resolve_token (context cascade)
|
||||
- Storybook generation tools
|
||||
- Component generation tools
|
||||
|
||||
**Conflict Resolution: MCP First vs Foundational Contracts**
|
||||
|
||||
When tool design would violate an API contract:
|
||||
```
|
||||
Hierarchy: Foundational Contracts > MCP First
|
||||
|
||||
Action:
|
||||
1. Design tool to honor contract
|
||||
2. If tool needs breaking change, bump API version
|
||||
3. Deprecate old tool, introduce new one in 1.3.0
|
||||
4. Remove old tool in 2.0.0
|
||||
|
||||
Example:
|
||||
Contract (v1.0): dss_create_project requires root_path
|
||||
New Tool (v1.1): Add optional root_path (default: '.')
|
||||
Breaking Change (v2.0): Remove root_path requirement
|
||||
```
|
||||
|
||||
**Red Flags**
|
||||
|
||||
```
|
||||
❌ "Just POST /api/projects directly"
|
||||
→ Should be dss_create_project tool (agents use tools)
|
||||
|
||||
❌ Tool that only wraps REST endpoint
|
||||
→ Tool should be primary; endpoint wraps tool
|
||||
|
||||
❌ Tool implementation scattered across 3 files
|
||||
→ All tools should be in tools/ directory, organized
|
||||
|
||||
❌ "REST API is the real source, MCP wraps it"
|
||||
→ Backwards; tools are source, REST wraps tools
|
||||
|
||||
❌ New feature added to REST API but not as MCP tool
|
||||
→ Every operation MUST be a tool first
|
||||
```
|
||||
|
||||
**Enforcement Mechanism**
|
||||
|
||||
Pre-commit hook: `tool-completeness.py`
|
||||
```python
|
||||
# Scans new API endpoints
|
||||
# Fails if: endpoint added without corresponding MCP tool
|
||||
# Exception: Only UI-specific endpoints (health, status) can skip
|
||||
```
|
||||
|
||||
CI Check: `tool-api-alignment`
|
||||
```yaml
|
||||
# Compares MCP tool schema against API_CONTRACTS.md
|
||||
# Fails if tool version doesn't match contract version
|
||||
# Validates all tools have input/output schema
|
||||
```
|
||||
|
||||
**Success Metrics**
|
||||
|
||||
- All major operations have MCP tools (no REST-only endpoints)
|
||||
- Agents can complete workflows via tools alone
|
||||
- Tool call audit trail in mcp_tool_usage (100% coverage)
|
||||
- Tool documentation auto-generated from JSON schema
|
||||
- Developer question: "How do I do X?" → Answer: "Use dss_X tool"
|
||||
|
||||
---
|
||||
|
||||
## Conflict Resolution Hierarchy
|
||||
|
||||
When principles seem to conflict, use this hierarchy:
|
||||
|
||||
```
|
||||
1. Foundational Contracts (immutable)
|
||||
2. Single Source of Truth
|
||||
3. MCP First
|
||||
4. Knowledge Persistence
|
||||
5. Current State Transparency
|
||||
6. Progressive Detail
|
||||
7. Phase Agnostic
|
||||
```
|
||||
|
||||
**Example Scenarios:**
|
||||
|
||||
**Scenario A: New feature requires API change**
|
||||
```
|
||||
Principle 1 (Contracts) vs Principle 7 (MCP First)
|
||||
→ Contracts win: Design tool to honor contract
|
||||
→ If breaking change needed, bump major version
|
||||
→ Keep old endpoint deprecated for 6+ months
|
||||
```
|
||||
|
||||
**Scenario B: Two places have conflicting information**
|
||||
```
|
||||
Principle 2 (SSoT) vs others
|
||||
→ SSoT wins: Find the true source
|
||||
→ Delete duplicates, link instead
|
||||
→ Update all references
|
||||
```
|
||||
|
||||
**Scenario C: Historic phase reports pile up**
|
||||
```
|
||||
Principle 5 (Phase Agnostic) vs Principle 4 (Knowledge Persistence)
|
||||
→ Phase Agnostic wins: Archive reports to docs/archive/
|
||||
→ Extract value into PROJECT_STATUS.md + IMPLEMENTATION_SUMMARY.md
|
||||
→ Keep ADR in .knowledge/decisions/ for rationale
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics for All Principles
|
||||
|
||||
- ✅ No duplicate documentation (link instead of copy)
|
||||
- ✅ All API endpoints documented once with version number
|
||||
- ✅ PROJECT_STATUS.md updated weekly (within 7 days)
|
||||
- ✅ All major decisions in .knowledge/decisions/ADRs
|
||||
- ✅ No PHASE_*_REPORT.md, DEPLOYMENT_*.md in root
|
||||
- ✅ Every operation has MCP tool (REST wraps tools)
|
||||
- ✅ Tier 1 files change only via semantic versioning
|
||||
- ✅ New developer reads QUICK_REFERENCE.md → starts coding (30 min)
|
||||
- ✅ Stale docs automatically detected and removed (monthly audit)
|
||||
- ✅ Team consensus: "Principles guide every PR"
|
||||
|
||||
---
|
||||
|
||||
## Evolution Path
|
||||
|
||||
**Year 1 (Now): Manual Enforcement**
|
||||
- Team follows principles consciously
|
||||
- Pre-commit hooks catch violations
|
||||
- CI/CD validates consistency
|
||||
- Enforcement: Rules enforced, not automated
|
||||
|
||||
**Year 2: Automation**
|
||||
- Generate semver from change detection
|
||||
- Auto-generate changelogs from commits
|
||||
- Tools self-discover from API schema
|
||||
- Enforcement: Rules mostly automated
|
||||
|
||||
**Year 3: Code-from-Graph**
|
||||
- ARCHITECTURE.md generates TypeScript types
|
||||
- API_CONTRACTS.md generates OpenAPI + SDK types
|
||||
- .knowledge/graph generates MCP tools
|
||||
- ADRs generate test suites
|
||||
- Enforcement: Rules are executable code
|
||||
|
||||
---
|
||||
|
||||
**This is an archived reference document. For current principles, see PRINCIPLES.md (v2.0.0).**
|
||||
|
||||
**Last Updated**: 2025-12-08
|
||||
**Archived From**: PRINCIPLES.md v1.2.0
|
||||
**Reference Status**: Complete elaboration available for deep dives
|
||||
Reference in New Issue
Block a user