1. Why Local-First Agents Need a Sovereign Cloud Bridge

When you build a local-first AI ecosystem, you quickly hit a physical friction point: your coding agents (Antigravity, Claude Code, Cursor) live on your bare-metal workstation, while your day-to-day documents, contracts, project briefs, calendar events, and inbox live in Google Workspace. Worse yet, when you are away from your desk with only your phone or tablet, you cannot easily edit a local system prompt or drop a PDF into a workstation directory for your agents to index.

Existing cloud connectors force an unacceptable trade-off: either hand third-party SaaS middlemen broad OAuth scopes and unencrypted refresh tokens, or settle for stateless API wrappers that dump raw, unindexed file blobs into your model's context window.

We built G-Krusch to solve this cleanly. Running locally on Node.js 22+ (`127.0.0.1:5446`), G-Krusch is a sovereign Google Workspace Hub and Model Context Protocol (MCP) server that turns a dedicated folder in your Google Drive into a structured, hybrid-indexed, cryptographically guarded workspace shared across your IDE coding agents and Krusch Companion.

Google Drive / └── G-Krusch/ ├── agent.md # Authoritative steering & invariants (edit on phone, tablet, or web) ├── context/ # Domain knowledge, architectural specs, SOPs, reference PDFs ├── memory/ # Decisions, invariants, cross-session project logs └── output/ # Agent-generated deliverables, audits, and reports

2. Cloud-Synced agent.md Steering & Epoch Coherency

Most agent frameworks treat system prompts as static local dotfiles. With G-Krusch, your top-level agent.md lives inside your G-Krusch/ Google Drive workspace. You can open Google Drive on your phone while commuting, update a project priority or add a non-negotiable architectural constraint to agent.md, and every connected agent immediately inherits that rule on its next turn via the get_agent_steering MCP tool or GET /api/steering REST endpoint.

Under the hood, G-Krusch caches steering rules in memory with a configurable TTL while enforcing strict mutation-epoch coherency (steeringCacheEpoch). If an in-flight background read resolves while a user or agent simultaneously writes or deletes agent.md via writeDriveFile or deleteDriveFile, the epoch counter increments and prevents stale in-flight payloads from repopulating the cache.

3. 1,024-Dim 3-Tier Embedding Cascade & FTS5 Hybrid RAG

Naive Google Drive integrations rely solely on Google's basic filename search. G-Krusch synchronizes your workspace documents (Google Docs exported to clean text, Markdown, JSON, CSV, and multi-page PDFs) into a local SQLite WAL database (`rag_documents`, `rag_chunks`, `rag_chunks_fts`, and `rag_embeddings_cache`) and runs a deterministic hybrid retrieval pipeline:

Tier 1: Local GPU Embeddings (1,024-Dim)

Queries our local bare-metal Ollama embedding host (bge-large:latest) first for zero-cost, 1,024-dimensional dense semantic vectors that never leave the local LAN.

Tier 2: Dimensionality-Pinned Cloud Fallback

If local GPU embeddings are unreachable, cascades to Gemini (models/gemini-embedding-001) pinned explicitly to outputDimensionality: 1024 so vector dimensions never drift across tiers.

Tier 3: Uncached Offline Trigram Fallback

In total air-gapped or offline conditions, computes a deterministic 64-dim character-trigram hash vector on CPU—explicitly bypassing rag_embeddings_cache so transient outages never poison persistent cache rows.

SQLite FTS5 BM25 + Self-Healing Sync

Combines dense cosine similarity (0.68 weight) with Porter-stemmed SQLite FTS5 BM25 keyword scores (0.32 weight). On boot, ensureFtsSync(db) verifies FTS5 row parity and rebuilds the index transactionally if drift is detected.

4. 3-Tier Page-Faithful PDF Ingestion & Pre-Spool Guards

Enterprise workspaces are full of PDFs—contracts, architecture datasheets, and regulatory filings. Before G-Krusch ever writes a downloaded PDF buffer to disk, validatePdfMagicBytes(buffer) inspects the first 1,024 bytes for the canonical %PDF- header, immediately rejecting disguised PE/ELF binaries or HTML error pages before they touch /tmp.

