Local‑First Specification Operating System for AI Development
Human → Specification → SovereignSpec → Agent → Implementation The specification is the durable artifact. The code is disposable.
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.
| 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 |
┌─────────────────────────────────────────────────┐
│ 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) │
└─────────────────────────────────────────────────┘
| 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) |
# 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| 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) |
| 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 |
| 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" |
| 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. |
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_tokenEvery 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:
- The SovereignSpec workflow and their role
- Required reading order: constitution → specs → ADRs → tasks → patterns → repository map
- 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
- The
.sspecformat quick-reference (all 14 fields) - The task file format (
[P]for parallel tasks, dependency notation) - The artifact submission protocol (JSON schema)
- The ADR creation workflow (template with all 5 sections)
- The knowledge graph structure (11 node types, 9 edge types, ID conventions)
- 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.
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
| 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 |
| 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 |
| 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 |
| 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 |
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.
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.
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
.sspecformat 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).
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/sovereignspecThen create ~/.agents/skills/sovereignspec/SKILL.md with the full skill content. The skill auto-activates — no configuration needed.
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.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
Every .sspec file must include these fields. They are enforced by the compiler.
- 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
- Human-readable title, 5-60 characters recommended, max 120
- Example:
JWT Authentication System - Compiler effect: Document title, graph node label
- Semver format:
/^\d+\.\d+\.\d+$/ - Major = breaking changes, Minor = additions, Patch = clarifications
- Must be >= previous version on update
- Example:
1.0.0
- Valid values:
draft | validated | approved | active | implemented | verified | archived - Transitions follow state machine rules (see lifecycle below)
- Only
activespecs generate tasks - Example:
draft
- 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
- 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
- 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
- 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
- Other spec IDs this spec depends on
- Example:
["database-schema", "user-model"]
- 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 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
- 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
- External documentation or standards with
titleandurl - Example:
references: - title: RFC 7519 - JSON Web Token url: https://tools.ietf.org/html/rfc7519
- Additional implementation guidance, architecture decisions, trade-offs
- Max 2000 characters
security_requirements(list of strings) — security controlsperformance_requirements(object) — performance targetsarchitecture_notes(string) — architectural guidanceimplementation_hints(list of strings) — implementation guidancetags(list of strings) — categorization tags
The compiler enforces these rules:
idmust be unique in projectversionmust be >= previous versionstatusmust follow valid state machine transitionsrequirementsmust contain action verbspurposemust be 50-500 chars and not duplicatetitle- All URLs in
referencesmust be valid format - All semver strings must match
/^\d+\.\d+\.\d+$/ - Each requirement should follow:
"System must [action] [object] [condition]."
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.
Execute these steps in order when building with sovereignspec.
sovereignspec init . --model qwen2.5-coder:32bCreates .sovereignspec/ directory structure.
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.
sovereignspec spec create {id} --title "{title}"Edit the generated .sovereignspec/specs/{id}.sspec with full required + optional fields.
sovereignspec spec validate {id} [--all]Fix any validation errors before proceeding.
sovereignspec spec compile {id} [--all]The compiler runs a 12-step pipeline:
- Parse
.sspecYAML → 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
sovereignspec clarify {id}Uses RAG-grounded retrieval to find related specs/ADRs/patterns and resolve ambiguities.
sovereignspec plan {id} --tech-stack "..."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.
sovereignspec analyze {id} [--all]Checks contradictions, duplicate IDs, dependency chain validity, narrative drift.
sovereignspec implement {id}If implement is a placeholder, implement tasks manually following the Agent Contract below.
When implementing against sovereignspec specs, you must follow these rules:
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.
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.
After completing a task, update .sovereignspec/tasks/{spec-id}-tasks.md:
- Change
[ ] pendingto[x] completed - Add completion note:
Completed: YYYY-MM-DD — Brief summary
Every implemented feature needs tests that validate the spec's acceptance criteria. Cover edge cases, error conditions, and boundary values.
For every module created or modified, document: what it does, its public API, usage examples, and configuration required.
After implementing, update .sovereignspec/graph/graph.json:
- Add a node for each new module or endpoint
- Add
REFERENCESedges from spec node to new nodes - Add
GENERATESedges 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
If implementation reveals a significant architectural decision not covered by existing ADRs:
- Find the next ADR number in
.sovereignspec/adr/ - Create
.sovereignspec/adr/ADR-NNN.mdwith: Context, Decision, Rationale, Alternatives Considered, Consequences
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"
}
]
}As work progresses, update the spec's status field:
- Start at
draft - Move to
validatedafter validation passes - Move to
approvedafter review - Move to
activewhen implementation begins - Move to
implementedwhen code is written - Move to
verifiedwhen all tests pass - Move to
archivedwhen stable
# .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 | 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 |
| 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} |
- Start with the constitution — establish tech stack and non-negotiables before writing specs
- Make specs granular — one spec per feature/system, not one monolith spec
- Be specific in constraints — vague constraints lead to ambiguous implementation
- Write testable acceptance criteria — each criterion should be a clear pass/fail test
- Use semver correctly — major = breaking, minor = additions, patch = clarifications
- Keep requirements actionable — use action verbs and measurable outcomes
- Validate early, validate often — run
sovereignspec spec validateafter every edit - Update the knowledge graph — it enables impact analysis (what breaks if this spec changes?)
- Use ADRs for architectural decisions — they create a permanent record of why decisions were made
- 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:
Contributions are welcome! Please read the contributing guidelines and open a PR against the main branch.
MIT © 2024‑2026 Daniel Kliewer
{ "agent": { "plan": { "permission": { "skill": { "sovereignspec": "deny" } } } } }