lib.contracts-runtime-kernel
Canonical framework-neutral ContractSpec engine, ports and storage; no Forms or backend authority
@lssm-tech/lib.contracts-runtime-kernelbun add @lssm-tech/lib.contracts-runtime-kernelManifest declarations describe the current workspace; they do not verify registry publication or runtime execution.
Package guide
The existing root owns the unchanged EventRegistry class. Legacy /events imports forward the same constructor and keep all event model and factory exports on their canonical Core owner. Registration, duplicate errors, version lookup and inherited filter/group behavior remain unchanged.
This canonical owner reuses the existing engine and supplied ports. No Forms/domain semantics, selected platform backend, host environment bridge, runtime authority or provider implementation enters this Foundation leaf. Legacy factory/function identity and native/browser storage conditions are preserved. Clean producer and consumer qualification remain pending.
Production declaration builds select tsconfig.build.json, preserving rootDir: src while excluding tests and the private engine test helper. Source typechecking retains these fixtures through the unchanged tsconfig.json; production-reachable portable helpers remain included.
Rich-reference registry and rich-content privacy
The existing root also owns the canonical reference-kind registry and subject, kind-policy, preference and audit port declarations. Registration remains explicit; duplicate registration and unknown-kind lookup retain their existing errors. Compatibility imports resolve the same registry and function bindings.
The existing @lssm-tech/lib.contracts-runtime-kernel/redaction root also exports the rich-content models and redactRichSegments, redactRichCodeBlock, redactRichDiffBlock and richSegmentsToText. Redacted references retain their existing placeholders and explanations while dropping values, links and metadata. Authentication, policy decisions and durable audit persistence remain supplied ports and do not become grants of action authority.
createDenialTokenSigner and createSessionSalt use the existing CryptoUtils HMAC implementation and Web Crypto randomness through the kernel root. Caller keys, per-request salt requirements and fail-closed verification remain unchanged. Crypto-free DENIAL_TOKEN_PREFIX and looksLikeDenialToken shape checks remain available through /redaction, alongside the original text/code/diff builders.
The root also exposes the canonical ResourceRegistry, resource metadata/template types, defineResourceTemplate, resourceRef and isResourceRef. Resource URI matching retains literal escaping, registration order and URI decoding behavior. Resource resolution remains the original caller-supplied read-only callback; registration and matching provide no authorization for executing that callback.
The existing root owns the canonical SpecContractRegistry, keyOfSpecContract and complete registry utility family. Legacy registry imports forward the same class, functions and grouping object; duplicate errors, latest-version selection, filters, defaults and insertion order remain unchanged. The five intentional package roots are unchanged.
The existing root exposes the canonical OperationSpecRegistry and supplied OperationHandlerCtx ports. Hosts retain their exact branding and translation types, and variant selection and handlers share the same context type. Legacy imports specialize this same constructor with the original product context; installer inference, protected subclass access and runtime authority guards remain intact. The executor uses private preparation and invocation modules to satisfy the package size limit. Preparation calls its typed continuation at the original guard boundary without an unconditional await, preserving handler and context-mutation onset; promise settlement and resulting-tree performance still require measurement.
Fail-closed execution (D-242)
OperationSpecRegistry.execute/executeResult enforce the policy a spec declares:
- With
ctx.decide, the decision is enforced as before (deny refuses, rate limits run). Without it, a spec declaring any non-anonymous requirement runs the baseline guard (checkPolicyForOperationpluscheckCombinedPolicyoveruserId,actor,roles,permissionsandfeatureFlags). Theadminlevel needs an explicitadminrole or a userId-backedactor: 'admin'(D-244); the actor label alone is not an admin credential. A spec declaringpoliciesorfieldPolicieswithoutdecideis refused (FORBIDDEN,PolicyUndecided). - Trust assumption: every identity fact in the context is host-asserted. The
actorlabel still authenticates for theuserlevel (the REST/MCP transport convention). Hosts must never deriveactor,userIdor roles from caller input; cron and worker contexts that execute admin specs carry a serviceuserId(for exampleservice:<job>) or the explicitadminrole. ctx.allowUndecided: { reason, record? }is the explicit host opt-out for hosts that evaluatepolicies/fieldPolicieselsewhere. It waives only those two; the baseline guard still checks auth, roles, permissions and flags. The reason is required; every waived execution is recorded throughrecord(a throwing recorder refuses the call) or, without it, aconsole.warnon every call.- Denials return the generic
FORBIDDENproblemPolicyDenied: <key>.v<version>without the reason;ctx.onPolicyDeniedreceives the specific reason (decider reason, missing roles or flags) for server-side logs or audit. - A human-review escalation requires a valid approval receipt through the existing
approvalPort, likeexecution.approval, and fails closed: a spec-levelpolicy.escalate: 'human_review'requires approval with or withoutdecide, unless the decision returns a typedescalationWaiver: { reason }with a non-empty reason (D-244). The kernel records every waived call throughctx.onEscalationWaived(a throwing recorder refuses the call) or, without it, aconsole.warnon every call. A bareescalate: nullnever waives, and a decision returningescalate: 'human_review'always requires approval.createDeclaredPolicyDecidercarries the spec escalation; host deciders map it withwithDeclaredEscalation(decide)ordeclaredEscalation(input), andPolicyEnginenever waives it. - When a spec variant runs the base spec's handler (fallback, or same key and version), the base spec's declared policy is enforced as well.
- Denied
fieldDecisionsrefuse input that sets a write-denied field and remove read-denied fields from the validated output (dot paths, applied through arrays and success envelopes). A field without afieldPoliciesentry is write and read for commands, read for queries. - Events emitted by the handler are validated, buffered and published only after the output passed validation; success telemetry follows publication. Any failure drops the buffered events and tracks failure telemetry; emitting after the execution settled is refused. A handler calling
ctx.eventPublisherdirectly joins the same buffer. Delivery after validation is described below (F6).
Transactional event outbox and idempotency (D-244 F6)
- Outbox. With
ctx.eventOutboxthe kernel hands every validated event of a successful execution toEventOutboxPort.appendin one call, after output validation and field redaction. The port stores the batch atomically or throws; the execution then fails and nothing is published. - Event ids. Each event id is
<executionId>:<sequence>(1-based emission order). The execution id comes from the idempotency record,ctx.executionId, a value derived from the caller scope, operation andctx.idemKey, or a random UUID. A retried execution with the same id therefore produces the same event ids, which the outbox and consumers deduplicate. The handler context carries the resolvedexecutionId. A caller-suppliedctx.executionIdmust be unique per execution: a second execution reusing it with identical payloads is stored as a retry of the first, so its events are not added. - Idempotency. With
ctx.idemKeyandctx.idempotencythe kernel claims the key before the handler, scoped by tenant, organization, workspace, user and actor and fingerprinted by the contract and validated input. A completed key replays its stored result without running the handler or emitting events. A key reused with a different input is refused (CONFLICT,IdempotencyKeyReused), as is a key held by a live execution (IdempotencyInProgress). An abandoned key is taken over afteridempotencyLeaseMs(default 60 s) with the same execution id. Approval nonces and ceremonies are checked before the claim: a retry of an approval-gated call needs a fresh receipt. - Atomic commit. When
ctx.eventOutbox.commitsIdempotencyOf(ctx.idempotency)is true, the kernel callscommitIdempotentonce: the batch and the completed key commit in one transaction or not at all. A committed batch therefore always has a completed key, and a retry replays instead of re-running a handler whose events need not be byte-identical. A failed commit stored nothing, so the key is released and the retry runs cleanly. The PostgreSQL runtime's stores are linked this way. With separate stores (outside production only), a key whose events may already be visible is never released: a failed completion leaves it in progress until its lease expires. - Profiles.
createOperationEventDelivery({ runtimeProfile, outbox, publisher })builds the context fields.'production'refuses a missing or in-memory outbox (EventOutboxRequired). Outside production, without an outbox, the direct sequential publisher remains, with a notice; it is not atomic. A production context that bypasses the factory is refused before the handler when it carries the in-memory outbox, or has no outbox while the spec declares events or a publisher is present (EventOutboxRequired). Production also refuses the in-memory idempotency store and anidemKeywithout an idempotency port (IdempotencyPortRequired), and anidemKeywhose outbox does not commit the idempotency record with the events (IdempotencyCommitSplit). Hosts setruntimeProfileexplicitly; a context without it is treated as non-production. - Consumers. Delivery from a relay is at least once.
dedupeEventHandlerandcreateEventIdDeduperdeduplicate by event id inside one process. The PostgreSQL outbox, idempotency store, ordered relay and durable consumer receipts live in@lssm-tech/integration.runtime/operation-outbox. - Test stores.
createMemoryEventOutboxandcreateMemoryIdempotencyStoreare for tests and local tools only.
createOperationApprovalPort requires an explicit nonceStore (D-244): there is no implicit fallback, and a missing store throws ApprovalNonceStoreRequired. Production hosts pass a durable shared store (the Connect approval store, the growth planning approval store, or createPostgresApprovalNonceStoreV1 from @lssm-tech/integration.lssm-os-state-postgres) and set runtimeProfile: 'production', which refuses the in-memory store. Tests and local development pass createMemoryApprovalNonceStore(now) explicitly, with the same clock as the port. contractFingerprintOf(spec) returns the stored contract:<key>@<version> format unchanged, so historical receipts keep matching.
The existing root owns the complete data-view filter-scope family: resolveDataViewFilters, sanitizeDataViewFilterSet, filterSetToClauses, pruneDataViewFilterClauses, pruneDataViewFilterSet and the two input/result interfaces. User filters override initial values even when explicitly empty; locked conflicts are pruned and locked clauses remain last. Range operators, null clauses, clone behavior and the visible-disabled chip default remain unchanged. Legacy leaf and barrel imports forward the same functions. Resolution supplies filter constraints and does not authorize query execution.
The existing root exposes evaluatePredicateSpec and PredicateEvaluation. The complete original evaluator uses canonical Core predicate models and preserves all comparison coercions, branch precedence, default path resolution, callback/getter errors and insertion order of accessed paths. Every child is evaluated with children.map before the group result is combined. Legacy imports forward this same three-argument function; the existing DecisionRuntime two-argument evaluatePredicate wrapper remains unchanged. Matching supplies evidence and does not grant action authority.
The existing root exposes the canonical FeatureRegistry and PresentationRegistry for caller-supplied Core contracts. Compatibility registry leaves forward these exact classes. Feature duplicate errors, filters, grouping and insertion order remain unchanged; presentation registration and latest-version lookup retain the shared nominal superclass. Registration provides no runtime effect authority.
Entity and DataView registries
DataViewRegistry, dataViewKey, EntityRegistry, and tech_contracts_entities_registry_DocBlocks are exported from the existing Runtime Kernel root. The original implementations consume portable Core models and the canonical SpecContractRegistry superclass. Duplicate handling, version selection, protected storage, edge order, defaults and error text are unchanged. Supported Legacy registry paths forward the same class objects; the original compatibility tests remain unchanged. No populated catalog or UI implementation is installed by importing these registries.
The canonical ./forms/form-registry and ./forms/projection-lookup leaves own the complete generic nominal form registry and projection lookup helpers over Core form contracts. They preserve duplicate/version selection, private map identity and all filtering/grouping behavior. They import no Forms services, UI, host DTO, provider or persistence implementation. Historical paths forward to the same class and functions; this ownership change grants no authority.
Policy, rich-reference runtime, idempotency and prompt registry
./policyand./policy/<leaf>(context,engine,guards,opa-adapter,registry,requirements,spec,validation) ownPolicyEngine,PolicyRegistry, policy context/guards, the OPA adapter and policy validation../policyalso exports the condition grammar:compilePolicyExpression,evaluatePolicyExpression,PolicyExpressionError,POLICY_CONDITION_ROOTSandPOLICY_EXPRESSION_LIMITS. Conditions are parsed and interpreted, never run withevalornew Function. A condition that cannot be parsed or evaluated fails closed: it applies a deny rule and never grants an allow rule.validatePolicySpecreports such conditions, and malformed specs, as error issues instead of throwing../rich-reference/handler,./rich-reference/redactionand./rich-reference/runtime[/<leaf>]own the reference handler contract, kind redaction and theReferenceRuntimedispatch/redaction enforcement../shared/idempotency(Node-onlyderiveIdempotencyKey) and./shared/idempotency-shape(browser-safe shape)../promptRegistryownsPromptRegistry(thePromptSpecmodel lives in@lssm-tech/lib.contracts-spec-core/prompt).
Legacy @lssm-tech/lib.contracts-spec paths forward to these same instances.
The ./pwa/registry entry owns PwaAppManifestRegistry, comparePwaVersions and getLatestPwaRelease. It consumes portable Core PWA models and preserves the canonical registry superclass and semantic version ordering. Historical PWA registry exports forward to this entry; PWA update contract definitions belong to the pure @lssm-tech/lib.progressive-delivery/pwa entry.
Built-in rich-reference kinds
The rich-reference/kinds entry owns the existing explicit seven-kind registration and entity resolver. The six pure kind definitions remain in Core; registration uses the same Kernel registry and rejects duplicate ids. The rich-reference/kinds/entity leaf and rich-reference/__fixtures__/cross-adapter-fixture preserve the existing entity contract and adapter parity data. Imports do not populate a registry or grant authority. Legacy contracts-spec paths forward the identical objects.
Canonical compatibility leaves: ./migrations, ./model-registry. These leaves preserve the original implementations and object/class identity; legacy ContractSpec imports forward to these owners.
Relationships
Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.
5 declarations
@lssm-tech/lib.schemaworkspace:^
Read the package manual ↗compare-versionscatalog:data
@lssm-tech/lib.contracts-spec-coreworkspace:^
Read the package manual ↗@lssm-tech/lib.crypto-utilsworkspace:^
Read the package manual ↗zodcatalog:
Declared capabilities
Existing query/cache/offline engine and supplied approval, transport, reachability, storage, collaboration, redaction and event ports.
Existing canonical reference-kind registry, denial-token signer and supplied subject, policy and audit ports, with rich-content builders/redaction preserving hidden values and metadata removal.
Original resource registry, template definitions and resource-ref descriptors with preserved canonical class identity and URI matching/decoding behavior.
Original complete filter sanitization, clause conversion and locked-scope precedence execution over canonical Core data-view models.
Original complete PredicateSpec evaluator and deterministic path/comparison helpers, preserving callback order and accessed-path evidence.
Original nominal entity, edge and DataView registries for caller-supplied portable contracts, preserving shared superclass identity, duplicate errors and version-selection behavior.
Scripts
buildcontractspec-bun-build buildbuild:bundlecontractspec-bun-build transpilebuild:typescontractspec-bun-build typeslint:checknode ../../../scripts/biome.cjs check .prebuildcontractspec-bun-build prebuildtypechecktsgo --noEmit -p tsconfig.json