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.
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:
-
HTTP
413TCPECONNRESETRaces (INV-LEGO-03,INV-LEGO-18): When enforcing a payload byte cap onnode:httpor multipart uploads, LLM-generated handlers routinely callres.writeHead(413)followed immediately byreq.destroy()while the client is still streaming body chunks. At the kernel socket layer, destroying an unread incoming stream sends a TCPRSTpacket that tears down the connection before the client reads the HTTP413JSON body—producing flakyECONNRESETfailures in CI (caught live inkrusch-stackGitHub Actions run40877285884). -
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-flightdns.lookup()before callingfetch(url)orhttpx.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 and169.254.169.254(cloud metadata) or127.0.0.1on the second socket-connect lookup; (b) IPv6 transition bypasses (::ffff:127.0.0.1,6to42002::/16,Teredo2001:0000::/32, octal/hex IPv4 literals, and Unicode IDNA homographs); and (c) cross-origin302redirects that silently forwardAuthorizationandCookieheaders to an untrusted host. -
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.dbfile aside as "corrupted." Under container memory pressure or lock contention, SQLite throwsSQLITE_NOMEM,SQLITE_BUSY, orENOSPC—notSQLITE_CORRUPTorSQLITE_NOTADB. Treating transient resource exhaustion as structural corruption causes an agent daemon to quarantine a healthy live database. -
FTS5 Query Syntax Injection & Leaked GPU Streams (
INV-LEGO-03,INV-LEGO-12): Passing raw user search text ("c++ router: fast-path?") into SQLiteMATCHcrashes immediately withfts5: syntax error near "+". Meanwhile, SSE endpoints withoutX-Accel-Buffering: noandreq.on('close', () => controller.abort())keep local Ollama GPUs generating thousands of orphaned tokens after a browser tab closes, and ReactuseEffect(() => { fetch(...) }, [])hooks withoutAbortControllertrigger stale-state races on rapid navigation. -
YAML 1.1 "Norway Bugs", Arbitrary Tags & Billion-Laughs Alias Bombs (
INV-LEGO-23): Default configuration loaders (yaml.loadinjs-yamlor unguardedPyYAML) silently coerce country codes (NO→false), turn ISO date strings into language-specificDate/datetimeobjects that break JSON schema checks, accept!!python/...or!!js/...tags, and expand recursive&a [*a, *a]anchor graphs exponentially until the process OOMs. -
Length-Leaking Webhook HMACs (
INV-LEGO-09): Hand-rolled Slack, GitHub, and Stripe webhook verifiers frequently callcrypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))without checking byte lengths first—throwing an uncaughtRangeError500on 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:
- Stage 1 (
krusch-lego stamp+ Subpath Imports): Gives humans and coding agents instant, zero-LLM project skeletons and small, composable runtime modules across Node 22 ESM, TypeScript, React, Cloudflare Workers, and Python 3.12. - Stage 2 (
krusch_context_nudge+krusch-lego audit): Deterministically inspects staged diffs before commit, rejecting rawpg.Pool,DatabaseSync,StdioServerTransport,multer, unsafeyaml.load, manual SSE headers, raw webhook HMACs, and un-aborted ReactuseEffectfetches. - Stage 3 (
krusch-lego scout+ Jean SRE): Continuously audits all100workspace projects, surfacing brownfield adoption targets (LEGO-ADOPT) and gating new toolkit extractions behind an empirical Rule-of-3 threshold (≥ 3independent repositories). - Stage 4 (
/spec-first-refactor+ Referee Convergence): Freezes module signatures and error codes inspec.md, builds disjoint modules in parallel, and requires two consecutive zero-finding passes from a blind cross-family Referee auditor before promotion. - Stage 5 (Wave-3 QLoRA SFT +
trl.DPOTrainer): Distills the new bricks,CLEAN_PASSaudits, and Rule-of-3 architectural judgments directly into local30Band120BMoE GGUF weights so agents reach for the right brick on turn 1—without burning retry loops against the pre-commit gate.
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:
- Zero-Build Runtime ESM +
60Strict.d.tsSubpaths:@krusch/toolkitexecutes directly as native Node 22.jsESM with zero transpilation step, while shipping hand-audited.d.tsdeclarations ("types"condition before"default"inpackage.jsonexports) verified viatsc --noEmit --strictagainst downstream.tsconsumers. - Zero-
node:*Isomorphic Purity:@krusch/toolkit/edge,./schema,./yaml,./cascade, and./audiocontain zeronode:*imports (enforced by static regex tests), executing unmodified across Cloudflare Workers, browser bundles, Deno, Bun, and Node 22. - Headless Optional Peers & Bare-Stdlib Python:
@krusch/toolkit/reactresolvesreactlazily (await import('react')withsetReactRuntimeinjection) so headless backend tests import UI tokens cleanly withoutnode_modules/react. Likewise, all 10 Python bricks inkrusch_toolkitv1.6.0import cleanly in bare Python 3.11+ stdlib even whenfastapi,httpx,streamlit,sqlalchemy, orPyYAMLare absent—loading heavy frameworks lazily at call time or accepting injected mocks for millisecond unit tests.
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:
node-api-sqlite(11files) — Node 22 ESM API + crash-safe SQLite WAL + test suite.node-ts-service(12files) — Zero-build TypeScript (tsc --noEmit --strict) + Node 22 ESM + SQLite WAL.node-rag-pgvector(12files) — Sovereign1024dsnowflake-arctic-embed2RAG API +pgvectormigrations.mcp-stdio-server(10files) — Stdio MCP server with mandatory 4-boolean tool annotations (INV-STACK-03).fullstack-react-vite(16files) — Node 22 SSE streaming backend + Vite ReactAppShell(useSSEStream).python-fastapi-service(10files) — Python 3.12create_fastapi_appservice +pytestsuite.cloudflare-worker(9files) — Zero-node:*Edge router + KV JSON store + SSE (wrangler.toml).
4. Deterministic Enforcement: Catching Hand-Rolled Plumbing Before Commit
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:
- Parses unified git diffs into added lines vs. surviving file context (so editing an unrelated line in a legacy file never triggers false alarms, while adding new boilerplate is caught immediately).
- Tracks JS regex literals (
tryScanJsRegexwith prefix-keyword disambiguation), nested${...}template literal brace stacks, Python triple-quoted strings ('''/"""), and#/////* ... */comments without shifting newline offsets. - Enforces
10high-precision anti-pattern rules across JS/TS/JSX/TSX and Python:
| 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:
-
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 rewriting37repositories unattended, Jean SRE logs prioritized adoption tickets behind/jean-loop-gatehuman review. When we migratedhome-aifromjs-yamlto@krusch/toolkit/yamlfrom a Tier-A ticket, the brick's strict validation surfaced and fixed a latent pre-validation config cache-poisoning bug. -
Tier B —
CANDIDATE_MEETS_RULE_OF_3(≥ 3Independent Repositories): Infrastructure plumbing—never domain business logic—that appears independently across at least three separate repositories. Across Waves 4, 5, and 6,lego-scoutempirically nominated8cross-repo clusters, and we promoted all8(100%Rule-of-3 coverage,0uncovered clusters remaining):schema-contract-validation(16repos using ad-hoc Zod/Ajv/JSON-Schema glue) →@krusch/toolkit/schema&krusch_toolkit.schema(INV-LEGO-17,INV-LEGO-20).python-httpx-resilience(12repos repeating rawhttpx.AsyncClientretries/timeouts) →krusch_toolkit.http_client(INV-LEGO-21).multipart-file-upload(10repos wiringmulter/busboy/python-multipart) →@krusch/toolkit/upload&krusch_toolkit.upload(INV-LEGO-18,INV-LEGO-20).yaml-safe-config-loader(10repos loadingPyYAML/js-yamlconfigs & authority packs) →@krusch/toolkit/yaml&krusch_toolkit.yaml_loader(INV-LEGO-23).cascade-swarm-routing(9repos wiring L1–L3 tier selection & burst fallbacks) →@krusch/toolkit/cascade(INV-LEGO-19).voice-whisper-audio(9repos framing RIFF/WAVE PCM16 buffers & Whisper/TTS calls) →@krusch/toolkit/audio(INV-LEGO-20).python-sqlalchemy-wal-pool(9repos configuringcreate_engine/SQLite WAL pragmas) →krusch_toolkit.db_async(INV-LEGO-24).streamlit-rag-shell(6repos duplicating air-gapped glassmorphism CSS & citation HTML) →krusch_toolkit.streamlit_ui(INV-LEGO-22).
-
Tier C —
BELOW_THRESHOLD_DO_NOT_EXTRACT(< 3Repositories — 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 taggedkeep-project-local. Even within promoted bricks,lego-scoutenforces strict seam discipline:@krusch/toolkit/uploadowns bounded RFC 7578 stream parsing and MIME magic bytes, while PDF/OCR chunking stays local to the RAG engine;@krusch/toolkit/yamlowns alias-bomb-safe YAML 1.2 + SHA-256 pack digests, while statutory slot schemas stay local tokrusch-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:
- First-Turn Synthesis Misses: When queried without external MCP documentation (
--no-tools), stock open-weights models scored only25.0%(1/4) on Wave-3 Lego & Rule-of-3 synthesis prompts—reaching for rawDatabaseSync, unescaped FTS5MATCHstrings, and premature 1-repo utility extractions. - Referee Over-Flagging on Compliant Bricks: When we ran our initial SFT-tuned
120BReferee auditor across 11 clean Lego slices,8/11passedCLEAN_PASS(and caught one real bug,SRE-01callback error-envelope wrapping inlib/cli.js), but3/11invented stylistic nitpicks. Inspecting our distillation exporter (export-120b-distillation.js) revealed why:scoreElitistTrajectoryfiltered out responses shorter than400characters and rewarded[BUG-*]tags—leaving zeroCLEAN_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):
- Stage 1 — Supervised Fine-Tuning (QLoRA SFT): Combines multi-file
gemini-4-argontest-verified remediations, 11-phase AST-grounded120Baudits, and38targeted calibration trajectories (10CLEAN_PASSzero-finding audits,10true-positive security/correctness remediations,14Lego-First brick implementations coveringopenSqliteDb+escapeFts5Query+ Reciprocal Rank FusionRRF(d) = ∑ᵢ wᵢ / (k + rankᵢ(d))+ DNS-pinnedsafeFetch, and4Rule-of-3lego-scoutarchitectural decisions). -
Stage 2 — Direct Preference Optimization (
trl.DPOTrainer,β = 0.1): Anchored to the Stage-1 SFT adapter across12balanced preference pairs (3xoversampled across Precision, Recall, and Architecture):- Precision pairs:
chosenemitsCLEAN_PASS(findings: []) on compliant@krusch/toolkitcode vs.rejectedhallucinating stylistic nitpicks. - Recall pairs:
chosenflags P0 FTS5 syntax injection / TOCTOU SSRF / transient SQLite quarantine vs.rejectedrubber-stamping broken code. - Architecture pairs:
chosenkeeps< 3-repo XML parsers project-local (BELOW_THRESHOLD_DO_NOT_EXTRACT) and adopts certified bricks for≥ 3-repo clusters vs.rejectedprematurely extracting single-repo helpers into@krusch/toolkit.
- Precision pairs:
| Model & Cascade Tier | Training Configuration (96 GB Blackwell G4) | Loss & Preference Margin | GGUF Fusion & Live Accuracy Lift |
|---|---|---|---|
Qwen/Qwen3-Coder-30B-A3B-InstructL2 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-120bL2.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 |
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
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.
-
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 ininitDborreadBoundedJsonBodybreaks the fleet. That blast radius is why every toolkit wave is treated as an L0 architectural change: frozenspec.mdcontracts, fault-injected VFS/socket tests (122/122Node suites +199/199pytestsuites), and Dual-Zero Cross-Family Referee Convergence (Passes #15 & #16consecutive0findings on Wave 4;Passes #9 & #10consecutive0findings on Wave 6) before sync. -
Monorepo Sibling Paths vs. Standalone Public CI:
Inside our monorepo, workspace services resolve
"@krusch/toolkit": "file:../../lib"or siblinglib-py/directly. When an individual sub-project (krusch-laworkrusch-biz) is pushed to its own standalone public GitHub repository, GitHub Actions runners do not have../../lib-pymounted unless the package is installed from a registry or shimmed. Untilkrusch-toolkitis published to PyPI/npm as a standalone semver artifact, standalone repos require explicitexcept ImportError:CI shims (INV-LEGO-25) or vendored wheels. -
100%Cluster Coverage ≠100%Consumer Migration (37Repos Pending): Promoting all8/8Rule-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 scoutcurrently tracks37brownfield projects with openLEGO-ADOPTopportunities (primarily legacypg.Poolscripts and older React views). By design, we migrate those incrementally under test-gated/jean-loop-gatereviews (home-ai,jean-sre,krusch-law,krusch-biz,krusch-bizlawcompleted first) rather than letting an autonomous daemon mass-refactor 37 repos unattended. -
Weight Staleness Between Fine-Tuning Waves:
Our Wave-3 QLoRA + DPO adapters (
qwen3-coder-30b-sre-loraandgpt-oss-120b-sre-lora) baked Waves 1–3 (24bricks) directly into model weights (100%--no-toolsrecall). Bricks promoted hours later in Waves 4–6 (schema,upload,cascade,audio,http_client,streamlit_ui,yaml,db_async) rely on Tier-1AGENTS.mdcontext hydration + Stage-2 MCPpre_commitnudges 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
- Unified 7-Pillar MCP & Agentic Stack (
39Tools + Canonical Templates):github.com/kruschdev/krusch-stack(npx krusch-stack init) - Autonomous 24/7 Auditor &
lego_scoutHarness:github.com/kruschdev/Jean-SRE-by-kruschdev - Zero-Leak SFT + DPO Dataset (
18,049Records):huggingface.co/datasets/krush420/sovereign-code-audit-sft - Fine-Tuned
L230B Student &L2.5120B Teacher Adapters:krush420/qwen3-coder-30b-sre-lora·krush420/gpt-oss-120b-sre-lora
Explore the Certified Stack & Open-Weights LoRA Adapters
npx krusch-stack init --defer-tools · 35 Certified Bricks · 18,049 Zero-Leak SFT + DPO Rows