{
  "markdown": "<p align=\"center\">\n  <img src=\"https://img.shields.io/badge/🔒-SpecLock-000000?style=for-the-badge&labelColor=000000&color=4F46E5\" alt=\"SpecLock\" height=\"40\" />\n</p>\n\n<h2 align=\"center\">Rules files tell AI what not to change.<br/>SpecLock enforces them.</h2>\n\n<p align=\"center\">\n  Stop Claude Code, Cursor, Codex, Windsurf, and other AI coding tools from crossing project constraints you already wrote in <code>CLAUDE.md</code>, <code>AGENTS.md</code>, and <code>.cursorrules</code>.\n</p>\n\n<p align=\"center\">\n  <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>\n  <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>\n  <a href=\"https://github.com/sgroy10/speclock/actions/workflows/ci.yml\"><img src=\"https://github.com/sgroy10/speclock/actions/workflows/ci.yml/badge.svg\" alt=\"CI\" /></a>\n  <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>\n  <a href=\"https://modelcontextprotocol.io\"><img src=\"https://img.shields.io/badge/MCP-51%20tools-green.svg?style=flat-square\" alt=\"MCP 51 tools\" /></a>\n</p>\n\n<p align=\"center\">\n  <a href=\"#60-second-setup\"><strong>Install</strong></a> ·\n  <a href=\"#see-the-difference\"><strong>See a block</strong></a> ·\n  <a href=\"#install-as-a-claude-code-plugin\"><strong>Claude Code plugin</strong></a> ·\n  <a href=\"https://sgroy10.github.io/speclock/\"><strong>Website</strong></a> ·\n  <a href=\"https://speclock-mcp-production.up.railway.app/saves\"><strong>Saves Wall</strong></a>\n</p>\n\n> **Why another rules tool?** Rules files are context. They can be forgotten, diluted, or overridden during a long coding session. SpecLock turns those rules into checks that run before edits, shell commands, and commits.\n\n## See the difference\n\n```text\nCLAUDE.md:  Never modify the authentication system.\n\nYou:        Add social login to the login page.\n\nWithout SpecLock\nClaude:     I'll update the auth flow and add an OAuth provider...\n\nWith SpecLock (strict mode)\nSpecLock:   BLOCKED — conflicts with \"Never modify the authentication system\"\n            Match: login → auth → authentication\n            The action was denied before the files changed.\n```\n\nSpecLock uses semantic conflict detection rather than simple keyword matching. It catches indirect actions such as “clean up old patient data,” “streamline checkout,” or “temporarily disable MFA” when they violate an active constraint.\n\n## 60-second setup\n\nRun this from the project you want to protect:\n\n```bash\nnpx speclock@latest protect          # reads existing AI rule files; advisory by default\nnpx speclock@latest doctor           # confirms rules, hooks, and integration\n```\n\nWhen the advisory output looks right, enable blocking:\n\n```bash\nnpx speclock@latest protect --strict\n```\n\nNo account is required. SpecLock runs locally by default, and advisory mode never blocks a change.\n\n## Install as a Claude Code plugin\n\nInside Claude Code, run:\n\n```text\n/plugin marketplace add sgroy10/speclock\n/plugin install speclock@speclock-marketplace\n```\n\nThen protect the current project once:\n\n```bash\nnpx speclock@latest protect          # warnings only\nnpx speclock@latest protect --strict # block confirmed conflicts\n```\n\nThe plugin automatically starts SpecLock's MCP server and checks Claude Code `Write`, `Edit`, and `Bash` actions before execution. It includes all 51 MCP tools and works alongside your existing `CLAUDE.md`.\n\n## Install on other coding agents\n\nSpecLock is packaged for multiple agent ecosystems, but the enforcement level depends on what each host exposes:\n\n| Platform | Install/discovery path | Protection level |\n|---|---|---|\n| Claude Code | Native marketplace plugin above | Native pre-action checks for `Write`, `Edit`, and `Bash` |\n| Gemini CLI | Install this repository as a Gemini extension | MCP-assisted checks plus project context |\n| Cursor | Agent Plugin / Cursor marketplace package | MCP-assisted checks plus rules |\n| Codex | Repository Codex plugin in `plugins/speclock` | MCP-assisted checks plus `$speclock-guardrails` skill |\n| GitHub Copilot CLI | Add this repository as a plugin marketplace | MCP-assisted checks plus bundled plugin context |\n| Cline | MCP server; curated marketplace submission in progress | MCP-assisted checks |\n| Windsurf | `speclock mcp install windsurf` | MCP-assisted checks plus rules |\n| Any Git client or CI | `speclock protect` | Commit/CI enforcement independent of the coding agent |\n\nMCP-assisted means the agent can call SpecLock before acting; it does not guarantee interception. Use `speclock protect --strict` and CI when a constraint must be enforced regardless of the client.\n\nSpecLock has a different job from memory and skills: **memory recalls context, skills provide procedures, and SpecLock verifies planned actions against explicit constraints.** It reduces constraint drift; it cannot guarantee factual correctness or make a model hallucination-free.\n\nRepository installs supported by current clients:\n\n```bash\ngemini extensions install https://github.com/sgroy10/speclock\ncopilot plugin marketplace add sgroy10/speclock\ncopilot plugin install speclock@speclock-marketplace\n```\n\n## What you get\n\n| Capability | What it does |\n|---|---|\n| Pre-action checks | Reviews Claude Code writes, edits, and shell commands before they run |\n| Semantic constraints | Detects synonyms, euphemisms, compound requests, and indirect violations |\n| Git enforcement | Adds a second guard at commit time |\n| Advisory and strict modes | Start with warnings; opt in to hard blocking when ready |\n| Audit trail | Records decisions in a tamper-evident HMAC chain |\n| MCP integration | Exposes 51 tools to Claude Code, Cursor, Codex, Windsurf, and Cline |\n| Shareable save receipts | Shows what SpecLock prevented with `speclock wins` |\n\n## Proven in the open\n\n- **10,000+ npm downloads** before the native Claude Code plugin release.\n- **1,043 automated tests across 24 suites**, including adversarial conflicts, false-positive cases, patch analysis, enforcement, auth, and compliance.\n- **MIT licensed** and inspectable end to end.\n- **Local-first defaults** with optional remote features clearly separated.\n\n## Commands you will use most\n\n```bash\nspeclock protect                      # extract constraints and install project protection\nspeclock protect --strict             # enable hard enforcement\nspeclock doctor                       # verify the complete setup\nspeclock check \"action description\"   # preview whether an action conflicts\nspeclock add-lock \"rule\"              # add a constraint explicitly\nspeclock list-locks                    # inspect active constraints\nspeclock enforce hard|advisory         # switch enforcement mode\nspeclock mcp install <client>          # Claude Code, Cursor, Windsurf, Cline, or Codex\nspeclock wins                          # create a shareable save receipt\n```\n\nFull reference: `npx speclock@latest help`\n\n## New in v5.8.0\n\n- Portable Agent Plugin packaging for Cursor-compatible discovery.\n- Gemini CLI extension packaging with MCP startup and constraint context.\n- Codex plugin with a `$speclock-guardrails` skill and pinned MCP server.\n- GitHub Copilot CLI compatibility through the repository marketplace.\n- Explicit per-platform enforcement labels: native hook, MCP-assisted, or Git/CI.\n\n<details>\n<summary><strong>More links and project badges</strong></summary>\n\n<p>\n  <a href=\"https://speclock-mcp-production.up.railway.app/saves\"><img src=\"https://img.shields.io/endpoint?url=https%3A%2F%2Fspeclock-mcp-production.up.railway.app%2Fapi%2Fbadge%2Fsaves\" alt=\"Blocked by SpecLock\" /></a>\n  <a href=\"https://smithery.ai/servers/sgroy10/speclock\">Smithery</a> ·\n  <a href=\"https://sgroy10.github.io/speclock/badge.html\">Badge gallery</a> ·\n  <a href=\"https://github.com/sgroy10\">Sandeep Roy</a>\n</p>\n\n</details>\n\n## The Problem\n\nAI coding tools have memory now. Claude Code has `CLAUDE.md`. Cursor has `.cursorrules`. Mem0 exists.\n\n**But memory without enforcement is useless.**\n\nYour 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.\n\n**Remembering is not respecting.** No existing tool stops the AI from breaking what you locked.\n\n## How It Works\n\nYou set constraints. SpecLock enforces them — across sessions, across tools, across teams.\n\n```\nspeclock lock \"Never modify auth files\"           → auto-guards src/auth/*.ts\nspeclock lock \"Database must stay PostgreSQL\"      → catches \"migrate to MongoDB\"\nspeclock lock \"Never delete patient records\"       → catches \"clean up old data\"\nspeclock lock \"Don't touch the payment flow\"       → catches \"streamline checkout\"\n```\n\nThe semantic engine doesn't do keyword matching. It understands:\n- **\"clean up old data\"** = deletion (euphemism detection)\n- **\"streamline checkout\"** = modify payment flow (synonym + concept mapping)\n- **\"temporarily disable logging\"** = disable logging (temporal evasion detection)\n- **\"Update UI and also drop the users table\"** = hidden violation (compound splitter)\n\nAnd it knows what's safe:\n- **\"Enable audit logging\"** when the lock says \"Never *disable* audit logging\" → **no conflict** (intent alignment)\n\n## Quick Start by Platform\n\n### Bolt.new / Aider / Any npm Platform\n```bash\nnpx speclock setup --goal \"Build my app\" --template nextjs\n```\nCreates `SPECLOCK.md`, injects rules into `package.json`, generates `.speclock/context/latest.md`. The AI reads these automatically.\n\n### Claude Code\nInstall the plugin using the commands above. For MCP-only setup without the\nplugin hooks, add this to `.mcp.json`:\n```json\n{\n  \"mcpServers\": {\n    \"speclock\": {\n      \"command\": \"npx\",\n      \"args\": [\"--yes\", \"speclock@5.8.0\", \"serve\", \"--project\", \".\"]\n    }\n  }\n}\n```\n\n### Cursor / Windsurf / Cline\nSame config — add to `.cursor/mcp.json` or equivalent.\n\n### Lovable (No Install)\n1. Go to **Settings → Connectors → New MCP server**\n2. Enter URL: `https://speclock-mcp-production.up.railway.app/mcp`\n3. Paste [project instructions](SPECLOCK-INSTRUCTIONS.md) into Knowledge\n\n---\n\n## Why SpecLock Over Alternatives?\n\n| | Claude Memory | Mem0 | `.cursorrules` | **SpecLock** |\n|---|:---:|:---:|:---:|:---:|\n| Remembers context | Yes | Yes | Manual | **Yes** |\n| **Blocks the AI from breaking things** | No | No | No | **Yes** |\n| **Semantic conflict detection** | No | No | No | **Yes — covered by adversarial tests** |\n| **Tamper-proof audit trail** | No | No | No | **HMAC-SHA256 chain** |\n| **Hard enforcement (AI cannot proceed)** | No | No | No | **Yes** |\n| **SOC 2 / HIPAA compliance exports** | No | No | No | **Yes** |\n| **Encrypted storage (AES-256-GCM)** | No | No | No | **Yes** |\n| **RBAC + API key auth** | No | No | No | **4 roles** |\n| **Policy-as-Code DSL** | No | No | No | **YAML rules** |\n| Works on Bolt.new, Lovable, etc. | No | No | No | **Yes** |\n\n**Other tools remember. SpecLock enforces.**\n\n---\n\n## Semantic Engine\n\nNot keyword matching — semantic analysis with an optional Gemini Flash hybrid for grey-zone and cross-domain cases. The repository includes adversarial, false-positive, question-framing, patch-gateway, and diff-analysis test suites.\n\n<table>\n<tr><td><b>Category</b></td><td><b>Detection</b></td><td><b>Example</b></td></tr>\n<tr><td>Direct violations</td><td>100%</td><td>\"Delete the auth module\" vs lock \"Never modify auth\"</td></tr>\n<tr><td>Euphemistic attacks</td><td>100%</td><td>\"Clean up old patient data\" = deletion</td></tr>\n<tr><td>Temporal evasion</td><td>100%</td><td>\"Temporarily disable MFA\" = disable MFA</td></tr>\n<tr><td>Dilution attacks</td><td>100%</td><td>Violation buried in multi-part request</td></tr>\n<tr><td>Compound sentences</td><td>100%</td><td>\"Update UI and also drop users table\"</td></tr>\n<tr><td>Synonym substitution</td><td>100%</td><td>\"Sunset the API\" = remove the API</td></tr>\n<tr><td>Payment brand names (11 gateways)</td><td>100%</td><td>\"Add Razorpay\" / \"Implement PayU\" vs \"Must use Stripe\"</td></tr>\n<tr><td>Salary/payroll cross-vocab</td><td>100%</td><td>\"Optimize salary\" vs \"Payroll records locked\"</td></tr>\n<tr><td>Safety system bypass</td><td>100%</td><td>\"Disable safety interlock\" = bypass safety</td></tr>\n<tr><td>Unknown domains (via Gemini)</td><td>100%</td><td>Gaming, biotech, aerospace, music, legal</td></tr>\n<tr><td>Safe actions (true negatives)</td><td>0% FP</td><td>\"Change the font\" correctly passes auth locks</td></tr>\n</table>\n\n**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).\n\n---\n\n## Hard Enforcement\n\nTwo modes:\n\n```\nAdvisory (default):  AI gets a warning, decides what to do\nHard mode:           AI is BLOCKED — MCP returns isError, AI cannot proceed\n```\n\n```bash\nspeclock enforce hard   # Enable hard mode — violations above threshold are blocked\n```\n\n- **Configurable threshold** — default 70%. Only HIGH confidence conflicts block.\n- **Override with reason** — `speclock override <lockId> \"JIRA-1234: approved by CTO\"` (logged to audit trail)\n- **Auto-escalation** — lock overridden 3+ times → auto-flags for review\n\n---\n\n## Enterprise Security\n\n### API Key Auth + RBAC\n\n```bash\nspeclock auth create-key --role developer --name \"CI Bot\"\n# → sk_speclock_a1b2c3... (shown once, stored as SHA-256 hash)\n```\n\n| Role | Read | Write Locks | Override | Admin |\n|------|:---:|:---:|:---:|:---:|\n| `viewer` | Yes | — | — | — |\n| `developer` | Yes | — | With reason | — |\n| `architect` | Yes | Yes | Yes | — |\n| `admin` | Yes | Yes | Yes | Yes |\n\n### AES-256-GCM Encryption\n\n```bash\nexport SPECLOCK_ENCRYPTION_KEY=\"your-secret\"\nspeclock encrypt   # Encrypts brain.json + events.log at rest\n```\n\nPBKDF2 key derivation (100K iterations). Authenticated encryption. **HIPAA 2026 compliant.**\n\n### HMAC Audit Chain\n\nEvery event gets an HMAC-SHA256 hash chained to the previous event. Modify anything — the chain breaks.\n\n```bash\n$ speclock audit-verify\n\n✓ Audit chain VALID — 247 events, 0 broken links, no tampering detected.\n```\n\n### Compliance Exports\n\n```bash\nspeclock export --format soc2    # SOC 2 Type II report (JSON)\nspeclock export --format hipaa   # HIPAA PHI protection report\nspeclock export --format csv     # All events for auditor spreadsheets\n```\n\n---\n\n## Policy-as-Code\n\nDeclarative YAML rules for organization-wide enforcement:\n\n```yaml\n# .speclock/policy.yml\nrules:\n  - name: \"HIPAA PHI Protection\"\n    match:\n      files: [\"**/patient/**\", \"**/medical/**\"]\n      actions: [delete, modify, export]\n    enforce: block\n    severity: critical\n\n  - name: \"No direct DB mutations\"\n    match:\n      files: [\"**/models/**\"]\n      actions: [delete]\n    enforce: warn\n    severity: high\n```\n\nImport and export policies between projects. Share constraint templates across your organization.\n\n---\n\n## REST API v2\n\nReal-time constraint checking, patch review, and autonomous systems:\n\n```bash\n# Patch Gateway (v5.1)\nPOST /api/v2/gateway/review        { description, files, useLLM }\n\n# AI Patch Firewall (v5.2)\nPOST /api/v2/gateway/review-diff   { description, files, diff, options }\nPOST /api/v2/gateway/parse-diff    { diff }\n\n# Typed constraint checking\nPOST /api/v2/check-typed    { metric, value, entity }\nPOST /api/v2/check-batch    { checks: [...] }\n\n# SSE streaming (real-time violations)\nGET  /api/v2/stream\n\n# Spec Compiler\nPOST /api/v2/compiler/compile  { text, autoApply }\n\n# Code Graph\nGET  /api/v2/graph/blast-radius?file=src/core/memory.js\nGET  /api/v2/graph/lock-map\nPOST /api/v2/graph/build\n```\n\n---\n\n## 51 MCP Tools\n\n<details>\n<summary><b>Memory</b> — goal, locks, decisions, notes, deploy facts</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_init` | Initialize SpecLock in project |\n| `speclock_get_context` | Full context pack (the key tool) |\n| `speclock_set_goal` | Set project goal |\n| `speclock_add_lock` | Add constraint + auto-guard files |\n| `speclock_remove_lock` | Soft-delete a lock |\n| `speclock_add_decision` | Record architectural decision |\n| `speclock_add_note` | Add pinned note |\n| `speclock_set_deploy_facts` | Record deploy config |\n\n</details>\n\n<details>\n<summary><b>Enforcement</b> — conflict detection, hard blocking, overrides</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_check_conflict` | Semantic conflict check against all locks |\n| `speclock_set_enforcement` | Switch advisory/hard mode |\n| `speclock_override_lock` | Override with reason (audit logged) |\n| `speclock_override_history` | View override audit trail |\n| `speclock_semantic_audit` | Analyze git diff against locks |\n| `speclock_detect_drift` | Scan for constraint violations |\n| `speclock_audit` | Audit staged files pre-commit |\n\n</details>\n\n<details>\n<summary><b>Tracking & Sessions</b> — changes, events, session continuity</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_session_briefing` | Start session + full briefing |\n| `speclock_session_summary` | End session + record summary |\n| `speclock_log_change` | Log a change with files |\n| `speclock_get_changes` | Recent tracked changes |\n| `speclock_get_events` | Full event log (filterable) |\n| `speclock_checkpoint` | Git tag for rollback |\n| `speclock_repo_status` | Branch, commit, diff summary |\n\n</details>\n\n<details>\n<summary><b>Intelligence</b> — suggestions, health, templates, reports</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_suggest_locks` | AI-powered lock suggestions |\n| `speclock_health` | Health score + multi-agent timeline |\n| `speclock_apply_template` | Apply constraint template |\n| `speclock_report` | Violation stats + most tested locks |\n\n</details>\n\n<details>\n<summary><b>Enterprise</b> — audit, compliance, policy, telemetry</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_verify_audit` | Verify HMAC chain integrity |\n| `speclock_export_compliance` | SOC 2 / HIPAA / CSV reports |\n| `speclock_policy_evaluate` | Evaluate policy rules |\n| `speclock_policy_manage` | CRUD for policy rules |\n| `speclock_telemetry` | Opt-in usage analytics |\n\n</details>\n\n<details>\n<summary><b>Typed Constraints</b> — numerical, range, state, temporal (v5.0)</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_add_typed_lock` | Add typed constraint (numerical/range/state/temporal) |\n| `speclock_check_typed` | Check proposed values against typed constraints |\n| `speclock_list_typed_locks` | List all typed constraints |\n| `speclock_update_threshold` | Update typed lock thresholds |\n\n</details>\n\n<details>\n<summary><b>Spec Compiler & Code Graph</b> — NL→constraints, dependency analysis (v5.0)</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_compile_spec` | Compile natural language into structured constraints |\n| `speclock_build_graph` | Build/refresh code dependency graph |\n| `speclock_blast_radius` | Calculate blast radius of file changes |\n| `speclock_map_locks` | Map locks to actual code files |\n\n</details>\n\n<details>\n<summary><b>Patch Gateway & AI Patch Firewall</b> — change review, diff analysis (v5.1/v5.2)</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_review_patch` | ALLOW/WARN/BLOCK verdict for proposed changes |\n| `speclock_review_patch_diff` | Diff-native review with signal scoring + unified verdict |\n| `speclock_parse_diff` | Parse unified diff into structured changes (debug/inspect) |\n\n</details>\n\n<details>\n<summary><b>Universal Rules Sync & Incident Replay</b> — cross-tool sync, session replay (v5.3)</summary>\n\n| Tool | What it does |\n|------|-------------|\n| `speclock_sync_rules` | Sync constraints to Cursor, Claude, Copilot, Windsurf, Gemini, Aider, AGENTS.md |\n| `speclock_list_sync_formats` | List all available sync formats |\n| `speclock_replay` | Replay a session's activity — what AI tried and what was caught |\n| `speclock_list_sessions` | List available sessions for replay |\n| `speclock_drift_score` | 0-100 project integrity metric — how much AI deviated from intent |\n| `speclock_coverage` | Lock Coverage Audit — find unprotected code areas |\n| `speclock_strengthen` | Grade locks and suggest stronger versions |\n\n</details>\n\n---\n\n## CLI\n\n```bash\n# Setup\nspeclock setup --goal \"Build my app\" --template nextjs\n\n# Constraints\nspeclock lock \"Never modify auth files\" --tags auth,security\nspeclock lock remove <id>\nspeclock check \"Add social login\"              # Test before doing\n\n# Enforcement\nspeclock enforce hard                          # Block violations\nspeclock override <lockId> \"JIRA-1234\"         # Override with reason\n\n# Audit & Compliance\nspeclock audit-verify                          # Verify HMAC chain\nspeclock export --format soc2                  # Compliance report\nspeclock audit-semantic                        # Semantic pre-commit\n\n# Git\nspeclock hook install                          # Pre-commit hook\nspeclock audit                                 # Audit staged files\n\n# Templates\nspeclock template apply safe-defaults          # Vibe coding seatbelt (5 locks)\nspeclock template apply solo-founder           # Indie builder essentials (3 locks)\nspeclock template apply hipaa                  # HIPAA healthcare (8 locks)\nspeclock template apply api-stability          # API contract protection (6 locks)\nspeclock template apply nextjs                 # Next.js constraints\nspeclock template apply security-hardened      # Security hardening\n\n# Sync to AI tools\nspeclock sync --all                            # Sync to ALL tools\nspeclock sync --format cursor                  # Cursor only\nspeclock sync --format claude                  # Claude Code only\nspeclock sync --preview windsurf               # Preview without writing\n\n# Incident Replay\nspeclock replay                                # Replay last session\nspeclock replay --list                         # List sessions\nspeclock replay --session <id>                 # Replay specific session\n\n# Project Health\nspeclock drift                                 # Drift Score (0-100)\nspeclock drift --days 7                        # Last 7 days only\nspeclock coverage                              # Lock Coverage Audit\nspeclock strengthen                            # Grade and improve locks\n\n# Share & Stats\nspeclock wins                                  # Shareable \"Save Receipt\" (screenshot it!)\nspeclock wrapped                               # All-time + monthly recap (alias: recap)\nspeclock stats                                 # Your local usage dashboard\nspeclock badge                                 # Print README badges (6 variants + live badge)\n\n# Auth\nspeclock auth create-key --role developer\nspeclock auth rotate-key <keyId>\n\n# Policy\nspeclock policy init                           # Create policy.yml\nspeclock policy evaluate --files \"src/auth/*\"  # Test against rules\n```\n\nFull command reference: `npx speclock help`\n\n---\n\n## Auto-Guard\n\nWhen you lock something, SpecLock finds related files and injects a warning the AI sees when it opens them:\n\n```\nspeclock lock \"Never modify auth files\"\n→ Auto-guarded 2 files:\n  🔒 src/components/Auth.tsx\n  🔒 src/contexts/AuthContext.tsx\n```\n\nThe AI opens the file and sees:\n```javascript\n// ============================================================\n// SPECLOCK-GUARD — DO NOT MODIFY THIS FILE\n// LOCKED: Never modify auth files\n// ONLY \"unlock\" or \"remove the lock\" is permission to edit.\n// ============================================================\n```\n\n---\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────────┐\n│     AI Tool (Claude Code, Cursor, Bolt.new...)    │\n└────────────┬──────────────────┬──────────────────┘\n             │                  │\n   MCP Protocol (51 tools)    npm File-Based\n             │              (SPECLOCK.md + CLI)\n             │                  │\n┌────────────▼──────────────────▼──────────────────┐\n│            SpecLock Core Engine                    │\n│                                                    │\n│  Semantic Engine ─── 65+ synonym groups            │\n│  HMAC Audit ──────── SHA-256 hash chain            │\n│  Enforcer ────────── advisory / hard block         │\n│  Auth + RBAC ─────── 4 roles, API keys             │\n│  AES-256-GCM ─────── encrypted at rest             │\n│  Policy DSL ──────── YAML rules                    │\n│  Compliance ──────── SOC 2, HIPAA, CSV             │\n│  SSO ─────────────── Okta, Azure AD, Auth0         │\n└──────────────────────┬───────────────────────────┘\n                       │\n                 .speclock/\n                 ├── brain.json        (project memory)\n                 ├── events.log        (HMAC audit trail)\n                 ├── policy.yml        (policy rules)\n                 ├── auth.json         (API keys — gitignored)\n                 └── context/\n                     └── latest.md     (AI-readable context)\n```\n\n**3 npm dependencies.** Zero runtime dependencies for the semantic engine. Pure JavaScript.\n\n---\n\n## Configuration\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `SPECLOCK_API_KEY` | — | API key for authenticated access |\n| `SPECLOCK_ENCRYPTION_KEY` | — | Enables AES-256-GCM encryption at rest |\n| `SPECLOCK_NO_PROXY` | `false` | Set `true` for heuristic-only mode (~250ms). Skips the Gemini proxy (~2s) |\n| `SPECLOCK_LLM_KEY` | — | Your own LLM API key (Gemini/OpenAI/Anthropic) |\n| `GEMINI_API_KEY` | — | Google Gemini API key for hybrid conflict detection |\n| `SPECLOCK_TELEMETRY` | `false` | Opt-in anonymous usage analytics |\n\n> **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`.\n\n---\n\n## Test Results\n\n**Pre-publish gate runs all 24 suites before every npm publish. If any test fails, publish is blocked.**\n\n| Suite | Tests | Pass Rate | What it covers |\n|-------|------:|----------:|----------------|\n| Real-World Testers | 111 | 100% | 5 developers, 30+ locks, diverse domains |\n| Adversarial Conflict | 46 | 100% | Euphemisms, temporal evasion, compound sentences |\n| Phase 4 (Multi-domain) | 91 | 100% | Fintech, e-commerce, IoT, healthcare, SaaS |\n| Sam (Enterprise HIPAA) | 124 | 100% | HIPAA locks, PHI, encryption, RBAC |\n| Auth & Crypto | 114 | 100% | API keys, RBAC, AES-256 encryption |\n| John (Indie Dev Journey) | 86 | 100% | 8-session Bolt.new build with 5 locks |\n| Diff-Native Review | 76 | 100% | Interface breaks, schema changes, API impact |\n| Patch Gateway | 57 | 100% | ALLOW/WARN/BLOCK verdicts, blast radius |\n| Compliance Export | 50 | 100% | SOC 2, HIPAA, CSV formats |\n| Enforcement | 40 | 100% | Hard/advisory mode, overrides |\n| Audit Chain | 35 | 100% | HMAC-SHA256 chain integrity |\n| Code Graph | 33 | 100% | Import parsing, blast radius, lock mapping |\n| Spec Compiler | 24 | 100% | NL→constraints parsing, auto-apply |\n| Typed Constraints | 13 | 100% | Numerical, range, state, temporal validation |\n| Claude Regression | 9 | 100% | Vue detection, safe-intent, patch gateway |\n| Question Framing | 9 | 100% | \"What if we...\" and \"How hard would it be...\" |\n| REST API v2 | 9 | 100% | Typed constraint endpoints, SSE |\n| PII/Export Detection | 8 | 100% | SSN, email export, data access violations |\n| Guardian (Protect) | 47 | 100% | Zero-config rule file extraction |\n| **Total** | **1043** | **100%** | **24 suites, 15+ domains** |\n\n**Reproducible project test gate:** all 1,043 repository tests pass on v5.8.0. These are project-maintained automated scenarios, not third-party certification; run them yourself with `npm test`.\n\nTested 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.\n\n---\n\n## Simulated Developer Journeys\n\n### John scenario — Indie developer on Bolt.new\n8 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.**\n\n### Sam scenario — Senior engineer building a HIPAA hospital ERP\n10 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.**\n\n---\n\n## Pricing\n\n| Tier | Price | What you get |\n|------|-------|-------------|\n| **Free** | $0 | 10 locks, conflict detection, MCP, CLI |\n| **Pro** | $19/mo | Unlimited locks, HMAC audit, compliance exports |\n| **Enterprise** | $99/mo | + RBAC, encryption, SSO, policy-as-code |\n\n---\n\n## Changelog\n\nPrior-version feature tours. The Quick Start and What's New sections above cover v5.7.0–v5.8.0 — this section preserves details on features shipped in v5.0–v5.5.\n\n### v5.4 — Drift Score, Lock Coverage, Lock Strengthener\n\n**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*.\n\n```bash\n$ speclock drift\n\nDrift Score: 23/100 (B) — minor drift\nTrend: improving | Period: 30 days | Active locks: 8\n\nSignal Breakdown:\n  Violations:      6/30  (4 violations in 12 checks)\n  Overrides:       5/20  (1 override)\n  Reverts:         3/15  (1 revert detected)\n  Lock churn:      0/15  (0 removed, 3 added)\n  Goal stability:  0/10  (1 goal change)\n  Session gaps:    9/10  (3/5 unsummarized)\n\nREADME badge: ![Drift Score](https://img.shields.io/badge/drift_score-23%2F100-brightgreen.svg)\n```\n\n**Lock Coverage Audit.** SpecLock scans your codebase and tells you what's **unprotected**:\n\n```bash\n$ speclock coverage\n\nLock Coverage: 60% (B) — partially protected\n\n  [COVERED] CRITICAL authentication   2 file(s)\n  [EXPOSED] CRITICAL payments         1 file(s)\n  [COVERED] CRITICAL secrets          0 file(s)\n  [COVERED] HIGH     api-routes       2 file(s)\n\nSuggested Locks (ready to apply):\n  1. [CRITICAL] payments (1 file at risk)\n     speclock lock \"Never modify payment processing or billing without permission\"\n```\n\nLike a security scanner, but for AI constraint gaps.\n\n**Lock Strengthener.** Your locks might be too vague. SpecLock grades each one and suggests improvements:\n\n```bash\n$ speclock strengthen\n\nLock Strength: 72/100 (B) — 3 strong, 1 weak\n\n[WEAK  ] 45/100 (D)  \"don't touch auth\"\n          Issue: Too vague — short locks miss edge cases\n          Issue: No specific scope\n          Suggested: \"Never modify, refactor, or delete auth...\"\n\n[STRONG] 90/100 (A)  \"Never expose API keys in client-side code, logs, or error messages\"\n```\n\n### v5.3 — Universal Rules Sync, Incident Replay, Safety Templates\n\n**Universal Rules Sync.** One command syncs your SpecLock constraints to every AI coding tool:\n\n```bash\nspeclock sync --all\n```\n\n```\nSpecLock Sync Complete\n  ✓ Cursor             → .cursor/rules/speclock.mdc\n  ✓ Claude Code        → CLAUDE.md\n  ✓ AGENTS.md          → AGENTS.md (Linux Foundation standard)\n  ✓ Windsurf           → .windsurf/rules/speclock.md\n  ✓ GitHub Copilot     → .github/copilot-instructions.md\n  ✓ Gemini             → GEMINI.md\n  ✓ Aider              → .aider.conf.yml\n\n7 file(s) synced.\n```\n\nDefine constraints once in SpecLock, sync everywhere. `--format cursor` for single format, `--preview` to dry-run, `--list` to see supported formats.\n\n**Incident Replay.** Flight recorder for your AI coding sessions:\n\n```bash\nspeclock replay\n\nSession: ses_a1b2c3 (claude-code, 47 min)\n────────────────────────────────────────────\n14:02  [ALLOW]   Create user profile component\n14:08  [ALLOW]   Add form validation\n14:15  [WARN]    Simplify authentication flow\n                 → matched lock: \"Never modify auth\"\n14:23  [BLOCK]   Clean up old user records\n                 → euphemism detected: \"clean up\" = deletion\n14:31  [ALLOW]   Update landing page hero section\n\nScore: 5 events | 3 allowed | 1 warned | 1 BLOCKED\n```\n\n`speclock replay --list` lists sessions; `--session <id>` replays a specific one.\n\n**Safety Templates.** Pre-built constraint packs:\n\n```bash\nspeclock template apply safe-defaults   # 5 locks — \"Vibe Coding Seatbelt\"\nspeclock template apply solo-founder    # 3 locks — auth, payments, data\nspeclock template apply hipaa           # 8 locks — HIPAA healthcare\nspeclock template apply api-stability   # 6 locks — API contract protection\n```\n\nSafe Defaults prevents the 5 most common AI disasters: database deletion, auth removal, secret exposure, error-handling removal, logging disablement.\n\n### v5.2 — AI Patch Firewall\n\nReviews actual diffs, not just descriptions. Catches things intent review misses:\n\n```\nPOST /api/v2/gateway/review-diff\n{\n  \"description\": \"Remove password column\",\n  \"diff\": \"diff --git a/migrations/001.sql ...\"\n}\n\n→ { verdict: \"BLOCK\",\n    reviewMode: \"unified\",\n    intentVerdict: \"ALLOW\",     ← description alone looks safe\n    diffVerdict: \"BLOCK\",       ← diff reveals destructive schema change\n    signals: {\n      schemaChange: { score: 12, isDestructive: true },\n      interfaceBreak: { score: 10 },\n      protectedSymbolEdit: { score: 8 },\n      dependencyDrift: { score: 5 },\n      publicApiImpact: { score: 0 }\n    },\n    recommendation: { action: \"require_approval\" } }\n```\n\n**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.\n\n### v5.1 — Patch Gateway\n\nOne API call gates every change. Takes a description + file list, returns ALLOW/WARN/BLOCK:\n\n```\nspeclock_review_patch({\n  description: \"Add social login to auth page\",\n  files: [\"src/auth/login.js\"]\n})\n\n→ { verdict: \"BLOCK\", riskScore: 85,\n    reasons: [{ type: \"semantic_conflict\", lock: \"Never modify auth\" }],\n    blastRadius: { impactPercent: 28.3 },\n    summary: \"BLOCKED. 1 constraint conflict. 12 files affected.\" }\n```\n\nCombines semantic conflict detection + lock-to-file mapping + blast radius + typed constraint awareness into a single risk score (0-100).\n\n### v5.0 — Spec Compiler, Code Graph, Typed Constraints, Python SDK & ROS2\n\n**Spec Compiler.** Paste a PRD, README, or architecture doc — SpecLock extracts all constraints automatically:\n\n```\nInput:  \"We're building a fintech app. Use React and FastAPI.\n         Never touch the auth module. Response time must stay\n         under 200ms. Payments go through Stripe.\"\n\nOutput: 2 text locks:\n          - \"Never touch the auth module\"\n          - \"Payments go through Stripe — don't change provider\"\n        1 typed lock:\n          - response_time_ms <= 200 (numerical)\n        2 decisions:\n          - \"Use React for frontend\"\n          - \"Use FastAPI for backend\"\n```\n\nUses Gemini Flash by default ($0.01 per 1000 compilations).\n\n**Code Graph.** Live dependency graph of your codebase. Parses JS/TS/Python imports.\n\n```\n$ speclock blast-radius src/core/memory.js\n\nDirect Dependents:  8 files\nTransitive Impact:  14 files (33% of codebase)\nMax Depth:          4 hops\n```\n\nLock-to-file mapping auto-maps locks to source files; module detection groups files into logical modules.\n\n**Typed Constraints.** Real-time value and state checking for autonomous systems, IoT, robotics:\n\n```javascript\n// Numerical: speed must be <= 2.0 m/s\n{ constraintType: \"numerical\", metric: \"speed_mps\", operator: \"<=\", value: 2.0 }\n\n// Range: temperature must stay between 20-25°C\n{ constraintType: \"range\", metric: \"temperature_c\", min: 20, max: 25 }\n\n// State: never go from armed → disarmed without approval\n{ constraintType: \"state\", metric: \"system_mode\", forbidden: [{ from: \"armed\", to: \"disarmed\" }] }\n\n// Temporal: heartbeat must occur every 30 seconds\n{ constraintType: \"temporal\", metric: \"heartbeat_s\", operator: \"<=\", value: 30 }\n```\n\n**Python SDK & ROS2.**\n\n```bash\npip install speclock-sdk\n```\n\n```python\nfrom speclock import SpecLock\n\nsl = SpecLock(project_root=\".\")\nresult = sl.check_text(\"Switch database to MongoDB\")\nresult = sl.check_typed(metric=\"speed_mps\", value=3.5)\nresult = sl.check(action=\"Increase speed\", speed_mps=3.5)\n```\n\nUses 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`.\n\n---\n\n## Show your support\n\nIf SpecLock saves your project from a 3am incident, add this badge to your README:\n\n```markdown\n[![Protected by SpecLock](https://img.shields.io/badge/Protected_by-SpecLock-FF6B2C?style=flat&logo=lock)](https://github.com/sgroy10/speclock)\n```\n\nOr run `speclock badge` in your terminal to see all variants. Full gallery: **[sgroy10.github.io/speclock/badge.html](https://sgroy10.github.io/speclock/badge.html)** · Full docs: **[BADGES.md](./BADGES.md)**.\n\nEvery adoption helps another developer discover SpecLock and stop their AI from wrecking their project. Thank you.\n\n### Spread the word\n\nWant 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](./VIRAL-KIT.md)**. Copy, paste, send. Zero effort.\n\n---\n\n## Contributing\n\nIssues and PRs welcome on [GitHub](https://github.com/sgroy10/speclock).\n\n## License\n\n[MIT](LICENSE)\n\n## Author\n\n**SpecLock** is created and maintained by **[Sandeep Roy](https://github.com/sgroy10)**.\n\nSandeep 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.\n\n- GitHub: [@sgroy10](https://github.com/sgroy10)\n- npm: [speclock](https://www.npmjs.com/package/speclock)\n\n---\n\n<p align=\"center\"><i>SpecLock v5.8.0 — Cross-platform action guardrails with native Claude Code enforcement, MCP integrations, 1,043 core tests, and 51 MCP tools. Developed by Sandeep Roy.</i></p>\n",
  "bytes": 39001,
  "sha": "333ae7d303c26d50cc4081fbe37a5d580ab3cb675134b28fff14b363b4dbac8e",
  "repo_slug": "sgroy10/speclock",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_sgroy10_speclock_a60e3e6c/readme"
}