Files
dss/docs/01_core/PRINCIPLES_DEEP.md
Digital Production Factory 276ed71f31 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
2025-12-09 18:45:48 -03:00

29 KiB

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:

# Pre-commit check: No hardcoded hex colors in component code
grep -r "#[0-9A-F]{6}" packages/components/ && exit 1
  1. 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. 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

# 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

# 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
  1. 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: {...}
  1. 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)
  1. 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

# 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

# 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
# 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
  1. 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)"
  1. 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
  1. 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

# 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

# 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

# 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

---
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
  1. Design Patterns Library

File: .knowledge/patterns/pattern-optional-auth.md

# 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
  1. Component Contract Graph

File: .knowledge/components/Button.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"
}
  1. Integration Points

File: .knowledge/integrations/figma-sync.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

# Validates .knowledge/*.json against schema
# Ensures all ADRs are properly formatted
# Warns if decision made in code without ADR

CI Check: orphaned-knowledge

# 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
  1. 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
  1. Tool Design Pattern
# 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(...)
  1. 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)
  1. 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

# 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

# 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