Technical TL;DR: Asking a coding agent to regenerate HTTP routers, SSE streams, database pools, multipart upload parsers, SSRF filters, or YAML loaders from scratch on every task produces code that passes happy-path unit tests while planting subtle systems bugs. Across 100 repositories (3,150+ source files), we replaced prompted infrastructure plumbing with a closed-loop Lego System for Code: (1) Dual-Runtime Certified Bricks (INV-LEGO-01..25): 35 runtime bricks (25 Node 22 ESM / TypeScript .d.ts / React / Cloudflare Worker bricks in @krusch/toolkit v1.7.0 across 60 typed export subpaths + 10 bare-stdlib Python 3.12 bricks in krusch_toolkit v1.6.0) and 7 zero-LLM project blueprints (krusch-lego stamp), verified by 122/122 Node test suites, 199/199 pytest suites, and strict tsc --noEmit; (2) Deterministic Pre-Commit MCP Guard: krusch_context_nudge({ trigger: "pre_commit" }) and krusch-lego audit run a 10-rule comment/string/regex-masked static analyzer over staged git diffs, blocking hand-rolled plumbing before commit; (3) Autonomous Rule-of-3 Anti-Bloat Scout (INV-LEGO-15): krusch-lego scout (wired into our 24/7 Jean SRE daemon) scans all 100 repositories to promote recurring infrastructure clusters (≥ 3 repos → 8/8 empirical clusters promoted, 100% coverage) while explicitly forbidding premature extraction of < 3-repo domain code; and (4) 2-Stage QLoRA SFT + DPO Weight Calibration (INV-LEGO-16): Fine-tuning Qwen3-Coder-30B-A3B (51.03 MB GGUF) and openai/gpt-oss-120b (45.58 MB GGUF) on 18,049 Zero-Leak SFT + trl.DPOTrainer records (4.18 Colab G4 CUs) lifted zero-tool Lego & Rule-of-3 architectural accuracy from 25.0% (1/4) to 100.0% (4/4) while eliminating Referee false positives on compliant code.
35 Bricks · 7 Blueprints
@krusch/toolkit v1.7 (60 .d.ts, 122/122 tests) + krusch_toolkit v1.6 (199/199 pytest)
25 Invariants · 10 Rules
INV-LEGO-01..25 + Comment/String-Masked MCP Pre-Commit Diff Gate
100 Repos · 8 / 8
3,150 Files Scanned by krusch-lego scout · 100% Rule-of-3 Cluster Coverage
25.0% → 100.0%
Zero-Tool Lego & Rule-of-3 Lift via 2-Stage QLoRA SFT + DPO (30B & 120B)

1. The Hidden Tax of "95%-Correct" Agent Boilerplate

Modern LLMs are deceptively fluent at infrastructure boilerplate. Ask any frontier or open-weights coding model for an Express or FastAPI server, a Server-Sent Events (SSE) stream, a PostgreSQL pgvector query, a webhook verifier, or a multipart file uploader, and it will emit clean-looking code in seconds.

In a single prototype repository, that fluency feels like velocity. Across 100 repositories maintained by autonomous coding agents, it becomes a compounding reliability hazard. Every time an agent synthesizes 150 lines of fresh plumbing from weights, it samples from the median of public GitHub tutorials—re-introducing subtle protocol, concurrency, and security defects that unit tests almost never exercise.

