*Measured across bare-metal x86_64 PostgreSQL 16 (54,456 AST symbols) and isolated 96 GB NVIDIA RTX PRO 6000 Blackwell clean-room benchmarks (73/73 SHA-256 gates).
⚠️ 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 relational state plane and transaction manager?
🏛️ 2. The Krusch Architecture: Five Sovereign Layers
Bundled into a single zero-ORM distribution via krusch-stack (39 MCP tools across 7 pillars, with Okapi BM25 --defer-tools cutting upfront schema payload by -68.5%), the ecosystem replaces conversational guardrails with hard relational invariants:
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 LLM preflight 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 L1/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 L1/L2 Neural Cascade
return cascadeRouter.dispatch(prompt);
🔀 4. Stage 1 & 2: krusch-cascade-router — Speculative SSE Abort & Verified Pareto Routing
When a query requires semantic reasoning beyond syntactic heuristics, krusch-cascade-router combines 42.5 µs CPU structural complexity scoring with 1.27 ms snowflake-arctic-embed2 (1024d) kNN prototype routing and live SSE streaming logprob inspection (read the full G4 Cascade Router benchmark paper →).
Live SSE Logprob Early-Token Inspection
Sequential cascades (call Model A to completion, inspect output, call Model B) double tail latency. krusch-cascade-router aborts uncertain streams mid-flight:
- It streams initial tokens from a fast local specialist (
gemma4:e4borqwen2.5-coder:7b) and inspects cumulative token logprob confidence and repetition entropy. - If confidence holds above threshold, the fast specialist completes at local speed with zero escalation tax.
- If confidence drops or loop entropy spikes, the HTTP stream is aborted immediately and escalated to
gpt-oss:120b(96 GB Blackwell burst) or frontier cloud reasoning (Gemini 4 Argon,Claude Sonnet 4,gpt-5). - In our hermetic 96 GB Blackwell
RouterArenalive benchmark (809live generations +420robustness perturbations, strictly billing all325aborted streams /58,743wasted tokens), live SSE cascade lifted7Baccuracy+11.93 pp(48.36% → 60.29%) while cutting120BTTFT by-48.0%(1,694.5 ms → 880.7 ms) and cost by-37.4%.
12,566 prompts and 13 frontier models on official ACL 2026 LLMRouterBench (including unseen OOD ARC-AGI and Humanity's Last Exam), krusch-cascade-router achieved the #1 lowest Pareto distance (0.4269) across all 10 evaluated policies at -83.95% cost vs. gpt-5, and routed 6-language agentic Polyglot loops 1,442x faster (0.395 ms vs. 569.51 ms) than an LLM preflight classifier while beating it by +30.00 pp Pass@2 (51.67% vs. 21.67%). On RouteWorks/RouterArena official GitHub CI (PR #169, currently open), it scored 0.7883 (80.72% accuracy at $0.2117/1K).
🧠 5. The Memory Substrate: krusch-context-mcp v2.0.0
A reliable harness requires bounded, persistent context across multi-million-token project histories without prompt bloat. krusch-context-mcp (v2.0.0) is a 5-verb Model Context Protocol server backed by 8,192-context snowflake-arctic-embed2 (1024d) embeddings (verified across all 2,000 Official ICLR 2026 BEAM 100K–10M probes →):
1. Temporal Recency Decay & Explicit Lineage Superseding
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 conventions evolve. krusch-context-mcp combines an exponential recency prior with explicit relational lineage (supersedes_id via krusch_context_revise):
FinalScore = CalibratedCosine × e^(-0.01 × age_in_days) · WHERE invalidated_at IS NULL AND superseded_by IS NULL
On Official ICLR 2026 BEAM, this relational grounding enabled our open-weights stack to beat commercial cloud past.dev across all 4 of 4 Contradiction Resolution splits (100K, 500K, 1M, and 10M tokens) while sustaining 92.58% (100K) and 93.00% (10M IE) recall and zero E2E QA drop from 100K to 1M (72.86%).
2. Two-Level Episode Rollups, Declarative Nuggets & SHA-256 Span Gates
Rather than bloating every turn's prompt window with a monolithic 4,000-token system prompt, declarative steering nuggets and 2-level episode rollups (ide_episode_rollups + 2-hop Gram-Schmidt orthogonal residual bridges) inject project invariants just-in-time. Every file-anchored rule carries a verbatim quoted_sentence and SHA-256 span check (INV-12), automatically flagging stale rules the moment underlying source lines drift.
3. Dual-Engine SQLite WAL & PostgreSQL 16 Parity
Single-developer laptops run zero-Docker node:sqlite WAL (.agent/context.db) with external-content Porter FTS5 and compact 4,096-byte IEEE-754 Float32Array vector blobs; multi-node swarms synchronize directly to PostgreSQL 16 + pgvector HNSW.
🛡️ 6. The Execution Core: krusch-coding-harness — 2PC Invariants Over Prompts
At the core of the execution tier is krusch-coding-harness (read the full Coding Harness architectural deep dive →). Where traditional agent loops rely on models to police their own file writes, krusch-coding-harness treats models as untrusted, interchangeable workers governed by a two-phase commit (2PC) 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 & Bubblewrap Verify-on-Stop
When a worker model proposes code modifications, no physical files in the developer's working tree are touched:
- Proposed edits are formatted as unified diffs, checked by a truncation guard, SHA-256 hashed, and inserted into
krusch_staged_diffswith statusPENDING. - Before any diff can advance, the harness mounts an isolated Bubblewrap (
bwrap) sandbox and executes the real language test suite (npm test,pytest,cargo test,go test,gradle,cmake), recording the result inkrusch_verification_runs. - The Core Invariant:
krusch_staged_diffscannot transition toAPPLYINGorAPPLIEDunless the latest verification run exited withexit_code: 0.
Actionable Failure Attribution & Empirical 2.64x Coding Lift
When sandboxed tests fail, naive agents retry the entire prompt blindly. krusch-coding-harness parses compiler and test output through KruschFailureClassifier into structured failure classes (ContextManagement, ToolUse, ObservationManagement, AgentLoop) and feeds structured repair diagnostics into a bounded Verify-on-Stop turn.
Aider Polyglot 225/225): Across all 225 official Exercism suites in C++, Go, Java, JavaScript, Python, and Rust using open-weights openai/gpt-oss-120b at $0 API cost, a single Verify-on-Stop + KruschFailureClassifier turn self-healed 72 failed tasks—lifting Pass@1 = 19.56% (44/225) to Pass@2 = 51.56% (116/225, 2.64x) with 0 truncated diffs, tying cloud Claude 3.5 Sonnet (51.6%) and beating GPT-4o (23.1%).
Atomic Apply Journal with Drift Detection & fsync Recovery
Applying verified changes to disk executes through an atomic write journal transitioning PENDING → APPLYING → APPLIED (<32 ms):
- Pre-Flight Drift Check: Before writing any file in a multi-file batch, the harness hashes each target file on disk against its recorded base hash. Any out-of-band edit aborts the entire batch cleanly.
- Atomic fsync & Rename: Files are written to temporary paths with explicit OS-level
fsync()flushes before atomic filesystem renames. - Startup Crash Recovery (
recoverInFlightApplies): On host power loss or process crash mid-apply, next startup reconciles disk hashes—promoting completed files toAPPLIEDand rolling partial writes back cleanly.
📐 7. Why AI Agents Made Us Write More Raw SQL, Not Less (Zero ORMs)
A popular refrain in modern web development claims that AI coding assistants and ORMs have made learning SQL, indexing, joins, and query planning obsolete. Building production agent infrastructure taught us the exact opposite lesson.
Across all 48 Git repositories in our ecosystem, we use 0 JavaScript ORMs (zero Prisma, zero Drizzle, zero TypeORM, zero Sequelize). Instead, the stack maintains 40 dedicated .sql migration files, 41 raw pg / node:sqlite driver modules, and 234 explicit index definitions (HNSW, GIN, composite B-Trees, and external-content Porter FTS5 virtual tables). Even in our five Python services that use SQLAlchemy for schema modeling, every retrieval hot path drops straight to parameterized SQL, pgvector operators, and composite Top-K lazy hydration.
Why? Because a human web user clicks a button once every few seconds; an autonomous coding swarm fires hybrid vector, lexical, AST-graph, and lock-acquisition queries on every single reasoning step. When an ORM hides an N+1 join, eagerly detoasts megabytes of bytea source blobs during a filter scan, or tricks the planner into a Seq Scan instead of an HNSW index walk, agent latency explodes.
Production Receipt: 252 ms Seq Scan → 15.25 ms HNSW + GIN CTE (16.5x Faster)
In krusch-git (v1.2.3, indexing 54,456 AST symbols and 4,788 live blobs with snowflake-arctic-embed2), every file edit creates a new immutable Git blob while historical snapshots remain in the blobs table. A naive query that deduplicates to the latest blob per path before ordering by vector distance—or joins full file content inside the candidate scan—forces PostgreSQL out of the HNSW index into a 252 ms sequential scan and sort.
Rewriting the hot path with an oversampled MATERIALIZED ANN CTE, a composite (repository_id, file_path, last_seen_at DESC) B-Tree NOT EXISTS anti-join, and deferred Top-K TOAST hydration cut query execution to 15.25 ms (16.5x faster):
-- Production hybrid pattern in krusch-git v1.2.3 (252 ms Seq Scan → 15.25 ms HNSW + B-Tree)
WITH ann_raw AS MATERIALIZED (
-- 1. Force pure pgvector HNSW index walk without detoasting bytea content
SELECT b.id, b.repository_id, b.file_path, b.symbol_spine,
b.last_seen_at, b.created_at,
(b.embedding <=> $1::vector) AS cosine_dist
FROM blobs b
WHERE b.embedding IS NOT NULL
AND (b.embed_model IS NULL OR b.embed_model = $4)
ORDER BY b.embedding <=> $1::vector ASC
LIMIT GREATEST(150, $3 * 20)
),
ann_latest AS (
-- 2. Deduplicate superseded Git blobs via composite B-Tree (idx_blobs_repo_path_seen)
SELECT * FROM ann_raw a
WHERE a.file_path IS NULL OR NOT EXISTS (
SELECT 1 FROM blobs b2
WHERE b2.repository_id = a.repository_id
AND b2.file_path = a.file_path
AND (b2.last_seen_at > a.last_seen_at
OR (b2.last_seen_at = a.last_seen_at AND b2.id > a.id))
)
ORDER BY a.cosine_dist ASC
LIMIT $3
)
-- 3. Defer repositories JOIN and TOASTed full_b.content read strictly to surviving Top-K rows
SELECT l.*, r.name AS project, encode(full_b.content, 'escape') AS snippet
FROM ann_latest l
JOIN blobs full_b ON full_b.id = l.id
JOIN repositories r ON r.id = l.repository_id
ORDER BY l.cosine_dist ASC;
Paired with a weighted GENERATED ALWAYS AS (setweight(to_tsvector(...))) STORED GIN index splitting camelCase identifiers and AST symbol spines, plus 2-hop git_edges call-graph bridging, this exact SQL substrate propelled krusch-git v1.2.3 to 19.12% 8-Split Macro Acc@1 and 68.58% Acc@5 across 47,998 RepoBench-R Python and Java cross-file queries—surpassing published CodeBERT and UniXcoder baselines.
👤 8. 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.
💎 9. Novelty vs. Existing Practice
The individual primitives in the Krusch stack are not invented from whole cloth; they are proven distributed systems and database engineering instincts applied rigorously to coding agents:
| Concept | Common Existing Practice | The Krusch Implementation |
|---|---|---|
| Data Access Layer | Heavy ORMs hiding N+1 joins & Seq Scans | Zero JS ORMs across 48 repos; parameterized SQL, MATERIALIZED HNSW/GIN CTEs (15.25ms) & FTS5 triggers |
| File Safety | Direct writeFile(), ad-hoc git worktrees | Diffs as first-class PostgreSQL rows with SHA-256 base-hash drift checks & atomic fsync journals |
| Verification | Post-commit CI/CD pipelines | Bubblewrap-sandboxed test pass (exit_code: 0) + Verify-on-Stop (19.56% → 51.56% Polyglot Pass@2) |
| Agent Memory | Cloud vector SaaS, flat Markdown logs | 5-verb MCP + 8K Arctic embeddings + lineage superseding + SHA-256 span-drift gates (100K–10M BEAM) |
| Model Routing | 500ms LLM preflight classifiers | Sub-15µs CPU Stage-0 gate + 1.27ms Arctic kNN + live SSE logprob abort (#1 LLMRouterBench Pareto) |
| State Authority | In-memory agent graphs, chat transcripts | PostgreSQL 16 FSM catalog (krusch_phase_edges) + FOR UPDATE SKIP LOCKED file leases |
The contribution is the unified system: binding these primitives into a single, sovereign transaction manager where models are interchangeable workers and relational state is durable law.
🚀 10. Why PostgreSQL (+ Local SQLite WAL) as the State Plane Wins
Why build this substrate on PostgreSQL 16 (paired with zero-Docker node:sqlite WAL for single-box CLI portability) rather than a tangle of Redis, Mongo, Neo4j, 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: 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 samplers plugged into a standard interface; PostgreSQL owns the state.
- Convergence of Four Modalities in One Planner: PostgreSQL 16 unifies ACID relational tables (task FSM, turns, leases),
JSONB(tool traces), dense vectors (pgvectorHNSW), weighted lexical search (tsvectorGIN), and AST call graphs (git_edgesCTEs) inside a single cost-based query planner—with zero cross-service network hops. - Multi-Agent Swarm Concurrency: Filesystems lack concurrency primitives for multi-agent swarms. PostgreSQL provides
FOR UPDATE SKIP LOCKED, unique partial 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, legal corpora, and debugging transcripts never leave self-hosted bare metal or clean-room 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 query planning, 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 Pareto-optimal multi-model cascades, krusch-context-mcp and krusch-git for index-accelerated hybrid memory and AST retrieval, and krusch-coding-harness for invariant PostgreSQL 2PC staging, we establish a deterministic contract for coding agents.
Language models provide the probabilistic spark. PostgreSQL and disciplined SQL engineering provide the transaction-managed state plane that turns that spark into production-ready software.
- krusch-stack — Unified 1-command 39-tool MCP distribution (read the 80,000+-query cross-stack benchmark comparison →).
- krusch-coding-harness — PostgreSQL 2PC coding harness, Bubblewrap Verify-on-Stop & atomic apply journal.
- krusch-git — Git DAG, relational AST graph & 15.25ms HNSW+GIN hybrid code search.
- krusch-context-mcp — 5-verb working memory, lineage superseding & SHA-256 span-drift gates (
v2.0.0). - krusch-cascade-router & krusch-pre-router — Sub-15µs CPU Stage-0 gate, Arctic kNN & live SSE logprob cascade.
- krush420/sovereign-g4-benchmarks — Public SHA-256 audit logs & verifiers across all 43 integrity gates.