Status:
FROZEN(2026-11-18) Packages:@krusch/toolkit(v1.8.1,40bricks,INV-LEGO-01..36) &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
-
13. Step 8F — Final 8 Brownfield Directories & 100% Zero-Boilerplate Workspace Completion (INV-LEGO-30)
- STATUS: FROZEN (
2026-11-01) - Governance Tier:
L0(77source files across8brownfield project directories;/spec-first-refactor+/parallel-build) - Objective: Migrate the final
8[LEGO-ADOPT]brownfield directories (79boilerplate findings across77files) identified bykrusch-lego scout projects/onto certified@krusch/toolkitbricks so the entire99-project workspace achieves0[LEGO-ADOPT]findings (99/99=100.0%Zero-Boilerplate Workspace) and0uncovered Rule-of-3 clusters, with100%backward compatibility across every unit test suite and TypeScript build.
-
Zero Boilerplate Hits & Zero Regressions:
node bin/krusch-lego.js scout <projects-dir>MUST report0projects with adoption opportunities and0Rule-of-3 extraction candidates.- Every migrated project's existing test suite and TypeScript compiler (
tsc) MUST pass with0regressions, and no external upstream Git remote (card-game-context) may be pushed. - Pre-existing hardcoded fallback password literals in legacy debug/worker pool scripts MUST be replaced with environment-resolved configuration (
process.env.DATABASE_URL/@krusch/toolkit/pgdefaults).
-
Disjoint Parallel Subagent Boundaries (
5Code Migration Subagents,77Files):- Disjoint Subagent 2 (
dbos-workerBatch A —28files):check_all_jobs.js,check_all_pending.js,check_connections.js,check_dbos_status.js,check_failed_jobs.js,check_job_payloads.js,check_locks.js,check_operation_outputs.js,check_schema.js,check_specific_intents.js,check_sre_jobs.js,check_summary.js,check_target_jobs.js,check_workflow_id.js,check_workflow_inputs.js,check_workflow_queue.js,find_job.js,heal_queue.js,list_dbos_tables.js,mass_deny.js,mcp_server.js,reset_all_ghosts.js,scratch_check.js,scratch_check_db.js,scratch_check_job_status.js,scratch_check_neurogolf_intents.js,scratch_check_outputs.js,scratch_check_parent.js.- Delegates PostgreSQL pool creation across all
28files (converting broken CJSrequire('pg')scripts inside ESM"type": "module"dbos-workerto valid ESM) tocreatePgPoolfrom'@krusch/toolkit/pg'.
- Delegates PostgreSQL pool creation across all
- Disjoint Subagent 3 (
dbos-workerBatch B —28files):scratch_check_recent_jobs.js,scratch_check_running_jobs.js,scratch_check_specifics.js,scratch_check_sre_jobs.js,scratch_clean_and_reset.js,scratch_clear.js,scratch_count.js,scratch_dates.js,scratch_force_fail.js,scratch_human_review.js,scratch_inspect_details.js,scratch_inspect_payload.js,scratch_inspect_whole_row.js,scratch_intent_results.js,scratch_jobs.js,scratch_list_queue.js,scratch_list_tables.js,scratch_query_intents.js,scratch_query_memory.js,scratch_query_queue.js,scratch_reject_human.js,scratch_requeue_sre_jobs.js,scratch_reset_job.js,scratch_reset_queue.js,scratch_test_new_tools.js,scratch_test_select.js,scratch_test_select_parts.js,scripts/unleash_swarm.js.- Delegates PostgreSQL pool creation across all
28files (including the remaining CJSrequire('pg')scripts) to ESMcreatePgPoolfrom'@krusch/toolkit/pg', preservingdbos-worker6/6tests.
- Delegates PostgreSQL pool creation across all
- Disjoint Subagent 4 (
krusch-life&krusch-research-mcp—7files):projects/krusch-life/db/run.js,projects/krusch-life/src/db/adapter.js,projects/krusch-life/src/ingestion/gmail.js,projects/krusch-life/src/ingestion/imessage.js,projects/krusch-research-mcp/db/pool.js,projects/krusch-research-mcp/src/server.js,projects/krusch-research-mcp/src/sqlite-engine.js.krusch-life: Delegates PG pool creation (db/run.js,adapter.js,gmail.js,imessage.js) tocreatePgPool(@krusch/toolkit/pg) and SQLite opening (adapter.js,imessage.js) toSQLiteDatabase(@krusch/toolkit/db), preserving all exported functions (initDb,createConnectionBundle, etc.) across all 8 inbound callers (10/10tests).krusch-research-mcp: Resolves sibling../../lib/{pg,mcp-server,db}.js(with@krusch/toolkit/*fallback) to delegatedb/pool.js(createPgPool),src/server.js(registerMcpHandlers&createMcpServerwith{ validateArgs: false, rethrowMcpError: true }), andsrc/sqlite-engine.js(SQLiteDatabase), preserving3/3tests and leaving pre-existing worktree state (D .env,?? .gitignore) untouched.
- Disjoint Subagent 5 (
krusch-worker,card-game-context,hivemind-companion-ext—7files):projects/krusch-worker/mcp_server.js,projects/krusch-worker/src/worker.ts,projects/krusch-worker/worker.js,projects/krusch-worker/scripts/local_audit_runner.js,projects/krusch-worker/scripts/swarm_researcher.js,projects/card-game-context/production/scripts/build-html.js,projects/hivemind-companion-ext/src/database/pgAdapter.ts.krusch-worker: Delegates PG pool creation in all 5 files tocreatePgPool(@krusch/toolkit/pg), preservingresolveDatabaseUrl,resolveMcpDatabaseUrl,ALLOWED_MODELS,npm run build(tsc), and7/7tests.card-game-context: Uses Node 22 synchronousrequire(esm)on../../../../lib/yaml.js(parseSafeYaml, withjs-yamlCORE_SCHEMAfallback) inproduction/scripts/build-html.js, preserving37/37YAML card validation tests (local-only, never pushed).hivemind-companion-ext: Uses runtimerequireon../../../../lib/pg.js(createPgPool, respectingtsconfig.json"rootDir": "src", with fallback if sibling absent) insrc/database/pgAdapter.ts, preservingnpm run compile(tsc -p ./) and7/7tests.
- Disjoint Subagent 6 (
annotated&heyjb—7files):projects/annotated/client/src/App.jsx,projects/annotated/client/src/SidePanelApp.jsx,projects/annotated/server/src/db.ts,projects/annotated/server/src/seed.ts,projects/heyjb/src/dashboard/routes/chat.js,projects/heyjb/src/dashboard/routes/mcp.js,projects/heyjb/src/dashboard/routes/media.js.annotated: WiresAbortController(signal+ cleanupcontroller.abort()) into everyuseEffectcallingfetch(...)inApp.jsxandSidePanelApp.jsx, and delegates PG pool creation inserver/src/db.ts(10inbound callers) andserver/src/seed.tsviacreateRequire(import.meta.url)('../../../../lib/pg.js').createPgPool(rootDir-safe fortsc), preservingnpm --prefix server run buildand3/3tests.heyjb: Delegates SSE headers/heartbeats inchat.js(checking400pre-conditions BEFOREsseResponse) andmcp.js(heartbeatMs: 30000, retryMs: 0) tosseResponse(@krusch/toolkit/streaming), and replacesmulterinmedia.jswithparseBoundedMultipart+sanitizeUploadFilename(@krusch/toolkit/upload, checkinggetContentById404BEFORE writing files, enforcing/^\.[a-z0-9]{1,10}$/extension hygiene, and blocking<svg/<scriptactive markup underimage/*), preserving13/13tests.
- Disjoint Subagent 2 (
STATUS: FROZEN (
2026-11-03) — Adds 4 zero-dependency enterprise application runtime bricks to@krusch/toolkitv1.8.0(idempotency,audit-log,rbac,pagination), advancingRUNTIME_BRICKSfrom35to39with 1:1 strict TypeScript.d.tsparity (INV-LEGO-11) andINV-LEGO-26Zero-Leak cleanliness.
-
INV-LEGO-31(Atomic Request Idempotency Lock, Payload Fingerprinting & Replay Cache —@krusch/toolkit/idempotency):-
Disjoint Subagent 1 Files:
lib/idempotency.js,lib/types/idempotency.d.ts -
Dependencies: Built-in
node:crypto+{ okEnvelope, errorEnvelope } from './http.js'(zero external npm packages). -
Exact Exports & Return Contracts:
-
DEFAULT_IDEMPOTENCY_OPTIONS:Object.freeze({ ttlMs: 86_400_000, maxEntries: 10_000, inFlightTimeoutMs: 60_000, maxKeyLength: 255, headerName: 'idempotency-key' }). -
normalizeIdempotencyKey(rawKey, { maxKeyLength = 255, tool = 'idempotency.key' } = {}):- Non-throwing validator rejecting invalid
maxKeyLength(!Number.isInteger(maxKeyLength) || maxKeyLength < 1 || maxKeyLength > 1024->IDEMPOTENCY_INVALID_OPTIONS), missing/non-string/whitespace-only keys (IDEMPOTENCY_KEY_MISSING), keys exceedingmaxKeyLengthafter trim (IDEMPOTENCY_KEY_TOO_LONG), and ASCII control characters[\x00-\x1f\x7f](IDEMPOTENCY_KEY_INVALID). - Returns
okEnvelope(tool, 'Idempotency key valid', { key })orerrorEnvelope(code, message, details, tool).
- Non-throwing validator rejecting invalid
-
computePayloadFingerprint(payload, { method = '', path = '', maxDepth = 32, tool = 'idempotency.fingerprint' } = {}):- Non-throwing canonical SHA-256 hex digest over
{ method: String(method).trim().toUpperCase(), path: String(path).trim(), body }. - Sorts plain-object own keys deterministically (
Object.keys), omitsundefinedobject property values (mappingundefinedarray elements or rootundefinedtonulland-0to0), encodesUint8Array/Buffercleanly as{ $bytesBase64 }, and rejects circular references (IDEMPOTENCY_CIRCULAR_PAYLOAD),maxDepthoverflow (IDEMPOTENCY_MAX_DEPTH), lone UTF-16 surrogates,BigInt,Symbol,Function, andNaN/Infinity(IDEMPOTENCY_INVALID_PAYLOAD). - Returns
okEnvelope(tool, 'Payload fingerprint computed', { fingerprint })orerrorEnvelope(code, message, details, tool).
- Non-throwing canonical SHA-256 hex digest over
-
createIdempotencyStore({ ttlMs = 86_400_000, maxEntries = 10_000, inFlightTimeoutMs = 60_000, maxKeyLength = 255, nowFn = Date.now } = {}):- Validates integer
maxEntries >= 1, finite positivettlMs >= 1,inFlightTimeoutMs >= 1, and1 <= maxKeyLength <= 1024(throwingRangeErroron invalid developer config). - Uses a prototype-safe
Mapwith LRU refresh on replay, automatic expiration ofCOMPLETEDentries (now >= expiresAt) and staleIN_FLIGHTentries (now - startedAt >= inFlightTimeoutMs), and eviction of expired/oldest-COMPLETEDentries atmaxEntries(never evicting activeIN_FLIGHTlocks; returnserrorEnvelope('IDEMPOTENCY_STORE_FULL', ..., { statusCode: 503 }, tool)fail-closed if allmaxEntriesare actively in flight). - Exposes frozen store API:
-
begin(key, fingerprint, { tool = 'idempotency.store' } = {}): Validateskeyand non-empty stringfingerprint(IDEMPOTENCY_INVALID_FINGERPRINT). On fingerprint mismatch against an activeIN_FLIGHTorCOMPLETEDentry, returnserrorEnvelope('IDEMPOTENCY_PAYLOAD_MISMATCH', ..., { key, statusCode: 422 }, tool)using constant-time byte comparison (crypto.timingSafeEqual). On matchingIN_FLIGHTentry, returnserrorEnvelope('IDEMPOTENCY_IN_FLIGHT', ..., { key, statusCode: 409 }, tool). On matchingCOMPLETEDentry, returnsokEnvelope(tool, 'Idempotency replay hit', { outcome: 'REPLAY', key, fingerprint, statusCode, body: deepClone(body), headers: { ...headers }, storedAt }). Otherwise acquires lock withlockToken = crypto.randomUUID()and returnsokEnvelope(tool, 'Idempotency lock acquired', { outcome: 'ACQUIRED', key, fingerprint, lockToken }). -
commit(key, lockToken, { statusCode = 200, body = null, headers = {}, tool = 'idempotency.store' } = {}): Verifies activeIN_FLIGHTownership oflockToken(IDEMPOTENCY_LOCK_LOST), deep-clonesbody(rejecting non-cloneable/circular bodies cleanly viaIDEMPOTENCY_INVALID_PAYLOAD), strips CR/LF fromheaders, and marksCOMPLETEDuntilnow + ttlMs. -
release(key, lockToken, { tool = 'idempotency.store' } = {}): DeletesIN_FLIGHTentry only iflockTokenmatches, returningokEnvelope(tool, ..., { released: boolean }). -
get(key),delete(key),clear(),size().
-
- Validates integer
-
withIdempotency(store, { key, payload = null, method = 'POST', path = '', cacheErrors = false, tool = 'idempotency.exec' } = {}, handlerFn):- Async execution helper normalizing
key, computingfingerprint, acquiring/replaying viastore.begin, executinghandlerFn({ key, fingerprint }), releasing lock without caching on thrown exceptions (IDEMPOTENCY_HANDLER_ERROR) or{ ok: false }results whencacheErrors === false, and committing + returningokEnvelope(tool, ..., { replayed: boolean, key, statusCode, result }).
- Async execution helper normalizing
-
createIdempotencyMiddleware(store = createIdempotencyStore(), { headerName = 'idempotency-key', methods = ['POST', 'PUT', 'PATCH', 'DELETE'], requireHeader = false, scopeKeyFn = null, tool = 'idempotency.middleware' } = {}):- Express / Node HTTP middleware
(req, res, next)scoping keys by${scope}:${method}:${pathname}:${key}(defaultscopefromscopeKeyFn(req)orreq.auth?.tenantId || req.user?.tenantId || req.user?.id || 'global'), rejecting duplicate header arrays (400), missing required header (400), payload mismatch (422), concurrent in-flight (409+Retry-After: 1), settingIdempotency-Replayed: falseon fresh executions and replaying cached responses withIdempotency-Replayed: true, and releasing locks without caching onstatusCode >= 500or premature socket close beforeres.writableEnded.
- Express / Node HTTP middleware
-
-
Disjoint Subagent 1 Files:
-
INV-LEGO-32(Tamper-Evident SHA-256 Hash-Chained Compliance Ledger —@krusch/toolkit/audit-log):-
Disjoint Subagent 2 Files:
lib/audit-log.js,lib/types/audit-log.d.ts -
Dependencies: Built-in
node:crypto,node:sqlite(DatabaseSync),node:fs,node:path+{ okEnvelope, errorEnvelope } from './http.js'(zero external npm packages). -
Exact Exports & Return Contracts:
-
GENESIS_AUDIT_HASH:'0'.repeat(64). -
canonicalizeAuditPayload(value, { maxDepth = 32, tool = 'audit.canonicalize' } = {}):- Non-throwing deterministic canonical JSON serializer sorting own keys lexicographically, normalizing
-0to0, omittingundefinedobject keys (undefinedarray elements ->null), and rejecting circular references (AUDIT_CIRCULAR_PAYLOAD),maxDepthoverflow (AUDIT_MAX_DEPTH), lone UTF-16 surrogates (AUDIT_INVALID_UNICODE), andBigInt/Symbol/Function/NaN/Infinity(AUDIT_NONFINITE_VALUE). ReturnsokEnvelope(tool, ..., { canonicalJson })orerrorEnvelope.
- Non-throwing deterministic canonical JSON serializer sorting own keys lexicographically, normalizing
-
computeAuditEntryHash(entryInput, { hmacSecret = '', tool = 'audit.hash' } = {}):- Validates
seq(>= 1safe integer), non-emptytimestamp,actor,action(all free of ASCII control chars[\x00-\x1f\x7f]), stringresource/tenantId/outcome, 64-char lowercase hexprevHash, and plain-objectmetadata(AUDIT_INVALID_ENTRY). - Serializes
{ seq, timestamp, tenantId, actor, action, resource, outcome, metadata, prevHash }viacanonicalizeAuditPayloadand computes SHA-256 hex digest (or HMAC-SHA256 hex digest over'krusch-audit-v1:' + canonicalJsonwhen non-emptyhmacSecretis provided). ReturnsokEnvelope(tool, ..., { entryHash, canonicalJson })orerrorEnvelope.
- Validates
-
verifyAuditChain(entries, { expectedGenesisHash = GENESIS_AUDIT_HASH, expectedTailHash = '', hmacSecret = '', startSeq = 1, tool = 'audit.verify' } = {}):- Non-throwing
$O(N)$ chain verifier checking array input (AUDIT_INVALID_CHAIN_INPUT), contiguous monotonicseq === startSeq + index(AUDIT_SEQUENCE_GAP), constant-timeentry.prevHash === expectedPrevHash(AUDIT_CHAIN_BROKEN), constant-time recomputedentryHash === entry.entryHash(AUDIT_ENTRY_TAMPERED), and optionalexpectedTailHashtruncation check (AUDIT_TAIL_MISMATCH). ReturnsokEnvelope(tool, ..., { valid: true, verifiedCount, headHash, tailHash })orerrorEnvelope.
- Non-throwing
-
createAuditLog({ sqlitePath = '', db = null, tableName = 'audit_ledger', hmacSecret = '', maxEntries = 50_000, nowFn = () => new Date().toISOString(), tool = 'audit.log' } = {}):- Supports in-memory append-only ledger (failing closed with
AUDIT_LOG_CAPACITY_EXCEEDEDatmaxEntriesrather than silently dropping compliance records) and durablenode:sqliteDatabaseSyncWAL mode (synchronous = FULL,busy_timeout = 5000, SQL-injection-guardedtableName, plus SQLiteBEFORE UPDATEandBEFORE DELETERAISE(ABORT, 'AUDIT_LEDGER_IMMUTABLE')immutability triggers). - Exposes frozen handle
{ append(record), verify(opts), query(filters), tail(), close() }returningINV-LEGO-01envelopes onappend,verify, andquery.
- Supports in-memory append-only ledger (failing closed with
-
-
Disjoint Subagent 2 Files:
-
INV-LEGO-33(Deny-by-Default RBAC Policy Evaluator & Multi-Tenant IDOR Guard —@krusch/toolkit/rbac):-
Disjoint Subagent 3 Files:
lib/rbac.js,lib/types/rbac.d.ts -
Runtime Purity: Zero
node:*imports (pure Web-standards ECMAScript with inlineINV-LEGO-01okEnvelope/errorEnvelopehelpers and zero host-specific transitive imports; runs unmodified in Node 22, Cloudflare Workers, and browsers). -
Exact Exports & Return Contracts:
-
matchPermissionPattern(grantedPattern, requiredPermission):- Deterministic ReDoS-free permission matcher supporting exact match, global
'*', multi-segment prefix'domain:**'(matching'domain:read'and'domain:sub:write'), and equal-length':'segment wildcards ('billing:*','*:read'). Rejects empty strings, whitespace, and control chars (false).
- Deterministic ReDoS-free permission matcher supporting exact match, global
-
createRbacPolicy(policyDefinition = {}, { maxInheritanceDepth = 16 } = {}):- Prototype-safe (
Object.create(null)/Map) static policy compiler validatingpolicyDefinition.roles({ allow?: string[], deny?: string[], inherits?: string[], allowCrossTenant?: boolean, description?: string }), throwingRangeErroron__proto__/constructor/prototypekeys, unknowninheritstargets, inheritance cycles, or depth overflow. - Returns frozen
RbacPolicyhandle{ listRoles(), getRolePermissions(roleName), evaluate(subject, permission, options) }.
- Prototype-safe (
-
assertTenantOwnership(subject, resource, { allowCrossTenant = false, checkOwner = false, ownerField = 'ownerId', tenantField = 'tenantId', tool = 'rbac.tenant' } = {}):- Non-throwing OWASP A01 / IDOR guard using
Object.hasOwn(blocking prototype-pollutedtenantId/ownerIdbypasses). Requires authenticatedsubject(RBAC_UNAUTHENTICATED,statusCode: 401), non-emptysubject.tenantId(RBAC_MISSING_SUBJECT_TENANT,403), non-emptyresource[tenantField](RBAC_MISSING_RESOURCE_TENANT,403), and exactsubject.tenantId === resource[tenantField](RBAC_CROSS_TENANT_DENIED,403) unless BOTHallowCrossTenant === trueANDsubject.allowCrossTenant === true. WhencheckOwner === true, enforces non-emptysubject.idmatchingresource[ownerField](RBAC_NOT_RESOURCE_OWNER,403). ReturnsokEnvelopeorerrorEnvelope.
- Non-throwing OWASP A01 / IDOR guard using
-
evaluateAccess(policy, subject, permission, { resource = null, requireTenantMatch = true, checkOwner = false, ownerField = 'ownerId', tenantField = 'tenantId', tool = 'rbac.evaluate' } = {}):- Deny-by-default evaluator: validates
policy,subject(401), andpermission(400); evaluates explicitdenyrules BEFOREallowrules (RBAC_EXPLICIT_DENY,403); requires at least one matchingallowgrant across inherited roles orsubject.permissions(RBAC_FORBIDDEN,403); enforcesassertTenantOwnershipwheneverresourceis provided andrequireTenantMatch !== false; returnsokEnvelope(tool, 'Access granted', { allowed: true, subjectId, tenantId, permission, matchedGrant })orerrorEnvelope.
- Deny-by-default evaluator: validates
-
createRbacGuard(policy, permission, { resolveSubject, resolveResource, requireTenantMatch = true, checkOwner = false, ownerField = 'ownerId', tenantField = 'tenantId', onAudit = null, tool = 'rbac.guard' } = {}):- Async-safe HTTP/Express middleware
(req, res, next)catching resolver/audit errors cleanly (500RBAC_RESOLVER_ERROR), invoking optionalonAudithook, responding401/403JSONerrorEnvelopeon denial, or attachingreq.authzand callingnext().
- Async-safe HTTP/Express middleware
-
-
Disjoint Subagent 3 Files:
-
INV-LEGO-34(HMAC-Signed Keyset Cursor & Bounded Limit Pagination —@krusch/toolkit/pagination):-
Disjoint Subagent 4 Files:
lib/pagination.js,lib/types/pagination.d.ts -
Dependencies: Built-in
node:crypto+{ okEnvelope, errorEnvelope } from './http.js'(zero external npm packages). -
Exact Exports & Return Contracts:
-
DEFAULT_PAGINATION_LIMITS:Object.freeze({ defaultLimit: 25, minLimit: 1, maxLimit: 100, maxCursorLength: 2048 }). -
clampPageLimit(rawLimit, { defaultLimit = 25, minLimit = 1, maxLimit = 100 } = {}):- Validates
1 <= minLimit <= defaultLimit <= maxLimit <= 10_000(RangeErroron invalid bounds); safely coercesundefined/null/''/boolean/Symbol/NaN/Infinity/non-integer strings todefaultLimitwithout throwing, and clamps integers into[minLimit, maxLimit].
- Validates
-
encodeCursor(cursorPayload, { secret = '', scope = '', ttlMs = 0, maxCursorLength = 2048, nowFn = Date.now, tool = 'pagination.encode' } = {}):- Non-throwing encoder validating plain-object
cursorPayload(rejecting primitives, arrays,__proto__/constructor/prototypeown keys, circular refs,BigInt, andNaN/InfinitywithCURSOR_INVALID_PAYLOAD), wrapping{ v: 1, d: cursorPayload, s?: scope, exp?: nowFn() + ttlMs }, base64url-encoding, signing with domain-separated HMAC-SHA256 ('krusch-cursor-v1.' + payloadB64) whensecretis provided, enforcing<= maxCursorLength(CURSOR_TOO_LARGE), and returningokEnvelope(tool, ..., { cursor, signed, expiresAt })orerrorEnvelope.
- Non-throwing encoder validating plain-object
-
decodeCursor(rawCursor, { secret = '', requireSignature = Boolean(secret), expectedScope = '', maxCursorLength = 2048, nowFn = Date.now, tool = 'pagination.decode' } = {}):- Non-throwing decoder enforcing length & charset bounds (
CURSOR_MISSING,CURSOR_TOO_LARGE,CURSOR_MALFORMED), constant-timecrypto.timingSafeEqualHMAC verification (CURSOR_SECRET_REQUIRED,CURSOR_SIGNATURE_MISSING,CURSOR_INVALID_SIGNATURE), prototype-safe JSON parsing,expTTL expiration (CURSOR_EXPIRED), andexpectedScopebinding (CURSOR_SCOPE_MISMATCH). ReturnsokEnvelope(tool, ..., { payload, scope, expiresAt, signed })orerrorEnvelope.
- Non-throwing decoder enforcing length & charset bounds (
-
buildKeysetPage(rows, { limit = 25, defaultLimit = 25, maxLimit = 100, sortField = 'createdAt', idField = 'id', secret = '', scope = '', ttlMs = 0, nowFn = Date.now, tool = 'pagination.page' } = {}):-
limit + 1lookahead keyset envelope builder slicingrowstoeffectiveLimit, computinghasMoreand signednextCursorover{ sortValue, id, sortField, idField }, and returningokEnvelope(tool, ..., { items, pageInfo: { limit, count, hasMore, nextCursor } })orerrorEnvelope.
-
-
paginateItems(allItems, { cursor = '', limit = 25, defaultLimit = 25, maxLimit = 100, sortField = 'id', idField = 'id', direction = 'asc', secret = '', scope = '', ttlMs = 0, nowFn = Date.now, tool = 'pagination.slice' } = {}):- Deterministic in-memory keyset paginator sorting
(sortField, idField)in'asc' | 'desc'(PAGINATION_INVALID_DIRECTION), verifyingcursorsignature/scope/expiry/sortField parity (CURSOR_SORT_MISMATCH), advancing strictly past(sortValue, id), and returningbuildKeysetPageokEnvelopeorerrorEnvelope.
- Deterministic in-memory keyset paginator sorting
-
-
Disjoint Subagent 4 Files:
-
Orchestrator Choke Points &
<1msSlop-Breaker Detectors (Phase 3B — Parent Orchestrator Only):-
lib/package.json(v1.8.0,./idempotency,./audit-log,./rbac,./paginationsubpaths),lib/index.js,lib/types/index.d.ts -
lib/catalog.js(RUNTIME_BRICKS->39bricks + deterministic$O(N)$ auditBoilerplateTextSlop-Breaker rulesraw-idempotency-key,mutable-audit-ledger,raw-tenant-rbac, andunsafe-pagination-cursorrecommendingidempotency,audit-log,rbac, andpaginationinscoreLegoBrickCoverage),lib/README.md,lib/test_lego_bricks.js,lib/test_wave5_bricks.js,lib/test_wave7_bricks.js
-
Extends @krusch/toolkit/catalog (auditBoilerplateText, scoreLegoBrickCoverage) and krusch-lego audit with deterministic, ReDoS-free <1ms/file) legacy ORM pagination, SSRF, and hardcoded auth-secret detectors mapped to existing sealed runtime bricks while preserving 100% zero-node:* isomorphic purity in lib/catalog.js.
-
INV-LEGO-35(ORM Pagination, Outbound SSRF & Auth-Secret Slop-Breaker Detectors + Coverage Alias Parity):-
Runtime Purity:
lib/catalog.jsMUST maintain zero outbound runtimeimport/requiredependencies (0resolved module specifiers under V8 ESM loading;node:*strings appear only inside renderedPROJECT_ARCHETYPESstarter templates) so it executes unmodified in Node 22, Cloudflare Workers, and browsers. -
Rule 14 Extension (
unsafe-pagination-cursor$\rightarrow$ pagination/@krusch/toolkit/pagination):- When
!isPython,!usesToolkitPagination, and!/\bMath\.min\s*\(/.test(codeOnly), also flag:- Bounded-window (
<= 800chars) Prisma.findMany({...})calls combining non-literalskip:with dynamictake:(limit,take,pageSize,perPage,per_page). - Chained MongoDB/Mongoose
.skip(...).limit(...)or.limit(...).skip(...)calls referencingreq.query/request.querywith non-literal.limit(...). - Unclamped HTTP controller coercions
(?:Number|parseInt)(req.query.limit|take|pageSize|per_page)paired withreq.query.(offset|skip|page).
- Bounded-window (
- When
-
Rule 15 (
unvalidated-outbound-ssrf$\rightarrow$ security/@krusch/toolkit/securityorpython_security/krusch_toolkit.security):- When lacking
@krusch/toolkit/security(safeFetch,validateOutboundUrl,isPrivateOrReservedIp) in JS/TS orkrusch_toolkit.security(validate_outbound_url,is_private_or_reserved_ip) in Python, inspect string-scrubbed code (stripStringBodiesForYamlAudit) to flag user-controlled target URLs passed to outbound HTTP clients:- Direct JS/TS request inputs (
req.query/req.body/req.params,request.query|body|params,c.req.query(...), or unprefixed template literals`${req.query...`) passed as the target URL to standalonefetch(...),axios(...)/axios.<verb>(...),needle.<verb>(...),got(...)/got.<verb>(...),http(s).get/request(...), oraxios({ url: ... })(excluding fixed-origin URLs likefetch(`https://api.example.com/${req.params.id}`)and non-HTTP.fetch(...)methods). - Single-file local variable taint (
const url = req.query.url + ...or destructuring URL-named keys{ url, webhookUrl, callbackUrl, targetUrl, endpointUrl, proxyUrl, feedUrl, imageUrl, sourceUrl, remoteUrl, uri, href } = req.query|body|params) passed as the first URL argument to those HTTP clients. - Python
httpx/requests/urllib.request.urlopencalls receivingrequest.query_params/request.args/request.formdirectly, via local URL variable taint, or via FastAPI@app/@routerroute parameters (url: str,target_url: str,webhook_url: str,callback_url: str,proxy_url: str).
- Direct JS/TS request inputs (
- When lacking
-
Rule 16 (
hardcoded-auth-secret-fallback$\rightarrow$ auth/@krusch/toolkit/auth):- When
!isPythonand lacking@krusch/toolkit/auth(createAuth), inspect string-scrubbed code (stripStringBodiesForYamlAudit) to flag hardcoded secret literals ($\ge 4$ chars, zero template interpolations):-
process.env.(JWT_SECRET|AUTH_SECRET|SESSION_SECRET|COOKIE_SECRET|TOKEN_SECRET|APP_SECRET|SIGNING_SECRET) || '<literal>'(or?? '<literal>'). -
jwt.(sign|verify)(payload, '<literal>', ...)(2nd top-level argument scanned via bounded balanced delimiters). - Top-level
secret: '<literal>'insidesession({...})/cookieSession({...})/expressjwt({...})/jwt({...})(bounded balanced-brace scan) or config propertiesjwtSecret/cookieSecret/sessionSecretassigned hardcoded string literals.
-
- When
-
scoreLegoBrickCoverageEntry Normalization &krusch-lego auditTelemetry:-
scoreLegoBrickCoverageaccepts both{ filePath, code }and{ path, content }object entries (LegoCoverageFileEntryinlib/types/catalog.d.ts). -
lib/bin/krusch-lego.jsauditcomputesscoreLegoBrickCoverageacross scanned files and attachessealedFiles,sealedBrickIds,sealedTouchpoints,recommendedBrickIds,sealedCoverageRatio,breakerTripped, andestimatedAuditTokensSavedontopayload.datawhile preservingtarget,scannedFiles,flaggedFiles,clean, andfindings.
-
-
Runtime Purity:
Wave 9: Collaborative Validated Brick Exchange, Ed25519 Lineage Seals & Deadbolt 2-Hop AST Fan-Out (@krusch/toolkit/brick-exchange)
Adapts and generalizes multi-company contract verification, permission-first discovery, and byte-exact lineage sealing from 0xANUSHKA/common-ground-8090 (EVOLVE 8090 Hackathon, MIT License, Copyright (c) 2026 Anushka Jogalekar and Common Ground contributors) onto @krusch/toolkit zero-dependency runtime bricks, fused with DEADBOLT 2-hop AST blast-radius and parallel multi-agent fan-out governance (RUNTIME_BRICKS.length === 40, 170/170 Node tests).
- Submodule & Export Contract (
lib/brick-exchange.js&lib/brick-exchange/*.js):lib/brick-exchange/sandbox.js(Zero-Ambient-I/O Safety & Fault-Injection Sandbox):scanBrickSourceSafety(source, { filePath } = {}): Rejects ambient network/filesystem/process/eval side effects (child_process,fs,net,http,https,dgram,tls,worker_threads,vm,process.env,eval,new Function, dynamicimport()) and private LAN/Tailscale IP literals (INV-LEGO-26).transpileBrickSourceToCjs(source)&executeInBrickSandbox(source, { entrypoint, testVectors, faultVectors, timeoutMs, maxMemoryMb } = {}): Executes candidate bricks inside an isolated child Node process (--permission/--experimental-permission+--disallow-code-generation-from-strings, stripped environment) and lockedvm.createContextcompartment.runBrickVerificationGates(spec, source, options): Enforces 4 sequential deterministic gates: (1) static safety &<1msSlop-Breaker scan, (2) input/output schema validation (@krusch/toolkit/schema), (3) deterministic golden test vectors, and (4) mandatory adversarial fault-injection challenges (null/malformed/boundary inputs must fail closed cleanly without uncaught crashes).
lib/brick-exchange/seal-and-policy.js(Ed25519 Lineage Seals & Tiered Org/Grant RBAC):generateBrickSigningKeyPair(),derivePublicKeyId(publicKeyPem),computeCanonicalHash(value),sealVerifiedBrick(bundleInput, { privateKeyPem, publicKeyPem, orgId, authorId, visibility }), andverifyBrickBundle(bundle, { trustedPublicKeys }): Normalizess.*schema builders viatoJsonSchema, canonicalizes deterministic JSON, and signs/verifies{ blueprintHash, contractHash, sourceHash, checksHash }with Nodenode:cryptoEd25519.canPublishBrick(actor, targetVisibility, policy)&canReceiveBrick(actor, brickRecord, grants): Enforcesteamintra-org commons plus Common Ground scoped cross-orgGrantrecords (activevsrevoked, expiration timestamps, allowedorgId/brickId/domainscopes).
lib/brick-exchange/store-and-matcher.js(SQLite WAL Registry, Optional HydraDB v2 Boost &.brick-lock.jsonDrift Gate):createBrickExchangeStore({ dbPath, auditDbPath, hydraAdapter } = {}): Persists sealed bricks, public keys, cross-org grants, inbox proposals, and adoption receipts innode:sqliteWAL paired with tamper-evident@krusch/toolkit/audit-logchains. Supports permission-pre-filtered hybrid FTS5/BM25 + boilerplate tag matching, optional permission-scoped@krusch/toolkit/hydradbv2 semantic re-ranking &/feedbacktelemetry, and automaticstageScoutCandidateSpecsstaging from@krusch/toolkit/lego-scout(CANDIDATE_MEETS_RULE_OF_3).tryBrickLocally,adoptBrickIntoRepo, &auditRepoBrickLocks(repoRoot): Vendors verified immutable bricks intobricks/<id>/index.js, writes an editable thin adapter atbricks/<id>/binding.js, pins cryptographic hashes in.brick-lock.json, and flags unsealed local tampering duringkrusch-lego auditand Jean SRE sweeps.
lib/brick-exchange/blast-radius.js(Deadbolt 2-Hop AST Blast Radius & Multi-Agent Fan-Out):extractRepoAstGraph(repoRoot, options)&analyzeBrickBlastRadius(repoRoot, targetFiles, options): Computes 1-hop direct importers and 2-hop transitive dependents, plus per-filenode --permissionfilesystem read/write capability flags.planAgentFanOut(repoRoot, tasks, { maxFilesPerSubagent = 2, protectedFiles = [] } = {}): Partitions multi-agent tasks into conflict-free parallel waves (2-hop AST cones disjoint,<= 2files per worker) while routing shared choke points (server.js,index.js,package.json,App.jsx,tools.js) to a serializedorchestratorChokePointsphase.verifyTwoHopBlastRadius(repoRoot, stagedChanges, { leaseFiles, protectedFiles, runPermissionTests } = {}): Pre-apply gate blocking out-of-lease mutations,Policy FloorprotectedFilesedits, broken named exports across 1-hop/2-hop callers, and 2-hop--permissiontest regressions.
lib/brick-exchange/hub-and-mcp.js&lib/bin/krusch-lego.js(HTTP Console, 10-Tool MCP & CLI):createBrickExchangeServer(19HTTP routes + zero-build dark-mode Reuse & Grants Web ConsolerenderBrickExchangeConsoleHtml) andcreateBrickExchangeMcpServer(BRICK_EXCHANGE_MCP_TOOLS: 10INV-STACK-034-boolean annotated MCP tools).krusch-legoCLI subcommands:keygen,seal,verify,try,adopt,suggest,share,revoke,inbox,hub,mcp,blast-radius,fanout, plus.brick-lock.jsonverification insidekrusch-lego audit.
Wave 10: Cross-Stack, Data-Port, Channel & MoE Ontology Backed by HydraScope (INV-LEGO-36, @krusch/toolkit/brick-exchange)
STATUS: FROZEN (
2026-11-17T19:33:00-08:00) — 100% clean-room@krusch/toolkit&HydraScopeextension (Copyright (c) 2026 kruschdev, zero external npm packages, preservingRUNTIME_BRICKS.length === 40,BRICK_EXCHANGE_MCP_TOOLS.length === 10,ALL_STACK_TOOLS.length === 39, and95/95benchmark SHA-256 pins).
-
INV-LEGO-36(4-Axis Formal Ontology, HydraScope OpenCypher + Embedded Graph Traversal & Zero-Upload Cross-StackbindingSynthesis):-
Canonical 4-Axis Frozen Registries (
lib/brick-exchange/ontology.js):-
ONTOLOGY_STACKS: Deep-frozen map/list of 5 canonical software stacks (node-esm,typescript-node,python-fastapi,react-vite,cloudflare-edge), declaring runtime family (jsvspython), Web-Standard purity requirement (requiresWebStandardPurity: trueoncloudflare-edgeandreact-vite), and adapter file conventions (binding.js,binding.ts,binding_adapter.py). -
ONTOLOGY_DATA_PORTS: Deep-frozen schema-typed port registry (timeseries_window,ledger_event,webhook_envelope,audit_record,identity_claims,document_page) with canonical field schemas,shared: truecross-component composability vs. namespace-scoped opaque IDs (slack:channel_id!==discord:channel_id), and deterministic field-alias synonym rings (ts_ms | timestamp | recorded_at | unix_ts -> ts,val | reading | measurement | metric_value -> val,amount_cents | amount_minor | gross_cents -> gross,tenant_id | company_id | workspace_id -> orgId). -
ONTOLOGY_CHANNELS: Deep-frozen communication & ingestion channel registry (webhook:github,webhook:slack,webhook:stripe,workspace:gmail,workspace:drive,workspace:calendar,mcp:stdio,http:sse,telemetry:timeseries), declaring inbound/outboundDataPortIDs, required security guard bricks (@krusch/toolkit/webhooks,@krusch/toolkit/security), HMAC/replay verification requirements, and Zero-Leak PII scrubbing flags. -
ONTOLOGY_MOE_PROFILES: Deep-frozen MoE & numerical/time-series specialist profiles (timeseries-cadence-moe,financial-integer-ledger,cross-stack-schema-adapter,channel-security-normalizer) pairing explicit numerical invariants (cadenceMs,requireMonotonicTimestamps,preserveNegativeValues,nanInfPolicy,anomalyMethod) with@krusch/toolkit/cascadedispatch tiers (TIER_0_DETERMINISTIC$0alias mapper ->L1_FASTgemma4:e4b->L2_HEAVY_MOEqwen3-coder-30b-moe:latest).
-
-
Metadata Normalization & Pre-Flight Compatibility Gate:
-
isWebStandardPureSource(source): Deterministic static scanner checking zeronode:*/ bare Node host module imports (fs,net,child_process,tls,dgram,sqlite,worker_threads,process.env,Bufferopt-in check) so pure ECMAScript/Web-API bricks automatically qualify forcloudflare-edgeandreact-vite. -
normalizeBrickOntologyMetadata(rawOntology, { source = '', blueprint = {} } = {}): Non-throwing normalizer validating stack slugs, port slugs (preserving namespace-scoped<ns>:<id>ports), channel slugs,moeProfile,supersedes(sourceHashorbrickId@sourceHashlist),validFrom/retiredAt, andtimeSeriesContract, auto-inferring compatible JS/Edge stacks when omitted. ReturnsINV-LEGO-01okEnvelope('brick-exchange.ontology.normalize', ...)orerrorEnvelope. -
checkOntologyCompatibility({ bundle, targetStack, targetChannel = null, providedSecurityBricks = [], localSampleOrSchema = null }):<1mszero-LLM answerability & compatibility gate rejectingSTACK_RUNTIME_INCOMPATIBLE(e.g.,node:fsor non-Web-Standard brick targetingcloudflare-edgeorreact-vite),CHANNEL_SECURITY_GUARD_MISSING(whenenforceChannelGuards: trueand required HMAC/SSRF brick is absent),TIMESERIES_INVARIANT_VIOLATION(NaN/Infinityor non-monotonic timestamps on a strict time-series contract), orPORT_NAMESPACE_COLLISION(slack:channel_idwired todiscord:channel_id). Forpython-fastapitargets adopting a JS/TS brick, returnsbridgeMode: 'contract-adapter'(generating a typed Python boundary adapter) rather than silently claiming native in-process execution.
-
-
HydraScope Graph Compiler, OpenCypher Sync & Permission-First 2-Hop Composition:
-
surrogateOntologyVertexId(namespace, logicalId): Deterministic 48-bit SHA-256 safe integer in[1000, 281474976711655]matching HydraScope'sHydraDB v0.4.0vertex ID contract. -
compileBrickOntologyGraph({ bricks = [], orgProfiles = [], namespace = 'brick-ontology' }): Compiles authorized bricks, org profiles, stacks, ports, channels, MoE profiles, and:SUPERSEDESlineage (retiredAt,isCurrent,supersededBy) into{ namespace, nodes, edges, stats }with typed edges (:TARGETS_STACK,:CONSUMES_PORT,:PRODUCES_PORT,:BRIDGES_CHANNEL,:ROUTES_TO_MODEL,:USES_STACK,:LISTENS_CHANNEL,:SUPERSEDES). Scrubs all string properties against private RFC1918/Tailscale IPs and secrets (INV-HS-02). -
syncBrickOntologyToHydra(graph, { hydraClient, graphId })&traverseBrickOntology(graph, { targetStack, targetChannel = null, requiredPorts = [], availableInputPorts = [], asOf = null, maxHops = 2, hydraClient = null }):- Syncs
MERGEstatements via OpenCypher whenhydraClientis configured and healthy, and falls back deterministically in<1msto embedded BFS when offline (INV-HS-03). - Filters out
:SUPERSEDES-retired bricks automatically (isCurrent === false) unlessasOf(YYYY-MM-DD) precedesretiredAt. - Returns ranked 1-hop direct bricks AND 2-hop composable pipelines (
brickA --[:PRODUCES_PORT]-> sharedPort --[:CONSUMES_PORT]-> brickB, never bridging across mismatched namespace-scoped opaque IDs). -
Permission-Before-Traversal Invariant: When invoked through
store.planCrossStackComposition({ viewerId, ... })orstore.suggestRecipients(...), ONLY bricks passingevaluateVisibilityForBundle/canReceiveBrickforviewerIdentercompileBrickOntologyGraph, guaranteeing zero cross-org existence or schema leakage.
- Syncs
-
-
Zero-Upload Cross-Stack Hexagonal
bindingAdapter Synthesis:-
synthesizeBrickBinding({ bundle, targetStack = 'node-esm', localSample = null, fieldMap = {}, bindingOverrides = {}, repairFn = null, maxRepairAttempts = 2 }):- Inspects
localSamplekeys/rows andbundle.blueprint.inputSchema/bindingSchema+ONTOLOGY_DATA_PORTSalias rings at$0zero-LLM cost to synthesize:-
bindingConfigplain object + canonical field mapping (adaptInput(raw)/adaptBatch(rows)) - Executable ESM/TS adapter module source (
binding.js/binding.ts) fornode-esm,typescript-node,react-vite,cloudflare-edge - Typed Python 3.11+ hexagonal contract adapter (
binding_adapter.py) whentargetStack === 'python-fastapi'
-
- When
localSampleis supplied andtargetStackis JS/TS/React/Edge, runsadaptInput(localSample)throughtryBrickLocallyinside the locked sandbox (0bytes uploaded externally), optionally invokingrepairFn(L2_HEAVY_MOEqwen3-coder-30b-moe) up tomaxRepairAttemptsif custom transformation is needed.
- Inspects
-
-
Disjoint Parallel Subagent Leases vs. Orchestrator Choke Points:
-
Subagent 1 (
lib/):lib/brick-exchange/ontology.js,lib/test_brick_ontology.js. -
Subagent 2 (
projects/hydrascope/):projects/hydrascope/src/engines/brick-ontology-bridge.js,projects/hydrascope/tests/brick-ontology-bridge.test.js. -
Subagent 3 (
projects/krusch-stack/):projects/krusch-stack/src/engines/brick-ontology-engine.js,projects/krusch-stack/tests/brick-ontology.test.js. -
Orchestrator Choke Points (Wave 2 Only):
lib/brick-exchange.js,lib/brick-exchange/seal-and-policy.js,lib/brick-exchange/store-and-matcher.js,lib/brick-exchange/hub-and-mcp.js,lib/bin/krusch-lego.js,lib/catalog.js,lib/types/brick-exchange.d.ts,lib/README.md,projects/hydrascope/src/runtime.js,projects/krusch-stack/src/engines/brick-exchange-engine.js,projects/krusch-stack/bin/krusch-stack.js.
-
Subagent 1 (
-
Canonical 4-Axis Frozen Registries (
Wave 10.1: Ontology & Brick Exchange Security, Cycle-Elimination & 3-Chair Fleet Alignment (STATUS: FROZEN 2026-11-21T12:20:00-08:00)
Remediates all verified P0–P3 findings from the Wave 10 Principal-Engineer /code-audit (projects/krusch-stack/.agent/audit/master_backlog.md) while preserving 100% backward compatibility on all public exports (RUNTIME_BRICKS.length === 40, BRICK_EXCHANGE_MCP_TOOLS.length === 10).
- Core Frozen Invariants (
SEC-01..08,BUG-01..06,PERF-02..03,ARCH-01,TYPE-01):- Process-Isolated Capability-Port Sandbox (
SEC-01):executeInBrickSandbox(lib/brick-exchange/sandbox.js) MUST NOT run untrusted brick code inside a parent-processvm.createContextexposing host-realm constructors (TextEncoder.constructor). Capability-port function bindings execute over an IPC/stdio JSON-RPC bridge inside thenode --permission --disallow-code-generation-from-stringschild worker, andscanBrickSourceSafetyblocks.constructor,['constructor'], bareprocess,Deno,Bun, and computed bracket access onglobalThis/global/self/window. - Unified Control-Header-Aware JS/TS Lexer (
SEC-02,SEC-08,ARCH-01):lib/brick-exchange/source-lexer.jsprovides a single hardened comment stripper, string/template masker, escaped-specifier decoder (\u006eode:fs/\x66srejected),isWebStandardPureSource, andcanonicalBrickHash. Control-header parentheses (if (...),while (...),for (...),with (...)) keepcanStartRegex = trueafter closing), and member properties (.in,?.of) never triggerREGEX_PRECEDING_KEYWORDS. - Cycle-Free Leaf Taxonomy & Bidirectional Metadata Attestation (
SEC-04,SEC-08,ARCH-01):lib/brick-exchange/ontology-taxonomy.jsholds the 4-axis frozen registries (ONTOLOGY_STACKS,ONTOLOGY_DATA_PORTS,ONTOLOGY_CHANNELS,ONTOLOGY_MOE_PROFILESincludingthreeChairModelsforgemma4:e2b,qwen3-coder-30b-moe:latest,inkling-2-mini:ud-iq4_xs-dspark),parsePortReference,arePortsCompatible,normalizeBrickOntologyMetadata(enforcingrequiresWebStandardPurityeven whenontology.stacksis explicitly passed), andextractRawOntologyFromBundle(failing closed withTAMPERED_ONTOLOGYif top-levelbundle.ontologyis present whenblueprint.ontologyis absent).seal-and-policy.jsimports from./ontology-taxonomy.js(zero circular ESM imports).sealVerifiedBrickbinds{ brickClass, capabilities, name, summary, replacesBoilerplate, estimatedHoursSaved }intolineage.metadataHashand setscreatedAt = lineage.sealedAt.verifyBrickBundleenforces bidirectionalbundle.ontology===bundle.blueprint.ontologyparity,bundle.createdAt === lineage.sealedAt(when both exist), and verifieslineage.metadataHashwhenever present.checkOntologyCompatibilityandcompileBrickOntologyGraphcallverifyBrickBundleon sealed bundles, enforce strictnewerBrick.orgId === targetBrick.orgIdon:SUPERSEDES, and ignore unattestedbundle.capabilitiesforenforceChannelGuardsunlesslineage.metadataHashis verified.
- Cross-Stack Synthesis, Python Verification & Store/Hub Multi-Org Isolation (
SEC-06..07,BUG-01..02,BUG-05..06,PERF-03):synthesizeBrickBindingrunstryBrickLocally(and MoErepairFnescalation) across all 5 stacks includingpython-fastapi(adaptedSample+resolvedBinding), preserves profilecomplexityScorewhen customtiers(THREE_CHAIR_BANDIT_TIERS) are passed, separatesINTEGER_HEADER_FIELDS(int) fromFLOAT_HEADER_FIELDS(float+math.isfinite) inbinding_adapter.py, validatesbindingSchema+timeSeriesContract+ Zero-Leak onadapterSource, and exports bothFIELD_MAP+fieldMapandinvokeBoundBrick+invokeAdaptedBrickin JS/TS adapters.createBrickExchangeStoreblocks cross-org(brick_id, source_hash)/brick_idownership overwrites (BRICK_ORG_CONFLICT), scopeslookupStoredBundlebyorgId, pre-validates UTF-16 well-formedness + rolls back newly inserted rows ifauditLog.appendfails, makesrevokeGrantidempotent, returnsbindingHashfromadoptBrickIntoRepo, and pre-scopeslistVisibleBricksSQL with aggregated adoption counts.hub-and-mcp.jsstrips internal keys (nowMs,repairFn,tiers,hydraOpenCypherClient,customRunner) and rejectsFORBIDDEN_KEYSon HTTP/MCP bodies, ignores falsyauthTokensentries, enforces401 VIEWER_REQUIRED+ cross-org recipient redaction onGET /api/grants&GET /api/adoptions, and checks store visibility before vendoring files inbrick_adopt.krusch-lego.jspasses[() => store.close()]toattachGracefulShutdown, validates--sample(file or inline JSON) without silent drops, propagates--dberrors asexitCode: 1, and rejects missing flag values / unknown flags.
- Process-Isolated Capability-Port Sandbox (