SpecLock - AI Constraint Engine

编码与调试

by sgroy10

面向AI编码的约束引擎,集成Patch Firewall、diff原生审查、Spec Compiler、Code Graph与Python SDK,兼容多种IDE。

什么是 SpecLock - AI Constraint Engine

面向AI编码的约束引擎,集成Patch Firewall、diff原生审查、Spec Compiler、Code Graph与Python SDK,兼容多种IDE。

核心功能 (44 个工具)

speclock_init

Initialize SpecLock in the current project directory.

speclock_get_context

THE KEY TOOL. Returns the full structured context pack.

speclock_set_goal

Set or update the project goal.

speclock_add_lock

Add a non-negotiable constraint (SpecLock).

speclock_remove_lock

Remove (deactivate) a SpecLock by its ID.

speclock_add_decision

Record an architectural or design decision.

speclock_add_note

Add a pinned note for reference.

speclock_set_deploy_facts

Record deployment configuration facts.

speclock_log_change

Manually log a significant change.

speclock_get_changes

Get recent file changes tracked by SpecLock.

speclock_get_events

Get the event log, optionally filtered by type.

speclock_check_conflict

Check if a proposed action conflicts with any active SpecLock. In hard mode, blocks above threshold.

speclock_session_briefing

Start a new session and get a full briefing.

speclock_session_summary

End the current session and record what was accomplished.

speclock_checkpoint

Create a named git tag checkpoint for easy rollback.

speclock_repo_status

Get current git repository status.

speclock_suggest_locks

AI-powered lock suggestions based on project patterns.

speclock_detect_drift

Scan recent changes for constraint violations.

speclock_health

Health check with completeness score and multi-agent timeline.

speclock_apply_template

Apply a pre-built constraint template (nextjs, react, express, supabase, stripe, security-hardened).

speclock_report

Violation report — how many times SpecLock blocked changes.

speclock_audit

Audit staged files against active locks.

speclock_verify_audit

Verify the integrity of the HMAC audit chain.

speclock_export_compliance

Generate compliance reports (SOC 2, HIPAA, CSV).

speclock_set_enforcement

Set enforcement mode: advisory (warn) or hard (block).

speclock_override_lock

Override a lock with justification. Logged to audit trail.

speclock_semantic_audit

Semantic pre-commit: analyzes code changes vs locks.

speclock_override_history

Show lock override history.

speclock_policy_evaluate

Evaluate policy-as-code rules against proposed actions.

speclock_policy_manage

Policy CRUD: list, add, remove policy rules.

speclock_telemetry

Opt-in usage analytics summary.

speclock_guard_file

Add SPECLOCK-GUARD header to lock specific files.

speclock_auto_guard

Auto-guard files related to lock keywords.

speclock_add_typed_lock

Add typed constraint (numerical/range/state/temporal).

speclock_check_typed

Check proposed values against typed constraints.

speclock_list_typed_locks

List all typed constraints with current thresholds.

speclock_update_threshold

Update typed lock thresholds dynamically.

speclock_compile_spec

Compile natural language (PRDs, READMEs) into structured constraints via Gemini Flash.

speclock_build_graph

Build/refresh code dependency graph from imports (JS/TS/Python).

speclock_blast_radius

Calculate blast radius — transitive dependents, impact %, depth.

speclock_map_locks

Map active locks to actual code files via the dependency graph.

speclock_review_patch

ALLOW/WARN/BLOCK verdict — combines semantic conflict + lock-file mapping + blast radius.

speclock_review_patch_diff

Diff-native review — parses actual diffs for interface breaks, protected symbols, dependency drift, schema changes.

speclock_parse_diff

Parse unified diff into structured changes — imports, exports, symbols, routes, schema detection.

README

