Skip to content

kliewerdaniel/sovereignSpec

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚔️ SovereignSpec

Local‑First Specification Operating System for AI Development

Version License Build Status Stars

Human → Specification → SovereignSpec → Agent → Implementation The specification is the durable artifact. The code is disposable.


Executive Summary

SovereignSpec is a local‑first, fully offline Spec‑Driven Development (SDD) engine that lets you define precise, structured specifications (.sspec files) which are validated, compiled, and grounded in a local knowledge graph. It ships with a 16-command Python CLI, 11 agent adapters, a SQLite + ChromaDB persistence layer, a knowledge graph engine (NetworkX), a 12-step compiler pipeline, 12 validation rules, GBNF grammar-constrained Ollama integration, and a Next.js dashboard. Agents read these specs and implement them deterministically — all inference is local via Ollama, zero cloud API calls.


Why SovereignSpec Exists

Gap Spec Kit SovereignSpec
Cloud dependency Every pipeline step calls external LLM endpoints Zero cloud APIs – all inference via local Ollama
RAG integration No vector search – specs are flat markdown ChromaDB‑powered semantic search over specs, ADRs, patterns
Grammar enforcement No output constraints – LLM can generate anything GBNF grammars constrain token space for deterministic output
Spec evolution tracking No version diffing, no drift detection Full version history, semantic diffs, contradiction detection
Knowledge graph No relationship modeling 11 node types, 9 edge types, graph queries for impact analysis
Local‑first Requires GitHub API and cloud LLMs Runs entirely offline on your machine

Architecture Overview

┌─────────────────────────────────────────────────┐
│                 SovereignSpec                    │
├─────────────────────────────────────────────────┤
│  Layer 7: Interface (Next.js + shadcn/ui)        │
│  Layer 6: Agent Integration (Adapters + Context) │
│  Layer 5: Specification Engine (.sspec compiler) │
│  Layer 4: Knowledge Graph (spec nodes + edges)   │
│  Layer 3: Repository Intelligence (RAG + maps)   │
│  Layer 2: Persistence (SQLite + ChromaDB)        │
│  Layer 1: Local Infrastructure (Ollama + files)  │
└─────────────────────────────────────────────────┘

Tech Stack

Component Technology
CLI Python 3.11+ with Click (16 commands)
Local LLM Ollama (Qwen, Llama 3.1, DeepSeek, Gemma, Mistral)
Spec Format .sspec (YAML superset via Pydantic)
Metadata DB SQLite (raw SQL + migration runner)
Vector Store ChromaDB (embedded, with caching)
Graph Store NetworkX (adjacency JSON persistence)
Grammar GBNF (8 grammar files for constrained LLM output)
Adapters 11 agent integrations (Claude Code, OpenCode, Cursor, etc.)
Tests 27 test files (~150 unit + integration tests)
UI Framework Next.js 16, TypeScript, Tailwind, shadcn/ui (scaffold)
Package Manager uv (Python)

Quick Start

# 1. Install the CLI (requires uv)
uv tool install sovereignspec --from git+https://github.com/kliewerdaniel/sovereignSpec.git

# 2. Verify system health
sovereignspec doctor

# 3. Initialise a new project
sovereignspec init my-project
cd my-project

# 4. Create a feature spec
sovereignspec spec create blog-posts --title "Blog Posts API"
# Edit the generated .sovereignspec/specs/blog-posts.sspec

# 5. Validate & compile the spec
sovereignspec spec validate blog-posts
sovereignspec spec compile blog-posts

# 6. Generate documentation from the spec
sovereignspec docs generate blog-posts

# 7. Assemble an agent context package
sovereignspec context blog-posts --agent opencode

# 8. Explore the knowledge graph
sovereignspec graph stats
sovereignspec graph query --what-breaks blog-posts

# 9. Manage Architecture Decision Records
sovereignspec adr create --title "Database Schema Design" --context "Choosing between SQLite and PostgreSQL for local-first requirements"
sovereignspec adr list

# 10. Map repository structure
sovereignspec repo map
sovereignspec repo patterns

CLI Command Reference

Fully Implemented

