Status:
FROZEN(2026-10-31T16:10:00-07:00) Packages:@krusch/toolkit(v1.7.0) &krusch-toolkit(python/v1.6.0) Enforcement:krusch-context-mcp(INV-LEGO-01),krusch-frontend-mcp,krusch-stack,scripts/verify-zero-leaks.js(INV-LEGO-26)
INV-LEGO-01(Universal Envelope Contract): Every HTTP helper, MCP tool helper, CLI inspector, and Python FastAPI factory MUST emit deterministic envelopes:- Success:
{ ok: true, tool: string, summary: string, data: object } - Error:
{ ok: false, tool: string, summary: string, error: { code: string, message: string, details?: any } }
- Success:
INV-LEGO-02(Zero Ghost Exports & Headless Import Safety): Every subpath documented inAGENTS.mdorlib/README.mdMUST exist on disk, be mapped inlib/package.jsonexports, and succeed underawait import(...)in pure Node 22 ESM even when optional UI peer libraries (react) are not installed locally inlib/node_modules.INV-LEGO-03(AbortController& Bounded Payload Safety):sseResponse,streamChat,fetchApiJson,useApiQuery, anduseSSEStreamMUST wireAbortControllerteardown on client disconnect / unmount / re-query.readBoundedJsonBodyMUST reject oversized bodies with HTTP413(PAYLOAD_TOO_LARGE) after draining/pausing safely without triggering raw TCPECONNRESETbefore headers flush.
INV-LEGO-04(OS-Drive & Portable Host Hygiene):- Zero retired or hardcoded private LAN, 10GbE, or Tailscale host IPs and zero retired model names (
spectralquant) inlib/scaffold.js,lib/catalog.js, orlib/llm-queue.js. - Generated
docker-compose.ymlblueprints MUST use Compose v2 syntax (no deprecated top-levelversion:), named or env-configurable data paths (${DATA_DIR:-./data}), and explicit comments warning against mounting persistent databases or model weights on OS boot drives. - Public-facing templates and runtime modules MUST obey
INV-STACK-04&INV-LEGO-26(127.0.0.1/localhost/ env vars only; zero hardcoded private LAN/CGNAT host IPs, zero host OS home or/mntpaths, and zero personal PII).
- Zero retired or hardcoded private LAN, 10GbE, or Tailscale host IPs and zero retired model names (
INV-LEGO-05(krusch-stackTool Count & Annotation Invariant):- Adding canonical Lego starter templates to
krusch-stack/src/engines/frontend-engine.jsMUST preserveALL_STACK_TOOLS.length === 39(INV-STACK-09) anddefineMcpToolinlib/mcp-server.jsMUST enforce all 4 boolean MCP annotations (readOnlyHint,destructiveHint,idempotentHint,openWorldHint) plustitle(INV-STACK-03).
- Adding canonical Lego starter templates to
INV-LEGO-06(krusch-context-mcpBEAM &INV-12Hygiene):projects/krusch-context-mcp/src/lego-boilerplate-guard.jsMUST contain zero BEAM oracle identifiers or dataset proper nouns banned bybenchmarks/verify_zero_leakage.js(probing_questions,source_chat_ids,ideal_response,OpenWeather,Formspree,BudgetTracker,Figma,Jira,Trello,DETAIL_HEAD_STEMS,ACTION_MODIFIER_STEMS), and MUST preserve39/39validINV-12span anchors.
INV-LEGO-07(GitHub Contributor Attribution):- Any commits or scaffolds embedding Git metadata/CI MUST attribute to
kruschdev <kruschdev@users.noreply.github.com>.
- Any commits or scaffolds embedding Git metadata/CI MUST attribute to
lib/http.js(@krusch/toolkit/http):okEnvelope(tool, summary, data = {})->{ ok: true, tool, summary, data }errorEnvelope(code, message, details = null, tool = 'http')->{ ok: false, tool, summary: message, error: { code, message, details } }asyncHandler(fn)->(req, res, next) => Promise.resolve(fn(req, res, next)).catch(next)readBoundedJsonBody(req, res, { maxBytes = 1048576 } = {})->Promise<object>: Safely reads UTF-8 JSON up tomaxBytes; if exceeded, drains remaining stream chunks safely and responds413JSONerrorEnvelope('PAYLOAD_TOO_LARGE', ...)returningnull; on malformed JSON responds400INVALID_JSONreturningnull.createCorsHeaders(origin, allowedOrigins = ['*'])-> headers object.createExpressBricks({ serviceName = 'krusch-service', version = '1.0.0', corsOrigins = ['*'], healthCheck = null, logger = null } = {})->{ requestContextMiddleware, corsMiddleware, healthHandler, doctorHandler, notFoundHandler, errorHandler }.createApiServer({ serviceName = 'krusch-service', version = '1.0.0', corsOrigins = ['*'], maxBodyBytes = 1048576, healthCheck = null, routes = {}, logger = null } = {}): Lightweight zero-Express nativenode:http.Serverrouter supporting"GET /path"/"POST /path"handlers(ctx) => object | voidwherectx = { req, res, url, query, body, requestId, sendJson }, built-inGET /health&GET /doctor,OPTIONSpreflight, 404/500 JSON envelopes.attachGracefulShutdown(server, cleanupFns = [], { timeoutMs = 5000, logger = null, signals = ['SIGTERM', 'SIGINT'] } = {})->{ shutdown, detach }.
lib/streaming.js(@krusch/toolkit/streaming):sseResponse(res, req = null, { heartbeatMs = 15000, corsOrigin = '*', retryMs = 3000 } = {}):- Writes HTTP
200headers (Content-Type: text/event-stream; charset=utf-8,Cache-Control: no-cache, no-transform,Connection: keep-alive,X-Accel-Buffering: no,Access-Control-Allow-Origin). Callsres.flushHeaders?.(). - Creates an
AbortController(controller.signal) automatically aborted whenreqorresemits'close'or'aborted', clearing the heartbeat timer. - Returns
{ signal, isClosed: () => boolean, send(event, data), sendToken(delta, meta), done(summaryOrPayload), error(err), close() }.
- Writes HTTP
streamChat(res, req, { systemPrompt = '', userMessage = '', config = {}, chatFn = null, fetchImpl = globalThis.fetch, tool = 'streamChat' } = {}):- Opens
sseResponse(res, req). - If
config.provider === 'ollama'and!chatFn, streams NDJSON/api/chat(stream: true) withsignalfromsse.signal, emittingsendToken(chunk)per delta anddone({ ok: true, tool, summary: 'Stream complete', data: { text } }). - Otherwise invokes
chatFn || chat(./llm.js), checkssse.signal.aborted, emitssendToken+done, and catches errors intosse.error(err).
- Opens
lib/mcp-server.js(@krusch/toolkit/mcp&@krusch/toolkit/mcp-server):defineMcpTool({ name, title, description, inputSchema, readOnlyHint = true, destructiveHint = false, idempotentHint = true, openWorldHint = false }): Returns normalized MCP tool definition with mandatory 4-booleanannotations+title(INV-STACK-03).okMcpResult(tool, summary, data = {}): Returns{ content: [{ type: 'text', text: JSON.stringify({ ok: true, tool, summary, data }) }] }.errorMcpResult(tool, code, message, details = null): Returns{ isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, tool, summary: message, error: { code, message, details } }) }] }.validateToolArgs(toolDef, args = {}): Deterministic check forinputSchema.requiredfields.createMcpServer(name, version, tools, toolHandler, options = {}): Preserves backward compatibility with existing signature while normalizingtoolsviadefineMcpToolif annotations are omitted, validating required args whenoptions.validateArgs !== false, and catching handler exceptions cleanly.
lib/pg.js(@krusch/toolkit/pg):buildPgConnectionString(dbConfig = {}): ResolvesdbConfig.url || process.env.DATABASE_URLor constructspostgresql://user:pass@host:port/databasesafely (encodeURIComponent).createPgPool(dbConfig = {}, { serviceName = 'krusch-pg', max = 15, idleTimeoutMillis = 30000, connectionTimeoutMillis = 3000, PoolClass = null, logger = null } = {}): Returns{ pool, query, queryOne, withTransaction, healthCheck, close }.runSqlMigrations(pgClientOrWrapper, migrations = [], { tableName = 'schema_migrations' } = {}): Runs idempotent{ id, sql }migrations insideBEGIN/COMMITtransactions, returning{ ok: true, tool: 'pg.migrate', summary, data: { applied: string[], skipped: string[] } }.pgVectorSearch(pgWrapper, { table, embeddingColumn = 'embedding', vector, selectColumns = ['id'], whereSql = '', params = [], limit = 10, expectedDims = 1024 } = {}): Validates table/column identifiers (^[a-zA-Z_][a-zA-Z0-9_]*$) against SQL injection, validatesvector.length === expectedDimsviavalidateVectorDimension(./embeddings.js), formats[v1,v2,...]::vector, and executes<=>cosine similarity search returning{ ok: true, tool: 'pg.vectorSearch', summary, data: { rows } }.
lib/llm-queue.js(@krusch/toolkit/llm-queue):- Default
DEFAULT_FLEET_OLLAMA_NODESto portable loopback (Object.freeze(['http://127.0.0.1:11434'])) overridable viaOLLAMA_NODES/OLLAMA_URL, preservingPRIORITY,AsyncLock, andPriorityQueueexports.
- Default
lib/react.js(@krusch/toolkit/react):- Headless-safe React resolution:
let _React = null; try { _React = await import('react'); } catch { _React = null; }plusexport function setReactRuntime(runtime)andexport function getReactRuntime(). - Preserve existing exports:
cn,STYLES,useMounted,useMediaQuery,useClickOutside,useCopyToClipboard. - Add
useAesthetics(variant = 'cyber'): Pure/hook token resolver returning{ surface, glow, headingText, bg, badge, buttonPrimary, input }class bundles (usable even without React state, or memoized when_React?.useMemois present). - Add
fetchApiJson(url, { signal, timeoutMs = 15000, headers = {}, ...init } = {}): Combines callersignal+ timeoutAbortController, parses JSON, unwraps{ ok, data, error }, throws structured Error on!res.ok || body?.ok === false. - Add
useApiQuery(url, { enabled = true, deps = [], fetchImpl = globalThis.fetch, initialData = null } = {}): React hook creatingnew AbortController()insideuseEffect, aborting in cleanup (() => controller.abort()), returning{ data, loading, error, reload }. - Add
useSSEStream(url, { fetchImpl = globalThis.fetch, method = 'POST' } = {}): React hook managing streaming SSE requests withAbortController, parsingdata: ...SSE lines, accumulatingtext&events, returning{ text, events, status, error, start, stop, reset }. - Add pure
createElementLego UI Components (AppShell,StatusPill,MetricCard,ErrorBoundary,StreamingChatPanel) usinggetReactRuntime().createElement.
- Headless-safe React resolution:
lib/catalog.js(@krusch/toolkit/catalog):RUNTIME_BRICKS: Frozen catalog array of core Lego bricks, each with{ id, runtime: 'node'|'python'|'react'|'edge', importPath, exports, summary, snippet, replacesBoilerplate }.PROJECT_ARCHETYPES: Frozen dictionary of 7 zero-LLM project blueprints (node-api-sqlite,node-rag-pgvector,mcp-stdio-server,fullstack-react-vite,python-fastapi-service,node-ts-service,cloudflare-worker), each with{ id, title, runtime, description, renderFiles({ projectName, port }) }.listLegoBricks({ runtime } = {}),getLegoBrick(id),listArchetypes(),getArchetype(id),auditBoilerplateText(code, filePath = '')->{ ok: true, tool: 'lego.catalog', summary, data: { findings } }.
lib/scaffold.js(@krusch/toolkit/scaffold):scaffoldProject(targetDir = process.cwd(), { archetype = 'node-api-sqlite', projectName = '', port = 3000, force = false, dryRun = false, quiet = false } = {}).
lib/bin/krusch-lego.js:- Executable (
#!/usr/bin/env node) zero-LLM CLI supportinglist,inspect,stamp,audit, andscout.
- Executable (
Subagent 5 — Disjoint Files: lib-py/krusch_toolkit/fastapi_app.py, lib-py/tests/test_fastapi_lego.py
lib-py/krusch_toolkit/fastapi_app.py:ok_envelope,error_envelope,format_sse_frame,create_fastapi_app,sse_event_response.
Subagent 6 — Disjoint Files: projects/krusch-context-mcp/src/lego-boilerplate-guard.js, projects/krusch-context-mcp/tests/lego-boilerplate-guard.test.js
projects/krusch-context-mcp/src/lego-boilerplate-guard.js:- Zero BEAM-banned tokens (
INV-LEGO-06). - Exports
detectHandRolledBoilerplate(code = '', filePath = '').
- Zero BEAM-banned tokens (
INV-LEGO-08(Web-Standards Edge Runtime Purity —@krusch/toolkit/edge):lib/edge.jsMUST contain zeronode:*imports so it executes unmodified on Cloudflare Workers, Pages Functions, Deno, Bun, and Node 22 Webfetch(request, env, ctx).edgeCorsHeadersMUST rejectOrigin: null,Origin: false, and CR/LF characters;readBoundedEdgeJsonMUST enforcemaxBytesacross bothContent-Lengthheaders and chunkedReadableStreambodies (413 PAYLOAD_TOO_LARGE);edgeSseResponseMUST propagateAbortSignalteardown on streamcancel()orrequest.signalabort;createEdgeRouterMUST emitINV-LEGO-01envelopes on/health,/doctor,404,413, and500(including CORS headers on error responses).
INV-LEGO-09(Constant-Time Webhook & Bearer Verification —@krusch/toolkit/webhooks):lib/webhooks.jsMUST verify HMAC-SHA256 signatures (verifySlackSignature,verifyGithubSignature,verifyStripeSignature) andverifyBearerTokenusingcrypto.timingSafeEqualONLY after verifying identical byte lengths, rejecting missing/blank secrets fail-closed, enforcing replay-window bounds (toleranceSeconds, rejecting NaN/expired/future timestamps), and returningINV-LEGO-01{ ok, tool, summary, data | error }envelopes without throwing on untrusted caller headers.
INV-LEGO-10(Atomic Single-Instance CLI & Daemon Lifecycle —@krusch/toolkit/cli):lib/cli.jsMUST use exclusivewxlockfile creation inwithSingleInstanceLockwith live-PID (process.kill(pid, 0)) +staleMsreclamation, callback exception wrapping intoCALLBACK_ERRORerrorEnvelope(SRE-01), and guaranteedfinallyunlink (only unlinking lockfiles owned by the current invocation),attachDaemonSignalswithAbortSignalpropagation,appendJsonlRecord, anddefineCliemittingINV-LEGO-01JSON envelopes under--json.
INV-LEGO-11(Zero-Build TypeScript Declaration Parity —lib/types/*.d.ts):@krusch/toolkitMUST remain zero-build runtime ESM.jswhile exposing strict.d.tsdeclarations ("types"condition before"default"inlib/package.json"exports") verified bytsc --noEmit --strictagainst consumer.tsimports, plusnode-ts-serviceandcloudflare-workerarchetypes inlib/catalog.js.
-
INV-LEGO-12(Zero-Native-Addonnode:sqlite+ FTS5 Escaping + Hybrid RRF —@krusch/toolkit/sqlite):-
Disjoint Files:
lib/sqlite.js,lib/types/sqlite.d.ts - Uses Node 22 built-in
DatabaseSync(node:sqlite) with zero native addon dependencies, applyingINV-REC-01..05WAL durability pragmas (busy_timeout = 5000,journal_mode = WAL,synchronous = NORMAL,wal_autocheckpoint = 1000,foreign_keys = ON) and closing the handle on pragma failure without leaking descriptors. - Exact exports:
-
openSqliteDb(dbPath = ':memory:', { wal = true, busyTimeout = 5000, synchronous, walAutocheckpoint = 1000, readOnly = false, DatabaseClass = null } = {}):- Returns
{ db, dbPath, isOpen: () => boolean, exec(sql), run(sql, params = []), query(sql, params = []), queryOne(sql, params = []), transaction(fn), healthCheck(), close() }. -
queryandqueryOnenormalize null-prototypenode:sqliterows into standard plain objects ({ ...row }). -
transaction(fn)usesBEGIN IMMEDIATEat depth 0 andSAVEPOINT sp_<depth>when nested, rolling back cleanly on exception without masking the original error. -
healthCheck()returnsINV-LEGO-01okEnvelope('sqlite.health', ...)orerrorEnvelope('SQLITE_UNHEALTHY', ...)without throwing.
- Returns
-
escapeFts5Query(rawQuery = '', { operator = 'AND', prefixLastToken = false, maxTokens = 32 } = {}):- Extracts Unicode alphanumeric/underscore tokens (
[\p{L}\p{N}_]+u), caps input length (<= 2048chars) and token count (maxTokens), wraps each token in double quotes ("token", escaping internal"as""), optionally appends*after the final quoted token ("tok"*) whenprefixLastToken === true, and joins with validated' AND 'or' OR '. Returns''when zero tokens match so callers never triggerfts5: syntax error.
- Extracts Unicode alphanumeric/underscore tokens (
-
fuseRrfResults(rankedLists = [], { k = 60, idKey = 'id', limit = 20, weights = [] } = {}):- Prototype-safe (
Object.hasOwn) Reciprocal Rank Fusion computing$\sum_i w_i / (k + \text{rank}_i)$ (1-indexedrank,k >= 1), deduplicating byString(item[idKey]), attachingrrfScore, sorting descending with deterministicString(id)tie-breaker, and slicing tolimit.
- Prototype-safe (
- Re-exports
DatabaseSyncfromnode:sqliteandisSqliteCorruptionErrorfrom./db.js.
-
-
Disjoint Files:
-
INV-LEGO-13(DNS-Rebinding-Safe SSRFsafeFetch& Bounded Rate Limiter —@krusch/toolkit/security):-
Disjoint Files:
lib/security.js,lib/types/security.d.ts - Exact exports:
-
isPrivateOrReservedIp(ipString = '', { allowPrivateLan = false, allowTailscale = false } = {}):- Fail-closed IPv4 + IPv6 classifier blocking unspecified (
0.0.0.0/8,::), loopback (127.0.0.0/8,::1), link-local / cloud metadata (169.254.0.0/16,fe80::/10), multicast/reserved/documentation/benchmarking ranges (192.0.0.0/24,192.0.2.0/24,198.18.0.0/15,198.51.100.0/24,203.0.113.0/24,224.0.0.0/4,ff00::/8), IPv4-mapped/compatible/6to4/Teredo IPv6 (::ffff:0:0/96,2002::/16,2001:0000::/32), non-canonical octal/hex/single-integer IPv4 literals, Tailscale CGNAT (100.64.0.0/10unlessallowTailscale === true), and RFC1918/ULA (10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7unlessallowPrivateLan === true).
- Fail-closed IPv4 + IPv6 classifier blocking unspecified (
-
validateOutboundUrl(rawUrl, { allowedProtocols = ['https:', 'http:'], allowPrivateLan = false, allowTailscale = false, allowedHosts = null, lookupFn = null, tool = 'security.ssrf' } = {}):- Async non-throwing validator returning
INV-LEGO-01okEnvelope({ url, hostname, port, resolvedAddresses }) orerrorEnvelope(SSRF_INVALID_URL,SSRF_BLOCKED_PROTOCOL,SSRF_CREDENTIALS_FORBIDDEN,SSRF_HOST_NOT_ALLOWED,SSRF_PRIVATE_IP,SSRF_DNS_FAILED). Rejects embedded URL credentials, localhost/metadata hostnames, and resolves all A/AAAA records, failing closed if any record is private/reserved.
- Async non-throwing validator returning
-
safeFetch(rawUrl, init = {}, { maxRedirects = 3, timeoutMs = 15000, allowPrivateLan = false, allowTailscale = false, allowedHosts = null, lookupFn = null, fetchImpl = globalThis.fetch, tool = 'security.fetch' } = {}):- Validates every hop via
validateOutboundUrl, enforces DNS-rebinding protection at socket connect via anundiciAgentcustomlookuphook when using nativeglobalThis.fetch(closing theAgentcleanly or preventing TOCTOU rebinding), follows redirects manually (redirect: 'manual'), stripsAuthorizationandCookieheaders on cross-origin redirects, enforcesAbortControllertimeout + callersignalpropagation, and returnsINV-LEGO-01okEnvelope({ status, url, redirected, redirects, headers, response }) orerrorEnvelope.
- Validates every hop via
-
createRateLimiter({ windowMs = 60000, max = 60, maxKeys = 10000, nowFn = Date.now, tool = 'security.rateLimit' } = {}):- Bounded
Maprate limiter with expired-bucket pruning + oldest-key FIFO eviction atmaxKeys, returning{ consume(key, cost = 1), reset(key), clear(), size(), middleware(opts), edgeCheck(request, opts) }with standardX-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset, andRetry-Afterheaders plus429RATE_LIMITEDerrorEnvelope.
- Bounded
-
-
Disjoint Files:
-
INV-LEGO-14(krusch_toolkitPythonv1.3.0Parity —mcp.py,pg.py,security.py):-
Disjoint Files:
lib-py/krusch_toolkit/mcp.py,lib-py/krusch_toolkit/pg.py,lib-py/krusch_toolkit/security.py,lib-py/tests/test_wave3_lego.py - All three modules MUST import cleanly in bare Python 3.11+ without optional
fastapior live PostgreSQL servers running:-
krusch_toolkit.mcp:define_mcp_tool(enforcingINV-STACK-034-boolean annotations +title),ok_mcp_result,error_mcp_result,validate_tool_args(Nonevs0/False/""accurate), and asyncdispatch_mcp_tool. -
krusch_toolkit.pg:assert_safe_pg_identifier(^[A-Za-z_][A-Za-z0-9_]*$),build_pg_connection_string(URL-encoded),format_pgvector_literal(validate_vector_dimension1024d default, rejectingbool/NaN/Inf),run_sql_migrations, andpg_vector_search(SQLi-guarded identifiers +where_sqlsemicolon/comment rejection +1 <= limit <= 200). -
krusch_toolkit.security:constant_time_equal,verify_webhook_hmac,verify_bearer_token(SHA-256 pre-hashed beforehmac.compare_digest),is_private_or_reserved_ip(covering IPv4-mapped/6to4/Teredo/metadata/RFC1918/Tailscale), andvalidate_outbound_url.
-
-
Disjoint Files:
-
INV-LEGO-15(Cross-Repo Rule-of-3 Lego Scout Engine —@krusch/toolkit/lego-scout&krusch-lego scout):-
Disjoint Files:
lib/lego-scout.js,lib/types/lego-scout.d.ts - Exports
CANDIDATE_PATTERN_SIGNATURES,formatPortableProjectPath, andscoutHomelabLegoCandidates(projectsRoot, { minProjects = 3, maxFilesPerProject = 400, maxFileBytes = 262144, portablePaths = false } = {}):- Safely walks
projectsRoot(never following symlinks outsideprojectsRoot, skippingkrusch-stack,node_modules,.git,.venv,dist,build,tests,benchmarks). - Computes
adoptionFindings(existing@krusch/toolkit/krusch_toolkitboilerplate hits viaauditBoilerplateText) andcandidateClusters(recurring infrastructure patterns classified into'ALREADY_COVERED_IN_TOOLKIT','CANDIDATE_MEETS_RULE_OF_3'whenprojectCount >= minProjects, or'BELOW_THRESHOLD_DO_NOT_EXTRACT'when< minProjects). - When
portablePaths === true, strips host-specific absolute prefixes so all paths are portable<WORKSPACE_ROOT>/projects/<repo>/...paths suitable for public SFT/DPO datasets (INV-STACK-04). - Returns
INV-LEGO-01okEnvelope('lego.scout', ...)orerrorEnvelope('SCOUT_INVALID_ROOT', ...).
- Safely walks
-
Disjoint Files:
-
INV-LEGO-16(Autonomouslego_scoutLoop & Zero-Leak SFT/DPO Training Flywheel):-
Orchestrator Files:
projects/jean-sre/src/prompts.js,projects/jean-sre/src/jean_sre_sweep.js,projects/jean-sre/scripts/harvest_lego_and_referee_calibration.js,projects/jean-sre/scripts/export-120b-distillation.js,projects/jean-sre/tests/lego-sft-calibration.test.js. - Adds
{ focus: 'lego_scout' }toINFRA_TARGETS, injects deterministicscoutHomelabLegoCandidatesJSON summary intolego_scoutcycles (andauditBoilerplateTexthints into1.5_ANTI_PATTERN), logslego_scoutfindings under/jean-loop-gate, and harvests Wave-3 Lego + Rule-of-3 Spec Synthesis SFT rows and Anti-Bloat Architectural Judgment DPO pairs passing10/10verifyZeroLeaksgates.
-
Orchestrator Files:
Promotes all 4 empirical CANDIDATE_MEETS_RULE_OF_3 clusters discovered across 100 workspace repositories by scoutHomelabLegoCandidates (schema-contract-validation [16 repos], multipart-file-upload [10 repos], cascade-swarm-routing [9 repos], and voice-whisper-audio [9 repos]) into zero-bloat runtime bricks (@krusch/toolkit v1.6.0 & krusch_toolkit v1.4.0).
-
INV-LEGO-17(Zero-Dependency Composable Schema,zodAdapter & MCP JSON Schema Compiler —@krusch/toolkit/schema):-
Disjoint Files:
lib/schema.js,lib/types/schema.d.ts -
Runtime Purity: Zero external npm dependencies and zero
node:*imports (pure ECMAScript +./http.jsenvelopes or isomorphic envelope builders; safe in Node 22, browsers, and Cloudflare Workers). - Exact exports:
-
s: Frozen composable schema builder namespace exposings.string(opts),s.number(opts),s.integer(opts),s.boolean(opts),s.literal(value, opts),s.enum(values, opts),s.array(itemSchema, opts),s.object(shape, opts),s.record(valueSchema, opts),s.union(schemas, opts),s.optional(schema),s.nullable(schema), ands.any(opts). Every builder node MUST expose.optional(),.nullable(),.safeParse(input, opts)({ success: boolean, data?, error?: { issues } }), and.toJsonSchema(). -
toJsonSchema(schema): Compiles anys.*builder or plain JSON Schema object into a clean JSON Schema Draft-7/2020-12 object ({ type, properties, required, additionalProperties, ... }) ready for MCPdefineMcpTool({ inputSchema }). -
validateSchema(schema, payload, { coerce = false, stripUnknown = true, maxDepth = 16, tool = 'schema.validate' } = {})and aliasvalidatePayload:- Accepts
s.*builders, duck-typed{ safeParse(input) }(zodv3/v4), or raw JSON Schema objects (type,properties,required,items,enum,const,minimum,maximum,minLength,maxLength,minItems,maxItems,format,additionalProperties). - Enforces
maxDepthrecursion cap (SCHEMA_MAX_DEPTH), circular-inputWeakSetprotection (SCHEMA_CIRCULAR_REF), prototype-pollution stripping (__proto__,constructor,prototypekeys never copied via unsafe bracket assignment ontoObject.prototype),NaN/Infinity/booleanrejection on numeric fields, and ReDoS-safe deterministicformatvalidators (email,uuid,url,iso-date,iso-datetime,ipv4,slug). - Never throws on untrusted
payload; returnsINV-LEGO-01okEnvelope(tool, 'Schema validation passed', validatedData)orerrorEnvelope('VALIDATION_ERROR' | 'SCHEMA_MAX_DEPTH' | 'SCHEMA_CIRCULAR_REF' | 'INVALID_SCHEMA', message, { issues }, tool).
- Accepts
-
createSchemaMiddleware(schema, { source = 'body', coerce = false, stripUnknown = true, tool = 'schema.middleware' } = {}): Express/Node(req, res, next)middleware validatingreq[source], attachingreq.validated, or responding HTTP400JSONerrorEnvelope.
-
-
Disjoint Files:
-
INV-LEGO-18(Byte-Bounded Multipart Upload, Filename Sanitizer & Magic-Byte MIME Guard —@krusch/toolkit/upload):-
Disjoint Files:
lib/upload.js,lib/types/upload.d.ts - Exact exports:
-
sanitizeUploadFilename(rawFilename = '', { fallback = 'upload.bin', maxLength = 128 } = {}):- Strips POSIX/Windows directory prefixes (
/and\), NUL bytes, ASCII/Unicode control & bidirectional override codepoints (U+0000..U+001F,U+007F..U+009F,U+202A..U+202E,U+2066..U+2069), leading dots (.env,..), trailing dots/spaces, and Windows reserved device names (CON,PRN,AUX,NUL,COM1..9,LPT1..9), truncating cleanly tomaxLengthwhile preserving valid extensions and returningfallbackwhen empty.
- Strips POSIX/Windows directory prefixes (
-
sniffMimeMagic(bytes):- Inspects leading
Uint8Array/Buffermagic signatures (application/pdf,image/png,image/jpeg,image/gif,image/webp,audio/wav,audio/mpeg,audio/ogg,video/webm,application/zip), returning detected canonical MIME string ornullwhen unrecognized.
- Inspects leading
-
verifyUploadMime(bytes, declaredMime = '', { allowedMimeTypes = null, requireMagicMatch = true, tool = 'upload.mime' } = {}):- Non-throwing validator comparing normalized
declaredMimeagainstsniffMimeMagic(bytes)(UPLOAD_MIME_MISMATCHon spoofed headers or missing magic signature when allowlist strictly requires magic-verifiable binary types) and enforcingallowedMimeTypes(exact MIME or wildcardimage/*,audio/*, returningUPLOAD_UNSUPPORTED_MIME). ReturnsINV-LEGO-01okEnvelopeorerrorEnvelope.
- Non-throwing validator comparing normalized
-
parseBoundedMultipart(input, { contentType = '', maxTotalBytes = 10485760, maxFileBytes = 5242880, maxFiles = 5, maxFields = 32, maxFieldBytes = 65536, allowedMimeTypes = null, requireMagicMatch = true, tool = 'upload.multipart' } = {}):- Accepts Web
Request, NodeIncomingMessage/Readable, or{ body: Uint8Array | Buffer, contentType: string }. - Enforces
maxTotalByteswhile streaming BEFORE full buffering (draining/resuming NodeIncomingMessageor canceling WebReadableStreamon overflow ->UPLOAD_TOO_LARGEwithout TCPECONNRESETor OOM), scans RFC 7578 boundaries in linear$O(N)$ byte time without catastrophic regex backtracking, enforcesmaxFiles,maxFields,maxFileBytes,maxFieldBytes, prototype-safefields(__proto__/constructor/prototypeblocked),sanitizeUploadFilename, andverifyUploadMime. ReturnsINV-LEGO-01okEnvelope(tool, ..., { fields, files, totalBytes })orerrorEnvelope.
- Accepts Web
-
-
Disjoint Files:
-
INV-LEGO-19(Deterministic Multi-Tier LLM Cascade, Single-Flight Circuit Breaker & Burst Probe —@krusch/toolkit/cascade):-
Disjoint Files:
lib/cascade.js,lib/types/cascade.d.ts -
Portability (
INV-LEGO-04/INV-STACK-04): Zero hardcoded private LAN or CGNAT host IPs; default URLs use127.0.0.1/ env overrides (OLLAMA_L1_URL,OLLAMA_L2_URL,COLAB_BURST_URL). - Exact exports:
-
DEFAULT_FLEET_CASCADE_TIERS: Frozen 4-tier descriptor list (L1_FAST,L2_HEAVY_MOE,L2_5_COLAB_BURST,L3_FRONTIER_ARGON). -
createTierCircuitBreaker({ failureThreshold = 3, cooldownMs = 30000, maxTiers = 64, nowFn = Date.now } = {}):- Bounded
Map(maxTierseviction, prototype-safe) managingCLOSED,OPEN, and single-flightHALF_OPENprobe transitions (canAttempt,recordSuccess,recordFailure,getState,snapshot,reset,clear) so concurrent callers never stampede a recovering tier duringHALF_OPEN.
- Bounded
-
selectCascadeTier({ complexityScore = 0, estimatedTokens = 0, requiresTools = false, requiresVision = false, allowBurst = false, allowFrontier = true, tiers = DEFAULT_FLEET_CASCADE_TIERS, breaker = null, tool = 'cascade.select' } = {}):- Deterministic zero-I/O tier selector returning
INV-LEGO-01okEnvelope(tool, ..., { selectedTier, candidateChain, reason })orerrorEnvelope('CASCADE_NO_HEALTHY_TIER', ...).
- Deterministic zero-I/O tier selector returning
-
probeBurstEndpoint(endpointUrl = 'http://127.0.0.1:11435', { timeoutMs = 1500, expectedModel = '', fetchImpl = globalThis.fetch, tool = 'cascade.probe' } = {}):- Non-throwing
AbortController-bounded Ollama/api/tagsprobe returningINV-LEGO-01okEnvelope({ reachable: true, endpointUrl, models, modelReady, latencyMs }) orerrorEnvelope('BURST_UNREACHABLE' | 'BURST_MODEL_MISSING', ...).
- Non-throwing
-
executeWithCascadeFallback(candidateChain, executorFn, { breaker = null, perAttemptTimeoutMs = 30000, signal = null, tool = 'cascade.execute' } = {}):- Iterates healthy tiers with combined caller
signal+ per-attemptAbortControllertimeout (guaranteed timer & listener cleanup infinally), halts immediately withCASCADE_ABORTEDif callersignalaborts externally, updatesbreakerstate on attempt outcomes, and returnsINV-LEGO-01okEnvelope(tool, ..., { tierId, attemptCount, attempts, result })orerrorEnvelope('CASCADE_EXHAUSTED' | 'CASCADE_ABORTED' | 'CASCADE_EMPTY_CHAIN', ...).
- Iterates healthy tiers with combined caller
-
-
Disjoint Files:
-
INV-LEGO-20(Isomorphic WAV/Whisper/TTS Audio Modality & Pythonkrusch_toolkitv1.4.0Schema/Upload Parity —@krusch/toolkit/audio,krusch_toolkit.schema,krusch_toolkit.upload):-
Disjoint Files:
lib/audio.js,lib/types/audio.d.ts,lib-py/krusch_toolkit/schema.py,lib-py/krusch_toolkit/upload.py,lib-py/tests/test_wave4_lego.py -
Part A (
lib/audio.js— Zeronode:*imports, pure Web Standards):-
encodeWavPcm16(samples, { sampleRate = 16000, channels = 1 } = {}): EncodesInt16Arrayor clampedFloat32Array([-1, 1],NaN -> 0) into a canonical 44-byte RIFF/WAVE PCM16 little-endianUint8Array. -
parseWavHeader(wavBytes, { tool = 'audio.wav' } = {}): Bounds-checked RIFF/WAVE chunk walker (fmt+data, tolerant of intermediateJUNK/LISTchunks) returningINV-LEGO-01okEnvelope({ audioFormat, channels, sampleRate, bitsPerSample, byteRate, dataOffset, dataBytes, durationSeconds }) orerrorEnvelope('WAV_INVALID_HEADER', ...). -
transcribeWhisperAudio(audioBytes, { endpointUrl = 'http://127.0.0.1:9000/v1/audio/transcriptions', filename = 'audio.wav', mimeType = 'audio/wav', model = 'whisper-1', language = '', prompt = '', apiKey = '', maxAudioBytes = 26214400, timeoutMs = 30000, signal = null, fetchImpl = globalThis.fetch, tool = 'audio.stt' } = {}): Enforces0 < byteLength <= maxAudioBytes, audio MIME allowlist,AbortControllertimeout + callersignalcleanup, and returnsINV-LEGO-01okEnvelope({ text, language, duration, segments }) orerrorEnvelope. -
synthesizeSpeechAudio(text, { endpointUrl = 'http://127.0.0.1:8880/v1/audio/speech', voice = 'af_heart', model = 'tts-1', responseFormat = 'wav', speed = 1.0, apiKey = '', maxTextChars = 4096, maxResponseBytes = 26214400, timeoutMs = 30000, signal = null, fetchImpl = globalThis.fetch, tool = 'audio.tts' } = {}): EnforcesmaxTextChars, streamedmaxResponseBytescap,AbortControllerteardown, and returnsINV-LEGO-01okEnvelope({ audioBytes, mimeType, byteLength }) orerrorEnvelope.
-
-
Part B (
krusch_toolkitPythonv1.4.0—schema.py&upload.py):- Both modules MUST import cleanly in bare Python 3.11+ stdlib without live servers or optional frameworks:
-
krusch_toolkit.schema:validate_json_schema,validate_payload(supporting JSON Schema dicts + duck-typed Pydantic v2model_validate, strictly rejectingboolforinteger/numberandNaN/Inf, enforcingmax_depth, stripping__proto__/constructor/prototype, and returningok_envelope/error_envelope("VALIDATION_ERROR", ...)). -
krusch_toolkit.upload:sanitize_upload_filename,sniff_mime_magic,verify_upload_mime, and asyncread_bounded_upload(chunkedmax_bytesenforcement before buffering + MIME magic verification returningok_envelope/error_envelope).
-
- Both modules MUST import cleanly in bare Python 3.11+ stdlib without live servers or optional frameworks:
-
Disjoint Files:
6. Wave 5 Python Rule-of-3 Promotion & Sentinel Telemetry Contracts (INV-LEGO-21..INV-LEGO-22 & INV-SENTINEL-MEM-01)
Promotes the 2 empirical Python CANDIDATE_MEETS_RULE_OF_3 clusters discovered across 100 workspace repositories by scoutHomelabLegoCandidates (python-httpx-resilience [12 repos] and streamlit-rag-shell [6 repos]) into krusch_toolkit v1.5.0 runtime bricks, registers Wave-6 empirical horizon detectors (python-sqlalchemy-wal-pool [7 repos] and yaml-safe-config-loader [7 repos]), and aligns Linux MemAvailable RAM telemetry in krusch-sentinel-mcp.
-
INV-LEGO-21(SSRF-Guarded, Bounded, Single-Flight Circuit-Broken Python HTTP Client —krusch_toolkit.http_client):- Disjoint Subagent 1 File:
lib-py/krusch_toolkit/http_client.py - Bare-Stdlib Import Purity: Module MUST import cleanly in bare Python 3.11+ stdlib even when
httpxis not installed (import httpxoccurs lazily inside default transport execution whenclientandsend_fnare omitted). - Exact Exports & Return Contracts:
HttpCircuitBreaker(failure_threshold: int = 3, cooldown_seconds: float = 30.0, max_hosts: int = 64, clock_fn: Callable[[], float] = time.monotonic)and factorycreate_http_circuit_breaker(...):- Thread-safe (
threading.Lock) boundedOrderedDict(max_hostsFIFO/LRU eviction, rejectingbool/non-positive bounds cleanly) managingCLOSED,OPEN, and single-flightHALF_OPENprobe states. - Methods:
can_attempt(key: str) -> dict[str, Any]({"allowed": bool, "state": str, "probe": bool, "retry_after_seconds": float}),record_success(key: str) -> dict[str, Any],record_failure(key: str, reason: str = "") -> dict[str, Any],release_probe(key: str) -> None(releases in-flightHALF_OPENprobe without recording failure if caller task is cancelled viaasyncio.CancelledError),get_state(key: str) -> dict[str, Any],snapshot() -> dict[str, dict[str, Any]],reset(key: str) -> None,clear() -> None.
- Thread-safe (
compute_retry_delay(attempt: int, *, base_delay: float = 0.25, max_delay: float = 5.0, retry_after_header: str | None = None, jitter_ratio: float = 0.0, rng_fn: Callable[[], float] = random.random) -> float:- Non-throwing pure float helper rejecting
bool/NaN/Inf; honors non-negative integer/HTTP-secondsRetry-Afterheaders clamped to[0.0, max_delay], otherwisemin(max_delay, base_delay * (2 ** max(0, attempt - 1)))with optional bounded jitter in[0.0, max_delay].
- Non-throwing pure float helper rejecting
build_resilient_headers(headers: Mapping[str, str] | None = None, *, api_key: str | None = None, bearer_token: str | None = None, request_id: str | None = None, accept_json: bool = True, tool: str = "http_client.headers") -> dict[str, Any]:- Validates all header names/values and auth tokens against
\r,\n,\x00, and non-string types (HTTP_INVALID_HEADER), injectsX-Request-ID(preserving caller's case-insensitively if already set) andAccept: application/json, and returnsINV-LEGO-01ok_envelope(tool, ..., {"headers": dict[str, str], "request_id": str})orerror_envelope.
- Validates all header names/values and auth tokens against
request_json(url: str, *, method: str = "GET", headers: Mapping[str, str] | None = None, json_body: Any = ..., timeout_seconds: float = 15.0, max_retries: int = 2, base_delay: float = 0.25, max_delay: float = 5.0, retry_on_post: bool = False, max_redirects: int = 3, max_response_bytes: int = 5_242_880, allow_private_lan: bool = False, allow_tailscale: bool = False, allow_loopback: bool = False, allowed_hosts: Sequence[str] | None = None, lookup_fn: Callable[[str], Sequence[str]] | None = None, breaker: HttpCircuitBreaker | None = None, client: Any = None, send_fn: Callable[..., Any] | None = None, sleep_fn: Callable[[float], None] = time.sleep, tool: str = "http_client.request") -> dict[str, Any]and async twinasync_request_json(...):- Validates
methodin{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}(HTTP_INVALID_METHOD), headers viabuild_resilient_headers, andjson_body(when provided) viajson.dumps(..., allow_nan=False)(HTTP_INVALID_JSON_BODYonNaN/Infinity/cycles). - Validates initial URL and every manual redirect hop (
follow_redirects=False, up tomax_redirects->HTTP_TOO_MANY_REDIRECTS) viavalidate_outbound_url(whenallow_loopback=True, strictly permitslocalhost/127.0.0.0/8/::1while still enforcingallowed_hostsand blocking0.0.0.0,169.254.169.254,fd00:ec2::254,metadata.google.internal, and IPv6 transition prefixes). Inasync_request_json, whenlookup_fn is Noneand the host is not an IP literal, resolves DNS viaawait asyncio.get_running_loop().getaddrinfo(...)so the event loop never blocks; when creating a defaulthttpx.Client/httpx.AsyncClient(client is Noneandsend_fn is None), pins the validated IP in the connect URL (Hostheader +extensions={"sni_hostname": host_norm}forhttps) to prevent connect-time DNS-rebinding TOCTOU. - Strips sensitive credentials (
Authorization,Cookie,X-API-Key,Proxy-Authorizationcase-insensitively) across cross-origin redirects ((scheme, hostname, port)change) and rewrites303(or301/302onPOST) to bodylessGET. - Enforces
max_response_byteson bothContent-Lengthand chunked stream reads BEFORE full buffering (HTTP_RESPONSE_TOO_LARGE). - Parses JSON strictly rejecting
NaN/Infinity/-Infinity(HTTP_INVALID_JSON, with204/HEADempty body ->None). - Retries transient transport/timeout errors and
{408, 429, 502, 503, 504}up tomax_retriesONLY for idempotent methods (GET,HEAD,OPTIONS,PUT,DELETE) orPOSTwhenretry_on_post=True. Updatesbreakerper attempt and guaranteesbreaker.release_probe(key)infinallyifasyncio.CancelledErrorinterrupts an in-flightHALF_OPENprobe (re-raisingCancelledError). - Returns
INV-LEGO-01ok_envelope(tool, ..., {"status": int, "url": str, "headers": dict[str, str], "body": Any, "attempts": int, "redirected": bool})on2xx, orerror_envelope(HTTP_UPSTREAM_ERROR,HTTP_TIMEOUT,HTTP_NETWORK_ERROR,HTTP_CIRCUIT_OPEN,HTTP_RESPONSE_TOO_LARGE,HTTP_INVALID_JSON,SSRF_*, etc.) without raising on untrusted inputs.
- Validates
- Disjoint Subagent 1 File:
-
INV-LEGO-22(Air-Gapped, XSS-Hardened Streamlit Sovereign RAG Shell —krusch_toolkit.streamlit_ui):- Disjoint Subagent 2 File:
lib-py/krusch_toolkit/streamlit_ui.py - Disjoint Subagent 3 Test File:
lib-py/tests/test_wave5_lego.py - Bare-Stdlib Import Purity: Module MUST import cleanly in bare Python 3.11+ stdlib without
streamlitinstalled (st_moduleinjectable for deterministic headless testing; lazyimport streamlitonly whenst_module is None). - Exact Exports & Return Contracts:
AIRGAPPED_THEME_PRESETS: Mapping Proxy (types.MappingProxyType) of frozen presets ("sky","gold","emerald").build_airgapped_theme_css(accent: str = "sky") -> str: Returns<style>...</style>CSS with offline system font stack, zero externalhttp:///https:///@importURLs, and strict preset or#RRGGBBhex validation (preventing CSS injection via arbitraryaccentstrings).build_rag_auth_headers(session_state: Mapping[str, Any] | None = None, *, api_key: str | None = None, tenant_id: str | None = None, bearer_token: str | None = None, default_api_key: str = "", default_tenant_id: str = "", tool: str = "streamlit.auth") -> dict[str, Any]: Resolves credentials from explicit args orsession_state, rejects\r/\n/\x00(STREAMLIT_INVALID_HEADER), and returnsok_envelope(tool, ..., {"headers": dict[str, str]})orerror_envelope.format_citation_badges_html(citations: Sequence[Mapping[str, Any]] | None, *, max_badges: int = 12, max_span_chars: int = 140) -> str: Escapes all text fields viahtml.escape(..., quote=True), formats numeric[0.0, 1.0]/[0.0, 100.0]confidence scores (ignoringbool/NaN/Inf), and ONLY emits<a href="..." target="_blank" rel="noopener noreferrer">whenurlparses cleanly ashttp://orhttps://without control/whitespace chars (neutralizingjavascript:,data:,vbscript:XSS payloads into inert<span>badges).render_citation_badges(citations: Sequence[Mapping[str, Any]] | None, *, st_module: Any = None, max_badges: int = 12, max_span_chars: int = 140, tool: str = "streamlit.citations") -> dict[str, Any]: Renders viast.markdown(..., unsafe_allow_html=True)and returnsok_envelope(tool, ..., {"html": str, "rendered_count": int})orerror_envelope("STREAMLIT_UNAVAILABLE", ...).init_rag_session_state(session_state: MutableMapping[str, Any] | None = None, *, st_module: Any = None, defaults: Mapping[str, Any] | None = None, messages_key: str = "messages", max_turns: int = 100, tool: str = "streamlit.state") -> dict[str, Any]: Ensures bounded listsession_state[messages_key]and deep-copied default keys without clobbering existing user values; returnsok_envelopeorerror_envelope.append_rag_turn(session_state: MutableMapping[str, Any] | None, role: str, content: str, *, citations: Sequence[Mapping[str, Any]] | None = None, st_module: Any = None, messages_key: str = "messages", max_turns: int = 100, tool: str = "streamlit.chat") -> dict[str, Any]: Validatesrolein{"user", "assistant", "system"}(STREAMLIT_INVALID_ROLE), non-emptystrcontent(STREAMLIT_EMPTY_CONTENT), integermax_turns >= 1(rejectingbool), sanitizes/copiescitations, trims oldest turns beyondmax_turns, and returnsok_envelope(tool, ..., {"turn": dict, "turn_count": int})orerror_envelope.render_sovereign_rag_shell(*, title: str, subtitle: str = "", badge_text: str = "AIR-GAPPED", disclaimer: str = "", accent: str = "sky", page_icon: str = "🛡️", health_status: str | None = None, configure_page: bool = True, max_turns: int = 100, st_module: Any = None, tool: str = "streamlit.shell") -> dict[str, Any]: Callsst.set_page_config(...)whenconfigure_page=True(gracefully catching duplicate-callStreamlitAPIException/StreamlitSetPageConfigMustBeFirstCommandError), injects air-gapped CSS +html.escape-hardened header/health/disclaimer banner, initializes session state, and returnsok_envelopeorerror_envelope.
- Disjoint Subagent 2 File:
-
INV-SENTINEL-MEM-01(LinuxMemAvailableParity inkrusch-sentinel-mcp):- Disjoint Subagent 4 Files:
projects/krusch-sentinel-mcp/src/tools/telemetry.ts,projects/krusch-sentinel-mcp/tests/sentinel.test.js(plusnpx tscrebuild ofdist/). - Exports pure
parseLinuxMeminfoBytes(meminfoText: string): { totalBytes: number; availableBytes: number } | nullparsingMemTotal:andMemAvailable:(falling back toMemFree + Buffers + CachedwhenMemAvailableis absent on legacy kernels, clamping0 <= availableBytes <= totalBytes). - Updates
getSystemStats(node?: string)so local Linux nodes read/proc/meminfo(MemAvailablerather than rawos.freemem()MemFree) and remote Linux nodes read/proc/meminfoviaexecRemote(locale-independent, avoidingLC_ALLfree -bheader mismatches), computingfreeMemGBfrom reclaimable-awareavailableBytesandusedMemPercentfrom((totalBytes - availableBytes) / totalBytes) * 100while preserving 100% of existing return properties and error fallback contracts.
- Disjoint Subagent 4 Files:
-
Orchestrator Choke Points (Phase 3B — Parent Orchestrator Only):
lib-py/pyproject.toml&lib-py/krusch_toolkit/__init__.py(v1.5.0exports)lib/catalog.js(python_http_client&python_streamlit_ui->32RUNTIME_BRICKS)lib/lego-scout.js(python-httpx-resilience&streamlit-rag-shell->COVERED_BY_TOOLKIT_V1_5, plus Wave-6 horizon detectorspython-sqlalchemy-wal-pool&yaml-safe-config-loader)lib/test_wave3_bricks.js,lib/test_wave5_bricks.js,lib/README.md, & workspaceAGENTS.md(< 18,432bytes)
7. Wave 6 Rule-of-3 Promotion & Swarm Queue Janitor Contracts (INV-LEGO-23..INV-LEGO-24 & INV-JANITOR-01)
STATUS: FROZEN (
2026-10-31) — Promotes the final 2 empiricalCANDIDATE_MEETS_RULE_OF_3clusters across all 100 workspace repositories (yaml-safe-config-loader[10repos] andpython-sqlalchemy-wal-pool[9repos]) into@krusch/toolkitv1.7.0&krusch_toolkitv1.6.0(35RUNTIME_BRICKS, achieving100%Rule-of-3 cluster coverage), and hardens the Jean SRE Swarm Queue Janitor (INV-JANITOR-01).
-
INV-LEGO-23(Cross-Runtime Safe YAML Config & Authority-Pack Loader —@krusch/toolkit/yaml&krusch_toolkit.yaml_loader):- Disjoint Subagent 1 Files (Node/Edge/Browser):
lib/yaml.js,lib/types/yaml.d.ts- Zero-Dependency, Zero-
node:*Isomorphic Purity:lib/yaml.jsMUST contain zeronode:*strings (/\bnode:[a-z_]+/i.test(src) === false) and import only{ validateSchema } from './schema.js', running unmodified in Node 22 ESM, Cloudflare Workers, and browsers. - Exact Exports & Return Contracts:
DEFAULT_YAML_LIMITS: Frozen{ maxBytes: 1_048_576, maxDepth: 32, maxNodes: 10_000, maxAliases: 64, maxAliasExpansionNodes: 1_000 }.parseSafeYaml(input, options = {}): Acceptsstring,Uint8Array, orArrayBuffer(elseerrorEnvelope('YAML_INVALID_INPUT', ...)). EnforcesmaxBytespre-parse (YAML_TOO_LARGE), rejects non-positive/bool/NaNnumeric options (YAML_INVALID_OPTIONS), rejects NUL bytes and invalid UTF-8 (YAML_PARSE_ERROR), and parses YAML 1.2 Core Schema (block/flow mappings & sequences, compact- key: valitems, single/double-quoted escapes, literal|/|-/|+& folded>/>-/>+block scalars,#comments,---/...markers). Security invariants:- No Arbitrary Tags: Rejects explicit tags (
!tag,!!python/...,!!js/...,!!binary,!!timestamp,!<...>,%TAG) outside strings/comments withYAML_FORBIDDEN_TAG. - YAML 1.2 Core Types (Norway-Safe & JSON-Safe): Only
true/True/TRUEandfalse/False/FALSEparse as booleans (NO,yes,on,offremainstring); ISO dates (2026-01-01) remainstring;.nan/.inf/-.infare rejected withYAML_NONFINITE_NUMBER. - Prototype, Key & Duplicate Guards: Rejects
__proto__,constructor,prototype(YAML_FORBIDDEN_KEY), non-string mapping keys (YAML_INVALID_KEY), and duplicate keys within the same mapping (YAML_DUPLICATE_KEY). - Bounded Anchors/Aliases & Merge Keys (
&a,*a,<<): Deep-clones dereferenced aliases while bounding total alias references (<= maxAliases) and cumulative cloned nodes (<= maxAliasExpansionNodes), aborting Billion-Laughs exponential blowups withYAML_ALIAS_BOMB(plusYAML_MAX_DEPTHandYAML_MAX_NODES). Rejects multi-document streams unlessallowMultipleDocuments === true(YAML_MULTIPLE_DOCUMENTS). - Returns
INV-LEGO-01okEnvelope(tool, ..., { value, byteLength, nodeCount, aliasCount })orerrorEnvelope.
- No Arbitrary Tags: Rejects explicit tags (
stringifySafeYaml(value, options = {}): Cycle-guarded, depth-bounded (maxDepth),NaN/Infinity/BigInt/function/symbol-rejecting YAML 1.2 serializer quoting ambiguous scalars (true,false,null,~, numeric literals, empty strings, control chars,:,#, leading indicator chars). ReturnsokEnvelope(tool, ..., { yaml })orerrorEnvelope('YAML_STRINGIFY_ERROR', ...).validateYamlConfig(input, schema, options = {}): Parses viaparseSafeYamland validates viavalidateSchema(value, schema, { tool }), returningokEnvelope(tool, ..., { value, byteLength, nodeCount })orerrorEnvelope.loadSafeYamlPack(input, options = {}): Parses viaparseSafeYaml, requires a plain JSON object root (YAML_INVALID_PACK), checks optionalrequiredKeys(string[]) and optionalschema, computes pure-JS synchronous SHA-256 hex digest over canonical UTF-8 input bytes, and returnsokEnvelope(tool, ..., { pack, sha256, byteLength, nodeCount })orerrorEnvelope.
- Zero-Dependency, Zero-
- Disjoint Subagent 2 File (Python):
lib-py/krusch_toolkit/yaml_loader.py- Bare-Stdlib Import Purity: Module MUST import cleanly in bare Python 3.11+ stdlib (
import yamloccurs lazily inside execution, returningYAML_UNAVAILABLEif PyYAML is absent andyaml_module=False). - Exact Exports & Return Contracts:
DEFAULT_YAML_LIMITS(types.MappingProxyType),parse_safe_yaml,dump_safe_yaml,validate_yaml_config,load_safe_yaml_pack.- Subclasses
yaml.SafeLoaderinto_SovereignSafeLoaderenforcing YAML 1.2 Core booleans (true/falseonly;NO/on/offstaystr), keeping ISO dates asstr(removingtag:yaml.org,2002:timestampandtag:yaml.org,2002:binary/omap/pairs/set), rejecting all custom/arbitrary!tags (YAML_FORBIDDEN_TAG),.nan/.inf(YAML_NONFINITE_NUMBER),__proto__/constructor/prototype(YAML_FORBIDDEN_KEY), non-string keys (YAML_INVALID_KEY), duplicate keys (YAML_DUPLICATE_KEY), and enforcingmax_bytes(YAML_TOO_LARGE),max_depth(YAML_MAX_DEPTH),max_nodes(YAML_MAX_NODES),max_aliases&max_alias_expansion_nodes(YAML_ALIAS_BOMBcounted during composition BEFORE full graph construction, returning deep-cloned alias subtrees so mutating one branch never mutates another). load_safe_yaml_pack(path_or_text, *, base_dir=None, from_file=False, required_keys=None, schema=None, ...): When reading from disk (from_file=Trueoros.PathLike), enforcesrealpathcontainment insidebase_dir(YAML_PATH_TRAVERSAL), verifies regular file viaos.open+os.fstat(S_ISREG) and boundedread(max_bytes + 1)(YAML_TOO_LARGE), computeshashlib.sha256, validates dict root +required_keys+validate_payload, and returnsok_envelope(tool, ..., {"pack": dict, "sha256": str, "byte_length": int, "node_count": int, "source_path": str | None})orerror_envelope.
- Bare-Stdlib Import Purity: Module MUST import cleanly in bare Python 3.11+ stdlib (
- Disjoint Subagent 1 Files (Node/Edge/Browser):
-
INV-LEGO-24(Python SQLAlchemy Sync/Async Pool, SQLite WAL & Transactional Session Scopes —krusch_toolkit.db_async):- Disjoint Subagent 3 File:
lib-py/krusch_toolkit/db_async.py - Bare-Stdlib Import Purity: Module MUST import cleanly in bare Python 3.11+ stdlib (
sqlalchemyimported lazily inside functions or injected viasa_module/async_engine_factory). - Exact Exports & Return Contracts:
DEFAULT_SQLITE_PRAGMAS(types.MappingProxyType),redact_database_url(database_url: str) -> str,apply_sqlite_wal_pragmas(dbapi_connection, *, busy_timeout_ms=5000, synchronous="NORMAL", foreign_keys=True, journal_mode="WAL") -> dict[str, Any].create_managed_engine(database_url=None, *, env_var="DATABASE_URL", pool_size=5, max_overflow=10, pool_timeout=30.0, pool_recycle=1800, busy_timeout_ms=5000, sqlite_wal=True, synchronous="NORMAL", foreign_keys=True, echo=False, sa_module=None, tool="db_async.engine") -> dict[str, Any]:- Rejects
bool/NaN/Inf/out-of-range numeric options and non-whitelistedsynchronousvalues (DB_INVALID_OPTIONS), missing URL (DB_MISSING_URL), and async driver schemes (+aiosqlite,+asyncpg) passed to sync engine (DB_ASYNC_DRIVER_MISMATCH). Attaches SQLiteconnectevent listener applyingWAL/synchronous/busy_timeout/foreign_keys/temp_storepragmas and configurespool_pre_ping=True+ bounded pool kwargs on pooled dialects. Returnsok_envelope(tool, ..., {"engine": engine, "session_factory": session_factory, "dialect": str, "redacted_url": str, "is_async": False})orerror_envelope(scrubbing credentials on driver/parse failure).
- Rejects
create_managed_async_engine(database_url=None, *, env_var="DATABASE_URL", pool_size=5, max_overflow=10, pool_timeout=30.0, pool_recycle=1800, busy_timeout_ms=5000, sqlite_wal=True, synchronous="NORMAL", foreign_keys=True, echo=False, async_engine_factory=None, tool="db_async.async_engine") -> dict[str, Any]:- Validates async URL scheme (
sqlite+aiosqlite,postgresql+asyncpg,postgresql+psycopg, etc.; rejects sync-only URLs whenasync_engine_factory is NonewithDB_ASYNC_DRIVER_MISMATCH), catches missing async DBAPI packages cleanly (DB_DRIVER_UNAVAILABLE), wiressync_engineSQLite WAL listener when present, and returnsok_envelope(..., {"engine": engine, "session_factory": session_factory, "dialect": str, "redacted_url": str, "is_async": True})orerror_envelope.
- Validates async URL scheme (
session_scope(session_factory)(@contextmanager) andasync_session_scope(session_factory)(@asynccontextmanager): Commit on clean exit, rollback and re-raise onBaseException(includingasyncio.CancelledError/KeyboardInterrupt), and close infinallywithout masking the primary exception.check_engine_health(engine, *, tool="db_async.health")andcheck_async_engine_health(engine, *, tool="db_async.health"): ExecuteSELECT 1(plusPRAGMA journal_modefor SQLite) and returnok_envelope(tool, ..., {"healthy": True, "dialect": str, "journal_mode": str | None})or credential-redactederror_envelope("DB_UNHEALTHY", ...).
- Disjoint Subagent 3 File:
-
INV-JANITOR-01(Protected-Queue Swarm Janitor —scripts/jean_queue_janitor.js):- Disjoint Subagent 4 Files:
scripts/jean_queue_janitor.js,scripts/test_jean_queue_janitor.js - Zero hardcoded database passwords or private LAN IPs in source; resolves
DATABASE_URLfrom environment /.envfiles (projects/jean-sre/.env,.env) orbuildPgConnectionString(@krusch/toolkit/pg), usingcreatePgPoolfrom../lib/pg.js(INV-LEGO-01). PROTECTED_JOB_TYPES = Object.freeze(['human_review', 'debate_proposal', 'debate_rebuttal']):triageStaleJobsMUST NEVER fail or mutate protected human-in-the-loop review items, and MUST evaluate staleness viaCOALESCE(started_at_ms, (EXTRACT(EPOCH FROM created_at) * 1000)::bigint) < $1so orphanedpendingintentrows withNULLstarted_at_msare also caught.commitSreMemoryprovides explicitcrypto.randomUUID()idwhen inserting intoide_agent_memory(handlingid uuid NOT NULLsafely without crashing ifgen_random_uuid()default is absent).- Exports
PROTECTED_JOB_TYPES,resolveJanitorDatabaseUrl,triageStaleJobs,purgeOldLogs, andrunQueueJanitorreturningINV-LEGO-01{ ok, tool: 'sre.queue_janitor', summary, data | error }envelopes while preserving CLI--dry-run(default) and--executeflags.
- Disjoint Subagent 4 Files:
-
Orchestrator Choke Points (Phase 3B — Parent Orchestrator Only):
lib/package.json(v1.7.0,./yamlsubpath),lib/index.js,lib/types/index.d.tslib/catalog.js(yaml,python_yaml,python_db_async->35RUNTIME_BRICKS[10Python] + Rule 10unsafe-yaml-loadflagging rawyaml.load(withoutSafeLoaderin Python orjs-yamlyaml.load(without@krusch/toolkit/yaml)lib/lego-scout.js(python-sqlalchemy-wal-pool->COVERED_BY_TOOLKIT_V1_6,yaml-safe-config-loader->COVERED_BY_TOOLKIT_V1_7, plus adopted-brick exemptions for@krusch/toolkit/yaml,krusch_toolkit.yaml_loader, andkrusch_toolkit.db_async) &projects/jean-sre/src/jean_sre_sweep.js(buildLegoScoutContextBriefexplicit0 uncovered clustersCANDIDATE_MEETS_RULE_OF_3line when100%covered)lib-py/pyproject.toml&lib-py/krusch_toolkit/__init__.py(v1.6.0exports)lib/test_lego_bricks.js,lib/test_wave3_bricks.js,lib/test_wave5_bricks.js,lib/test_wave6_bricks.js,lib-py/tests/test_wave6_lego.py,lib/README.md, & workspaceAGENTS.md(< 18,432bytes)
8. Step 8B — Brownfield FastAPI Shell Parity & Sovereign Legal/Corporate Suite Migration (INV-LEGO-25)
STATUS: FROZEN (
2026-10-31T15:10:00-07:00) — Extendskrusch_toolkit.fastapi_app.create_fastapi_appwith opt-in, zero-regression brownfield compatibility switches and migrates all three Sovereign Legal & Corporate engines (krusch-law,krusch-biz,krusch-bizlaw) to0krusch-lego auditboilerplate findings while preserving 100% of existing REST, Streamlit,krusch-gateway-mcp, and standalone GitHub Actions CI contracts.
-
INV-LEGO-25(Brownfield FastAPI Shell Compatibility & Zero-Breakage Consumer Adoption):-
Disjoint Subagent 1 Files (
lib-py/):lib-py/krusch_toolkit/fastapi_app.py,lib-py/tests/test_fastapi_lego.py-
100% Default Backward Compatibility: Calling
create_fastapi_app(...)with default keyword arguments MUST remain byte-identical tov1.6.0(ok_envelopeonly on/health&/doctor, stricterror_envelopewithout"detail"onHTTPException/RequestValidationError/500, andallow_credentials = len(resolved_origins) > 0 and "*" not in resolved_origins). -
Extended Signature:
create_fastapi_app(title: str = "Krusch Service", version: str = "1.0.0", *, description: str = "", docs_url: str | None = "/docs", redoc_url: str | None = "/redoc", service_name: str | None = None, cors_origins: list[str] | None = None, allow_credentials: bool | None = None, lifespan: Callable[[Any], Any] | None = None, health_check: Callable[..., Any] | None = None, flatten_health_payload: bool = False, legacy_error_detail: bool = False, startup_hooks: list[Callable[[], Any]] | None = None, shutdown_hooks: list[Callable[[], Any]] | None = None, logger: Any = None) -> Any -
Lifespan Composition: Runs
startup_hooksin order, entersasync with lifespan(_app): yieldwhenlifespan is not None(elseyield), and runsshutdown_hooksinfinallywithout masking a primary startup/lifespan/runtime exception. -
CORS Credentials Guard: When
allow_credentialsisNone, computeslen(resolved_origins) > 0 and "*" not in resolved_origins; when aboolis passed, clamps toFalseif"*"is inresolved_originsorlen(resolved_origins) == 0so browsers never reject wildcard CORS preflights. -
Request-Aware Health & Doctor Probes:
- Inspects
health_checkviainspect.signature: ifhealth_checkaccepts$\ge 1$ positional argument (POSITIONAL_ONLY,POSITIONAL_OR_KEYWORD, orVAR_POSITIONAL), passesrequest(health_check(request)), else callshealth_check(). - Explicitly binds
__annotations__ = {"request": Request, "return": Any}on route handlers so FastAPI'sget_typed_signatureresolvesstarlette.requests.Requestcleanly underfrom __future__ import annotations. -
GET /doctorALWAYS returns strictINV-LEGO-01ok_envelope(resolved_name, "Service healthy", payload). -
GET /healthreturns strictok_envelopewhenflatten_health_payload=False, and{**payload, **ok_envelope(resolved_name, "Service healthy", payload)}whenflatten_health_payload=True(exposing top-level domain keys likestatus,service,security,database_connected, andfleet_connectivityalongside immutableok,tool,summary, anddataenvelope fields; on503unhealthy responses whenlegacy_error_detail=True, attaches"detail": msg).
- Inspects
-
Dual-Envelope Error Compatibility (
legacy_error_detail=True):- Adds
423: "LOCKED"and424: "FAILED_DEPENDENCY"to_HTTP_STATUS_CODES. - When
legacy_error_detail=True,_http_exception_handlerattaches"detail": jsonable_encoder(raw_detail) if raw_detail is not None else messagetoerror_envelope(...), and_validation_exception_handlerattaches"detail": encoded_errorstoerror_envelope(...).
- Adds
-
100% Default Backward Compatibility: Calling
-
Disjoint Subagent 2 Files (
krusch-law):projects/krusch-law/src/backend/main.py,projects/krusch-law/tests/unit/test_fastapi_lego_shell.py- Discovers sibling monorepo
lib-pyviaos.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "lib-py"))(strictly zero hardcoded OS home paths and zero external cloud vendor stringsgoogle|gemini|openai|anthropicenforced byci.yml). - Imports
from krusch_toolkit.fastapi_app import create_fastapi_app, error_envelope, ok_envelopewith a standalone CIexcept ImportError:fallback (usingapp.add_api_route, never@app.get("/health")) so standalone GitHub Actions runs pass on Python3.11&3.12. - Replaces hand-rolled
FastAPI(...),CORSMiddleware, and@app.get("/health")withhealth_check()+create_fastapi_app(..., service_name="kruschlaw-backend", version="0.3.0", cors_origins=settings.cors_origins_list, allow_credentials=True, lifespan=lifespan, health_check=health_check, flatten_health_payload=True, legacy_error_detail=True, logger=logger).
- Discovers sibling monorepo
-
Disjoint Subagent 3 Files (
krusch-biz):projects/krusch-biz/src/backend/main.py,projects/krusch-biz/tests/test_fastapi_lego_shell.py- Discovers sibling monorepo
lib-pyviaos.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "lib-py"))(zero hardcoded OS home paths) and importsfrom krusch_toolkit.fastapi_app import create_fastapi_app, error_envelope, ok_envelopewith standalone CIexcept ImportError:fallback. - Updates
health_check(db_or_request: Any = None)sorequest: Requestresolves DB sessions throughrequest.app.dependency_overrides.get(get_db, get_db)()(closing the generator infinally), directSessionobjects execute directly, andNoneusesget_db(), returning HTTP200"healthy"/"degraded"diagnostics viacreate_fastapi_app(..., service_name="kruschbiz-backend", version="0.1.0-alpha.1", cors_origins=settings.cors_origins_list, allow_credentials=True, lifespan=lifespan, health_check=health_check, flatten_health_payload=True, legacy_error_detail=True, logger=logger).
- Discovers sibling monorepo
-
Disjoint Subagent 4 Files (
krusch-bizlaw):projects/krusch-bizlaw/src/backend/main.py,projects/krusch-bizlaw/tests/test_fastapi_lego_shell.py- Discovers sibling monorepo
lib-pyviaos.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "lib-py"))(zero hardcoded OS home paths) and importsfrom krusch_toolkit.fastapi_app import create_fastapi_app, error_envelope, ok_envelopewith standalone CIexcept ImportError:fallback. - Replaces hand-rolled
FastAPI(...),CORSMiddleware, and@app.get("/health")withhealth_check(request: Request)+create_fastapi_app(..., title="KruschBizLaw API", version="0.2.0", service_name="krusch-bizlaw", cors_origins=settings.cors_origins_list, allow_credentials=True, lifespan=lifespan, health_check=health_check, flatten_health_payload=True, legacy_error_detail=True, logger=logger)followed by_init_service_clients(app).
- Discovers sibling monorepo
-
Orchestrator Choke Points (Phase 3B — Parent Orchestrator Only):
-
lib/spec.md(Section 8 frozen contract) - Reconcile
krusch-bizINV-12anchor#8(.github/workflows/ci.yml) viakrusch_context_revise - Full
krusch-lego audit(0boilerplate findings acrosskrusch-law,krusch-biz,krusch-bizlaw), L0 Dual-Zero-Finding Referee convergence, GitHub Actions CI verification, multi-nodelib-pysync,kdcodere-indexing, andGEMINI_INFLIGHT.mdupdate.
-
-
9. Public Open-Source Release, Zero-Leak Sanitization & Unified Node + Python Distribution (INV-LEGO-26)
STATUS: FROZEN (
2026-10-31T16:10:00-07:00) — Publishes@krusch/toolkit(v1.7.0Node/TS/Workers at repository root) andkrusch_toolkit(v1.6.0Python 3.11+ insidepython/) tohttps://github.com/kruschdev/toolkitwith deterministic Zero-Leak CI enforcement (scripts/verify-zero-leaks.js), clean orphan single-root Git history (kruschdev <kruschdev@users.noreply.github.com>), and companion cross-linking inkrusch-stack.
INV-LEGO-26(Public Toolkit Zero-Leak Gate, Standalone Portability & Unified Distribution):-
Zero-Leak Invariant: Every tracked file in
kruschdev/toolkit(and upstreamlib/+lib-py/) MUST passnode ./scripts/verify-zero-leaks.js --strict-releasewith0findings:- Zero Secret Tokens / Keys:
0matches for API keys, PATs, PEM blocks, or hardcoded DB credentials (AIzaSy*,sk-*,ghp_*,github_pat_*,xox*,PRIVATE KEY). - Zero Private Host IPs:
0hardcoded LAN/10GbE/Tailscale host IPs (192.168.<h>.<h>,10.10.<h>.<h>,10.0.0.<1-255>,100.<65-127>.<h>.<h>), permitting only RFC subnet CIDR masks (10.0.0.0/8,192.168.0.0/16,100.64.0.0/10) and generic RFC test vectors (10.1.2.3,172.16.1.2,100.64.1.2,198.51.100.*,203.0.113.*,127.0.0.1). - Zero Host Filesystem Paths:
0/home/<user>/or/mnt/<volume>host paths anywhere in runtime code, blueprints, docs, or tests. - Zero Internal Hostnames, DB Names, or Personal PII: Enforced via SHA-256 salted token digests in
scripts/verify-zero-leaks.jsso the scanner itself never embeds plaintext PII or internal hostnames while catching any accidental re-introduction. - Zero Unlinked Git Emails & Zero Relative
file:../git+ssh://Dependencies (--strict-release): Author/committer attribution strictlykruschdev <kruschdev@users.noreply.github.com>;package.jsonandpackage-lock.jsoncontain zero"file:.."parent monorepo references and zero"git+ssh://"URLs (krusch-cascade-routerdeclared via SHA-512 integrity-pinned HTTPS tarball inoptionalDependencieswith lazy dynamic import inlib/llm.js).
- Zero Secret Tokens / Keys:
-
Disjoint Subagent 1 Files (JS Core Runtime Sanitization):
lib/config.js,lib/embeddings.js,lib/llm.js,lib/llm-queue.js,lib/polygres.js,lib/dbos.js,lib/tracing.js- Preserves all public function/class signatures (
getHomelabTopology,getHomelabContext,DEFAULT_EMBED_HOST = 'http://127.0.0.1:11434',DEFAULT_FLEET_OLLAMA_NODES = Object.freeze(['http://127.0.0.1:11434']), lazyawait import('krusch-cascade-router')inlib/llm.js,bgBaseUrl = process.env.OLLAMA_BG_URL || ollamaBaseUrl,appdbdefault inpolygres.js,os.tmpdir()default trace path intracing.js).
-
Disjoint Subagent 2 Files (JS Governance, Skill & Spatial Sanitization):
lib/prune.js,lib/trajectory-guard.js,lib/skiller.js,lib/types/skiller.d.ts,lib/evqa-grounding.js,lib/kv-cache-manager.js,lib/lego-scout.js- Replaces personal/internal keywords in
prune.jswith generic infra & billing domain triggers; generalizes credential leak regex intrajectory-guard.js; defaultsstageSkillForMonorepotargetDirtopath.join(process.cwd(), '.agent', 'skills'); defaultsEvidenceGroundingEnginepropertyIdto'demo-property'; defaultscreateGvaAllocator&createKvCacheManagernodeto'gpu-node-0'andstorageDirto'./.cache/kv_cache'; generalizes OS home-path scrub comments inlego-scout.js.
-
Disjoint Subagent 3 Files (JS Test Suites & Standalone CI Portability):
lib/test_physical_ai_research.js,lib/test_new_research_refinements.js,lib/test_new_research_modules.js,lib/test_september_ai_research.js,lib/test_september_mid_ai_research.js,lib/test_raw_rag.js,lib/test_embeddings.js,lib/test_wave3_bricks.js,lib/test_wave4_bricks.js,lib/test_lego_bricks.js,lib/test-browser.js- Scrubs residential street address & internal node/DB fixtures; updates
DEFAULT_EMBED_HOST&DEFAULT_FLEET_OLLAMA_NODESassertions to'http://127.0.0.1:11434'; guards optional sibling repo assertions intest_lego_bricks.js(checking./pythonwhen../lib-pyis absent and guarding../projects/krusch-stackwithfs.existsSync); hardens headless Chrome skip guard across all steps intest-browser.js.
-
Disjoint Subagent 4 Files (Python
krusch_toolkitRuntime & Tests Sanitization):lib-py/krusch_toolkit/embeddings.py,lib-py/krusch_toolkit/tracing.py,lib-py/krusch_toolkit/system.py,lib-py/krusch_toolkit/swarm/architect.py,lib-py/krusch_toolkit/swarm/director.py,lib-py/krusch_toolkit/swarm/db_bridge.py,lib-py/tests/test_embeddings.py,lib-py/tests/test_raw_rag.py,lib-py/tests/test_wave3_lego.py,lib-py/tests/test_wave6_lego.py,lib-py/.gitignore- Sets
DEFAULT_EMBED_HOST = "http://127.0.0.1:11434"; usestempfile.gettempdir()fallback intracing.py; removessudoand internal node references insystem.py; replaces internal IPs, legacy placeholder keys, and DB names inswarm/*; updates all Python test fixtures to generic RFC test IPs andappdb.
-
Orchestrator Choke Points (Phase 3B — Parent Orchestrator Only):
lib/catalog.js,lib/AGENTS.md,lib/README.md,lib/.gitignore,lib/.env.example,lib/LICENSE(MIT),lib/package.json(v1.7.0, MIT,verify:zero-leaks,optionalDependencies),lib/scripts/verify-zero-leaks.js,lib/test_zero_leaks.js- Standalone release assembly (
python/synced fromlib-py/,.github/workflows/ci.yml, cleanpackage-lock.json, single-commit orphan push tokruschdev/toolkit) - Companion cross-link in
projects/krusch-stack/README.md(kruschdev/krusch-stack)
-
STATUS: FROZEN (
2026-10-31T19:33:00-07:00) — Extends@krusch/toolkit/streaming(deferHeaders) andkrusch_toolkit.fastapi_app.sse_event_response(passthrough) with 100%-backward-compatible brownfield transport options and migrates 5 flagshipAGENTS.mdcore services (krusch-ci-sentinel,berean,krusch-agentic-proxy,g-krusch,krusch-frontend-mcp) to0krusch-lego auditboilerplate findings (9findings eliminated across8source files, reducing fleet[LEGO-ADOPT]from37$\rightarrow$ 32).
INV-LEGO-27(Deferred-Header MCP SSE, Passthrough OpenAI SSE & Standalone CI Fallback Parity):-
Orchestrator Pre-Wire (Additive Toolkit Enhancements — Zero Breaking Changes):
lib/streaming.js&lib/types/streaming.d.ts:- Adds
deferHeaders?: boolean(default: false) tosseResponse(res, req, options). - When
deferHeaders === false(default): behavior is 100% byte-identical (writeSseHeaders+retry: <ms>\n\n). - When
deferHeaders === true: setsX-Accel-Buffering: noviares.setHeaderwithout flushing status/headers or writing an initialretry:frame so downstream transports (e.g.@modelcontextprotocol/sdk'sSSEServerTransport.start()) can callres.writeHead(200, ...)withoutERR_HTTP_HEADERS_SENT, while attachingAbortControllerdisconnect listeners and unref'd: ping\n\nheartbeats (writing heartbeats only onceres.headersSent === true).
- Adds
lib-py/krusch_toolkit/fastapi_app.py:- Adds
passthrough: bool = False(andheartbeat_comment: str | None = "ping") tosse_event_response. - When
passthrough=False(default): behavior is 100% byte-identical (INV-LEGO-03structuredevent: token/event: done/event: errorframes). - When
passthrough=True: yields rawstr | bytesSSE chunks untouched (for OpenAIchat.completion.chunkdata: ...\n\ndata: [DONE]\n\nstreams and upstreamhttpxbyte-stream proxies) while preserving_is_request_disconnected(request)cancellation,aclosing(_iterate_sse_source(...))deterministic upstream socket/generator cleanup, optional: <heartbeat>\n\ncomment whenheartbeat_commentis non-empty, andCache-Control: no-cache, no-transform/Connection: keep-alive/X-Accel-Buffering: noanti-buffering headers.
- Adds
-
Disjoint Subagent 1 Files (
krusch-ci-sentinel):projects/krusch-ci-sentinel/src/mcp_bridge.js,projects/krusch-ci-sentinel/test/verifier.test.js- Eliminates hardcoded host path in
mcp_bridge.jsby resolvingprocess.env.KRUSCH_CONTEXT_DB_PATHor relative sibling../../krusch-context-mcp/.agent/context.db(plus optionalentry.dbPathoverride for hermetic tests). - Loads
openSqliteDbfrom sibling../../../lib/sqlite.js(@krusch/toolkit/sqlite) when available with a standalone CI fallback (node:sqlite), closing the handle infinallyinsiderecordContextMemory.
- Eliminates hardcoded host path in
-
Disjoint Subagent 2 Files (
berean):projects/berean/db/pool.js,projects/berean/routes/api.js,projects/berean/tests/conversations.test.js- Replaces raw
new pg.Pool(dbConfig)indb/pool.jswithcreatePgPool(dbConfig, { serviceName: 'berean-db' })from@krusch/toolkit/pgwhile preservingexport const dbConfig,export default pool, exactimport { DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD } from '../src/config/dbConfig.js', and zeroprocess.envreads (ARCH-02). - Replaces manual
res.writeHead(200, { 'Content-Type': 'text/event-stream', ... })inPOST /api/ask/stream(routes/api.js) withsseResponse(res, req, { tool: 'berean.ask_stream' })from@krusch/toolkit/streaming, emitting{ type: 'meta' | 'chunk' | 'sources' | 'done' | 'error' }payloads viastream.send('message', ...)and terminating withstream.close()soclient/dist/app.jsline-baseddata:parsing remains 100% compatible.
- Replaces raw
-
Disjoint Subagent 3 Files (
krusch-agentic-proxy):projects/krusch-agentic-proxy/src/api_gateway.py,projects/krusch-agentic-proxy/src/router.py,projects/krusch-agentic-proxy/tests/test_lego_sse.py- Discovers sibling monorepo
lib-pyviaos.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "lib-py"))(strictly zero hardcoded OS home paths) and importsfrom krusch_toolkit.fastapi_app import sse_event_responsewith a standalone CIexcept ImportError:fallback (usingaclosing+ anti-buffering headers without literal rawtext/event-streamboilerplate). - Wraps
_event_generator()in_build_sse_response(src/api_gateway.py) andstream_generator()inWaterfallRouter._try_stream(src/router.py) withsse_event_response(..., passthrough=True, heartbeat_comment=""), preserving 100% of OpenAIchat.completion.chunkwire framing and upstream byte-stream passthrough.
- Discovers sibling monorepo
-
Disjoint Subagent 4 Files (
g-krusch):projects/g-krusch/src/index.js,projects/g-krusch/src/lib/db.js,projects/g-krusch/test/hardening.test.js- Loads
sseResponsefrom sibling../../../lib/streaming.js/@krusch/toolkit/streaming(with standalone CI fallback) insrc/index.js, wiringGET /mcp/ssewithsseResponse(res, req, { deferHeaders: true, retryMs: 0, heartbeatMs: 15000, corsOrigin: false, tool: 'g-krusch.mcp_sse' })soSSEServerTransport.start()ownsres.writeHead(200, ...)withoutERR_HTTP_HEADERS_SENTwhile preservingGKR-01&GKR-07(app.get('/mcp/sse', apiLimiter, ...)andhandlePostMessage(req, res, req.body)) and zero hardcoded OS home paths (INV-12). - Loads
initDb&closeDbfrom sibling../../../../lib/db.js/@krusch/toolkit/db(with standalone CI fallback) insrc/lib/db.js, passing_DatabaseClass: Database(better-sqlite3) andbusyTimeout: 5000so WAL/durability pragmas and test exit cleanup remain 100% preserved without modifyingpackage.json(npm cisafe).
- Loads
-
Disjoint Subagent 5 Files (
krusch-frontend-mcp):projects/krusch-frontend-mcp/src/index.js,projects/krusch-frontend-mcp/src/lib/db.js,projects/krusch-frontend-mcp/tests/db.test.js- Loads
createMcpServer&defineMcpToolfrom sibling../../../lib/mcp-server.js/@krusch/toolkit/mcp(with standalone CI fallback) insrc/index.js, normalizingFRONTEND_TOOL_DEFINITIONSviadefineMcpTooland booting stdio viacreateMcpServer("krusch-frontend-mcp", VERSION, FRONTEND_TOOL_DEFINITIONS, (name, args) => dispatchFrontendTool({ params: { name, arguments: args } }), { validateArgs: false })while preservingVERSION,FRONTEND_TOOL_CAPABILITIES,FRONTEND_TOOL_DEFINITIONS,dispatchFrontendTool, and live child-process stdio execution (scripts/evaluate-swarm.js). - Loads
initDb&closeDbfrom sibling../../../../lib/db.js/@krusch/toolkit/db(with standalone CI fallback) insrc/lib/db.js, passing_DatabaseClass: Database(preservingsqlite-vecC-extension ABI compatibility,validateDbPath,initDbAsyncmutex serialization, andresetDbForTestsingleton reset).
- Loads
-
STATUS: FROZEN (
2026-10-31T21:08:00-07:00) — Extends@krusch/toolkit/mcpwith synchronousregisterMcpHandlersand cross-realmrethrowMcpErrorJSON-RPC protocol propagation, alignsCATALOG_AUDIT_EXEMPT_PATH_RE(benchmarks?) withlego-scoutSKIP_SUBDIRECTORIES(krusch-cascade-router/benchmark/routellm/...), and migrates all 6 remainingAGENTS.mdactive core services (krusch-context-mcp,krusch-git,krusch-coding-harness,krusch-companion,home-ai,first-things-first) to0krusch-lego auditboilerplate findings — achieving24/24(100%) Zero-Boilerplate Core Services acrossAGENTS.md(27findings eliminated across26files; fleet[LEGO-ADOPT]reduced32$\rightarrow$ 26).
-
INV-LEGO-28(Synchronous MCP Handler Registration, Cross-RealmMcpErrorPropagation & 100% Core-Fleet Parity):-
Orchestrator Pre-Wire (Additive Toolkit Enhancements — Zero Breaking Changes):
-
lib/mcp-server.js,lib/index.js,lib/catalog.js,lib/types/mcp-server.d.ts,lib/types/index.d.ts:- Exports synchronous
registerMcpHandlers(server, tools, toolHandler, options)(called internally bycreateMcpServer), passing(toolName, toolArgs, request)totoolHandlerso brownfield synchronous MCP server factories (krusch-coding-harness'screateMcpServer(),krusch-git's exportedserver, andkrusch-context-mcp'sserver.getClientVersion()provenance hook) wireListToolsRequestSchemaandCallToolRequestSchemawithout breaking synchronous callers. - Adds
rethrowMcpError?: boolean(default: false) andcapabilities?: Record<string, unknown>: whenrethrowMcpError === true, JSON-RPCMcpErrorinstances (error instanceof McpError || error.name === 'McpError' || (typeof error.code === 'number' && error.code <= -32000)) are rethrown acrossnode_modulesboundaries rather than wrapped intoerrorMcpResult, preserving 100% ofassert.rejects(..., McpError)integration contracts.
- Exports synchronous
-
lib/catalog.js:- Updates
CATALOG_AUDIT_EXEMPT_PATH_REfrombenchmarkstobenchmarks?to matchlib/lego-scout.jsSKIP_SUBDIRECTORIES, exempting vendored third-party benchmark suites (krusch-cascade-router/benchmark/routellm/...) without touching SHA-256-pinneddist/index.js.
- Updates
-
-
Standalone GitHub CI Invariant (
INV-LEGO-28A):- Standalone GitHub repositories (
krusch-context-mcp,krusch-git,krusch-coding-harness,krusch-companion) MUST NOT add relative"file:../../lib"dependencies topackage.json(npm ciin GitHub Actions runs without siblinglib/). Each migrated module resolves its siblinglib/<brick>.jsviaexistsSync(new URL('...', import.meta.url))$\rightarrow$ import('@krusch/toolkit/<subpath>')$\rightarrow$ deterministic standalone fallback free of raw boilerplate triggers and zero hardcoded OS home paths. - Monorepo-resident applications (
home-ai,first-things-first) already declare"@krusch/toolkit": "file:../../lib"and import directly from@krusch/toolkit/<subpath>. - Zero SHA-256-pinned benchmark files (
68/68pins) orINV-12quoted-span files may be modified, and zero BEAM evaluation dataset tokens may appear inprojects/krusch-context-mcp/src/*.js.
- Standalone GitHub repositories (
-
Disjoint Subagent 1 Files (
krusch-context-mcpStorage & DB):projects/krusch-context-mcp/db/pool.js,projects/krusch-context-mcp/scripts/clear_sqlite_embeddings.js,projects/krusch-context-mcp/src/sqlite-engine.js,projects/krusch-context-mcp/src/storage-adapter.js-
db/pool.js: Preserves lazypgloading insidegetPoolInstance()(#877: SQLite-only installs withoutpgnever fail at module import time), checkingrequire.resolve('pg')before delegating pool construction tocreatePgPoolfrom sibling../../../lib/pg.js/@krusch/toolkit/pg(with standalonepgfallback). -
clear_sqlite_embeddings.js,src/sqlite-engine.js,src/storage-adapter.js: Delegatesnode:sqliteconnection opening toopenSqliteDbfrom siblinglib/sqlite.js/@krusch/toolkit/sqlite(with standalonenode:sqlitefallback), preservingsqlite-engine.jsinode-rotation checks, corrupt-SQLite rotation recovery, WAL/busy_timeoutpragmas, and zero dataset vocabulary insrc/*.js.
-
-
Disjoint Subagent 2 Files (
krusch-context-mcpStdio Server):projects/krusch-context-mcp/src/index.js- Normalizes
CORE_TOOL_DEFINITIONSviadefineMcpTool, registers tool handlers viaregisterMcpHandlers(validateArgs: false, rethrowMcpError: true) alongsideListPromptsRequestSchema/GetPromptRequestSchema, and connects stdio inrunServer()viacreateMcpServerfrom@krusch/toolkit/mcp(with standalone CI fallback), preservingVERSION,CORE_TOOLS,CORE_PROMPTS,connectedClientprovenance injection, legacy aliases (retrieve,remember,revise,nudge,health,status), and graceful shutdown.
- Normalizes
-
Disjoint Subagent 3 Files (
krusch-git):projects/krusch-git/db/pool.js,projects/krusch-git/server/mcp.js,projects/krusch-git/client/src/App.jsx-
db/pool.js: Delegates live pool creation tocreatePgPool(@krusch/toolkit/pg+ standalone fallback) while preservingKRUSCH_EPHEMERAL/CImockPoolfallback andexport { query, pool }. -
server/mcp.js: Normalizes the 7krusch_git_*tool schemas viadefineMcpTool, attaches handlers synchronously onexport const serverviaregisterMcpHandlers(validateArgs: false, rethrowMcpError: true), and connects stdio inmain()viacreateMcpServer, preservingpg_git_*backward-compatible aliases,verifyDatabase(), andMcpErrorJSON-RPC rejections. -
client/src/App.jsx: WiresAbortController{ signal: controller.signal }+controller.abort()teardown across all 3useEffecthooks (/api/repos,/api/tree,/api/blob).
-
-
Disjoint Subagent 4 Files (
krusch-coding-harness):projects/krusch-coding-harness/db/migrate.js,projects/krusch-coding-harness/src/brain/pool.js,projects/krusch-coding-harness/src/approvals/hitl-slack-gate.js,projects/krusch-coding-harness/src/server/mcp-server.js-
db/migrate.js&src/brain/pool.js: Delegates non-ephemeral PostgreSQL pool creation tocreatePgPool(@krusch/toolkit/pg+ standalone fallback), preservingPGliteephemeral mode,getPool(),pool,query,withTransaction,closePool, andmigrate(). -
src/approvals/hitl-slack-gate.js: Delegates HMAC computation and constant-time Slackv0verification tosignWebhookHmac&verifySlackSignature(@krusch/toolkit/webhooks+ standalone fallback), preservingcomputeSlackSignature(TypeErroron missing secret) and exact{ valid, reason }return codes (missing_signing_secret,invalid_timestamp,stale_timestamp_skew_*,invalid_signature_format,signature_mismatch,ok) inverifySlackWebhookSignature. -
src/server/mcp-server.js: Keepsexport function createMcpServer(options = {})synchronous viadefineMcpTool+registerMcpHandlers(validateArgs: false, rethrowMcpError: true), and connects stdio instartMcpServer()via@krusch/toolkit/mcp, preservingserver.registerTask,server.listTasks,server.closedrain hooks, andMcpErrorrejections.
-
-
Disjoint Subagent 5 Files (
krusch-companionDB & React Views):projects/krusch-companion/src/db/index.js,projects/krusch-companion/client/src/views/CompanionView.jsx,projects/krusch-companion/client/src/views/FocusView.jsx,projects/krusch-companion/client/src/views/SetupView.jsx,projects/krusch-companion/client/src/views/SystemMemoryView.jsx,projects/krusch-companion/client/src/views/TodayView.jsx-
src/db/index.js: Delegates SQLite WAL initialization toinitDb/closeDb(@krusch/toolkit/db+ standalone fallback with_DatabaseClass: Database), preservinginitCompanionDb(customPath)singleton/custom-path semantics and all exported helpers. - React Views (
5files): WiresAbortController{ signal: controller.signal }+controller.abort()cleanup across everyuseEffectfetch(...)call, ignoringAbortErroron unmount.
-
-
Disjoint Subagent 6 Files (
home-ai&first-things-firstServices/Routes):projects/home-ai/scripts/seed-home-tasks.js,projects/home-ai/server/services/ollama.js,projects/home-ai/server/routes/api.js,projects/home-ai/server/routes/wall.js,projects/first-things-first/seed-home-tasks.js-
seed-home-tasks.js(home-ai&first-things-first): UsesinitDbfrom@krusch/toolkit/db(convertingfirst-things-first/seed-home-tasks.jsfrom broken CommonJS to valid ESM). -
home-ai/server/services/ollama.js&home-ai/server/routes/api.js(/notifications/stream): Replaces manualtext/event-streamwriteHeadcalls withsseResponsefrom@krusch/toolkit/streaming, preserving exactdata: ...\n\nevent payloads andheartbeat.jsaddSSEClient(res)compatibility. -
home-ai/server/routes/api.js(/transcribe) &home-ai/server/routes/wall.js(/photos/upload,/voice/transcribe): ReplacesmulterwithparseBoundedMultipart,verifyUploadMime, andsanitizeUploadFilenamefrom@krusch/toolkit/upload, preserving byte limits (10 MBphotos,25 MBaudio), magic-byte image verification, disk write toWALL_PHOTOS_DIR, and exact HTTP400/413/422/200JSON responses.
-
-
Parent Orchestrator Choke Points (Wired After Subagent Completion):
-
projects/krusch-companion/src/server.js&projects/krusch-companion/src/agent/tools.js: Replacesmulteracross/api/companion/voice,/api/companion/transcribe, and/api/companion/visionwithparseBoundedMultipart(@krusch/toolkit/upload+ standalone CI fallback), passing non-multipart/form-datarequests (e.g.,application/json{ prompt, base64Image }on/api/companion/vision) straight through tonext()untouched, and guardsSKYLIGHT_CALENDAR_TOOL.executeinsrc/agent/tools.jswith anexistsSynclocal-twin fallback when siblingkrusch-companion-skylight-connectoris absent in standalone GitHub Actions CI. -
projects/first-things-first/server.js: Replacesmulteron/api/voice/transcribewithparseBoundedMultipart+sanitizeUploadFilenamefrom@krusch/toolkit/upload, ensuringdata/voicedirectory creation and preserving exact response fields.
-
-
12. Step 8E — Scanner Hygiene, Standalone Connectors, Secondary MCPs, Orchestrator Scripts & Trade Suite LEGO-ADOPT Migration (INV-LEGO-29)
STATUS: FROZEN — Pre-execution contract governing toolkit audit/scout scanner parity and the 6-subagent parallel
LEGO-ADOPTmigration across standalone connectors, secondary MCP servers, rootscripts/,roughin-suite,lightmind, and clean 1–2 file monorepo apps (44target files +3toolkit scanner modules).
- INV-LEGO-29 (Scanner Hygiene & Secondary Fleet Zero-Boilerplate Migration):
-
Toolkit Scanner Alignment (
lib/catalog.js,lib/bin/krusch-lego.js,lib/lego-scout.js):lib/catalog.js(CATALOG_AUDIT_EXEMPT_PATH_RE): Exempts vendored/cache/scratch directory segments (site-packages,__pycache__,vendor,third_party,archive,_archive,archive_scratch,scratch) in addition tolib,lib-py,krusch_toolkit,krusch-stack,test/tests/__tests__,benchmark/benchmarks, andnode_modules.lib/bin/krusch-lego.js(SKIP_DIRECTORIES,isExemptAuditPath,collectAuditFiles): Addsvenv,env,site-packages,__pycache__,benchmark,vendor,third_party,archive,_archive,archive_scratch, andscratchtoSKIP_DIRECTORIES, and skips any directory (or ancestor directory up to 8 levels) containingpyvenv.cfg(matchinglib/lego-scout.jsvirtualenv detection so custom-named virtualenvs such asbench_venvormcp_envare never crawled).lib/lego-scout.js(SKIP_TOP_PROJECTS,SKIP_SUBDIRECTORIES): Addsvllm,lib,lib-py, andscratchtoSKIP_TOP_PROJECTSandscratch+archive_scratchtoSKIP_SUBDIRECTORIES.
-
Standalone Sibling-Optional Resolution (
INV-LEGO-28AContinuation) & Legal Corpus Isolation (INV-05):- Standalone GitHub repositories (
kruschdev/krusch-polygres-connector,kruschdev/krusch-companion-skylight-connector) and standalone-manifest projects without@krusch/toolkitinpackage.jsonresolve toolkit bricks viafs.existsSyncsibling check (../../../lib/<brick>.jsor../../../../lib/<brick>.js), then dynamicimport('@krusch/toolkit/<subpath>'), then a deterministic local fallback using already-installed dependencies (pg,node:sqlite,@modelcontextprotocol/sdk,node:buffer) so fresh standalonegit clone && npm ci && npm testruns pass without siblinglib/orpackage.jsonfile:..mutations. projects/krusch-pocketlawyer-mcp/src/shared.jsstrictly preservesDB_PORTdefault5433andbge-large:latest(keep_alive: '5m') perINV-05.
- Standalone GitHub repositories (
-
Explicitly Deferred Non-Target Directories (
8Projects Untouched):dbos-worker(package.json+src/legacy worker pending archive),krusch-research-mcp(unrelated uncommitted worktree edits),card-game-context(external upstream git remote), and 5 legacy untracked/archive prototypes (annotated,heyjb,hivemind-companion-ext,krusch-life,krusch-worker), plusscripts/self_heal_infra.js(INV-12span-anchored,0audit hits) and all68/68SHA-256-pinned benchmark files.
-
Disjoint Subagent 1 Files (
Standalone Connectors — 4 files):projects/krusch-polygres-connector/src/index.js,projects/krusch-polygres-connector/src/context-bridge.js,projects/krusch-polygres-connector/src/git-bridge.js,projects/krusch-companion-skylight-connector/src/companion-bridge.jskrusch-polygres-connector: Delegates PostgreSQL pool initialization tocreatePgPool(../../../lib/pg.js/@krusch/toolkit/pg+ fallback) and SQLite opening incontext-bridge.jstoopenSqliteDb(../../../lib/sqlite.js/@krusch/toolkit/sqlite+ fallback), preservingisEphemeralMode(),polygresPoolErrorcaching, and[ContextBridge] Local SQLite database at '...' corrupt or unreadablediagnostics.krusch-companion-skylight-connector: Delegates SQLite WAL opening incompanion-bridge.jstoopenSqliteDb(../../../lib/sqlite.js/@krusch/toolkit/sqlite+ fallback), preserving0o750/0o640permissions, schema bootstrap, prepared statements, andclose().
-
Disjoint Subagent 2 Files (
Secondary MCP Servers — 6 files):projects/krusch-pocketlawyer-mcp/src/shared.js,projects/krusch-pocketlawyer-mcp/src/index.js,projects/krusch-sequential-mcp/src/config.ts,projects/krusch-sequential-mcp/src/index.ts,projects/hivemind-mcp/src/index.js,projects/krusch-agentic-mcp/src/router.pykrusch-pocketlawyer-mcp: Delegates PG pool creation insrc/shared.jstocreatePgPool(INV-055433+bge-large:latestpreserved) and MCP stdio wiring insrc/index.jstodefineMcpTool/registerMcpHandlers/createMcpServer, preservinghandleListToolsandhandleCallTool(request, deps).krusch-sequential-mcp&hivemind-mcp: Delegates PG pool creation (config.ts) tocreatePgPooland MCP tool normalization / stdio transport (index.ts,hivemind-mcp/src/index.js) todefineMcpTool,registerMcpHandlers(validateArgs: false, rethrowMcpError: true), andcreateMcpServer, preserving exportedserver, validation helpers, andnpm run buildTypeScript compilation.krusch-agentic-mcp/src/router.py: Wrapsstream_generator()withsse_event_response(..., heartbeat_comment=None, passthrough=True)fromkrusch_toolkit.fastapi_app(withlib-pysys.path+ standalone fallback).
-
Disjoint Subagent 3 Files (
Orchestrator scripts/ — 12 files):scripts/brain-wakeup.js,scripts/check_audits.js,scripts/check_db.js,scripts/check_queue.js,scripts/dispatch_mcp_jobs.js,scripts/dispatch_sandbox_audits.js,scripts/homelab_memory_mcp.js,scripts/query_episodes.js,scripts/query_local_jobs.js,scripts/query_orbit_jobs.js,scripts/search_all_tables.js,scripts/swarm_cli.js- Delegates PostgreSQL pool creation across all 12 scripts to
createPgPoolvia'../lib/pg.js'(withimport('@krusch/toolkit/pg')fallback), and delegates MCP tool/stdio wiring inscripts/homelab_memory_mcp.jstodefineMcpTool,registerMcpHandlers, andcreateMcpServervia'../lib/mcp-server.js', preservingvalidateQueueEnvandcreateQueuePoolexports inscripts/check_queue.js.
- Delegates PostgreSQL pool creation across all 12 scripts to
-
Disjoint Subagent 4 Files (
roughin-suite Pool, React & Upload Middlewares — 6 files):projects/roughin-suite/db/pool.js,projects/roughin-suite/packages/climacore/public/src/pages/CodeRef.jsx,projects/roughin-suite/packages/drainflux/public/src/pages/CodeRef.jsx,projects/roughin-suite/packages/climacore/routes/middleware.js,projects/roughin-suite/packages/drainflux/routes/middleware.js,projects/roughin-suite/packages/spark/routes/middleware.jsdb/pool.js: Delegates pool creation tocreatePgPoolfrom@krusch/toolkit/pg, preservingquery,queryOne,run,getPool,closePool, andexport default pool.CodeRef.jsx(climacore&drainflux): WiresAbortController{ signal: controller.signal }+controller.abort()cleanup inuseEffect.routes/middleware.js(climacore,drainflux,spark): ReplacesmulterwithparseBoundedMultipart+sanitizeUploadFilenamefrom@krusch/toolkit/upload(requireMagicMatch: falsefor ISO-BMFFmp4/mov/heiccompatibility, plus<svg/<scriptpayload rejection on image uploads), preservingasyncHandler,createUpload(spark),upload, andvideoUpload(.single()/.fields()), writing accepted files toconfig.uploads.dir, returning413on byte-cap overflow, and leavingreq.file = undefined+next()on unsupported MIME so downstream route handlers emit their exact400messages.
-
Disjoint Subagent 5 Files (
roughin-suite & lightmind Upload Routes — 6 files):projects/roughin-suite/packages/drainflux/routes/survey.js,projects/roughin-suite/packages/roughin/routes/auth.js,projects/roughin-suite/packages/roughin/routes/blueprints.js,projects/roughin-suite/packages/roughin/routes/photos.js,projects/roughin-suite/packages/roughin/routes/video-scan.js,projects/lightmind/server/routes/tracks.js- Replaces
multeracross all 6 route modules withparseBoundedMultipart+sanitizeUploadFilename(@krusch/toolkit/uploadinroughin-suite; sibling../../../../lib/upload.js+@krusch/toolkit/upload+ fallback inlightmind/server/routes/tracks.js), usingrequireMagicMatch: falsewheremp4/mov/heic/flacare accepted, rejecting<svg/<scriptmarkup on image uploads, writing files to the exact per-route upload directories, and preservingreq.file/req.files/req.bodyshapes and HTTP status codes (400/404/413/200/201).
- Replaces
-
Disjoint Subagent 6 Files (
Clean Monorepo 1–2 File Apps — 10 files):projects/ai-watch/index.js,projects/Brain3/lib/db.js,projects/signet/lib/dbService.js,projects/caren/db/database.js,projects/caren/db/seed.js,projects/conversational-rag/lib/proxy.js,projects/parasite-proxy/server.js,projects/kruschstack/mcp-server.js,projects/kruschstack/server.js,projects/spectralquant-ollama-bridge/backend/server.py- Delegates
ai-watch/index.jstocreatePgPool(@krusch/toolkit/pg),Brain3/lib/db.jstoopenSqliteDb(@krusch/toolkit/sqlite+ sibling fallback),signet/lib/dbService.jsto read-onlyopenSqliteDb(filepath, { readOnly: true })(@krusch/toolkit/sqlite, replacing rawbetter-sqlite3new Database),caren/db/{database,seed}.jstoinitDb/SQLiteDatabase(@krusch/toolkit/db+ sibling fallback),conversational-rag/lib/proxy.js(heartbeatMs: 0, retryMs: 0) ¶site-proxy/server.js(heartbeatMs: 15000, retryMs: 0) tosseResponse(@krusch/toolkit/streaming),kruschstack/{mcp-server,server}.jsto@krusch/toolkit/mcp&@krusch/toolkit/streaming, andspectralquant-ollama-bridge/backend/server.pytosse_event_response(..., request=request, heartbeat_comment=None, passthrough=True)fromkrusch_toolkit.fastapi_app.
- Delegates
-