<p align="center"> <img src="https://img.shields.io/badge/🔒-SpecLock-000000?style=for-the-badge&labelColor=000000&color=4F46E5" alt="SpecLock" height="40" /> </p> <h3 align="center">Your AI keeps breaking things you told it not to touch.<br/>SpecLock makes it stop.</h3> <p align="center"> <a href="https://www.npmjs.com/package/speclock"><img src="https://img.shields.io/npm/v/speclock.svg?style=flat-square&color=4F46E5" alt="npm version" /></a> <a href="https://www.npmjs.com/package/speclock"><img src="https://img.shields.io/npm/dm/speclock.svg?style=flat-square&color=22C55E" alt="npm downloads" /></a> <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square" alt="MIT License" /></a> <a href="https://modelcontextprotocol.io"><img src="https://img.shields.io/badge/MCP-51_tools-green.svg?style=flat-square" alt="MCP 51 tools" /></a> </p> <p align="center"> <img src="https://img.shields.io/badge/drift_score-12%2F100-brightgreen.svg?style=flat-square" alt="Drift Score" /> <img src="https://img.shields.io/badge/lock_coverage-83%25-brightgreen.svg?style=flat-square" alt="Lock Coverage" /> <img src="https://img.shields.io/badge/lock_strength-85%2F100-brightgreen.svg?style=flat-square" alt="Lock Strength" /> </p> <p align="center"> <a href="https://github.com/sgroy10/speclock"><img src="https://img.shields.io/badge/Protected_by-SpecLock-FF6B2C?style=flat&logo=lock" alt="Protected by SpecLock" /></a> <a href="https://github.com/sgroy10/speclock"><img src="https://img.shields.io/badge/Protected_by-SpecLock-FF6B2C?style=flat-square&logo=lock" alt="Protected by SpecLock" /></a> <a href="https://github.com/sgroy10/speclock"><img src="https://img.shields.io/badge/PROTECTED_BY-SPECLOCK-FF6B2C?style=for-the-badge&logo=lock&logoColor=white" alt="Protected by SpecLock" /></a> </p> <p align="center"> <a href="https://www.npmjs.com/package/speclock"><img src="https://img.shields.io/npm/v/speclock?label=SpecLock&color=FF6B2C&logo=lock" alt="SpecLock" /></a> <a href="https://github.com/sgroy10/speclock"><img src="https://img.shields.io/badge/SpecLock_Tests-1009%20passing-success" alt="Tests" /></a> <a href="https://www.npmjs.com/package/speclock"><img src="https://img.shields.io/npm/dm/speclock?label=SpecLock%20downloads&color=FF6B2C" alt="Downloads" /></a> </p> <p align="center"><sub>Browse all badge variants at <a href="https://sgroy10.github.io/speclock/badge.html">sgroy10.github.io/speclock/badge.html</a> &middot; or run <code>speclock badge</code> in your terminal.</sub></p> <p align="center"> <a href="https://sgroy10.github.io/speclock/">Website</a> · <a href="https://www.npmjs.com/package/speclock">npm</a> · <a href="https://smithery.ai/servers/sgroy10/speclock">Smithery</a> · <a href="https://github.com/sgroy10/speclock">GitHub</a> </p> <p align="center"><strong>Developed by <a href="https://github.com/sgroy10">Sandeep Roy</a></strong> · Free &amp; Open Source (MIT License)</p>

Quick Start

bash
npx speclock protect              # Install in your project (creates CLAUDE.md if missing)
speclock mcp install claude-code  # Wire up MCP for Claude Code (or cursor, windsurf, cline, codex)
speclock doctor                   # Verify everything is set up correctly

That's it. Your AI now has rules it can't ignore. Default mode is WARN (loud warnings, no blocks). Opt in to hard enforcement with speclock protect --strict.

What's New in v5.5.4

  • Default WARN mode — no more false-positive blocks. Loud warnings instead. Opt in to strict with --strict or SPECLOCK_STRICT=1.
  • speclock mcp install <client> — autoinstaller for Claude Code, Cursor, Windsurf, Cline, Codex. No more hand-editing JSON.
  • Greenfield supportspeclock protect in fresh projects auto-creates CLAUDE.md with safe defaults.
  • speclock doctor — health check verifying installation, git hook, rule files, and MCP integration. Prints exact fix commands for any issues.