Command Description
sovereignspec init [path] [--force] [--model] [--adapter] Initialise a new SovereignSpec project with full directory structure, templates, and config
sovereignspec doctor [--repair] Verify system health — checks Python, project integrity, Ollama connectivity, SQLite, ChromaDB, filesystem
sovereignspec spec create <spec-id> [--title] Create a .sspec file with auto-generated YAML from the Pydantic specification model
sovereignspec spec validate <spec-id> [--all] Run 12 validation rules (purpose, requirements, constraints, acceptance criteria, test cases, dependencies, cycles, duplicates, security, status transitions, drift, contradictions)
sovereignspec spec compile <spec-id> [--all] Run the 12‑step compiler pipeline (parse, validate, resolve deps, check contradictions, compute drift, generate plan, task tree, context, docs, update graph + embeddings + version record)
sovereignspec spec list [--status <s>] List all .sspec files with id, version, status, title — supports status filtering
sovereignspec graph query --what-breaks <spec-id> | --affects-module <path> Query the knowledge graph for impact analysis
sovereignspec graph stats Show knowledge graph statistics (node/edge counts by type)
sovereignspec context <spec-id> [--agent <name>] Assemble agent context package — loads spec, related specs, ADRs, patterns, graph context via RAG pipeline
sovereignspec adr create [--title <t>] [--context <c>] Auto‑numbered ADR creation with markdown file output
sovereignspec adr update <file> Update ADR status (proposed → accepted → deprecated → superseded)
sovereignspec adr list List all ADRs with status
sovereignspec memory sync [--rebuild-graph] Run SQLite migrations, verify ChromaDB collections, optionally rebuild graph from specs
sovereignspec memory status Show SQLite table counts, ChromaDB collection stats, graph.json node/edge counts
sovereignspec repo map Generate repository intelligence map — detects languages, entrypoints, test files, module boundaries
sovereignspec repo patterns Extract coding patterns (naming conventions with confidence scores)
sovereignspec docs generate <spec-id> [--all] [--format markdown|html] Generate documentation from spec fields (purpose, requirements, constraints, acceptance criteria, test cases)

Partially Implemented (CLI entry exists, calls LLM, needs refinement)

Command Description Missing
sovereignspec sovereign-constitution <text> Generates constitution text via Ollama Does not persist to constitution.md
sovereignspec clarify <spec-id> RAG‑grounded clarification via Ollama --question parameter not wired in Click; no RAG retrieval used
sovereignspec plan <spec-id> Generates implementation plan via Ollama Raw LLM output, no structured file written
sovereignspec tasks <spec-id> Decomposes plan into tasks via Ollama Raw LLM output, no task file creation
sovereignspec analyze <spec-id> [--all] Cross‑spec analysis via Ollama Doesn't use ContradictionDetector or DriftTracker engines
sovereignspec implement <spec-id> Executes implementation via Ollama Raw LLM output, no agent workflow execution

Placeholder (Not Yet Wired)

Command Description
sovereignspec spec diff <spec-id> Semantic diff between spec versions — prints "Not yet implemented"
sovereignspec spec graph <spec-id> Visualise spec in knowledge graph — prints "Not yet implemented"
sovereignspec specify <description> Generate a new spec from natural language — prints "LLM generation not yet connected"

Not Yet Implemented as CLI (engine code exists)

Command Notes
sovereignspec integrate --agent <name> 11 adapters exist in adapters/ with write_integration_files(), but no CLI command wires them. Only stored in config during init --adapter.

Spec File Format (.sspec)

id: jwt-authentication
title: JWT Authentication System
version: 1.0.0
status: draft
purpose: Provide secure JWT‑based authentication with access and refresh token flows.

requirements:
  - Users must authenticate with email and password
  - System issues short‑lived access tokens (15 min) and long‑lived refresh tokens (7 days)
  - Refresh tokens are single‑use and rotated on each refresh
  - Role‑based access control with admin, user, and viewer roles

constraints:
  - No third‑party auth providers (Google, GitHub OAuth)
  - Tokens must be stateless (no server‑side session store)
  - All secrets must be environment‑variable configured
  - Passwords hashed with bcrypt (cost factor >= 12)

acceptance_criteria:
  - POST /auth/login returns { access_token, refresh_token }
  - POST /auth/refresh with valid refresh token returns new token pair
  - POST /auth/refresh with expired token returns 401
  - GET /protected without token returns 401
  - Rate limiting on /auth/login: 5 attempts per minute per IP

dependencies: []

test_cases:
  - id: AUTH-001
    description: Successful login returns tokens
    given: Valid registered user credentials
    when: POST /auth/login with valid email and password
    then: Response status 200 with access_token and refresh_token

Agent Bootstrap Pattern

