@lssm-tech/lib.builder-runtime
Website: https://contractspec.io
Backend-neutral Builder runtime primitives for source ingestion, omnichannel normalization, fusion, planning, previews, readiness, and replay.
Governed patch runs validate canonical repository-relative edit paths against the approved scope before mutation. Duplicate paths, traversal, Git metadata and prefix lookalikes fail closed. This lexical admission complements required workspace-adapter symlink, preimage and filesystem isolation checks.
What It Provides
Workspace creation accepts a host-verified BuilderOperationInput.authorityScope
separately from untrusted payloads, copies it into the workspace record, and retains it on rename/archive. Hosts must resolve it from current authority and must never copy a request body's scope into this trusted input.
- In-memory and interface-based Builder stores.
- Omnichannel ingestion pipeline for chat, voice, file, zip, Studio, Telegram, and WhatsApp inputs.
- Versioned, deterministic extraction and structure-aware chunking for UTF-8 text, strict JSON and bounded YAML, Markdown, HTML, CSV/TSV, RFC-like email, transcript JSON/text, generated PDFs, and approved DOCX/PPTX/XLSX ZIP/XML documents.
- Specs-pack V0 runtime for safe zip/folder import, deterministic file classification, source refs, analysis, readiness, implementation planning, delivery-loop projection, and Connect-gated task-ledger/apply evidence that fails closed before repository writes.
- The repository canonical Builder v3 specs pack is covered by runtime regression tests so release evidence proves realistic packs stay read-only, traceable, and fail-closed when their structure needs review.
- Pure RoleMorph preview helpers for AirDesk role selectors, policy variant previews, surface inspections, diffs, safe missing-binding suggestions, Workbench packets, preference snapshots, authorization summaries, replay bundles, and assurance/audit evidence checks.
- Deterministic precedence-based fusion and blueprint compilation.
- Execution-lane plan compilation and lightweight execution lifecycle helpers.
- Preview, readiness, replay bundle, automatic economic evidence packet, safe replay sink serialization, and customer-delivery-loop projection helpers.
- Pure platform-planning orchestration, deterministic topology comparison, reviewed handoff/receipt, contract-first task-ledger, and readiness projection helpers.
./production includes a bounded patch-run service with Codex as primary, OpenCode Go as explicit fallback, isolated-worktree enforcement, Connect and check receipts, deterministic risk classification, rollback refs, and no permission bypass.
./production/workflow owns the production run workflow (plan, complete, verify, resume, cancel, tmux evidence, handoff) and its run-state transitions behind a BuilderProductionRunStore and a
BuilderProductionProviderPort. Hosts supply concrete provider CLIs/SDKs and durable storage; createInMemoryBuilderProductionRunStore() covers tests and ephemeral hosts. A run that verifies as ready completes with its
economicReplayPacket. listBuilderProductionModes() derives mode source aliases (ultrawork/ulw -> team.coordinated, ralphone -> verify_fix on complete.persistent) from Builder lane selection.
./readiness exports summarizeBuilderBootstrap(snapshot, mode), the mode-aware bootstrap prerequisite summary used by the CLI status report and the workbench managed-bootstrap label.
Public Entry Points
. resolves through ./src/index.ts
./builder-intelligence resolves through ./src/builder-intelligence/index.ts
./stores resolves through ./src/stores/index.ts
./ingestion resolves through ./src/ingestion/index.ts
./specs-pack resolves through ./src/specs-pack/index.ts
./fusion resolves through ./src/fusion/index.ts
./planning resolves through ./src/planning/index.ts
./preview resolves through ./src/preview/index.ts
./rolemorph-preview resolves through ./src/rolemorph-preview/index.ts
./readiness resolves through ./src/readiness/index.ts
./replay resolves through ./src/replay/index.ts
./production resolves through ./src/production/index.ts
./production/workflow resolves through ./src/production/workflow/index.ts
Notes
- This package stays backend-neutral. Durable database storage belongs in integration and app layers.
- Channel dispatch is bridged through an injected outbox adapter so Builder can reuse host messaging infrastructure without depending on app shells.
- Unknown, malformed, oversized, remotely-referencing, or unsafe archive content fails closed with stable diagnostics and zero extracted content; it is never decoded as an authoritative fallback.
- Generated/page-content PDFs extract locally. Scanned PDFs and images return
requires_provider with zero content unless the host injects an OCR adapter. Voice behaves the same way for STT, including unapproved locales; no synthetic transcript is created.
BuilderExtractorRegistry publishes builder.extractor-registry.v1. Structured parts and chunks carry stable source/parent/sequence links, exact page/row/section/slide/sheet/cell/timestamp locators, hashes, classification, ACL, language, warnings, and extractor/chunker versions.
- Extraction enforces configurable byte, time, structure-depth, archive-member, compressed, expanded-size, and expansion-ratio limits. CSV, TSV, and XLSX formula cells are neutralized with a stable warning by default or can be rejected through
formulaPolicy: "fail".
Economic Evidence Replay
When all production workflow lanes complete, or a production run verifies as ready, Builder runtime creates economicReplayPacket automatically (ensureBuilderRunEconomicReplayPacket), including explicit packets for workflows with no child economic refs yet. Consumers should send replay packets to logs or replay indexes through serializeBuilderWorkflowEconomicEvidencePacketForSink() from @lssm-tech/lib.builder-runtime/replay, which exposes safe packet metadata, child ref counts, allowlisted evidence refs, replay bundle metadata, and redaction decisions without raw provider receipts, prompts, operation payloads, or replay payloads.
Model routing evidence
Builder runtime consumes the provider-ranking router during plan compilation and carries routing summaries into readiness and replay. The runtime remains backend-neutral: it records selected provider/model, policy, risk flags, reason codes, review requirements, and evidence references, but host runtimes execute the chosen model.
Contract Intelligence runtime
Builder-runtime exposes the first dry-run Contract Intelligence helpers for fixture-backed brownfield analysis, redacted bundle export/import validation, reconciliation, and selective adoption planning. Apply-capable flows remain blocked until Connect decision and replay evidence exist.
Builder Intelligence runtime
Builder-runtime exposes pure Builder Intelligence helpers for Phase 1 indexing/retrieval and Phase 2 memory/trajectory projection. buildBuilderIndex() creates deterministic BuilderIndexManifestV1 and BuilderChunkV1 artifacts from caller-provided refs without writing stores. queryBuilderIndex() performs in-memory exact lookup, graph-ref expansion, symbol matching, sparse text scoring, stale filtering, reranking, and BuilderContextPacketV1 packing with selection reasons. projectBuilderMemoryItems(), createStaleMemoryReport(), proposeBuilderMemoryConsolidation(), and captureBuilderTrajectory() keep durable memory review-gated, hash-invalidated, provenance-backed, and free of raw hidden reasoning. Later-phase helpers add draft-only ReasoningBank strategy cards, SONA-lite route explanations, non-authoritative GraphRAG community summaries, and neural-adaptation readiness gates without automatic mutation or training.
RoleMorph preview runtime
Builder-runtime exposes ./rolemorph-preview for backend-neutral RoleMorph preview artifacts. The helpers build AirDesk role/policy selector previews, inspect resolved surfaces, diff default versus VIP policy outcomes, produce safe repair suggestions for missing component/data bindings, create Workbench packets, snapshot host-referenced preferences, summarize authorization, assemble replay bundles, and validate branded assurance/audit evidence. They depend on @lssm-tech/lib.surface-runtime/rolemorph and @lssm-tech/lib.builder-spec only; they do not render React, write stores, call providers, or bypass Connect-gated apply paths.
Builder customer-delivery-loop runtime
Builder-runtime exposes pure customer-delivery-loop helpers from the root entry point. createBuilderCustomerDeliveryLoop() assembles the ref/evidence aggregate, evaluateBuilderDeliveryReadiness() projects validation blockers, projectBuilderDeliveryHandoff() fails closed until acceptance, release, and customer-handoff evidence exists, and createBuilderDeliveryReplaySummary() collects Connect/replay/release refs for audit and release evidence.
The helpers do not write repositories, call providers, persist stores, dispatch messages, or send customer communications. Host apps and integrations own durable storage and production delivery.
The ./planning entry point exposes pure helpers around the injected read-only
BuilderPlatformPlanningPort. Builder may validate intent, compare solo and monorepo architecture, inspect exact/range/stale cost evidence, and preview a plan. It cannot apply infrastructure or own credentials. Deterministic handoff packets preserve their Connect review ref and exact digest; consumers receive a review receipt rather than execution authority. Readiness remains three independent projections so software readiness cannot imply operational or production readiness.
Managed readiness requires a registered, unblocked, export-capable managed runtime target and an active non-offline provider. Catalog capability alone is insufficient. Rerun readiness after upgrading to refresh persisted reports; this availability check does not replace execution authority or live qualification.
Builder index retrieval requires matching workspace identities and matching manifest chunk IDs/content hashes. Duplicate manifest references and duplicate chunks fail explicitly. These consistency checks do not grant read authority or attest provider-controlled content; the host must authorize the source set.
Hosted preview evidence
Blueprint-only previews remain pending and have no fabricated hosted URL. Change summaries use blueprint versions, never preview IDs; legacy records without a previous version receive a neutral refresh summary.
BuilderPreview records source/artifact identity and a canonical deployment receipt reference only after host observation qualifies the target and health. The runtime's optional previewHost reads host-owned deployment state; request payloads cannot supply evidence. Ready requires the exact workspace, blueprint version, source revision, target and artifact set, a digest-valid successful delivery receipt with health evidence, and a recent HTTPS URL observation on an allowed origin. Refresh invalidates previous readiness before observation and rejects blueprint changes during IO. Observation is bounded to twenty seconds.
This bridge does not grant deployment authority. Concrete provider provisioning, live observation adapters and their production qualification remain required.
Snapshot and preview reads also revalidate stored canonical receipt material and blueprint version. Legacy ready records, missing receipts, changed blueprints, tampered digests and stale observations project as pending with no hosted URL; this does not rewrite stored records or require a blanket data migration.
Retained candidate artifacts can be read through BuilderRetainedPatchArtifactReadPort. The local createBuilderRetainedPatchArtifactReader binds a protected project artifact root and checks the exact work order, base/head revisions and patch hash. It verifies both retained patch and bundle bytes after checkout disposal, rejects ambiguous matches and fails explicitly when its bounded inventory is exceeded. Cancellation returns no artifact. This is read-only artifact evidence, not member authorization, deployment authority or a hosted preview.
Candidate execution
Supply candidateService to BuilderRuntimeService to connect a reviewed plan to the host’s current policy, approval verification, canonical admission and AgentHost execution. executeCandidateAction supports prepare, approve, execute and status. Existing plan approve/execute commands use this same service and no longer manufacture approved/completed plan timestamps. Missing host configuration returns unavailable; missing identity, stale reviewed material and uncertain outcomes fail closed.
Hosts supply candidateActor separately from payload. Requests bind the exact
planRef and a request ID; hosts also deduplicate by workspace and plan digest. Compilation records sourceBlueprintDigest, and snapshots expose the matching
candidatePlanRef. Recompile legacy plans before candidate actions. Terminal success requires canonical operation/receipt references and retained artifact evidence; the host must independently verify those records and current authority.
Draft delivery service
./builder-delivery owns the existing draft-only delivery service, injected filesystem storage, idempotency store, evidence references and simulated receipts. Leaf entries preserve compatibility forwarding from workspace services. Hosts supply complete generic filesystem/logger ports from CLI-runtime and own concrete adapters, visibility policy and production-mode settings. Production dispatch, approval and receipt guards remain fail-closed; this service grants no runtime authority.
Portable filesystem and logging contracts now have one canonical owner in
@lssm-tech/lib.utils-typescript/ports/fs and /ports/logger. Their complete interfaces are unchanged. Existing CLI /ports/fs and /ports/logger imports remain compatible type exports; Builder delivery uses the portable contracts directly and no longer depends on the CLI host.
Control-plane contract composition
The control-plane/contracts entry owns the original operation, event and capability objects and explicit registration functions. Narrow commands,
events, queries and capabilities entries preserve the same definitions. Registration accepts the existing nominal RuntimeCore OperationSpecRegistry, Kernel EventRegistry and SurfaceRuntime CapabilityRegistry. Builder spec retains the existing constants and approve/reject/trace definitions. Registration itself grants no execution authority, and legacy facade paths share every object.