What is SpecLock?

SpecLock is an AI constraint engine that enforces your project rules across every AI coding session. Your AI keeps breaking things you told it not to touch — SpecLock makes it stop.

Commands Reference

bash
speclock protect                      # Install pre-commit hook + extract locks from rule files
speclock protect --strict             # Hard enforcement mode (blocks violations)
speclock doctor                       # Health check — verifies install, hooks, rules, MCP
speclock mcp install <client>         # Wire up MCP server (claude-code, cursor, windsurf, cline, codex)
speclock check "action description"   # Test if an action would conflict with locks
speclock add-lock "rule"              # Add a new lock
speclock list-locks                   # Show all locks
speclock enforce hard|advisory        # Change enforcement mode

Full command reference: npx speclock help


code
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. 991 tests across 19 suites. 0 false positives. 15.7ms per check.

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.

code
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

bash
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:

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).

<table> <tr><td><b>Category</b></td><td><b>Detection</b></td><td><b>Example</b></td></tr> <tr><td>Direct violations</td><td>100%</td><td>"Delete the auth module" vs lock "Never modify auth"</td></tr> <tr><td>Euphemistic attacks</td><td>100%</td><td>"Clean up old patient data" = deletion</td></tr> <tr><td>Temporal evasion</td><td>100%</td><td>"Temporarily disable MFA" = disable MFA</td></tr> <tr><td>Dilution attacks</td><td>100%</td><td>Violation buried in multi-part request</td></tr> <tr><td>Compound sentences</td><td>100%</td><td>"Update UI and also drop users table"</td></tr> <tr><td>Synonym substitution</td><td>100%</td><td>"Sunset the API" = remove the API</td></tr> <tr><td>Payment brand names (11 gateways)</td><td>100%</td><td>"Add Razorpay" / "Implement PayU" vs "Must use Stripe"</td></tr> <tr><td>Salary/payroll cross-vocab</td><td>100%</td><td>"Optimize salary" vs "Payroll records locked"</td></tr> <tr><td>Safety system bypass</td><td>100%</td><td>"Disable safety interlock" = bypass safety</td></tr> <tr><td>Unknown domains (via Gemini)</td><td>100%</td><td>Gaming, biotech, aerospace, music, legal</td></tr> <tr><td>Safe actions (true negatives)</td><td>0% FP</td><td>"Change the font" correctly passes auth locks</td></tr> </table>

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:

code
Advisory (default):  AI gets a warning, decides what to do
Hard mode:           AI is BLOCKED — MCP returns isError, AI cannot proceed
bash
speclock enforce hard   # Enable hard mode — violations above threshold are blocked
  • Configurable threshold — default 70%. Only HIGH confidence conflicts block.
  • Override with reasonspeclock 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

bash
speclock auth create-key --role developer --name "CI Bot"
# → sk_speclock_a1b2c3... (shown once, stored as SHA-256 hash)
RoleReadWrite LocksOverrideAdmin
viewerYes
developerYesWith reason
architectYesYesYes
adminYesYesYesYes

AES-256-GCM Encryption

bash
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.

bash
$ speclock audit-verify

✓ Audit chain VALID — 247 events, 0 broken links, no tampering detected.

Compliance Exports

bash
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:

yaml
# .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.


REST API v2

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

bash
# 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

51 MCP Tools