Every project contains .sovereignspec/bootstrap.md — a 317-line universal agent contract. Any file-aware coding agent (OpenCode, Claude Code, Cursor, Cline, etc.) reads this file on start-up and learns:

  1. The SovereignSpec workflow and their role
  2. Required reading order: constitution → specs → ADRs → tasks → patterns → repository map
  3. The agent contract (8 rules): read specs before coding, honor constraints, update task status, generate tests, generate docs, update the knowledge graph, record new ADRs, register artifacts
  4. The .sspec format quick-reference (all 14 fields)
  5. The task file format ([P] for parallel tasks, dependency notation)
  6. The artifact submission protocol (JSON schema)
  7. The ADR creation workflow (template with all 5 sections)
  8. The knowledge graph structure (11 node types, 9 edge types, ID conventions)
  9. Universal constraints (9 rules that must never be violated)

The bootstrap file is the primary integration point — no agent plugin or API needed, just file system reads.


Directory Structure (after sovereignspec init)

my-project/
├─ .sovereignspec/
│  ├─ adr/                     # Architecture Decision Records (ADR-*.md)
│  ├─ agents/                  # Context packages per agent
│  ├─ docs/                    # Generated markdown docs per spec
│  ├─ grammar/                 # 8 GBNF grammar files
│  │   ├─ spec_validation_result.gbnf
│  │   ├─ implementation_plan.gbnf
│  │   ├─ task_list.gbnf
│  │   ├─ api_spec.gbnf
│  │   ├─ adr.gbnf
│  │   ├─ test_case.gbnf
│  │   ├─ contradiction_report.gbnf
│  │   └─ drift_report.gbnf
│  ├─ graph/
│  │   └─ graph.json           # Knowledge graph (adjacency list)
│  ├─ memory/
│  │   ├─ chromadb/            # Vector store (ChromaDB)
│  │   └─ sovereignspec.db     # SQLite metadata DB
│  ├─ patterns/
│  │   ├─ pattern_library.json # Extracted coding conventions
│  │   └─ repository_map.json  # Repository structure map
│  ├─ specs/                   # .sspec specification files
│  ├─ tasks/                   # Task lists per spec
│  ├─ templates/               # .sspec, ADR, and tasks templates
│  ├─ config.json              # Project configuration
│  ├─ constitution.md          # Project governing principles
│  └─ bootstrap.md             # Universal agent contract (317 lines)
└─ src/ …                      # Your source code

Current State (as of v1.0.1)

What's Production-Ready

Area Details
sovereignspec init Full project initialization with directory structure, config, templates, bootstrap
sovereignspec doctor Full health check with --repair flag
sovereignspec spec create/validate/compile/list Complete spec lifecycle — create YAML, validate 12 rules, run 12-step compiler pipeline
sovereignspec graph query/stats Knowledge graph queries via NetworkX (impact analysis, what-breaks, dependency chains)
sovereignspec context RAG agent context package assembly (spec + related specs + ADRs + patterns)
sovereignspec adr create/update/list Full ADR lifecycle with auto-numbering and markdown output
sovereignspec memory sync/status SQLite migrations, ChromaDB verification, graph rebuild
sovereignspec repo map/patterns Repository intelligence — language detection (20+ extensions), entrypoints, naming conventions
sovereignspec docs generate Documentation generation from spec fields (markdown or HTML)
Engine Validator (12 rules), Compiler (12 steps), GraphEngine (NetworkX), OllamaClient (generate/embed/stream), DriftTracker (cosine similarity), RAGPipeline (ChromaDB search + context assembly), RepositoryMapper, PatternExtractor, FileWatcher
Models Specification, ADR, KnowledgeGraph, Task, Artifact — all Pydantic with full YAML/markdown/JSON roundtrip, checksumming, lifecycle validation
Persistence SQLite (9 tables, full CRUD, migration runner), ChromaDB (CRUD, search with caching, metadata filters, repair)
Adapters 11 agent adapters (Claude Code, OpenCode, Cursor, Cline, RooCode, Codex CLI, Gemini CLI, Aider, Windsurf, Continue, Generic) — all produce correct integration files
Tests 27 test files (~150 tests) covering models, engine, persistence, adapters

What's Partially Working

Command What Works What's Missing
sovereign-constitution Generates text via Ollama No persistence to constitution.md
clarify Calls Ollama with prompt --question parameter not wired in Click; no RAG retrieval
plan Raw LLM output No structured file output or persistence
tasks Raw LLM output No task file creation
analyze Raw LLM output Doesn't use ContradictionDetector or DriftTracker engines
implement Raw LLM output No agent workflow execution
Compiler steps 3, 4, 10, 11 Pipeline runs Depedency resolution, contradiction check, graph update, embedding update are stubs