Once validated, G-Krusch extracts page-bounded text (`[contract.pdf p.1]`) through a resilient 3-tier parser cascade:

  • Tier 1 (KruschNexus Layout Engine): Uses the sovereign KruschNexus pdftotext -bbox-layout binary to preserve multi-column physical reading order and form-feed (\f) page boundaries.
  • Tier 2 (System Poppler pdftotext): Invokes system Poppler with sanitized temporary filenames (sanitizePdfTempName) and an explicit -- end-of-options separator to eliminate flag-injection vectors.
  • Tier 3 (Pure-JS Stream Fallback): If neither binary is installed on a lightweight edge node, extractPdfTextNative(buffer) decompresses FlateDecode streams and parses PDF text operators (Tj, TJ, ', ") directly in Node.js.

5. The 12-Tool MCP Surface & Krusch Companion Bridge

G-Krusch speaks both protocols required by a modern agentic fleet: Model Context Protocol (MCP) over SSE (`/mcp/sse`) and Stdio (`--stdio`) for coding IDEs, and a hardened REST API (`/api/*` on port `:5446`) for Krusch Companion's 16-tool <holodata> Agentic Proxy and background Sentinel Watchdog daemon.

Domain MCP Tool / REST Endpoint Sovereign Capability & Safety Boundary
Steering & Health get_agent_steering
get_workspace_status
Hydrates cloud-synced agent.md rules with epoch coherency and reports OAuth, RAG chunk counts, and embedding provider status.
Hybrid Drive RAG search_drive_rag
sync_drive_rag
Runs 1,024-dim vector + FTS5 BM25 hybrid retrieval with page citations and incremental MD5/modifiedTime delta indexing.
Workspace I/O read_drive_file
write_drive_file
delete_drive_file
list_drive_workspace
Reads, writes, and lists files strictly inside the G-Krusch Drive root. Enforces isFileInWorkspace ancestry checks and atomic RAG/FTS5 cleanup on deletion.
Google Calendar list_calendar_events
create_calendar_event
Lists upcoming agenda windows and creates Google Calendar events with attendee and ISO-8601 window validation.
Gmail Extensions search_gmail_messages
compose_gmail_message
Parallelized Promise.all inbox metadata search and RFC-2822 / RFC-2047 UTF-8 base64url email draft creation or direct sending.

6. Security & Concurrency Hardening (INV-01 – INV-13)

Because G-Krusch holds OAuth 2.0 credentials to your personal or enterprise Google Workspace, we subjected the entire codebase to a 13-invariant principal security and concurrency audit (`INV-01` through `INV-13`):

  • NIST SP 800-38D AES-256-GCM Token Vault (INV-05): OAuth access and refresh tokens are encrypted at rest in SQLite WAL using 256-bit keys (validated for full 32-byte hex entropy), 12-byte (96-bit) IVs, and 16-byte authentication tags, with backward-compatible decryption for legacy 16-byte IV records.
  • Multi-Tab OAuth2 CSRF State Pool & Atomic Disconnect (INV-02): Issues 32-byte CSPRNG one-time state tokens (bounded to MAX_PENDING_OAUTH_STATES = 32 with a 10-minute TTL) verified in constant time on /auth/google/callback. Disconnecting via POST /auth/disconnect atomically wipes OAuth tokens, Drive folder caches, and indexed RAG chunks in a single SQLite transaction.
  • Loopback Binding, CORS Lockdown & Constant-Time Auth Guard (INV-03 & INV-11): Binds to 127.0.0.1 by default, restricts browser CORS to localhost, RFC1918 LAN, and Tailscale (100.64.0.0/10) origins, and protects every read/write `/api/*` and `/mcp/*` endpoint with crypto.timingSafeEqual bearer/header verification and a 2 MB UTF-8 payload ceiling.
  • Drive Query Escaping & Workspace Ancestry Verification (INV-04): Escapes backslashes and single quotes in all Drive API q filters (escapeDriveQueryLiteral) and verifies parent-chain ancestry (isFileInWorkspace) before reading or trashing any raw fileId—preventing an agent from reading or deleting personal Drive files outside the G-Krusch workspace.
  • Per-Session MCP SSE Isolation & Keyed FIFO Mutexes (INV-10): Instantiates a dedicated McpServer per SSE connection to prevent multi-client transport collisions, while AsyncKeyedMutex serializes concurrent OAuth token refreshes, folder creation, and RAG indexing without deadlocks.

Explore G-Krusch & the Sovereign Agent Stack

G-Krusch is open source under the MIT License and ships with a 12-check production diagnostic CLI (npm run doctor) and 30 hermetic security and RAG verification tests (npm test).

GitHub Repository (kruschdev/g-krusch) → Read Krusch Companion Deep Dive →