<details> <summary><b>Memory</b> — goal, locks, decisions, notes, deploy facts</summary>
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
</details> <details> <summary><b>Enforcement</b> — conflict detection, hard blocking, overrides</summary>
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
</details> <details> <summary><b>Tracking & Sessions</b> — changes, events, session continuity</summary>
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
</details> <details> <summary><b>Intelligence</b> — suggestions, health, templates, reports</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
</details> <details> <summary><b>Enterprise</b> — audit, compliance, policy, telemetry</summary>
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
</details> <details> <summary><b>Typed Constraints</b> — numerical, range, state, temporal (v5.0)</summary>
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
</details> <details> <summary><b>Spec Compiler & Code Graph</b> — NL→constraints, dependency analysis (v5.0)</summary>
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
</details> <details> <summary><b>Patch Gateway & AI Patch Firewall</b> — change review, diff analysis (v5.1/v5.2)</summary>
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)
</details> <details> <summary><b>Universal Rules Sync & Incident Replay</b> — cross-tool sync, session replay (v5.3)</summary>
ToolWhat it does
speclock_sync_rulesSync constraints to Cursor, Claude, Copilot, Windsurf, Gemini, Aider, AGENTS.md
speclock_list_sync_formatsList all available sync formats
speclock_replayReplay a session's activity — what AI tried and what was caught
speclock_list_sessionsList available sessions for replay
speclock_drift_score0-100 project integrity metric — how much AI deviated from intent
speclock_coverageLock Coverage Audit — find unprotected code areas
speclock_strengthenGrade locks and suggest stronger versions
</details>

CLI

bash
# 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 safe-defaults          # Vibe coding seatbelt (5 locks)
speclock template apply solo-founder           # Indie builder essentials (3 locks)
speclock template apply hipaa                  # HIPAA healthcare (8 locks)
speclock template apply api-stability          # API contract protection (6 locks)
speclock template apply nextjs                 # Next.js constraints
speclock template apply security-hardened      # Security hardening

# Sync to AI tools
speclock sync --all                            # Sync to ALL tools
speclock sync --format cursor                  # Cursor only
speclock sync --format claude                  # Claude Code only
speclock sync --preview windsurf               # Preview without writing

# Incident Replay
speclock replay                                # Replay last session
speclock replay --list                         # List sessions
speclock replay --session <id>                 # Replay specific session

# Project Health
speclock drift                                 # Drift Score (0-100)
speclock drift --days 7                        # Last 7 days only
speclock coverage                              # Lock Coverage Audit
speclock strengthen                            # Grade and improve locks

# 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:

code
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:

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

Architecture

