"A large language model is a probabilistic sampler. Side effects require a transaction manager; a sampler is not one. If you rely on prompts to police disk mutation, you have built an engine on quicksand. Real guardrails are encoded in relational schemas, sandbox verifications, and atomic apply journals."
3.51 µs
p50 CPU Stage-0 Pre-Route*
$0.00
Fast-Path Syntactic Tax
0
Unvetted Disk Writes
100%
Crash Recovery Verification

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

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:

Stage 0
krusch-pre-router (Microsecond Syntactic Gate) CPU regex & LRU memoization engine. Intercepts structured code fences, SQL, LaTeX, and stack traces in <10µs with $0.00 cost, zero token burn, and honest misses to Stage 1.
Stage 1 & 2
krusch-cascade-router (Neural Cascade & Speculative Hedging) Evaluates logprob confidence on initial output tokens. Dispatches to 5 specialist models; triggers speculative "Second Thought" hedging and frontier reasoning escalation when confidence drops.
Memory Substrate
krusch-context-mcp (Persistent Working Memory & Declarative Nuggets) 16-tool Model Context Protocol server. Provides mathematical temporal recency decay (e^-0.01t), lightweight declarative steering facts, and AST symbol graphs via PostgreSQL + pgvector.
State Plane
krusch (The Invariant Coding Harness) Authoritative PostgreSQL finite state machine (FSM). Enforces pre-commit diff staging, sandboxed test verification, failure attribution (Modular RSI), single-writer file leases, and atomic apply journals.
Workbench
kd-Code & @pierre/diffs (Developer Control Plane & Human Gate) Visual review surface where developers inspect verified staged diffs, evaluate sandbox test outcomes, and grant explicit commit approvals.

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

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:

  1. It buffers the first 5 tokens from an efficient domain specialist and evaluates the cumulative token logprob confidence.
  2. If confidence exceeds 0.85, the fast model continues generating without interruption.
  3. 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).
  4. 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.
⚖️ Heuristic Calibration Note: Early-token logprob thresholding is an empirical heuristic. In production swarms, logprob calibration varies between model providers. The threshold (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:

  1. Proposed edits are formatted as unified diffs and SHA-256 hashed.
  2. Diffs are inserted into the krusch_staged_diffs relational table with status PENDING.
  3. 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:

Atomic Apply Journal with Drift Detection & fsync Recovery

Applying verified changes to disk is executed through an atomic write journal transitioning PENDING → APPLYING → APPLIED:

  1. 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.
  2. Atomic fsync & Rename: Files are written using atomic temporary files with explicit OS-level fsync() flushes, followed by atomic filesystem renames.
  3. 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 to APPLIED; files matching the base hash are rolled back to PENDING. 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:

💎 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?

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

Explore the Sovereign Repositories on GitHub:
  • 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/diffs review.