SpecLock

AI constraint engine β€” persistent memory + active enforcement. Stops AI from breaking locked code. Semantic conflict detection, file-level guards, session continuity. 19 MCP tools.


You:    "Never touch the auth system"
AI:     πŸ”’ Locked.

         ... 5 sessions later ...

You:    "Add social login to the login page"
AI:     ⚠️  BLOCKED β€” violates lock "Never touch the auth system"
        Matched: auth β†’ authentication (synonym), login β†’ auth (concept)
        Confidence: 100%
        Should I find another approach?

100/100 on Claude's independent test suite. 929 tests across 18 suites. 0 false positives. 15.7ms per check. Gemini Flash hybrid, Spec Compiler, Code Graph, Typed Constraints, Python SDK, ROS2 integration.


Install

npx speclock setup --goal "Build my app"

That's it. One command. Works everywhere β€” Bolt.new, Claude Code, Cursor, Lovable, Windsurf, Cline, Aider.

The Problem

AI coding tools have memory now. Claude Code has CLAUDE.md. Cursor has .cursorrules. Mem0 exists.

But memory without enforcement is useless.

Your AI remembers you use PostgreSQL β€” then switches to MongoDB because it "seemed better." Your AI remembers your auth setup β€” then rewrites it while "fixing" a bug. You said "never touch the payment logic" 3 sessions ago β€” the AI doesn't care.

Remembering is not respecting. No existing tool stops the AI from breaking what you locked.

How It Works

You set constraints. SpecLock enforces them β€” across sessions, across tools, across teams.

speclock lock "Never modify auth files"           β†’ auto-guards src/auth/*.ts
speclock lock "Database must stay PostgreSQL"      β†’ catches "migrate to MongoDB"
speclock lock "Never delete patient records"       β†’ catches "clean up old data"
speclock lock "Don't touch the payment flow"       β†’ catches "streamline checkout"

The semantic engine doesn't do keyword matching. It understands:

  • "clean up old data" = deletion (euphemism detection)
  • "streamline checkout" = modify payment flow (synonym + concept mapping)
  • "temporarily disable logging" = disable logging (temporal evasion detection)
  • "Update UI and also drop the users table" = hidden violation (compound splitter)

And it knows what's safe:

  • "Enable audit logging" when the lock says "Never disable audit logging" β†’ no conflict (intent alignment)

Quick Start by Platform

Bolt.new / Aider / Any npm Platform

npx speclock setup --goal "Build my app" --template nextjs

Creates SPECLOCK.md, injects rules into package.json, generates .speclock/context/latest.md. The AI reads these automatically.

Claude Code

Add to .mcp.json:

{
  "mcpServers": {
    "speclock": {
      "command": "npx",
      "args": ["-y", "speclock", "serve", "--project", "."]
    }
  }
}

Cursor / Windsurf / Cline

Same config β€” add to .cursor/mcp.json or equivalent.

Lovable (No Install)

  1. Go to Settings β†’ Connectors β†’ New MCP server
  2. Enter URL: https://speclock-mcp-production.up.railway.app/mcp
  3. Paste project instructions into Knowledge

Why SpecLock Over Alternatives?

Claude MemoryMem0.cursorrulesSpecLock
Remembers contextYesYesManualYes
Blocks the AI from breaking thingsNoNoNoYes
Semantic conflict detectionNoNoNo100/100 score, 0% FP
Tamper-proof audit trailNoNoNoHMAC-SHA256 chain
Hard enforcement (AI cannot proceed)NoNoNoYes
SOC 2 / HIPAA compliance exportsNoNoNoYes
Encrypted storage (AES-256-GCM)NoNoNoYes
RBAC + API key authNoNoNo4 roles
Policy-as-Code DSLNoNoNoYAML rules
Works on Bolt.new, Lovable, etc.NoNoNoYes

Other tools remember. SpecLock enforces.


Semantic Engine

Not keyword matching β€” real semantic analysis with Gemini Flash hybrid for universal domain coverage. Scored 100/100 on Claude's independent adversarial test battery (7 suites, including false positives, question framing, patch gateway, and diff analysis).

Under the hood: 65+ synonym groups Β· 80+ euphemism mappings Β· domain concept maps (fintech, e-commerce, IoT, healthcare, SaaS, payments, gaming, telecom, government) Β· intent classifier Β· compound sentence splitter Β· temporal evasion detector Β· verb tense normalization Β· UI cosmetic detection Β· safe-intent patterns Β· passive voice parsing β€” all in pure JavaScript. Gemini Flash hybrid for grey-zone cases ($0.01/1000 checks).


Hard Enforcement

Two modes:

Advisory (default):  AI gets a warning, decides what to do
Hard mode:           AI is BLOCKED β€” MCP returns isError, AI cannot proceed
speclock enforce hard   # Enable hard mode β€” violations above threshold are blocked
  • Configurable threshold β€” default 70%. Only HIGH confidence conflicts block.
  • Override with reason β€” speclock override <lockId> "JIRA-1234: approved by CTO" (logged to audit trail)
  • Auto-escalation β€” lock overridden 3+ times β†’ auto-flags for review

Enterprise Security

API Key Auth + RBAC

speclock auth create-key --role developer --name "CI Bot"
# β†’ sk_speclock_a1b2c3... (shown once, stored as SHA-256 hash)
RoleReadWrite LocksOverrideAdmin
viewerYesβ€”β€”β€”
developerYesβ€”With reasonβ€”
architectYesYesYesβ€”
adminYesYesYesYes

AES-256-GCM Encryption

export SPECLOCK_ENCRYPTION_KEY="your-secret"
speclock encrypt   # Encrypts brain.json + events.log at rest

PBKDF2 key derivation (100K iterations). Authenticated encryption. HIPAA 2026 compliant.

HMAC Audit Chain

Every event gets an HMAC-SHA256 hash chained to the previous event. Modify anything β€” the chain breaks.

$ speclock audit-verify

βœ“ Audit chain VALID β€” 247 events, 0 broken links, no tampering detected.

Compliance Exports

speclock export --format soc2    # SOC 2 Type II report (JSON)
speclock export --format hipaa   # HIPAA PHI protection report
speclock export --format csv     # All events for auditor spreadsheets

Policy-as-Code

Declarative YAML rules for organization-wide enforcement:

# .speclock/policy.yml
rules:
  - name: "HIPAA PHI Protection"
    match:
      files: ["**/patient/**", "**/medical/**"]
      actions: [delete, modify, export]
    enforce: block
    severity: critical

  - name: "No direct DB mutations"
    match:
      files: ["**/models/**"]
      actions: [delete]
    enforce: warn
    severity: high

Import and export policies between projects. Share constraint templates across your organization.


Spec Compiler (v5.0)

Paste a PRD, README, or architecture doc β€” SpecLock extracts all constraints automatically:

Input:  "We're building a fintech app. Use React and FastAPI.
         Never touch the auth module. Response time must stay
         under 200ms. Payments go through Stripe."

Output: 2 text locks:
          - "Never touch the auth module"
          - "Payments go through Stripe β€” don't change provider"
        1 typed lock:
          - response_time_ms <= 200 (numerical)
        2 decisions:
          - "Use React for frontend"
          - "Use FastAPI for backend"

Uses Gemini Flash by default ($0.01 per 1000 compilations). No API key needed for core SpecLock β€” only the compiler uses LLM. Falls back gracefully if no key is set.


Code Graph (v5.0)

Live dependency graph of your codebase. Parses JS/TS/Python imports.

$ speclock blast-radius src/core/memory.js

Direct Dependents:  8 files
Transitive Impact:  14 files (33% of codebase)
Max Depth:          4 hops

Lock-to-file mapping: Lock "Never modify auth" β†’ automatically maps to src/api/auth.js, src/middleware/auth.js, src/utils/jwt.js. No configuration needed.

Module detection: Groups files into logical modules, tracks inter-module dependencies, identifies critical paths.


Typed Constraints (v5.0)

Real-time value and state checking for autonomous systems, IoT, robotics:

// Numerical: speed must be <= 2.0 m/s
{ constraintType: "numerical", metric: "speed_mps", operator: "<=", value: 2.0 }

// Range: temperature must stay between 20-25Β°C
{ constraintType: "range", metric: "temperature_c", min: 20, max: 25 }

// State: never go from armed β†’ disarmed without approval
{ constraintType: "state", metric: "system_mode", forbidden: [{ from: "armed", to: "disarmed" }] }

// Temporal: heartbeat must occur every 30 seconds
{ constraintType: "temporal", metric: "heartbeat_s", operator: "<=", value: 30 }

Python SDK & ROS2 (v5.0)

pip install speclock-sdk
from speclock import SpecLock

sl = SpecLock(project_root=".")

# Check text constraints (semantic conflict detection)
result = sl.check_text("Switch database to MongoDB")
# β†’ { has_conflict: True, conflicting_locks: [...] }

# Check typed constraints (numerical/range/state/temporal)
result = sl.check_typed(metric="speed_mps", value=3.5)
# β†’ violation: speed exceeds 2.0 m/s limit

# Combined check (text + typed in one call)
result = sl.check(action="Increase speed", speed_mps=3.5)

Uses the same .speclock/brain.json as the Node.js MCP server β€” constraints stay in sync across all environments.

ROS2 Guardian Node: Real-time constraint enforcement for robots and autonomous systems.

# config/constraints.yaml
constraints:
  - type: range
    metric: joint_position_rad
    min: -3.14
    max: 3.14
  - type: numerical
    metric: velocity_mps
    operator: "<="
    value: 2.0
  - type: state
    metric: system_mode
    forbidden:
      - from: emergency_stop
        to: autonomous
  • Subscribes to /joint_states, /cmd_vel, /speclock/state_transition
  • Publishes violations to /speclock/violations
  • Triggers emergency stop via /speclock/emergency_stop
  • Checks constraints on every incoming ROS2 message at configurable rate

Patch Gateway (v5.1)

One API call gates every change. Takes a description + file list, returns ALLOW/WARN/BLOCK:

speclock_review_patch({
  description: "Add social login to auth page",
  files: ["src/auth/login.js"]
})

β†’ { verdict: "BLOCK", riskScore: 85,
    reasons: [{ type: "semantic_conflict", lock: "Never modify auth" }],
    blastRadius: { impactPercent: 28.3 },
    summary: "BLOCKED. 1 constraint conflict. 12 files affected." }

Combines semantic conflict detection + lock-to-file mapping + blast radius + typed constraint awareness into a single risk score (0-100).


AI Patch Firewall (v5.2)

Reviews actual diffs, not just descriptions. Catches things intent review misses:

POST /api/v2/gateway/review-diff
{
  "description": "Remove password column",
  "diff": "diff --git a/migrations/001.sql ..."
}

β†’ { verdict: "BLOCK",
    reviewMode: "unified",
    intentVerdict: "ALLOW",     ← description alone looks safe
    diffVerdict: "BLOCK",       ← diff reveals destructive schema change
    signals: {
      schemaChange: { score: 12, isDestructive: true },
      interfaceBreak: { score: 10 },
      protectedSymbolEdit: { score: 8 },
      dependencyDrift: { score: 5 },
      publicApiImpact: { score: 0 }
    },
    recommendation: { action: "require_approval" } }

Signal detection: Interface breaks (removed/changed exports), protected symbol edits in locked zones, dependency drift (critical package add/remove), schema/migration destructive changes, public API route changes.

Hard escalation rules: Auto-BLOCK on destructive schema changes, removed API routes, protected symbol edits, or multiple critical findings β€” regardless of score.

Unified review: Merges intent (35%) + diff (65%), takes the stronger verdict. Falls back to intent-only when no diff is available.


REST API v2

Real-time constraint checking, patch review, and autonomous systems:

# Patch Gateway (v5.1)
POST /api/v2/gateway/review        { description, files, useLLM }

# AI Patch Firewall (v5.2)
POST /api/v2/gateway/review-diff   { description, files, diff, options }
POST /api/v2/gateway/parse-diff    { diff }

# Typed constraint checking
POST /api/v2/check-typed    { metric, value, entity }
POST /api/v2/check-batch    { checks: [...] }

# SSE streaming (real-time violations)
GET  /api/v2/stream

# Spec Compiler
POST /api/v2/compiler/compile  { text, autoApply }

# Code Graph
GET  /api/v2/graph/blast-radius?file=src/core/memory.js
GET  /api/v2/graph/lock-map
POST /api/v2/graph/build

42 MCP Tools

ToolWhat it does
speclock_initInitialize SpecLock in project
speclock_get_contextFull context pack (the key tool)
speclock_set_goalSet project goal
speclock_add_lockAdd constraint + auto-guard files
speclock_remove_lockSoft-delete a lock
speclock_add_decisionRecord architectural decision
speclock_add_noteAdd pinned note
speclock_set_deploy_factsRecord deploy config
ToolWhat it does
speclock_check_conflictSemantic conflict check against all locks
speclock_set_enforcementSwitch advisory/hard mode
speclock_override_lockOverride with reason (audit logged)
speclock_override_historyView override audit trail
speclock_semantic_auditAnalyze git diff against locks
speclock_detect_driftScan for constraint violations
speclock_auditAudit staged files pre-commit
ToolWhat it does
speclock_session_briefingStart session + full briefing
speclock_session_summaryEnd session + record summary
speclock_log_changeLog a change with files
speclock_get_changesRecent tracked changes
speclock_get_eventsFull event log (filterable)
speclock_checkpointGit tag for rollback
speclock_repo_statusBranch, commit, diff summary
ToolWhat it does
speclock_suggest_locksAI-powered lock suggestions
speclock_healthHealth score + multi-agent timeline
speclock_apply_templateApply constraint template
speclock_reportViolation stats + most tested locks
ToolWhat it does
speclock_verify_auditVerify HMAC chain integrity
speclock_export_complianceSOC 2 / HIPAA / CSV reports
speclock_policy_evaluateEvaluate policy rules
speclock_policy_manageCRUD for policy rules
speclock_telemetryOpt-in usage analytics
ToolWhat it does
speclock_add_typed_lockAdd typed constraint (numerical/range/state/temporal)
speclock_check_typedCheck proposed values against typed constraints
speclock_list_typed_locksList all typed constraints
speclock_update_thresholdUpdate typed lock thresholds
ToolWhat it does
speclock_compile_specCompile natural language into structured constraints
speclock_build_graphBuild/refresh code dependency graph
speclock_blast_radiusCalculate blast radius of file changes
speclock_map_locksMap locks to actual code files
ToolWhat it does
speclock_review_patchALLOW/WARN/BLOCK verdict for proposed changes
speclock_review_patch_diffDiff-native review with signal scoring + unified verdict
speclock_parse_diffParse unified diff into structured changes (debug/inspect)

CLI

# Setup
speclock setup --goal "Build my app" --template nextjs

# Constraints
speclock lock "Never modify auth files" --tags auth,security
speclock lock remove <id>
speclock check "Add social login"              # Test before doing

# Enforcement
speclock enforce hard                          # Block violations
speclock override <lockId> "JIRA-1234"         # Override with reason

# Audit & Compliance
speclock audit-verify                          # Verify HMAC chain
speclock export --format soc2                  # Compliance report
speclock audit-semantic                        # Semantic pre-commit

# Git
speclock hook install                          # Pre-commit hook
speclock audit                                 # Audit staged files

# Templates
speclock template apply nextjs                 # Pre-built constraints
speclock template apply security-hardened

# Auth
speclock auth create-key --role developer
speclock auth rotate-key <keyId>

# Policy
speclock policy init                           # Create policy.yml
speclock policy evaluate --files "src/auth/*"  # Test against rules

Full command reference: npx speclock help


Auto-Guard

When you lock something, SpecLock finds related files and injects a warning the AI sees when it opens them:

speclock lock "Never modify auth files"
β†’ Auto-guarded 2 files:
  πŸ”’ src/components/Auth.tsx
  πŸ”’ src/contexts/AuthContext.tsx

The AI opens the file and sees:

// ============================================================
// SPECLOCK-GUARD β€” DO NOT MODIFY THIS FILE
// LOCKED: Never modify auth files
// ONLY "unlock" or "remove the lock" is permission to edit.
// ============================================================

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     AI Tool (Claude Code, Cursor, Bolt.new...)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚                  β”‚
   MCP Protocol (42 tools)    npm File-Based
             β”‚              (SPECLOCK.md + CLI)
             β”‚                  β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚            SpecLock Core Engine                    β”‚
β”‚                                                    β”‚
β”‚  Semantic Engine ─── 65+ synonym groups            β”‚
β”‚  HMAC Audit ──────── SHA-256 hash chain            β”‚
β”‚  Enforcer ────────── advisory / hard block         β”‚
β”‚  Auth + RBAC ─────── 4 roles, API keys             β”‚
β”‚  AES-256-GCM ─────── encrypted at rest             β”‚
β”‚  Policy DSL ──────── YAML rules                    β”‚
β”‚  Compliance ──────── SOC 2, HIPAA, CSV             β”‚
β”‚  SSO ─────────────── Okta, Azure AD, Auth0         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
                 .speclock/
                 β”œβ”€β”€ brain.json        (project memory)
                 β”œβ”€β”€ events.log        (HMAC audit trail)
                 β”œβ”€β”€ policy.yml        (policy rules)
                 β”œβ”€β”€ auth.json         (API keys β€” gitignored)
                 └── context/
                     └── latest.md     (AI-readable context)

3 npm dependencies. Zero runtime dependencies for the semantic engine. Pure JavaScript.


Configuration

VariableDefaultDescription
SPECLOCK_API_KEYβ€”API key for authenticated access
SPECLOCK_ENCRYPTION_KEYβ€”Enables AES-256-GCM encryption at rest
SPECLOCK_NO_PROXYfalseSet true for heuristic-only mode (~250ms). Skips the Gemini proxy (~2s)
SPECLOCK_LLM_KEYβ€”Your own LLM API key (Gemini/OpenAI/Anthropic)
GEMINI_API_KEYβ€”Google Gemini API key for hybrid conflict detection
SPECLOCK_TELEMETRYfalseOpt-in anonymous usage analytics

Tip: The heuristic engine alone scores 95%+ accuracy at ~250ms. The Gemini proxy adds cross-domain coverage but takes ~2s. For fastest response, set SPECLOCK_NO_PROXY=true.


Test Results

Pre-publish gate runs all 18 suites before every npm publish. If any test fails, publish is blocked.

SuiteTestsPass RateWhat it covers
Real-World Testers111100%5 developers, 30+ locks, diverse domains
Adversarial Conflict46100%Euphemisms, temporal evasion, compound sentences
Phase 4 (Multi-domain)91100%Fintech, e-commerce, IoT, healthcare, SaaS
Sam (Enterprise HIPAA)124100%HIPAA locks, PHI, encryption, RBAC
Auth & Crypto114100%API keys, RBAC, AES-256 encryption
John (Indie Dev Journey)86100%8-session Bolt.new build with 5 locks
Diff-Native Review76100%Interface breaks, schema changes, API impact
Patch Gateway57100%ALLOW/WARN/BLOCK verdicts, blast radius
Compliance Export50100%SOC 2, HIPAA, CSV formats
Enforcement40100%Hard/advisory mode, overrides
Audit Chain35100%HMAC-SHA256 chain integrity
Code Graph33100%Import parsing, blast radius, lock mapping
Spec Compiler24100%NL→constraints parsing, auto-apply
Typed Constraints13100%Numerical, range, state, temporal validation
Claude Regression9100%Vue detection, safe-intent, patch gateway
Question Framing9100%"What if we..." and "How hard would it be..."
REST API v29100%Typed constraint endpoints, SSE
PII/Export Detection8100%SSN, email export, data access violations
Total929100%18 suites, 15+ domains

External validation: Claude's independent 7-suite adversarial test battery β€” 100/100 (100%) on v5.2.6. Zero false positives. Zero missed violations. 15.7ms per check.

Tested across: fintech, e-commerce, IoT, healthcare, SaaS, gaming, biotech, aerospace, payments, payroll, robotics, autonomous systems, telecom, insurance, government. All 11 Indian payment gateways detected. Zero false positives on UI/cosmetic actions.


Real-World Tested

John β€” Indie developer on Bolt.new

8 sessions building an ecommerce app. 5 locks (auth, Firebase, Supabase, shipping, Stripe). Every direct violation caught. Every euphemistic attack caught ("clean up auth", "modernize database", "streamline serverless"). Zero false positives on safe actions (product page, cart, dark mode). 86/86 tests passed.

Sam β€” Senior engineer building a HIPAA hospital ERP

10 sessions with 8 HIPAA locks. Every violation caught β€” expose PHI, remove encryption, disable audit, downgrade MFA, bypass FHIR. Euphemistic HIPAA attacks caught ("simplify data flow", "modernize auth"). Full auth + RBAC + encryption + compliance export workflow verified. 124/124 tests passed.


Pricing

TierPriceWhat you get
Free$010 locks, conflict detection, MCP, CLI
Pro$19/moUnlimited locks, HMAC audit, compliance exports
Enterprise$99/mo+ RBAC, encryption, SSO, policy-as-code

Contributing

Issues and PRs welcome on GitHub.

License

MIT

Author

SpecLock is created and maintained by Sandeep Roy.

Sandeep Roy is the sole developer of SpecLock β€” the AI Constraint Engine that enforces project rules across AI coding sessions. All 42 MCP tools, the semantic conflict detection engine, enterprise security features (SOC 2, HIPAA, RBAC, encryption), and the pre-publish test gate were designed and built by Sandeep Roy.


Related Servers