code
┌──────────────────────────────────────────────────┐
│     AI Tool (Claude Code, Cursor, Bolt.new...)    │
└────────────┬──────────────────┬──────────────────┘
             │                  │
   MCP Protocol (51 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_KEYAPI key for authenticated access
SPECLOCK_ENCRYPTION_KEYEnables AES-256-GCM encryption at rest
SPECLOCK_NO_PROXYfalseSet true for heuristic-only mode (~250ms). Skips the Gemini proxy (~2s)
SPECLOCK_LLM_KEYYour own LLM API key (Gemini/OpenAI/Anthropic)
GEMINI_API_KEYGoogle 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
Guardian (Protect)47100%Zero-config rule file extraction
Total991100%19 suites, 15+ domains

External validation: Claude's independent 7-suite adversarial test battery — 100/100 (100%) on v5.5.4. 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

Changelog

Prior-version feature tours. The Quick Start and What's New sections above cover v5.5.4 — this section preserves details on features shipped in v5.0–v5.4.

v5.4 — Drift Score, Lock Coverage, Lock Strengthener

Drift Score. How much has your AI-built project drifted from your original intent? Only SpecLock can answer this — because only SpecLock knows what was intended vs what was done.

bash
$ speclock drift

Drift Score: 23/100 (B) — minor drift
Trend: improving | Period: 30 days | Active locks: 8

Signal Breakdown:
  Violations:      6/30  (4 violations in 12 checks)
  Overrides:       5/20  (1 override)
  Reverts:         3/15  (1 revert detected)
  Lock churn:      0/15  (0 removed, 3 added)
  Goal stability:  0/10  (1 goal change)
  Session gaps:    9/10  (3/5 unsummarized)

README badge: ![Drift Score](https://img.shields.io/badge/drift_score-23%2F100-brightgreen.svg)

Lock Coverage Audit. SpecLock scans your codebase and tells you what's unprotected:

bash
$ speclock coverage

Lock Coverage: 60% (B) — partially protected

  [COVERED] CRITICAL authentication   2 file(s)
  [EXPOSED] CRITICAL payments         1 file(s)
  [COVERED] CRITICAL secrets          0 file(s)
  [COVERED] HIGH     api-routes       2 file(s)

Suggested Locks (ready to apply):
  1. [CRITICAL] payments (1 file at risk)
     speclock lock "Never modify payment processing or billing without permission"

Like a security scanner, but for AI constraint gaps.

Lock Strengthener. Your locks might be too vague. SpecLock grades each one and suggests improvements:

bash
$ speclock strengthen

Lock Strength: 72/100 (B) — 3 strong, 1 weak

[WEAK  ] 45/100 (D)  "don't touch auth"
          Issue: Too vague — short locks miss edge cases
          Issue: No specific scope
          Suggested: "Never modify, refactor, or delete auth..."

[STRONG] 90/100 (A)  "Never expose API keys in client-side code, logs, or error messages"

v5.3 — Universal Rules Sync, Incident Replay, Safety Templates

Universal Rules Sync. One command syncs your SpecLock constraints to every AI coding tool:

bash
speclock sync --all
code
SpecLock Sync Complete
  ✓ Cursor             → .cursor/rules/speclock.mdc
  ✓ Claude Code        → CLAUDE.md
  ✓ AGENTS.md          → AGENTS.md (Linux Foundation standard)
  ✓ Windsurf           → .windsurf/rules/speclock.md
  ✓ GitHub Copilot     → .github/copilot-instructions.md
  ✓ Gemini             → GEMINI.md
  ✓ Aider              → .aider.conf.yml

7 file(s) synced.

Define constraints once in SpecLock, sync everywhere. --format cursor for single format, --preview to dry-run, --list to see supported formats.

Incident Replay. Flight recorder for your AI coding sessions:

bash
speclock replay

Session: ses_a1b2c3 (claude-code, 47 min)
────────────────────────────────────────────
14:02  [ALLOW]   Create user profile component
14:08  [ALLOW]   Add form validation
14:15  [WARN]    Simplify authentication flow
                 → matched lock: "Never modify auth"
14:23  [BLOCK]   Clean up old user records
                 → euphemism detected: "clean up" = deletion
14:31  [ALLOW]   Update landing page hero section

Score: 5 events | 3 allowed | 1 warned | 1 BLOCKED

speclock replay --list lists sessions; --session <id> replays a specific one.

Safety Templates. Pre-built constraint packs:

bash
speclock template apply safe-defaults   # 5 locks — "Vibe Coding Seatbelt"
speclock template apply solo-founder    # 3 locks — auth, payments, data
speclock template apply hipaa           # 8 locks — HIPAA healthcare
speclock template apply api-stability   # 6 locks — API contract protection

Safe Defaults prevents the 5 most common AI disasters: database deletion, auth removal, secret exposure, error-handling removal, logging disablement.

v5.2 — AI Patch Firewall

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

code
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, protected symbol edits in locked zones, dependency drift, schema/migration destructive changes, public API route changes. Hard escalation: auto-BLOCK on destructive schema changes, removed API routes, protected symbol edits. Unified review: merges intent (35%) + diff (65%), takes the stronger verdict.

v5.1 — Patch Gateway

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

code
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).

v5.0 — Spec Compiler, Code Graph, Typed Constraints, Python SDK & ROS2

Spec Compiler. Paste a PRD, README, or architecture doc — SpecLock extracts all constraints automatically:

code
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).

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

code
$ 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 auto-maps locks to source files; module detection groups files into logical modules.

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

javascript
// 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.

bash
pip install speclock-sdk
python
from speclock import SpecLock

sl = SpecLock(project_root=".")
result = sl.check_text("Switch database to MongoDB")
result = sl.check_typed(metric="speed_mps", value=3.5)
result = sl.check(action="Increase speed", speed_mps=3.5)

Uses the same .speclock/brain.json as the Node.js MCP server. ROS2 Guardian Node subscribes to /joint_states, /cmd_vel, /speclock/state_transition; publishes violations to /speclock/violations; triggers emergency stop via /speclock/emergency_stop.