What's Placeholder

Command Status
spec diff Prints "Not yet implemented"
spec graph Prints "Not yet implemented"
specify Prints "LLM generation not yet connected"
ContradictionDetector.detect() Stub returning [] — no LLM-based detection

What's Documented but Unimplemented

Feature Notes
sovereignspec integrate --agent 11 adapters exist with write_integration_files(), but no CLI command. Only stored in config during init --adapter.
sovereignspec agent list/status Documented in CLI_REFERENCE.md, no CLI code exists

UI Dashboard

The ui/ directory contains a Next.js 16 scaffold with dashboard, spec editor, task board, graph visualization, and agent status components. It displays placeholder data and is not yet wired to the Python backend.


Agent Skill Integration

SovereignSpec ships as a native skill for OpenCode and can be installed as a skill for any other file-aware coding agent (Claude Code, Cursor, Cline, Codex CLI, Gemini CLI, etc.). The skill instructs the agent to follow the SDD pipeline whenever you scaffold a new application or start a feature — all fully local, no cloud calls.

How the Skill Works

The skill is a SKILL.md file placed in a directory where the agent looks for skills. When active, it provides the agent with:

  • The complete sovereignspec command reference
  • Step-by-step SDD workflow instructions (init → constitution → specify → validate → compile → clarify → plan → tasks → analyze → implement)
  • The agent contract (9 rules for implementing against specs)
  • The .sspec format reference
  • Knowledge graph update procedures
  • ADR creation and artifact registration workflows

The agent auto-loads the skill when your request matches its description (scaffolding a new app, planning a feature, or mentioning SDD/sovereignspec/.sspec).

Install for OpenCode

The skill is located at:

~/.agents/skills/sovereignspec/SKILL.md

OpenCode discovers skills automatically by searching these paths (in order):

Location Scope
.opencode/skills/<name>/SKILL.md Project-level
~/.config/opencode/skills/<name>/SKILL.md Global
.claude/skills/<name>/SKILL.md Project (Claude-compatible)
~/.claude/skills/<name>/SKILL.md Global (Claude-compatible)
.agents/skills/<name>/SKILL.md Project (agent-compatible)
~/.agents/skills/<name>/SKILL.md Global (agent-compatible)

To install, create the file at any of these paths. For global availability across all projects:

mkdir -p ~/.agents/skills/sovereignspec

Then create ~/.agents/skills/sovereignspec/SKILL.md with the full skill content. The skill auto-activates — no configuration needed.

Create the Skill

Paste the following content into the SKILL.md file:

Click to expand the full SKILL.md content
---
name: sovereignspec
description: "Local-first Spec-Driven Development (SDD) engine for planning and building applications. Uses sovereignspec CLI to create structured .sspec specifications, establish project constitutions, generate implementation plans, decompose into tasks, and track work through a knowledge graph — all fully offline via Ollama. Use this skill when the user wants to scaffold a new application, plan a feature, write specifications before coding, or follow a spec-driven development workflow. Also use when the user mentions sovereignspec, .sspec, SDD, spec-driven development, local-first development, or wants a structured approach to building software without cloud dependencies."
---

# SovereignSpec Skill

Local-First Spec-Driven Development (SDD) Engine powered by sovereignspec.

## What This Skill Does

This skill guides you through the sovereignspec pipeline: a fully offline, local-first SDD engine that uses structured `.sspec` files, a knowledge graph, and GBNF grammar-constrained local LLM inference (via Ollama) to plan, specify, and implement applications.

**Core Philosophy:** *The specification is the durable artifact. The code is disposable.*
- If code disagrees with spec, regenerate from spec, not the other way around
- Specs are YAML-superset with typed fields, validation rules, and lifecycle states
- Machine-readable, compiler-processable, deterministic
- Grounded in a local knowledge graph, versioned with semantic awareness
- All offline — nothing leaves your machine

## When to Use This Skill

Use this skill when:

- **Scaffolding a new application** — before writing any code, establish specs and a constitution
- **Planning a feature** — define requirements, constraints, and acceptance criteria in structured `.sspec` format
- **Writing or editing `.sspec` files** — authoring, validating, or maintaining specification files
- **Following SDD workflow** — the user wants constitutional governance → specification → clarification → planning → tasks → implementation
- **Avoiding cloud dependency** — the user wants Spec Kit capabilities but fully local (no cloud LLM calls)
- **The user mentions** sovereignspec, .sspec, SDD, spec-driven development, local-first development, or structured specification

**Do NOT use this skill when:** the user just wants quick code without planning, or when sovereignspec CLI is not installed.

## Prerequisites

Before running any sovereignspec commands, verify:

1. **sovereignspec CLI installed** — Run `sovereignspec doctor` to check
2. **Ollama running**`ollama serve` should be active
3. **Ollama model available** — Works best with code-capable local models

If sovereignspec isn't installed:
```bash
uv tool install sovereignspec --from git+https://github.com/kliewerdaniel/sovereignSpec.git

File Location Convention

.sovereignspec/
├── specs/{id}.sspec           # Specification files
├── tasks/{spec-id}-tasks.md   # Generated task lists
├── adr/ADR-NNN.md             # Architecture Decision Records
├── graph/graph.json            # Knowledge graph
├── agents/opencode/            # Agent integration artifacts
├── patterns/                   # Repository patterns
├── bootstrap.md                # Universal agent contract
└── constitution.md             # Project constitution

Required .sspec Fields

Every .sspec file must include these fields. They are enforced by the compiler.

id (string, required)

  • Unique kebab-case identifier: /^[a-z0-9]+(-[a-z0-9]+)*$/
  • Immutable after first commit
  • Example: jwt-authentication, blog-posts-api
  • Compiler effect: Used as graph node prefix (spec-{id}) and filename

title (string, required)

  • Human-readable title, 5-60 characters recommended, max 120
  • Example: JWT Authentication System
  • Compiler effect: Document title, graph node label

version (string, required)

  • Semver format: /^\d+\.\d+\.\d+$/
  • Major = breaking changes, Minor = additions, Patch = clarifications
  • Must be >= previous version on update
  • Example: 1.0.0

status (enum, required)

  • Valid values: draft | validated | approved | active | implemented | verified | archived
  • Transitions follow state machine rules (see lifecycle below)
  • Only active specs generate tasks
  • Example: draft

purpose (string, required)

  • 1-3 sentence description answering "Why are we building this?"
  • 50-500 characters
  • Must contain action verb, must not duplicate title
  • Compiler effect: Primary LLM prompt context, ChromaDB embedding

requirements (list of strings, required, min 1)

  • Each must have action verb + measurable outcome
  • Format: "System must [action] [object] [condition]."
  • Example:
    requirements:
      - Users must authenticate with email and password
      - System issues short-lived access tokens (15 min) and long-lived refresh tokens (7 days)
      - Admin role must have access to user management endpoints

Optional .sspec Fields

constraints (list of strings)

  • Technical, architectural, or business constraints (hard limits)
  • Example:
    constraints:
      - All endpoints must respond within 200ms at p95
      - No external API calls during token validation
      - Must support offline token refresh

acceptance_criteria (list of strings)

  • Testable conditions for implementation verification
  • Should map directly to requirements
  • Example:
    acceptance_criteria:
      - Given valid credentials, system returns JWT with 15-minute expiry
      - Given invalid credentials, system returns 401 within 100ms

dependencies (list of strings)

  • Other spec IDs this spec depends on
  • Example: ["database-schema", "user-model"]

api_specification (object)

  • API endpoints and their request/response schemas
  • Example:
    api_specification:
      endpoints:
        - path: /api/auth/login
          method: POST
          request:
            body:
              email: string (required)
              password: string (required)
          response:
            200:
              access_token: string
              refresh_token: string
            401:
              error: string

data_models (list of objects)

  • Data structures and schemas with typed fields
  • Example:
    data_models:
      - name: JWTToken
        fields:
          - name: sub
            type: string
            description: User ID
          - name: exp
            type: integer
            description: Expiration timestamp

test_cases (list of objects)

  • Structured test scenarios: given, when, then
  • Example:
    test_cases:
      - name: valid_login
        given: valid email and password
        when: POST /api/auth/login
        then: 200 with access_token and refresh_token
      - name: expired_token
        given: token with exp < now
        when: any protected endpoint
        then: 401 Unauthorized

references (list of objects)

  • External documentation or standards with title and url
  • Example:
    references:
      - title: RFC 7519 - JSON Web Token
        url: https://tools.ietf.org/html/rfc7519

implementation_notes (string)

  • Additional implementation guidance, architecture decisions, trade-offs
  • Max 2000 characters

Other optional fields

  • security_requirements (list of strings) — security controls
  • performance_requirements (object) — performance targets
  • architecture_notes (string) — architectural guidance
  • implementation_hints (list of strings) — implementation guidance
  • tags (list of strings) — categorization tags

Validation Rules

The compiler enforces these rules:

  • id must be unique in project
  • version must be >= previous version
  • status must follow valid state machine transitions
  • requirements must contain action verbs
  • purpose must be 50-500 chars and not duplicate title
  • All URLs in references must be valid format
  • All semver strings must match /^\d+\.\d+\.\d+$/
  • Each requirement should follow: "System must [action] [object] [condition]."

Spec Lifecycle (State Machine)

draft → validated → approved → active → implemented → verified → archived
                                    ↓
                              (loop back for revisions)
From To Gate
draft validated All required fields present, valid format
validated approved Stakeholder sign-off
approved active Dependencies resolved, ready for implementation
active implemented All tasks complete, code written
implemented verified All tests pass, acceptance criteria met
verified archived Feature stable, no further changes expected

Only active specs generate tasks. Specs can loop back from later states for revisions.

The SovereignSpec Workflow

Execute these steps in order when building with sovereignspec.

Step 1: Initialize the Project

sovereignspec init . --model qwen2.5-coder:32b

Creates .sovereignspec/ directory structure.

Step 2: Establish the Constitution

The constitution defines governing principles — tech stack, architectural style, non-negotiables.

sovereignspec sovereign-constitution "Build a REST API with Python FastAPI, SQLite, and Pydantic."

Or create .sovereignspec/constitution.md manually with tech stack, architectural rules, and constraints.

Step 3: Specify What to Build

sovereignspec spec create {id} --title "{title}"

Edit the generated .sovereignspec/specs/{id}.sspec with full required + optional fields.

Step 4: Validate the Spec

sovereignspec spec validate {id} [--all]

Fix any validation errors before proceeding.

Step 5: Compile the Spec

sovereignspec spec compile {id} [--all]

The compiler runs a 12-step pipeline:

  1. Parse .sspec YAML → 2. Validate required fields → 3. Resolve dependency graph (topological sort) → 4. Check contradictions → 5. Compute drift score against constitution → 6. Generate implementation plan → 7. Generate task tree → 8. Generate agent context package → 9. Generate documentation → 10. Update knowledge graph → 11. Update ChromaDB embeddings → 12. Commit version record to SQLite

Step 6: Clarify the Spec (if ambiguous)

sovereignspec clarify {id}

Uses RAG-grounded retrieval to find related specs/ADRs/patterns and resolve ambiguities.

Step 7: Generate Implementation Plan

sovereignspec plan {id} --tech-stack "..."

Step 8: Generate Tasks

sovereignspec tasks {id}

Decomposes plan into actionable tasks at .sovereignspec/tasks/{spec-id}-tasks.md.

Task format:

## [P] Task 1: Description
Status: [ ] pending
Files to create/modify:
  - src/...
Dependencies: Task 0
Acceptance: ...

Tasks marked [P] can run in parallel with siblings.

Step 9: Analyze Cross-Spec Consistency

sovereignspec analyze {id} [--all]

Checks contradictions, duplicate IDs, dependency chain validity, narrative drift.

Step 10: Implement Tasks

sovereignspec implement {id}

If implement is a placeholder, implement tasks manually following the Agent Contract below.

Agent Contract

When implementing against sovereignspec specs, you must follow these rules:

1. Read Specs Before Writing Code

Always start by reading the relevant .sspec file(s). Understand the purpose, requirements, constraints, acceptance criteria, and test cases. Specs are the source of truth — code is disposable.

2. Honor All Spec Constraints

Constraints are non-negotiable. If a constraint says "No ORM," do not introduce an ORM. If it says "No cloud APIs," do not call any external API.

3. Update Task Status on Completion

After completing a task, update .sovereignspec/tasks/{spec-id}-tasks.md:

  • Change [ ] pending to [x] completed
  • Add completion note: Completed: YYYY-MM-DD — Brief summary

4. Generate Tests for Every Feature

Every implemented feature needs tests that validate the spec's acceptance criteria. Cover edge cases, error conditions, and boundary values.

5. Generate Documentation for Every Module

For every module created or modified, document: what it does, its public API, usage examples, and configuration required.

6. Update the Knowledge Graph

After implementing, update .sovereignspec/graph/graph.json:

  • Add a node for each new module or endpoint
  • Add REFERENCES edges from spec node to new nodes
  • Add GENERATES edges from spec to documentation files

Node ID conventions:

Type ID Convention Example
Spec spec-{spec-id} spec-blog-posts
Module mod-{path-slug} mod-src-posts-service
Endpoint ep-{method}-{path-slug} ep-get-api-posts
ADR adr-{NNN} adr-001

Edge types: IMPLEMENTS, DEPENDS_ON, REFERENCES, GENERATES, SUPERSEDES, CONFLICTS_WITH, RELATED_TO, VALIDATES

7. Record Architectural Decisions (ADRs)

If implementation reveals a significant architectural decision not covered by existing ADRs:

  1. Find the next ADR number in .sovereignspec/adr/
  2. Create .sovereignspec/adr/ADR-NNN.md with: Context, Decision, Rationale, Alternatives Considered, Consequences

8. Register Artifacts

After completing all tasks for a spec, register generated files at .sovereignspec/agents/opencode/artifacts.json:

{
  "agent": "opencode",
  "artifacts": [
    {
      "id": "uuid-v4",
      "task_id": "task-uuid",
      "artifact_type": "code|test|doc|config|migration",
      "file_path": "src/posts/service.py",
      "validated": false,
      "created_at": "2025-01-15T10:30:00Z"
    }
  ]
}

9. Update Spec Status Through Lifecycle

As work progresses, update the spec's status field:

  • Start at draft
  • Move to validated after validation passes
  • Move to approved after review
  • Move to active when implementation begins
  • Move to implemented when code is written
  • Move to verified when all tests pass
  • Move to archived when stable

Complete .sspec Example

# .sovereignspec/specs/jwt-authentication.sspec

id: jwt-authentication
title: JWT Authentication System
version: 1.0.0
status: draft
purpose: >
  Provide secure JWT-based authentication with access and refresh token flows,
  supporting role-based access control for admin, user, and viewer roles.

requirements:
  - Users must authenticate with email and password
  - System issues short-lived access tokens (15 min) and long-lived refresh tokens (7 days)
  - Admin role must have access to user management endpoints
  - System must validate JWT signature on every protected request
  - Refresh tokens must be rotated on each use

constraints:
  - All endpoints must respond within 200ms at p95
  - No external API calls during token validation
  - Must support offline token refresh for cached tokens

acceptance_criteria:
  - Given valid credentials, system returns JWT with 15-minute expiry
  - Given invalid credentials, system returns 401 within 100ms
  - Given expired refresh token, system returns 401 and clears cookie
  - Given valid admin JWT, user management endpoints return 200

dependencies:
  - database-schema
  - user-model

api_specification:
  endpoints:
    - path: /api/auth/login
      method: POST
      request:
        body:
          email: string (required, format: email)
          password: string (required, min: 8 chars)
      response:
        200:
          access_token: string (JWT)
          refresh_token: string (JWT)
          expires_in: integer (seconds)
        401:
          error: string
    - path: /api/auth/refresh
      method: POST
      request:
        body:
          refresh_token: string (required)
      response:
        200:
          access_token: string (new JWT)
        401:
          error: string

data_models:
  - name: JWTToken
    fields:
      - name: sub
        type: string
        description: User ID (subject)
      - name: exp
        type: integer
        description: Expiration timestamp (Unix epoch)
      - name: role
        type: string
        description: User role (admin/user/viewer)
      - name: jti
        type: string
        description: JWT ID for refresh token rotation

test_cases:
  - name: valid_login
    given: valid email and password
    when: POST /api/auth/login
    then: 200 with access_token and refresh_token
  - name: invalid_password
    given: valid email, wrong password
    when: POST /api/auth/login
    then: 401 with error message
  - name: expired_access_token
    given: access_token with exp < current_time
    when: GET /api/protected
    then: 401 Unauthorized
  - name: rotated_refresh_token
    given: refresh_token already used
    when: POST /api/auth/refresh
    then: 401 and old token invalidated

references:
  - title: RFC 7519 - JSON Web Token
    url: https://tools.ietf.org/html/rfc7519
  - title: OWASP JWT Security Checklist
    url: https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_Cheat_Sheet_for_Java.html

implementation_notes: >
  Use HS256 or RS256 algorithm. Store refresh tokens in database for rotation tracking.
  Implement token blacklist for immediate revocation. Consider JTI (JWT ID) for
  preventing token replay attacks.

Command Reference

Command Description
sovereignspec init [path] Initialize project structure
sovereignspec doctor Verify system health
sovereignspec integrate --agent <name> Configure agent adapter
sovereignspec spec create <spec-id> Create blank .sspec file
sovereignspec spec validate <spec-id> [--all] Run validation rules
sovereignspec spec compile <spec-id> [--all] Run 12-step compiler pipeline
sovereignspec spec list [--status <s>] List specs by status
sovereignspec spec diff <spec-id> Semantic diff between versions
sovereignspec spec graph <spec-id> Visualize spec in knowledge graph
sovereignspec sovereign-constitution <text> Set project constitution
sovereignspec specify <description> Generate spec from description
sovereignspec clarify <spec-id> RAG-grounded clarification
sovereignspec plan <spec-id> Generate implementation plan
sovereignspec tasks <spec-id> Decompose plan into tasks
sovereignspec analyze <spec-id> [--all] Cross-spec consistency analysis
sovereignspec implement <spec-id> Execute implementation
sovereignspec context <spec-id> [--agent <name>] Assemble agent context package
sovereignspec adr create Create Architecture Decision Record
sovereignspec adr list List all ADRs
sovereignspec memory sync Synchronize memory stores
sovereignspec memory status Show memory store status
sovereignspec repo map Generate repository intelligence map
sovereignspec docs generate <spec-id> [--all] Generate Markdown documentation

Knowledge Graph Node Types

Type Description ID Convention
Project The project itself proj-{name}
Feature A user-facing feature feat-{kebab-name}
Specification A .sspec file spec-{spec-id}
Module A source code module mod-{path-slug}
Endpoint An API endpoint ep-{method}-{path-slug}
ADR Architecture Decision Record adr-{NNN}
Task An implementation task task-{uuid}
Document A generated doc file doc-{path-slug}

Tips for Effective Spec-Driven Development

  1. Start with the constitution — establish tech stack and non-negotiables before writing specs
  2. Make specs granular — one spec per feature/system, not one monolith spec
  3. Be specific in constraints — vague constraints lead to ambiguous implementation
  4. Write testable acceptance criteria — each criterion should be a clear pass/fail test
  5. Use semver correctly — major = breaking, minor = additions, patch = clarifications
  6. Keep requirements actionable — use action verbs and measurable outcomes
  7. Validate early, validate often — run sovereignspec spec validate after every edit
  8. Update the knowledge graph — it enables impact analysis (what breaks if this spec changes?)
  9. Use ADRs for architectural decisions — they create a permanent record of why decisions were made
  10. Regenerate, don't edit code — when spec requirements change, recompile and regenerate rather than patching around the old implementation

</details>

### Install for Other Agents

The same skill file works with any agent that supports SKILL.md discovery. Place it at the appropriate path for your agent:

| Agent | Path |
|-------|------|
| **Claude Code** | `~/.claude/skills/sovereignspec/SKILL.md` |
| **Cursor** | `.cursor/rules/sovereignspec.mdc` (converted to Cursor rule format) |
| **Cline** | `.clinerules` (append the skill content) |
| **Codex CLI** | `.opencode/skills/sovereignspec/SKILL.md` or `AGENTS.md` |
| **Gemini CLI** | `~/.gemini/skills/sovereignspec/SKILL.md` |
| **Windsurf** | `.windsurfrules` (append the skill content) |
| **Roo Code** | `.roo/rules/sovereignspec.md` |
| **Generic** | `.sovereignspec/bootstrap.md` (always loaded by any file-aware agent) |

### Per-Agent Skill Permissions (OpenCode)

To control skill permissions in OpenCode, add to `~/.config/opencode/opencode.jsonc`:

```jsonc
{
  "permission": {
    "skill": {
      "sovereignspec": "allow"
    }
  }
}

To disable for a specific agent profile:

{
  "agent": {
    "plan": {
      "permission": {
        "skill": {
          "sovereignspec": "deny"
        }
      }
    }
  }
}

Contributing

Contributions are welcome! Please read the contributing guidelines and open a PR against the main branch.


License

MIT © 2024‑2026 Daniel Kliewer

About

A local-first, offline spec-driven development engine that treats specifications as living, graph-grounded artifacts and enforces deterministic code generation through structured pipelines — no cloud API calls required.

Resources

License

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors