2. The Swappable Architecture: Console, Cartridge, and Drive
Developer tooling has historically conflated the agent tool with the database hosting it. If you change where memory is saved, you have to rewrite your agent's MCP servers, prompts, and workflows.
We decouple agent intelligence into three clean, swappable layers:
- The Console: The agent-facing APIs. Cursor, Windsurf, or Claude Code talk exclusively to standard MCP tools (
krusch-context-mcpandkrusch-git). The model never writes raw SQL and never interacts with vendor SDKs. - The Cartridges: Portable workspaces. Repositories (
krusch-git,@krusch/toolkit), decision logs, and symbol snapshots. Cartridges can be checked into git or synced across environments. - The Drives: Where the data physically executes. By default, developers use local SQLite and local PostgreSQL. When distributed teams need shared context, they mount Polygres Cloud as the drive.
3. Compatibility Matrix: What Belongs Where
Not every database is designed for every workload. Context is not graph; graph is not vector search; vector search is not OCR. The following matrix defines the exact boundary across our local and cloud drives:
| Substrate Capability | Local Default (SQLite WAL / Local PG 16) | Polygres Cloud (`pgContext` + `pgGraph`) | Wondersearch Drive |
|---|---|---|---|
| krusch-context (Working Memory) | .agent/context.db (Instant local execution, single workstation) |
pgContext (Shared ACID memory across remote IDE swarms) |
OUT OF SCOPE (Structured memory is not document search) |
| krusch-git (AST & Call Graph) | Local PostgreSQL 16 recursive CTEs (Port 5432) | pgGraph (Serverless relational graph CTEs over HTTPS) |
OUT OF SCOPE (Graph CTEs require relational SQL substrate) |
| krusch-git (Code Passage Search) | Local Ollama bge-large (Requires 2GB local VRAM) |
In-engine PostgreSQL vector index | repo-code-drive (Managed hybrid BM25 + dense neural search) |
| Scanned Filings & TSV OCR | Local Poppler TSV + Tesseract OCR (Bare-metal only) | OUT OF SCOPE (No cloud OCR execution) | OUT OF SCOPE (No scanned geometry extraction) |
4. Deep Dive: krusch-context as a First-Class Product
krusch-context is not a key-value store or a fuzzy chat history buffer. It is an ACID-compliant working memory substrate designed to enforce invariants and survive model swaps.
4.1 The Record (Nugget) Schema & Storage Field Map
Every piece of working memory is stored as a strongly-typed record. Whether persisted in local SQLite WAL (.agent/context.db) or synchronized to Polygres Cloud pgContext, the schema maps 1-to-1:
| Field Name | SQLite WAL Schema | Polygres `pgContext` DTO | Purpose & Operational Invariant |
|---|---|---|---|
id / external_id |
INTEGER PRIMARY KEY |
BIGINT / ctx-{ns}-{id} |
Global monotonic sequence identifier. |
project / namespace |
TEXT NOT NULL |
VARCHAR(64) NOT NULL |
Workspace boundary (e.g. homelab, krusch-git). |
category |
TEXT CHECK(...) |
ENUM(...) |
Closed taxonomy: decision | invariant | bug | lesson | blocker. |
content / body |
TEXT NOT NULL |
TEXT NOT NULL |
The actionable steering instruction or architectural rule. |
tags |
TEXT (JSON ARRAY) |
TEXT[] |
Indexed keywords for fast deterministic filtering. |
author / provenance |
TEXT (JSON) |
JSONB |
Attribution: agent client ID, model name, and confidence score. |
status |
TEXT DEFAULT 'active' |
VARCHAR(16) |
Lifecycle state: active | superseded | invalidated. |
superseded_by |
INTEGER REFERENCES memories(id) |
BIGINT REFERENCES ctx_records(id) |
Direct lineage pointer to the newer architectural decision. |
justification |
TEXT |
TEXT |
Mandatory rationale required whenever a rule is invalidated. |
4.2 Multi-Agent Write Conflict Resolution
When multiple agents (e.g. Cursor modifying a frontend component while Claude Code refactors an API in the terminal) write to memory simultaneously, naive syncing creates race conditions. krusch-context uses causal monotonic sequence numbering and optimistic concurrency checks:
- Every update requires a
target_idand the rule's last known state hash. - If Agent B attempts to update Rule #12 while Agent A has already superseded Rule #12 with Rule #15,
pgContextrejects Agent B's write with aStaleMemoryConflictError. - Agent B is forced to re-hydrate active memory via
retrieve(), discover the new Rule #15, and adjust its plan before touching code.
4.3 The Sanitization Invariant: What Must NEVER Sync
Before any memory record leaves the local machine for
pgContext, it passes through an automated cryptographic sanitization filter. The sync bridge strictly rejects any memory containing:
- API keys and tokens (e.g. regex patterns matching
sk-*,cfut_*,ghp_*). - Environment variable blocks or
.envfile paths. - Cryptographic keys (
-----BEGIN PRIVATE KEY-----). - Un-anonymized customer or counterparty names.
5. Deep Dive: krusch-git & The SHA-Pinning Join Story
krusch-git splits codebase understanding into two complementary substrates: relational AST symbol graphs (on pgGraph) and semantic code passages (on Wondersearch). But how do these two systems stay synchronized without drifting?
5.1 The SHA-Pinning Protocol
The danger of splitting graph traversal from semantic search is the split-brain index: an agent retrieves an AST symbol from HEAD, but searches for code passages that reflect a commit from last week.
To eliminate this failure mode, krusch-git binds every query and synchronization to an explicit Git commit SHA:
If the remote Wondersearch drive is still indexing a fresh push, the connector flags the SHA mismatch and falls back to local AST diffing for unstaged files, guaranteeing the agent never consumes conflicting representations.
5.2 The Refactoring Walk: resolve_controlling_clause
Let's trace how an autonomous coding agent uses krusch-git to prepare a refactor of resolve_controlling_clause() in repository krusch-biz:
import { createPolygresConnector } from '@krusch/polygres-connector';
const connector = createPolygresConnector({
polygresUrl: process.env.POLYGRES_URL,
wondersearchApiKey: process.env.WONDERSEARCH_API_KEY
});
// Step 1: Find authoritative AST declaration with exact line boundaries
const symbol = await connector.git.findSymbol('krusch-biz', 'resolve_controlling_clause');
// Returns: { file: 'src/backend/resolver.py', lines: [142, 280], kind: 'function' }
// Step 2: Calculate blast radius via recursive caller CTE (inbound dependencies)
const blastRadius = await connector.git.getDependencyGraph('krusch-biz', 'resolve_controlling_clause');
// Returns:
// Inbound Callers: src/backend/main.py:L215 (POST /conflicts), tests/test_resolver.py:L48
// Outbound Callees: _evaluate_precedence_hop (L198), _detect_clause_conflict (L245)
// Step 3: Semantic code search with exponential recency decay applied (exp(-0.01 * days))
const passages = await connector.git.searchCode('krusch-biz', 'precedence resolution hop');
// Returns passages with decay weight 0.970 for fresh commits vs 0.026 for 2-year-old stale code
6. Empirical Parity Benchmark: 20 Pure Context & Code Operations
Below is the empirical evaluation benchmark comparing Local Substrates (PostgreSQL 5432 + SQLite WAL) and Polygres Cloud across 20 representative developer queries, proving complete parity across working memory and codebase graphs without a single external legal query:
| # | Subsystem | Query / Operation | Target Entity / Resolved Target | Parity Verification | Operational Notes |
|---|---|---|---|---|---|
| 1 | KruschContext | Active invariant hydration (turn 1 prompt briefing) | Rule #310 (homelab context) | MATCH [pgContext: Rule] | Hydrated across remote IDE sessions in <10ms. |
| 2 | KruschContext | Decision supersede lineage traversal | Rule #278 → Decision #279 | MATCH [pgContext: Lineage] | Preserves parent/child superseded relationship. |
| 3 | KruschContext | Invalidated rule check (retired legacy workflow) | Rule #84 (Invalidated single-agent loop) | MATCH [pgContext: Retired] | Guarantees retired rules are never returned to agent. |
| 4 | KruschContext | Pre-commit invariant audit finding check | Rule #205 (Seer letterboxing fix) | MATCH [pgContext: Rule] | Emits identical pre-commit nudge finding. |
| 5 | KruschContext | Concurrent write conflict detection | Rule #12 simultaneous revision | MATCH [StaleConflictError] | Rejects stale write; forces agent re-hydration. |
| 6 | KruschContext | Secret & credential sanitization filter | Sync payload containing sk-or-v1-... |
MATCH [SyncRejected] | Blocks API keys and private keys from leaving local machine. |
| 7 | KruschContext | 30-day memory decay candidate review | Store Hygiene Audit | MATCH [pgContext: Health] | Identifies stale steering rules ready for revision. |
| 8 | KruschContext | Fleet node hardware mapping and IP endpoints | Fleet Inventory (homelab context) | MATCH [pgContext: State] | Provides immediate fleet topology without scanning network. |
| 9 | KruschContext | Open task blocker tracking & diagnostic recovery | Blocker #271 (Diagnostic trace) | MATCH [pgContext: Blocker] | Preserves error trace across terminal reconnects. |
| 10 | KruschContext | Category filter retrieval: invariants only | retrieve({ category: "invariant" }) |
MATCH [Exact Filter] | Returns only non-negotiable steering rules. |
| 11 | KruschGit | Function declaration resolve_controlling_clause | src/backend/resolver.py:L142 |
MATCH [AST: FunctionDef] | Authoritative AST symbol found in <15ms via pgGraph. |
| 12 | KruschGit | Inbound callers to parse_file_symbols | server/mcp.js:L88, scripts/sync.js:L42 |
MATCH [pgGraph: InboundCTE] | Identical caller list returned across backends. |
| 13 | KruschGit | Outbound callees of resolve_controlling_clause | _evaluate_precedence_hop (L198) |
MATCH [pgGraph: OutboundCTE] | Maps complete downward dependency tree. |
| 14 | KruschGit | Multi-file interface implementation search | NexusClient protocol implementers |
MATCH [AST: Protocol] | Identifies LocalProvider and WondersearchProvider. |
| 15 | KruschGit | Git DAG commit parent pointer traversal | server/git-engine.js:L115 |
MATCH [AST: Function] | DAG traversal identifies common ancestor merge base. |
| 16 | KruschGit | SHA-pinned semantic code search | searchCode('precedence hop', sha='a4f8e21') |
MATCH [SHA Assertion] | Guarantees search passage matches exact commit SHA. |
| 17 | KruschGit | Exponential temporal recency decay function | scripts/sync_to_pg.js:L54 |
MATCH [AST: Function] | Calculates exp(-0.01 * days) code ranking formula. |
| 18 | KruschGit | Stale legacy passage suppression | 2-year-old deprecated helper passage | MATCH [Decay: 0.026] | Suppressed by 97.4% score reduction. |
| 19 | KruschGit | Multi-repo symbol collision resolution | krusch-context-mcp vs krusch-git |
MATCH [Repo Scoping] | Repository namespace disambiguates identically named tools. |
| 20 | KruschGit | Class inheritance hierarchy traversal | BaseExtractor → TreeSitterExtractor |
MATCH [pgGraph: EXTENDS] | Full class inheritance chain mapped via recursive CTE. |
7. Real Engineering Metrics: Local vs. Cloud Substrates
| Operational Metric | Local Homelab (Bare-Metal) | Polygres Cloud (`pgContext` + `pgGraph`) | Engineering Impact |
|---|---|---|---|
| Time-to-First-Working-Agent (Cold Machine) | 42 minutes, 15 seconds (Docker build, pull Ollama bge-large, migrations) |
35 seconds (`npm install -g @krusch/polygres-connector`, set env) |
72x Faster Setup: Ephemeral agents, CI runners, and GitHub Codespaces start immediately. |
| Agent Working Memory Sync (`krusch-context`) | Local disk only (Siloed per machine) | <12ms ACID Sync (`pgContext`) | Eliminates cross-IDE amnesia between Cursor, Windsurf, and Claude Code. |
| Code Symbol Search Latency (p95) | 38ms (Local pgvector HNSW) | 45ms (Polygres REST API) | Virtually identical interactive performance (+7ms network delta). |
| Repo AST Graph Ingestion Latency | 2 minutes, 28 seconds (Local HNSW rebuild) | 4.1 seconds (REST sync via connector) | Instant live index updates across distributed agent swarms. |
| Hardware Resource Utilization | 8GB VRAM + 16GB RAM + 40GB SSD | Zero GPU + <100MB RAM | Enables full development on ultralight laptops and $5/mo VPS instances. |
8. Getting Started in 60 Seconds
To power KruschContext and KruschGit on your choice of local or cloud substrates, follow this 3-step path:
-
Install the Connector & Configure Credentials:
npm install -g @krusch/polygres-connector # Set your Polygres Cloud endpoint (or leave blank to default to local SQLite/Postgres) export POLYGRES_URL="postgresql://user:[email protected]:5432/team_db" export STORAGE_PROVIDER="polygres" # 'local' | 'polygres' export ALLOW_CLOUD=1 -
Sync Agent Memory & Codebase Graphs:
# Push local invariants and Git AST symbols to the target drive krusch-polygres sync-context homelab krusch-polygres sync-git krusch-git -
Query Symbols & Memory from Any Agent:
import { createPolygresConnector } from '@krusch/polygres-connector'; const connector = createPolygresConnector({ polygresUrl: process.env.POLYGRES_URL }); // Instant AST symbol graph lookup via pgGraph const symbol = await connector.git.findSymbol('krusch-git', 'find_symbol'); console.log(symbol.file_path, symbol.location.lines);
9. Conclusion: Decoupling Agent Intelligence from Infrastructure
The future of AI coding agents is not about stuffing millions of raw code tokens into larger context windows, nor is it about locking developer tooling into proprietary cloud silos.
By decoupling agent intelligence into Consoles (stable agent APIs like krusch-context and krusch-git), Cartridges (portable codebases and decision logs), and Swappable Drives (local SQLite, PostgreSQL, or Polygres Cloud), you gain complete sovereignty.
You can run 100% locally on your laptop when working solo, mount Polygres Cloud when coordinating swarms across remote IDEs, and maintain absolute confidence that your agent's memory and code understanding will remain identical across every environment.
- krusch-context-mcp — Working memory, invariant steering, and decision lineage engine.
- krusch-git — Git DAG in SQL, AST symbol graphs, and recency hybrid search (v1.2.1).
- @krusch/polygres-connector — Standalone bridge toolkit for Polygres Cloud & Wondersearch.
- krusch-nexus — Universal document ingestion engine & dual-provider RAG substrate (v0.2.6).
- krusch-law — 100% air-gapped on-premises sovereign legal intelligence fortress (v0.8.0).