*Measured on bare-metal Intel Core i7 x86_64 hardware in-process across 10,000 synthetic iterations.
⚠️ 1. The Core Tension: Prompts as Policy vs. Real Working Trees
Between 2024 and 2026, the software industry saw a massive wave of agent frameworks attempting to automate software engineering. While these frameworks demonstrated compelling chat demos, many engineering teams found them brittle when pointed at complex, multi-file production repositories.
The root problem was not that modern frontier models lack intelligence. The tension is architectural:
- Prompt-as-Policy is Fragile: System prompts like "Please do not edit files until you have verified your logic" or "Adhere strictly to project conventions" are behavioral suggestions, not systemic invariants. Under long context windows, deep tool call traces, or complex edge cases, model adherence drifts. A sampler cannot guarantee its own behavioral boundaries.
- Unmediated File Clobbering: Standard coding agents invoke naive file-write tools that execute direct
writeFile()calls on the developer's working directory. If a model generates an ambitious refactor across five files and the API connection times out or fails on file 3, the repository is left in an unverified, half-applied state. The test suite breaks, Git status is polluted, and the agent enters an unrecoverable hallucination loop attempting to diagnose its own half-written changes. - Ephemeral State & Fragmented Memory: Storing task state, turn history, and architectural context inside process memory or ad-hoc Markdown files (
MEMORIES.md) leads to amnesia whenever an agent process restarts or context windows are compacted. - The Frankenstein SaaS Stack: To mitigate these issues, orchestrators often assemble a fragmented web of specialized services: Pinecone for vectors, Redis for caching, MongoDB for logs, Neo4j for graphs, and local scratchpads. This introduces latency, operational complexity, and leaks proprietary codebase topology across third-party cloud vendors.
Many advanced teams have mitigated this using git worktrees, patch sandboxes, and continuous integration. But these remain fragmented scripts wrapped around an untrusted agent. What happens when we elevate this principle into a formal state plane and transaction manager?
🏛️ 2. The Krusch Architecture: The Four Sovereign Layers
The Krusch ecosystem replaces conversational guardrails with hard transactional invariants. Every component has a strictly bounded responsibility:
⚡ 3. Stage 0: krusch-pre-router — Eradicating the "Routing Tax"
One of the most wasteful practices in modern AI systems is spending a 500-millisecond, $0.02 frontier model call simply to classify whether a query is pure SQL, arithmetic, or a stack trace.
krusch-pre-router is an in-process, zero-dependency CPU heuristic gate that intercepts closed-world tasks before any model API is invoked:
- Sub-15µs CPU Execution: In bare-metal benchmarks (Node v22, Intel Core i7 x86_64, 10,000 iterations), cold regex scans execute at a p50 of 3.51 µs (average 4.32 µs, ~220,000 ops/sec). Warm LRU cache lookups resolve in 4.65 µs.
- Structural Priority Scanning: Evaluates closed-world syntax: markdown code fences (
```python,```sql), LaTeX equations ($$ \sum ... $$), runtime stack traces (Traceback (most recent call last)), and raw SQL statements. - Strict ReDoS Safety Budget: Every pattern in the catalog is tested against 8KB adversarial payloads under a strict 2ms execution budget to prevent regex denial-of-service.
- Honest Miss Delegation: Unlike fuzzy neural classifiers that risk misclassifying ambiguous inputs,
krusch-pre-routerexecutes an honest miss. Unstructured, conversational, or clinical prompts returnisFastPath: falseand cleanly delegate to the L2 neural cascade.
import { createPreRouter } from 'krusch-pre-router';
const router = createPreRouter({ cache: { maxSize: 2000 } });
// Stage-0 Hot Path (<4µs CPU)
const route = router.classify(prompt);
if (route.isFastPath) {
// ⚡ Direct specialist dispatch ($0.00 routing overhead)
return dispatchSpecialist(route.role, prompt);
}
// 🔍 Clean delegation to L2 Neural Cascade
return cascadeRouter.dispatch(prompt);
🔀 4. Stage 1 & 2: krusch-cascade-router — Speculative Hedging & Dynamic Cascading
When a query requires semantic reasoning beyond syntactic heuristics, krusch-cascade-router manages model dispatching across a 5-specialist domain matrix (code, reasoning_deep, factual_stem, games_spatial, general_fast).
Logprob Early-Token Inspection
Sequential cascades (call Model A, inspect output, call Model B) double tail latency. krusch-cascade-router employs an early-token streaming heuristic:
- It buffers the first 5 tokens from an efficient domain specialist and evaluates the cumulative token logprob confidence.
- If confidence exceeds
0.85, the fast model continues generating without interruption. - If confidence drops below threshold—or if degenerate repetition loops or entropy collapse are detected—the stream is aborted and cascaded to frontier reasoning (e.g., Claude 3.7 Sonnet, DeepSeek-R1).
- For borderline complexity prompts (scores between 0.35 and 0.65), Speculative Branching ("Second Thought") fires a fast specialist and a frontier model in parallel, returning whichever valid completion resolves first.
0.85) and buffer window (5 tokens) are tunable hyperparameters calibrated against specific domain regression sets, not axiomatic guarantees.
🧠 5. The Memory Substrate: krusch-context-mcp
A reliable harness requires deep, persistent context without prompt bloat. krusch-context-mcp is a sovereign 16-tool Model Context Protocol server providing three core capabilities:
1. Mathematical Temporal Recency Decay
Flat vector search treats a memory created six months ago identically to one created five minutes ago if their cosine similarities match. In real software projects, architectural patterns evolve. krusch-context-mcp applies an exponential decay prior:
FinalScore = CosineSimilarity × e^(-0.01 × age_in_days)
After 30 days of inactivity, a stale memory's weight naturally decays by ~26%. When an engineer refactors a subsystem, newer memories automatically supersede outdated conventions.
2. Declarative Steering Nuggets
Rather than bloating every turn's context window with a monolithic 4,000-token system prompt, declarative steering nuggets store atomic micro-facts (e.g., "Use ESM imports in this package", "Postgres pool size is 20"). The harness queries nuggets dynamically during task planning, injecting project conventions just-in-time.
3. Native PostgreSQL + pgvector Storage
Memories, symbol graphs, and interaction traces are persisted in PostgreSQL using pgvector (HNSW indexing) with local SQLite fallback for sub-5ms offline operation. Proprietary code and architectural decisions stay within your sovereign infrastructure.
🛡️ 6. The Execution Core: krusch — Invariants Over Prompts
At the core of the stack is krusch, the PostgreSQL-backed invariant coding harness (read the full Krusch Harness architectural deep dive →). Where traditional agent loops rely on models to police their own file writes, krusch treats models as untrusted, interchangeable workers governed by a relational transaction manager.
The Relational Finite State Machine (FSM)
The lifecycle of an engineering task is cataloged as a relational state graph in PostgreSQL (krusch_phase_edges):
INIT → PLAN → IMPLEMENT → VERIFY → APPROVAL_GATE → COMMITTED
Phase transitions are validated inside row-locked transactions and SQL triggers. If an agent attempts an illegal transition—such as jumping from PLAN directly to COMMITTED, or attempting shell execution during planning—the database engine immediately aborts the transaction with an invariant violation error.
Diff Staging Invariant
When a worker model produces code modifications, no physical files on disk are touched:
- Proposed edits are formatted as unified diffs and SHA-256 hashed.
- Diffs are inserted into the
krusch_staged_diffsrelational table with statusPENDING. - The developer's working tree remains completely clean and unpolluted.
Sandboxed Ground-Truth Verification
Before any code can progress toward disk mutation, the harness mounts a shadow staged working tree and executes the real test suite (npm test, pytest, cargo test). The execution record is permanently written to krusch_verification_runs.
The Core Invariant: krusch_staged_diffs cannot transition to APPLYING or APPLIED unless the latest verification run passed with exit_code: 0. The model cannot persuade the test runner; passing verification is a hard database requirement for entering the approval gate.
Actionable Failure Attribution (Modular RSI)
When tests fail, naive agents retry the entire prompt blindly, often compounding errors. krusch deploys the KruschFailureClassifier, parsing test stdout and stderr into four structured failure classes:
ContextManagement: Missing imports, undefined symbols, or module resolution errors. The harness extracts the missing symbol, queries the local symbol index, and injects the exact signature into the prompt.ToolUse: Syntax errors, malformed JSON, or schema argument violations.ObservationManagement: Assertion failures (expected vs. received). The harness extracts the exact diff and commands the model to preserve the expected invariant.AgentLoop: Cyclic oscillations or exceeded turn budgets, triggering automatic escalation to a frontier reasoning tier or clean termination.
Atomic Apply Journal with Drift Detection & fsync Recovery
Applying verified changes to disk is executed through an atomic write journal transitioning PENDING → APPLYING → APPLIED:
- Pre-Flight Drift Check: Before writing any file in a multi-file batch, the harness hashes each target file on disk and verifies it matches the recorded base hash. If an external edit modified a file out-of-band, the entire batch aborts before touching disk.
- Atomic fsync & Rename: Files are written using atomic temporary files with explicit OS-level
fsync()flushes, followed by atomic filesystem renames. - Startup Crash Recovery (
recoverInFlightApplies): If the host loses power or the process crashes mid-apply, the harness inspects disk hashes on next startup. Files matching the staged hash are promoted toAPPLIED; files matching the base hash are rolled back toPENDING. Partial-batch crashes roll back temporary files cleanly.
👤 7. The Human Gate is the Feature, Not a Compromise
A common misconception in the agent space is that human intervention represents an engineering failure. In professional software engineering, the opposite is true: unsupervised autonomy on mission-critical repositories is reckless.
The goal of the Krusch harness is not to eliminate the human; it is to eliminate the cognitive tax on the human:
- In unmediated agent frameworks, the human acts as an exhausted human linter, constantly reviewing broken syntax, half-applied file edits, and hallucinated imports.
- In Krusch, the human developer sits at the center of
kd-Code, reviewing verified staged diffs rendered with@pierre/diffs. The human is only ever asked for approval after the staged diffs have compiled, passed sandboxed test suites (exit_code: 0), and verified zero out-of-band disk drift.
💎 8. Novelty vs. Existing Practice
The individual primitives in the Krusch stack are not invented from whole cloth; they are proven distributed systems instincts applied rigorously to coding agents:
| Concept | Common Existing Practice | The Krusch Implementation |
|---|---|---|
| File Safety | Git worktrees, patch files, Docker sandboxes | Diffs as first-class PostgreSQL rows with SHA-256 validation |
| Verification | CI/CD pipelines | Test pass (exit_code: 0) as an enforced DB trigger invariant on apply |
| Agent Memory | External vector DBs (Pinecone), markdown logs | In-process MCP + pgvector + mathematical recency decay prior |
| Model Routing | Sequential fallback, RouteLLM | Sub-15µs CPU Stage-0 regex + early-token logprob abort |
| State Authority | In-memory agent graphs, chat transcripts | PostgreSQL FSM catalog (krusch_phase_edges) + single-writer file leases |
The contribution is the unified system: binding these primitives into a single, sovereign transaction manager where models are interchangeable workers and state is durable law.
🚀 9. Why PostgreSQL as the State Plane Wins
Why build this substrate on PostgreSQL rather than an ad-hoc combination of SQLite, Redis, and vector SaaS?
- ACID Invariants Beat Prompts: In distributed systems, integrity is enforced with serialized transactions, write-ahead logs, and schema constraints. AI models are stochastic; treating their prompt output as authoritative state is an architectural mistake. PostgreSQL is the deterministic anchor.
- Decoupling Compute from State: Frontier model weights are replaced every few months. If your agent's state and workflow are coupled to a specific model wrapper or vendor platform, upgrading models requires a rewrite. In Krusch, models are stateless workers plugged into a standard interface; PostgreSQL owns the state.
- Convergence of Modalities: PostgreSQL 16 unifies relational records (task FSM, turns, leases), JSONB (tool invocation traces), dense vectors (
pgvectorwith HNSW), and graph queries (AST symbol graphs via recursive CTEs) in a single battle-tested engine. - Multi-Agent Swarm Concurrency: Filesystems lack concurrency primitives for multi-agent swarms. PostgreSQL provides
FOR UPDATE SKIP LOCKED, unique indexes on active file leases ((project_path, file_path)), and automated TTL expiration to prevent agent write collisions. - 100% Air-Gapped Sovereignty: Confidential codebases, AST symbols, and debugging transcripts never leave self-hosted bare metal or private cloud instances.
🏁 Conclusion: A Sampler is Not a Transaction Manager
Language models have unlocked remarkable creative capabilities in code generation. But code generation is only half of software engineering. The other half is verification, state management, transaction safety, and regression prevention.
By pairing krusch-pre-router on the CPU for sub-15µs zero-tax gating, krusch-cascade-router for speculative multi-model efficiency, krusch-context-mcp for decay-weighted episodic memory, and krusch for invariant PostgreSQL staging, we establish a deterministic contract for coding agents.
Language models provide the probabilistic spark. PostgreSQL provides the transaction-managed state plane that turns that spark into production-ready software.
- krusch — Invariant PostgreSQL coding harness & atomic apply journal.
- krusch-pre-router — Sub-15µs CPU Stage-0 syntactic gate & LRU memoizer.
- krusch-cascade-router — Dual-stage speculative cascade router with logprob gating.
- krusch-context-mcp — Sovereign Model Context Protocol server for persistent memory.
- kd-Code — Developer workbench with center-stage
@pierre/diffsreview.