Every invariant in our Lego system (INV-LEGO-01 through INV-LEGO-25) originated from a real failure class caught in CI or production audits across our own stack:

  1. HTTP 413 TCP ECONNRESET Races (INV-LEGO-03, INV-LEGO-18): When enforcing a payload byte cap on node:http or multipart uploads, LLM-generated handlers routinely call res.writeHead(413) followed immediately by req.destroy() while the client is still streaming body chunks. At the kernel socket layer, destroying an unread incoming stream sends a TCP RST packet that tears down the connection before the client reads the HTTP 413 JSON body—producing flaky ECONNRESET failures in CI (caught live in krusch-stack GitHub Actions run 40877285884).
  2. Connect-Time DNS-Rebinding SSRF & Cross-Origin Credential Leaks (INV-LEGO-13, INV-LEGO-21): Prompted SSRF guards almost always check a hostname with a regex (!/^(localhost|127\.|10\.|192\.168\.)/) or run a pre-flight dns.lookup() before calling fetch(url) or httpx.AsyncClient().get(url). That leaves three holes wide open: (a) TOCTOU DNS rebinding, where an attacker's authoritative nameserver returns a public IP during validation and 169.254.169.254 (cloud metadata) or 127.0.0.1 on the second socket-connect lookup; (b) IPv6 transition bypasses (::ffff:127.0.0.1, 6to4 2002::/16, Teredo 2001:0000::/32, octal/hex IPv4 literals, and Unicode IDNA homographs); and (c) cross-origin 302 redirects that silently forward Authorization and Cookie headers to an untrusted host.
  3. Transient SQLite OOM/Lock Quarantine (INV-REC-01, INV-LEGO-12): When an embedded SQLite WAL database fails to open, naive recovery wrappers catch any exception and move the .db file aside as "corrupted." Under container memory pressure or lock contention, SQLite throws SQLITE_NOMEM, SQLITE_BUSY, or ENOSPC—not SQLITE_CORRUPT or SQLITE_NOTADB. Treating transient resource exhaustion as structural corruption causes an agent daemon to quarantine a healthy live database.
  4. FTS5 Query Syntax Injection & Leaked GPU Streams (INV-LEGO-03, INV-LEGO-12): Passing raw user search text ("c++ router: fast-path?") into SQLite MATCH crashes immediately with fts5: syntax error near "+". Meanwhile, SSE endpoints without X-Accel-Buffering: no and req.on('close', () => controller.abort()) keep local Ollama GPUs generating thousands of orphaned tokens after a browser tab closes, and React useEffect(() => { fetch(...) }, []) hooks without AbortController trigger stale-state races on rapid navigation.
  5. YAML 1.1 "Norway Bugs", Arbitrary Tags & Billion-Laughs Alias Bombs (INV-LEGO-23): Default configuration loaders (yaml.load in js-yaml or unguarded PyYAML) silently coerce country codes (NO → false), turn ISO date strings into language-specific Date/datetime objects that break JSON schema checks, accept !!python/... or !!js/... tags, and expand recursive &a [*a, *a] anchor graphs exponentially until the process OOMs.
  6. Length-Leaking Webhook HMACs (INV-LEGO-09): Hand-rolled Slack, GitHub, and Stripe webhook verifiers frequently call crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)) without checking byte lengths first—throwing an uncaught RangeError 500 on malformed caller headers—or omit replay-window timestamp tolerances (toleranceSeconds).

Prompts and markdown style guides cannot permanently fix these six bugs, because prompt adherence is probabilistic while systems invariants are binary. The only way to drive boilerplate defect rates to zero—while slashing scaffolding tokens to zero—is to take infrastructure plumbing out of the token generation loop altogether.

2. Architecture Overview: The 5-Stage Closed-Loop Lego System

Most "internal shared libraries" fail in one of two opposite ways: either agents ignore the library and keep writing raw new pg.Pool() / FastAPI() code anyway, or engineers dump every speculative helper into @company/utils until the package becomes an unmaintainable monolith.

To prevent both failure modes, we designed the Lego system as a five-stage closed feedback loop connecting runtime packages, static MCP gates, cross-repository AST/source scouting, spec-first Referee verification, and local model weight distillation:

Each stage enforces a hard architectural boundary:

3. Inside the Dual-Runtime Substrate (@krusch/toolkit v1.7 & krusch_toolkit v1.6)

Design Law 1: The Universal Envelope Contract (INV-LEGO-01)

When an AI agent orchestrates HTTP microservices, Model Context Protocol (MCP) tools, CLI scripts, and Python RAG backends, inconsistent return shapes ({ data } vs. { result } vs. raw strings vs. thrown exceptions) force defensive glue code at every seam. Every brick in @krusch/toolkit and krusch_toolkit emits the same deterministic JSON envelope and never throws on untrusted caller input:

// Success envelope (HTTP 2xx, MCP okMcpResult, CLI --json, schema/SSRF/upload validators)
{
  ok: true,
  tool: "security.fetch",
  summary: "Fetched https://example.com/feed.json (HTTP 200)",
  data: { status: 200, redirected: false, redirects: 0 /* ... */ }
}

// Error envelope (HTTP 4xx/5xx, MCP isError: true, fail-closed policy blocks)
{
  ok: false,
  tool: "security.fetch",
  summary: "Blocked private or reserved IP address",
  error: {
    code: "SSRF_PRIVATE_IP",
    message: "Resolved address 169.254.169.254 is in a private or reserved range",
    details: { hostname: "metadata.example.internal", resolvedAddresses: ["169.254.169.254"] }
  }
}

Design Law 2: Zero-Build ESM + .d.ts Parity, Edge Purity & Bare-Stdlib Imports (INV-LEGO-02, INV-LEGO-08, INV-LEGO-11)

Shared toolkits die quickly if importing a tiny helper drags in a 400 MB dependency tree or requires a build step before node --test can run:

Complete 35-Brick Dual-Runtime Catalog

Plane JavaScript / TypeScript / Edge (@krusch/toolkit v1.7.0) Python 3.12 (krusch_toolkit v1.6.0) Bugs Eliminated by Construction
HTTP, Edge & Streaming http (createApiServer, readBoundedJsonBody), streaming (sseResponse, streamChat), edge (createEdgeRouter, edgeSseResponse, createEdgeKvJsonStore) fastapi_app (create_fastapi_app, sse_event_response), http_client (request_json, async_request_json, HttpCircuitBreaker) 413 TCP ECONNRESET races, CRLF header splitting, wildcard CORS credential leaks, orphaned SSE streams, connect-time DNS rebinding.
MCP Tool Substrates mcp (defineMcpTool, createMcpServer, validateToolArgs) python_mcp (define_mcp_tool, dispatch_mcp_tool, validate_tool_args) Missing 4-boolean MCP safety annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint), stdout JSON corruption, 0/False/"" falsy arg drops.
Relational, WAL & Vector State pg (createPgPool, runSqlMigrations, pgVectorSearch), db (initDb, isSqliteCorruptionError), sqlite (openSqliteDb, escapeFts5Query, fuseRrfResults) python_pg (assert_safe_pg_identifier, pg_vector_search), python_db_async (create_managed_async_engine, async_session_scope, redact_database_url) Transient OOM/lock DB quarantine, SQLite WAL/busy_timeout omissions, fts5: syntax error crashes, SQLi in pgvector <=> queries, CancelledError session leaks, DSN password leaks in logs.
Security, Webhooks & Uploads security (safeFetch, validateOutboundUrl, createRateLimiter), webhooks (verifySlackSignature, verifyGithubSignature, verifyStripeSignature, verifyBearerToken), upload (parseBoundedMultipart, verifyUploadMime) python_security (verify_webhook_hmac, verify_bearer_token, validate_outbound_url), python_upload (sanitize_upload_filename, verify_upload_mime, read_bounded_upload) IPv4/IPv6/6to4/Teredo/metadata SSRF, RangeError length leaks in timingSafeEqual, replay attacks, path-traversal/DOS filenames, <svg>/<script> XSS disguised as image/*, unbounded Map OOMs.
Schemas & Safe YAML Packs schema (s, toJsonSchema, validateSchema), yaml (parseSafeYaml, loadSafeYamlPack, stringifySafeYaml) python_schema (validate_json_schema, validate_payload), python_yaml (_SovereignSafeLoader, load_safe_yaml_pack) Prototype pollution (__proto__), bool-as-int & NaN/Inf coercion, YAML 1.1 Norway bug (NO: false), !tag code execution, Billion-Laughs *alias bombs, unpinned statutory packs.
Routing, AI & Modalities cascade (selectCascadeTier, createTierCircuitBreaker, executeWithCascadeFallback), llm, embeddings (1024d snowflake-arctic-embed2), raw-rag (256/32-tok), decide (1-tok logprob), vision, audio (encodeWavPcm16, parseWavHeader, Whisper/TTS) (Plus krusch_toolkit.ai, embeddings, and raw_rag parity helpers) HALF_OPEN retry stampedes, <25µs routing regressions (7.05µs avg), asymmetric query-prefix drift, lossy RAG summarization, RIFF JUNK-chunk WAV parse failures.
UI, CLI & Governance react (useApiQuery, useSSEStream, AppShell), auth (httpOnly JWT), config, log, cli (withSingleInstanceLock, defineCli), lego-scout (scoutHomelabLegoCandidates) python_streamlit_ui (render_sovereign_rag_shell, format_citation_badges_html, append_rag_turn) Un-aborted React useEffect fetches, overlapping cron/daemon PID races, javascript:/data: citation XSS in Streamlit, external font calls in air-gapped UIs.

Code Teardown A: Eliminating 413 TCP ECONNRESET & SVG Upload XSS

In @krusch/toolkit/http (readBoundedJsonBody) and @krusch/toolkit/upload (parseBoundedMultipart), oversized request streams are drained up to a bounded window before flushing the HTTP 413 envelope, and uploaded file bytes are checked against binary magic headers rather than trusting Content-Type:

import { createApiServer, okEnvelope } from '@krusch/toolkit/http';
import { parseBoundedMultipart } from '@krusch/toolkit/upload';

const server = createApiServer({
  serviceName: 'document-intake',
  maxBodyBytes: 1_048_576, // Drains safely on overflow -> clean HTTP 413 JSON (zero TCP RST)
  routes: {
    'POST /api/upload': async ({ req, sendJson }) => {
      const parsed = await parseBoundedMultipart(req, {
        maxTotalBytes: 10 * 1024 * 1024,
        maxFiles: 3,
        allowedMimeTypes: ['application/pdf', 'image/*'],
        requireMagicMatch: true // Sniffs magic bytes; blocks <svg>/<script> XSS under image/*
      });
      if (!parsed.ok) return sendJson(400, parsed);
      return okEnvelope('intake.upload', 'Verified upload', {
        files: parsed.data.files.map((f) => ({ name: f.filename, mime: f.detectedMime, bytes: f.size }))
      });
    }
  }
});

Code Teardown B: Closing the DNS-Rebinding TOCTOU Gap in Both Node & Python

Validating a URL before calling fetch() is useless if the HTTP client performs a second DNS lookup when opening the socket. Both @krusch/toolkit/security (safeFetch, using an undici Agent custom lookup hook) and krusch_toolkit.http_client (async_request_json, pinning the validated IP in the httpx connect URL while passing TLS extensions={"sni_hostname": host_norm} and Host headers) bind the socket directly to the vetted IP, follow redirects manually (follow_redirects=False), strip credentials across origins, and release single-flight HALF_OPEN circuit-breaker probes cleanly even on asyncio.CancelledError:

from krusch_toolkit.http_client import create_http_circuit_breaker, async_request_json

breaker = create_http_circuit_breaker(failure_threshold=3, cooldown_seconds=30.0)

# Non-blocking loop.getaddrinfo -> IPv4/IPv6/6to4/Teredo/IDNA SSRF check ->
# IP-pinned TLS SNI connect -> manual redirect hop re-validation -> 5 MiB stream cap
result = await async_request_json(
    "https://partner.example.org/v1/statutes",
    bearer_token=token,
    max_retries=2,
    max_response_bytes=5_242_880,
    breaker=breaker,
)
if not result["ok"]:
    # Deterministic envelope: SSRF_PRIVATE_IP | HTTP_CIRCUIT_OPEN | HTTP_RESPONSE_TOO_LARGE
    return result

Zero-LLM Blueprints: Stamping Full Services in <15ms

Bricks solve module-level reuse; Project Archetypes (krusch-lego stamp <archetype> <dir>) solve day-1 repository topology. Rather than spending 4,000–8,000 LLM output tokens generating package.json, tsconfig.json, Dockerfile, Compose v2 manifests, /health + /doctor probes, and smoke tests, scaffoldProject stamps 7 deterministic blueprints in <15ms at $0.00 token cost:

  1. node-api-sqlite (11 files) — Node 22 ESM API + crash-safe SQLite WAL + test suite.
  2. node-ts-service (12 files) — Zero-build TypeScript (tsc --noEmit --strict) + Node 22 ESM + SQLite WAL.
  3. node-rag-pgvector (12 files) — Sovereign 1024d snowflake-arctic-embed2 RAG API + pgvector migrations.
  4. mcp-stdio-server (10 files) — Stdio MCP server with mandatory 4-boolean tool annotations (INV-STACK-03).
  5. fullstack-react-vite (16 files) — Node 22 SSE streaming backend + Vite React AppShell (useSSEStream).
  6. python-fastapi-service (10 files) — Python 3.12 create_fastapi_app service + pytest suite.
  7. cloudflare-worker (9 files) — Zero-node:* Edge router + KV JSON store + SSE (wrangler.toml).

4. Deterministic Enforcement: Catching Hand-Rolled Plumbing Before Commit

Why AGENTS.md Rules Need a Parser Behind Them: System-prompt instructions degrade as conversation trajectories grow past 30,000 tokens. Pairing concise AGENTS.md brick tables with a sub-millisecond static diff guard turns a soft preference into a hard pre-commit invariant.

Whenever an agent prepares to finish a multi-file edit, our workflow invokes krusch_context_nudge({ trigger: "pre_commit", code: "<git diff>" }) (backed by lego-boilerplate-guard.js in krusch-context-mcp and mirrored in krusch-lego audit <path>).

Naive regex linters fail constantly on real repositories because documentation comments, markdown code blocks, SQL strings, and JavaScript regex literals mention fetch(, yaml.load(, or new pg.Pool(. Our guard runs a dedicated character-level lexer (stripCodeComments + extractAddedCodeLines) that:

Rule ID Detected Anti-Pattern in Added Code Required Certified Brick Replacement
raw-mcp-stdio new Server(...) + StdioServerTransport defineMcpTool, createMcpServer (@krusch/toolkit/mcp)
manual-sse-headers Raw text/event-stream response headers sseResponse (./streaming), edgeSseResponse (./edge), or sse_event_response (fastapi_app)
raw-pg-pool new pg.Pool(...) / new Pool(...) createPgPool, runSqlMigrations, pgVectorSearch (@krusch/toolkit/pg)
raw-sqlite-database new Database(...) (better-sqlite3) initDb, query, transaction, isSqliteCorruptionError (@krusch/toolkit/db)
raw-node-sqlite new DatabaseSync(...) (node:sqlite) openSqliteDb, escapeFts5Query, fuseRrfResults (@krusch/toolkit/sqlite)
raw-fastapi-boilerplate CORSMiddleware + @app.get("/health") create_fastapi_app (krusch_toolkit.fastapi_app)
unaborted-useeffect-fetch fetch(...) inside useEffect(...) without signal useApiQuery, useSSEStream, or fetchApiJson (@krusch/toolkit/react)
raw-webhook-hmac createHmac(...) on Slack/GitHub/Stripe headers verifySlackSignature, verifyGithubSignature, verifyStripeSignature (./webhooks)
raw-multer-upload multer(...) multipart middleware parseBoundedMultipart, verifyUploadMime, sanitizeUploadFilename (./upload)
unsafe-yaml-load yaml.load() / unsafe_load() / js-yaml load() parseSafeYaml, loadSafeYamlPack (./yaml or krusch_toolkit.yaml_loader)

Brownfield Adoption Without Breaking Legacy Callers (INV-LEGO-25)

Strict greenfield envelopes ({ ok, tool, summary, data }) are clean for new services, but migrating mature production backends—such as our Sovereign Legal & Corporate RAG engines (krusch-law, krusch-biz, and krusch-bizlaw)—poses a classic compatibility trap: existing Streamlit UIs, MCP gateways, and integration tests already expect top-level health keys (status, database_connected, security) and FastAPI's native {"detail": ...} error field.

Rather than forking the brick or breaking callers, INV-LEGO-25 extended krusch_toolkit.fastapi_app.create_fastapi_app with opt-in brownfield adapters (flatten_health_payload=True, legacy_error_detail=True, and inspect.signature-dispatched health_check(request) probes) while keeping default v1.6.0 behavior byte-identical. All three legal/corporate backends migrated to 0 krusch-lego audit boilerplate findings with 100% backward-compatible REST and CI suites.

5. Stopping Utility-Library Bloat: The Autonomous Rule-of-3 lego-scout Engine

If a pre-commit guard tells agents "use bricks for recurring infrastructure," the natural Failure Mode #2 appears immediately: what stops every developer or autonomous agent from turning every clever 40-line helper into Brick #36, #37, …, #200?

Bloated shared toolkits destroy agent performance. Every unnecessary export inflates AGENTS.md token budgets, dilutes BM25/vector tool retrieval precision, and couples unrelated domain models together.

To govern when code is allowed into @krusch/toolkit and krusch_toolkit, we built @krusch/toolkit/lego-scout (INV-LEGO-15, exposed via krusch-lego scout <projects-root>) and wired it directly into our 24/7 autonomous Jean SRE sweep daemon (focus: 'lego_scout'). On each sweep across 100 workspace repositories (3,150 source files, symlink-contained via fs.realpathSync and scrubbed to portable <HOMELAB_ROOT>/projects/... paths for zero-leak dataset export), scoutHomelabLegoCandidates classifies every detected pattern into three mutually exclusive tiers:

  1. Tier A — LEGO-ADOPT (Existing Brick Not Yet Adopted): Files in brownfield repositories that still hand-roll patterns already solved by a certified brick. Rather than rewriting 37 repositories unattended, Jean SRE logs prioritized adoption tickets behind /jean-loop-gate human review. When we migrated home-ai from js-yaml to @krusch/toolkit/yaml from a Tier-A ticket, the brick's strict validation surfaced and fixed a latent pre-validation config cache-poisoning bug.
  2. Tier B — CANDIDATE_MEETS_RULE_OF_3 (≥ 3 Independent Repositories): Infrastructure plumbing—never domain business logic—that appears independently across at least three separate repositories. Across Waves 4, 5, and 6, lego-scout empirically nominated 8 cross-repo clusters, and we promoted all 8 (100% Rule-of-3 coverage, 0 uncovered clusters remaining):
    • schema-contract-validation (16 repos using ad-hoc Zod/Ajv/JSON-Schema glue) → @krusch/toolkit/schema & krusch_toolkit.schema (INV-LEGO-17, INV-LEGO-20).
    • python-httpx-resilience (12 repos repeating raw httpx.AsyncClient retries/timeouts) → krusch_toolkit.http_client (INV-LEGO-21).
    • multipart-file-upload (10 repos wiring multer/busboy/python-multipart) → @krusch/toolkit/upload & krusch_toolkit.upload (INV-LEGO-18, INV-LEGO-20).
    • yaml-safe-config-loader (10 repos loading PyYAML/js-yaml configs & authority packs) → @krusch/toolkit/yaml & krusch_toolkit.yaml_loader (INV-LEGO-23).
    • cascade-swarm-routing (9 repos wiring L1–L3 tier selection & burst fallbacks) → @krusch/toolkit/cascade (INV-LEGO-19).
    • voice-whisper-audio (9 repos framing RIFF/WAVE PCM16 buffers & Whisper/TTS calls) → @krusch/toolkit/audio (INV-LEGO-20).
    • python-sqlalchemy-wal-pool (9 repos configuring create_engine/SQLite WAL pragmas) → krusch_toolkit.db_async (INV-LEGO-24).
    • streamlit-rag-shell (6 repos duplicating air-gapped glassmorphism CSS & citation HTML) → krusch_toolkit.streamlit_ui (INV-LEGO-22).
  3. Tier C — BELOW_THRESHOLD_DO_NOT_EXTRACT (< 3 Repositories — Hard Anti-Bloat Gate): Patterns found in only 1 or 2 repositories—such as single-domain XML parsers (fast-xml-parser / xml2js), OpenXML slide note injectors, or PDF OCR heuristics—are explicitly tagged keep-project-local. Even within promoted bricks, lego-scout enforces strict seam discipline: @krusch/toolkit/upload owns bounded RFC 7578 stream parsing and MIME magic bytes, while PDF/OCR chunking stays local to the RAG engine; @krusch/toolkit/yaml owns alias-bomb-safe YAML 1.2 + SHA-256 pack digests, while statutory slot schemas stay local to krusch-authority-packs.

6. Teaching Local Weights the Bricks: Wave-3 QLoRA SFT + DPO Calibration

External MCP guards guarantee that bad boilerplate cannot land, but if local open-weights models (Qwen3-Coder-30B-A3B at L2 and openai/gpt-oss-120b at L2.5) do not know our Lego bricks in their weights, two inefficiencies remain:

  1. First-Turn Synthesis Misses: When queried without external MCP documentation (--no-tools), stock open-weights models scored only 25.0% (1/4) on Wave-3 Lego & Rule-of-3 synthesis prompts—reaching for raw DatabaseSync, unescaped FTS5 MATCH strings, and premature 1-repo utility extractions.
  2. Referee Over-Flagging on Compliant Bricks: When we ran our initial SFT-tuned 120B Referee auditor across 11 clean Lego slices, 8/11 passed CLEAN_PASS (and caught one real bug, SRE-01 callback error-envelope wrapping in lib/cli.js), but 3/11 invented stylistic nitpicks. Inspecting our distillation exporter (export-120b-distillation.js) revealed why: scoreElitistTrajectory filtered out responses shorter than 400 characters and rewarded [BUG-*] tags—leaving zero CLEAN_PASS (findings: []) examples in the training set. We had inadvertently trained the Referee that an audit is only "good" if it finds a bug.

The 2-Stage SFT + DPO Recipe (18,049 Zero-Leak Records, 4.18 CUs)

To fix both first-turn synthesis and Referee calibration simultaneously, we built a 2-stage training pipeline (harvest_lego_and_referee_calibration.js) exported to krush420/sovereign-code-audit-sft and gated by 10/10 verifyZeroLeaks checks (0 private IPs/hostnames/paths, 0 benchmark oracle tokens across 37,524 total split rows):

Model & Cascade Tier Training Configuration (96 GB Blackwell G4) Loss & Preference Margin GGUF Fusion & Live Accuracy Lift
Qwen/Qwen3-Coder-30B-A3B-Instruct
L2 Local MoE Student (3B active)
krush420/qwen3-coder-30b-sre-lora
8192 ctx · Stage-1 QLoRA SFT (320 trajs) + Stage-2 DPO (beta=0.1) · 59.34 GB peak VRAM SFT: 1.0523 → 0.9265 (75.42% tok acc)
DPO: 0.7014 → 0.4457 (+0.6325 margin)
51.03 MB GGUF · 192/192 tensor pairs fused in 6.81s (0 GEMV overhead) · --no-tools Lego & Rule-of-3: 25.0% → 100.0% (4/4) + 100% P0 FTS5 recall
openai/gpt-oss-120b
L2.5 Burst Teacher (116.8B / 5.1B active)
krush420/gpt-oss-120b-sre-lora
5120 ctx eager attention (74.89 GB peak VRAM vs. 95.3 GiB BF16 [1,64,S,S] OOM at 8K) · MXFP4 QLoRA SFT + DPO SFT: 1.8257 → 1.3664 (60.55% → 68.02%)
DPO: 0.6931 → 0.5824 (+0.2438 margin)
45.58 MB GGUF · In-place GGUF fusion in ~1.7s (preserves MXFP4 experts & Harmony renderer) · Calibrated CLEAN_PASS Referee convergence
Zero-Overhead GGUF LoRA Fusion on Ollama ≥ 0.40: Rather than serving dynamic LoRA adapters at inference time (which adds per-token GEMV kernel overhead and can conflict with quantized MoE expert routing), fuse_lora_into_gguf.py dequantizes only the 192 targeted Q4_K/Q6_K attention tensors, adds ΔW = (α / r) · B · A in FP32, and re-quantizes in place in 1.7s–6.81s—preserving native 124+ tok/s local MoE throughput.

7. Honest Tradeoffs, Failure Boundaries & Where Bricks Hurt

Where Shared Lego Systems Bite Back: Centralizing infrastructure into 35 bricks eliminates copy-paste bugs, but it introduces four real engineering costs that have to be managed explicitly rather than swept under the rug.
  1. Blast-Radius Concentration Requires Heavy Spec Discipline: When 40 services hand-roll SQLite wrappers, a bug in one breaks one app; when 40 services import @krusch/toolkit/db, a regression in initDb or readBoundedJsonBody breaks the fleet. That blast radius is why every toolkit wave is treated as an L0 architectural change: frozen spec.md contracts, fault-injected VFS/socket tests (122/122 Node suites + 199/199 pytest suites), and Dual-Zero Cross-Family Referee Convergence (Passes #15 & #16 consecutive 0 findings on Wave 4; Passes #9 & #10 consecutive 0 findings on Wave 6) before sync.
  2. Monorepo Sibling Paths vs. Standalone Public CI: Inside our monorepo, workspace services resolve "@krusch/toolkit": "file:../../lib" or sibling lib-py/ directly. When an individual sub-project (krusch-law or krusch-biz) is pushed to its own standalone public GitHub repository, GitHub Actions runners do not have ../../lib-py mounted unless the package is installed from a registry or shimmed. Until krusch-toolkit is published to PyPI/npm as a standalone semver artifact, standalone repos require explicit except ImportError: CI shims (INV-LEGO-25) or vendored wheels.
  3. 100% Cluster Coverage ≠ 100% Consumer Migration (37 Repos Pending): Promoting all 8/8 Rule-of-3 clusters means every recurring infrastructure pattern in our 100-repo workspace now has a certified brick—not that every legacy repository has been rewritten overnight. krusch-lego scout currently tracks 37 brownfield projects with open LEGO-ADOPT opportunities (primarily legacy pg.Pool scripts and older React views). By design, we migrate those incrementally under test-gated /jean-loop-gate reviews (home-ai, jean-sre, krusch-law, krusch-biz, krusch-bizlaw completed first) rather than letting an autonomous daemon mass-refactor 37 repos unattended.
  4. Weight Staleness Between Fine-Tuning Waves: Our Wave-3 QLoRA + DPO adapters (qwen3-coder-30b-sre-lora and gpt-oss-120b-sre-lora) baked Waves 1–3 (24 bricks) directly into model weights (100% --no-tools recall). Bricks promoted hours later in Waves 4–6 (schema, upload, cascade, audio, http_client, streamlit_ui, yaml, db_async) rely on Tier-1 AGENTS.md context hydration + Stage-2 MCP pre_commit nudges until the next periodic SFT/DPO refresh cycle folds Waves 4–6 trajectories into the weights.

8. Quickstart & Verification Commands

Every CLI inspector, boilerplate auditor, zero-LLM blueprint stamper, and fine-tuned LoRA adapter described in this paper is runnable locally with zero cloud API keys:

# 1. List all 35 certified runtime bricks (Node/TS/React/Edge/Python) & 7 blueprints
node lib/bin/krusch-lego.js list

# 2. Inspect exact exports, canonical snippet & replaced anti-pattern for any brick
node lib/bin/krusch-lego.js inspect security
node lib/bin/krusch-lego.js inspect python_yaml

# 3. Stamp a complete zero-LLM TypeScript, MCP, Cloudflare Worker, or FastAPI service in <15ms
node lib/bin/krusch-lego.js stamp node-ts-service ./my-service --port 3010
node lib/bin/krusch-lego.js stamp python-fastapi-service ./my-py-api --port 8090

# 4. Run the 10-rule comment/string-masked boilerplate guard against any file or repo
node lib/bin/krusch-lego.js audit ./projects/my-service --json

# 5. Scan an entire multi-repo workspace for LEGO-ADOPT & Rule-of-3 cluster candidates
node lib/bin/krusch-lego.js scout ./projects --json

# 6. Verify all 122 Node tests, 60 strict .d.ts subpaths, and 199 Python pytest tests
(cd lib && npm test && npx tsc --noEmit)
(cd lib-py && pytest -q)

Public Artifacts & Open Weights

Explore the Certified Stack & Open-Weights LoRA Adapters

npx krusch-stack init --defer-tools · 35 Certified Bricks · 18,049 Zero-Leak SFT + DPO Rows

GitHub: krusch-stack → 🤗 HF SFT + DPO Dataset → Audit & Distillation Pipeline →