Show your support

If SpecLock saves your project from a 3am incident, add this badge to your README:

markdown
[![Protected by SpecLock](https://img.shields.io/badge/Protected_by-SpecLock-FF6B2C?style=flat&logo=lock)](https://github.com/sgroy10/speclock)

Or run speclock badge in your terminal to see all variants. Full gallery: sgroy10.github.io/speclock/badge.html · Full docs: BADGES.md.

Every adoption helps another developer discover SpecLock and stop their AI from wrecking their project. Thank you.

Spread the word

Want to help SpecLock reach more developers? Everything you need to post — tweets, LinkedIn drafts, Reddit templates, Show HN copy, Discord messages, one-liners, elevator pitches — is pre-written and fact-checked in VIRAL-KIT.md. Copy, paste, send. Zero effort.


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 51 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.


<p align="center"><i>SpecLock v5.5.4 — Your AI has rules. SpecLock makes them unbreakable. 991 tests, 100% pass rate, 51 MCP tools, Default WARN mode, MCP Autoinstaller, Greenfield support, Doctor health check. Developed by Sandeep Roy.</i></p>

常见问题

SpecLock - AI Constraint Engine 是什么?

面向AI编码的约束引擎,集成Patch Firewall、diff原生审查、Spec Compiler、Code Graph与Python SDK,兼容多种IDE。

SpecLock - AI Constraint Engine 提供哪些工具?

提供 44 个工具,包括 speclock_init、speclock_get_context、speclock_set_goal

相关 Skills

前端设计

by anthropics

Universal
热门

面向组件、页面、海报和 Web 应用开发,按鲜明视觉方向生成可直接落地的前端代码与高质感 UI,适合做 landing page、Dashboard 或美化现有界面,避开千篇一律的 AI 审美。

想把页面做得既能上线又有设计感,就用前端设计:组件到整站都能产出,难得的是能避开千篇一律的 AI 味。

编码与调试
未扫描137.2k

网页应用测试

by anthropics

Universal
热门

用 Playwright 为本地 Web 应用编写自动化测试,支持启动开发服务器、校验前端交互、排查 UI 异常、抓取截图与浏览器日志,适合调试动态页面和回归验证。

借助 Playwright 一站式验证本地 Web 应用前端功能,调 UI 时还能同步查看日志和截图,定位问题更快。

编码与调试
未扫描137.2k

网页构建器

by anthropics

Universal
热门

面向复杂 claude.ai HTML artifact 开发,快速初始化 React + Tailwind CSS + shadcn/ui 项目并打包为单文件 HTML,适合需要状态管理、路由或多组件交互的页面。

在 claude.ai 里做复杂网页 Artifact 很省心,多组件、状态和路由都能顺手搭起来,React、Tailwind 与 shadcn/ui 组合效率高、成品也更精致。

编码与调试
未扫描137.2k

相关 MCP Server

GitHub

编辑精选

by GitHub

热门

GitHub 是 MCP 官方参考服务器,让 Claude 直接读写你的代码仓库和 Issues。

这个参考服务器解决了开发者想让 AI 安全访问 GitHub 数据的问题,适合需要自动化代码审查或 Issue 管理的团队。但注意它只是参考实现,生产环境得自己加固安全。

编码与调试
85.9k

by Context7

热门

Context7 是实时拉取最新文档和代码示例的智能助手,让你告别过时资料。

它能解决开发者查找文档时信息滞后的问题,特别适合快速上手新库或跟进更新。不过,依赖外部源可能导致偶尔的数据延迟,建议结合官方文档使用。

编码与调试
55.6k

by tldraw

热门

tldraw 是让 AI 助手直接在无限画布上绘图和协作的 MCP 服务器。

这解决了 AI 只能输出文本、无法视觉化协作的痛点——想象让 Claude 帮你画流程图或白板讨论。最适合需要快速原型设计或头脑风暴的开发者。不过,目前它只是个基础连接器,你得自己搭建画布应用才能发挥全部潜力。

编码与调试
47.1k

评论