Laya-OCR-Guard
The Sandwich Pattern Regression Guard for AI-Assisted Development
Dual-Gate Impact Analysis & Regression Guard for AI-Assisted Development.
A zero-token, high-velocity safety harness wrapping AI coding agents (Claude Code, Cursor, Windsurf, Aider, omp) to prevent regressions, security leaks, memory leaks, and breaking changes.
1. Overview & Vision
Coding agents are fast, but they can be careless: they accidentally delete keyboard shortcuts, drop responsive CSS classes, leak API tokens, or make out-of-scope modifications across untouched files.
guard enforces a deterministic Sandwich Pattern around every task:
After code is written (Post-Task): Alibaba Open Code Review (OCR) measures the exact diff blast radius and scans static rulebooks, the project test suite verifies compilation, Laya scores invariant preservation, and your configured LLM issues the final authoritative verdict (
APPROVED or REVISE).
2. Three-Pillar Architecture
[User Task / Issue Prompt]
│
▼
┌─────────────────────────────────────────────────────────────┐
│ 1. PRE-TASK PHASE: `guard pre "<prompt>"` │
│ • Laya (<30ms, 0-cost): Intent, domain & risk triage │
│ • Domain Contract Extractor (FE / BE / Infra / MB) │
│ • Lock Invariant Rules (Must NOT be broken) │
│ ➔ Emits: "### 🔍 PRE-TASK IMPACT NOTE" │
└─────────────────────────────────────────────────────────────┘
│
▼ (AI Coding Agent / Developer modifies code)
│
┌─────────────────────────────────────────────────────────────┐
│ 2. POST-TASK PHASE: `guard post` │
│ • OCR Inspector (0-cost): Diff audit & blast radius check │
│ • Static Rulebook: Detect Secrets, SQLi, Memory Leaks, NPE │
│ • Project Health Check: Automated compile & test execution │
│ • Laya Scoring (0-cost): Score invariant compliance (Yes/No)│
│ ➔ Compiles: "### 🧪 POST-TASK VERIFICATION" │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ 3. FINAL SAFETY GATE: YOUR CONFIGURED LLM │
│ (Claude-3.7-Sonnet / GPT-4o / DeepSeek / Ollama...) │
│ • Reviews the aggregated post-task verification report │
│ • Technical Audit (Architecture, Memory Leaks, Scope) │
│ • Cross-Platform UX/UI & Ergonomics Assessment │
│ • Verdict: [APPROVED] or [REVISE] with Actionable Remediation│
└─────────────────────────────────────────────────────────────┘
3. 2D Quality Matrix: Platform Domains × Quality Pillars
Instead of only checking syntax, Guard evaluates code across a two-dimensional matrix combining 4 Platform Domains and 7 Cross-Cutting Quality Pillars.
| Platform Domain | 🛡️ Security | 🧠 Memory Safety | ⚡ Performance | 🧱 Integrity & Schema | ♿ UX & Ergonomics | 🧹 Code Hygiene | 🛋️ Simplicity (KISS/YAGNI) |
|---|---|---|---|---|---|---|---|
| Frontend (React, Vue, Tailwind) | XSS prevention, CSP, token leaks | Dangling listeners, detached DOM | Blocking sync I/O, re-render lag | UI states (loading, disabled) | Escape key, backdrop, mobile view | Orphan components, commented JSX blocks | Native Web APIs, no premature abstractions |
| Backend (Go, Python, Rust, Nest) | SQL injection, Auth middleware, RBAC | Connection leaks, unclosed streams | N+1 queries, async blocking | JSON Schema compatibility, ACID | Standardized error codes & status | Unused imports, dead helper functions | No redundant packages, YAGNI logic |
| Infra / DevOps (Docker, K8s, Terraform) | Forbid 0.0.0.0, no hardcoded secrets | Container OOM limits, quotas | Fast startup, lightweight images | Zero-downtime rolling updates | Liveness & readiness probe health | Orphan compose files, stale scripts | Lightweight manifests, minimal base images |
| Mobile (Flutter, React Native, Swift) | Runtime permissions check, keychain | Unreleased Bitmaps, retained controllers | Smooth 60/120 FPS, battery efficiency | Offline cache synchronization | SafeArea boundaries, dynamic notch | Unused assets, commented native bridges | Native UI primitives, zero bloated SDKs |
Focused Deep-Dives (--focus)
By default, all quality pillars are audited at 100% rigor. When investigating specific defects, use the --focus flag to direct the LLM gate's analytical scrutiny:
# Scrutinize KISS, YAGNI, over-engineering & dependency bloat:
guard review --focus simplicity
# Scrutinize dead code, zombie blocks & orphan files:
guard review --focus dead-code
# Scrutinize memory leaks (listeners, unclosed handles):
guard review --focus memory
# Scrutinize security vulnerabilities (SQLi, XSS, secrets):
guard review --focus security
# Scrutinize performance (blocking I/O, heavy operations):
guard review --focus performance
# Scrutinize ergonomics and responsive UX:
guard review --focus ux
4. Installation Guide (Cross-Platform)
Works natively on Windows, Linux, and macOS:
# Recommended: Install globally via pipx (Linux/macOS)
pipx install git+https://github.com/okrath/laya-ocr-guard.git
# Or with standard pip (Windows / Linux / macOS)
pip install git+https://github.com/okrath/laya-ocr-guard.git
# Verify installation health
guard doctor
5. LLM Setup Wizard & Auto-Sync
Run the interactive step-by-step wizard to configure your preferred LLM provider. Settings automatically synchronize to Alibaba OCR CLI:
guard config llm
- OpenAI / OpenAI-Compatible: OpenAI (
gpt-4o), DeepSeek (deepseek-chat), Ollama (http://localhost:11434/v1), OpenRouter, or Local Gateways (http://127.0.0.1:8090/v1). - Anthropic: Claude API (
claude-3-7-sonnet).
Test your connection with an instant sub-second verification ping:
guard config test
6. Automated Agent Directives (omp, Claude Code, Cursor)
To protect any target repository, navigate to the repo root and execute:
guard hook install
This provides flexible protection profiles tailored for any workflow:
- Multi-Repo Workspace Mode: Running
guard hook installinside an outer workspace folder automatically scans all child Git repositories. The interactive menu lets you choose[A](all child repos),[1-N](specific repos like2,3,7,8),[G](Global Git hooks), or[N](Agent directives only at workspace root). - Global Git Hooks (
--global/-g): Configuresgit config --global core.hooksPath ~/.guard/hooksto protect every Git repository on your machine automatically with zero per-repo setup required. - Ghost / Stealth Mode (
--stealth/--mode git): Installs local.git/hooks/pre-commitand configures.git/info/exclude. Zero workspace footprint (no files ever pushed to remote; ideal for company or client repos). - Agent Directives (
--mode agent): Safely appends Guard protocols toCLAUDE.mdandAGENT.mdin workspace root (backed up to.guard.bak, never overwriting existing user directives). - Dual-Gate Full Protection (
--mode all): Combines Git pre-commit hook enforcement, workspace agent directives, and harness wrapper script.
<!-- === LAYA-OCR-GUARD DUAL-GATE HOOK === --> markers with automatic .guard.bak backups.
Check hook and agent directive status at any time:
guard hook status
7. CLI Command Reference
| Command | Description | Common Flags |
|---|---|---|
guard pre "<prompt>" |
Run Pre-Task Guard: fast triage, baseline contracts & locked invariants | --quick, --repo <path> |
guard post |
Run Post-Task Guard: diff audit, build test, invariants, LLM final gate | --focus <area>, --auto-fix |
guard run "<prompt>" -- <cmd> |
Execute Sandwich Pattern: pre ➔ command ➔ post | --auto-fix |
guard review |
Perform on-demand LLM Code Review on current git diff | --focus <area> |
guard config llm |
Launch interactive LLM configuration wizard | --local |
guard config test |
Send instant token-free ping test to configured LLM | — |
guard hook install |
Install Git hooks (single repo, child repos in workspace, or machine-wide global) | --global, --stealth, --all-repos, --select-repos <list> |
guard update |
Safely upgrade Alibaba OCR respecting 3-day quarantine | --check, --force, self |
guard doctor |
Check system environment health and supply-chain security | --no-updates, -q <days> |
8. Supply-Chain Security & Quarantine Policy
To protect development environments against zero-day npm supply-chain backdoors, Guard enforces a 3-Day Quarantine Cooling Period on Alibaba OCR releases:
- New releases published < 3 days ago are placed on QUARANTINE HOLD to allow security researchers time to detect malicious insertions.
- Releases published ≥ 3 days ago are marked SAFE UPDATE.
# Check update status safely without installing:
guard update --check
# Safely upgrade (automatically halts if release is under quarantine):
guard update
# Bypass quarantine hold explicitly if verified:
guard update --force