npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lssm/lib.contracts-spec

v17.3.2

Published

Spec definitions and registries for ContractSpec

Readme

@lssm/lib.contracts-spec

./companyos/auth-production-topology adds CompanyOsPreviewAuthTopologyV1 and defineCompanyOsPreviewAuthTopology for explicit preview web/API origins, same-origin browser auth and host-only cookies. This additive topology contract does not grant access or prove infrastructure isolation. Production callback resolution rejects external, backslash and control-character destinations.

Adaptive delivery profiles and scoped autonomy

The ./quality surface also exports QualityEnvironmentV1 and its material, digest and validation helpers. Optional environment references in quality profile bindings and planned checks preserve existing V1 inputs while binding new checks to exact mocked/integrated/deployed fixtures, network policy and bounded dependency readiness. Environment descriptions contain no credentials and do not grant authority.

The existing ./delivery entrypoint adds DeliveryProjectProfileV1 and DeliveryAutonomyPolicyV2 without changing TenantDeliveryPolicyV1. Project profiles independently select adoption, control-plane placement, application hosting, optional agents, quality, previews, and budget references. Contracts-only adoption requires no infrastructure. Managed application and container hosting can be mixed without Kubernetes or a persistent agent.

resolveDeliveryAutonomyV2 computes a restrictive policy explanation from a server-loaded organization root and explicit parent policies. It intersects autonomy, risk and cost ceilings and unions required checks. Missing parents, expired/revoked policies, cycles, scope expansion and substituted digests block progression. Hosts must provide the complete applicable policy set and current authenticated scope; this projection always returns authorizesExecution: false. Connect must independently revalidate current policy and execution authority.

These additive contracts describe configuration and policy. They do not claim live cloud/agent qualification or provision infrastructure.

[email protected] is a recipient-owned contract. Browser operations derive the user and personal tenant from the authenticated session, calendars come only from personal Google grants, graph context requires explicit calendar-to-currently-authorized-workspace mapping, and event attendees are never delivery recipients. Preview input remains exactly one document kind; the server runs the current user's bounded personal pipeline, returns only privacy-safe delivery evidence, and fails closed when setup, authority, or an eligible preparation event is missing. Routed email delivery now distinguishes durable CommunicationOS queue admission from provider acceptance and confirmed delivery.

Calendar drafts may additionally carry CalendarIntelligenceGenerationProvenance: a versioned binding digest, prompt version, model, processing/transit approval references, and verified inference region. Deterministic fallback has no model provenance, and legacy receipts must not be retroactively qualified. Provenance records do not grant private-processing or delivery authority.

Core contract declarations, registries, and shared execution primitives for ContractSpec.

The additive ./creator-operations subpath defines reusable creator campaigns, immutable agreements, submissions/reviews, exact currency-and-scale compensation, canonical wallet entries and settlement operations. Implementations live in lib.creator-operations-runtime, integration.creator-persistence and module.creator-operations. Importing this surface does not migrate existing Hirly API identities or records; the ownership amendment and Marketing Operations status describe the remaining parity and qualification work.

Intent-to-production delivery protocol

@lssm/lib.contracts-spec/delivery is the provider-neutral trust chain for one exact candidate. It exports digest-bound DeliveryPlanV1, DeliveryEvidenceEnvelopeV2, TenantDeliveryPolicyV1, typed ownership and risk rules, ManualAuthorAttestationV1 for non-authoritative authorship evidence, CiBudgetStateV2 for reconciled tenant economic admission, plus the complete quality protocol (QualityProfileSpec, QualityPlanV1, QualityCheckRef, and QualityRunReceiptV1). The narrower ./quality subpath is also available for evidence producers.

@lssm/lib.contracts-spec/telemetry/v2 defines strict privacy, residency, deterministic sampling, cardinality, ingestion, cost, redaction, and evidence-link policy. The ./telemetry barrel also exports the canonical ContractSpec engineering event taxonomy. Telemetry is a sanitized analysis projection and never grants mutation or promotion authority.

The protocol deliberately contains no Railway, GCP, GitHub Actions, PostHog, or other provider configuration. Connect owns authority, CI executes an exact quality plan, and Runtime Nodes execute separately signed work orders.

The root barrel preserves the canonical PolicyRef from ./policy and VisualizationRef from ./visualizations. The ./features subpath continues to expose its convenience aliases, while root consumers receive one unambiguous type for each reference without changing import syntax.

Provider-neutral visual development contracts are available from @lssm/lib.contracts-spec/visual-scenarios. VisualScenarioSpec links deterministic named cases to a React presentation, validates modes and typed binding references, and requires explicit safe-data classification. Publishing captures to an external visual-diff service fails closed unless capture.external is explicitly enabled. FeatureModuleSpec.visualScenarios and the visual-scenario capability surface make these contracts installable and discoverable without coupling the core package to Storybook or Chromatic.

Website: https://contractspec.io/

Why this package exists

@lssm/lib.contracts-spec is the foundation of the split from @lssm/lib.contracts.

It gives you one place to define behavior before implementation:

  1. Declare specs (operations, events, forms, resources, policies).
  2. Bind handlers.
  3. Project the same contracts into REST, GraphQL, MCP, and React runtimes.

SupportOS v1 adds three additive contract families: customer-support-v1 for cases, queues, SLAs, provider migration, graduated AI policy, and the capability/qualification matrix; decision-operations-v1 for deterministic effect-free branching and replay; and living-sops-v1 for generated, simulated, qualified, revision-pinned procedures that compile into WorkflowSpec when effects are required. Living-SOP generation sources are canonical discriminated contributions with immutable source revision, observation/expiry, opaque evidence, and exact capability, integration, operation, policy, health, Knowledge, incident, or case semantics; a content-addressed snapshot, not a delivery matrix, owns replay provenance. Its composite SupportPlatformAuthorityPort declares workspace, case, routing, SLA, profile, decision, SOP, provider, AI, customer, and administration facets. The deprecated four-method authority adapts only the case facet; every absent facet remains explicitly unavailable and fails conformance. Case assignment v2 models claim, release, administrator assignment, and governed steal as strict semantic modes; steal decisions bind scope, case, target, revision, expiry, and immutable server-verified evidence while v1 remains explicitly discoverable for migration. Identity-resolution v1 accepts only opaque source references, delegates tenant/workspace-scoped lookup hashing to a server-side evidence port, exposes redacted candidates, and models merges as governed reversible graph edges without rewriting profile or CommunicationOS identity data. Attachment-safety v1 keeps bytes, storage, names, MIME data, and channel linkage in CommunicationOS while SupportOS stores only scope-bound scan, quarantine, consent, and governed-release evidence. Case presence is an additive ephemeral contract with server-owned time and expiry, monotonic opaque sessions, scope-bound authorization, and count-only projections; it is never durable case history or an identity-disclosure surface. Internal-note contracts carry only opaque CommunicationOS content/evidence references and reject note bodies from portable SupportOS operations. Matrix source and test-definition references are inventory evidence only. Executed proof requires an immutable run receipt, while production receipts require a digest, observation time, and expiry relative to the matrix asOf. Form predicates remain wire-compatible through the shared PredicateSpec adapter.

SupportOS Company actions are additive, body-free contracts for refund, credit, entitlement-adjustment, and account-change plans. CompanyOS owns the minimized case/profile/entitlement evidence projection, Connect owns allow/approval decisions, and Workflow owns effect execution and outcome evidence. Every plan binds the exact action identity, case revision, policy, Workflow revision, input digest, and optional independently revision-pinned compensation Workflow. SupportOS records only opaque references and immutable lifecycle receipts; it never accepts an amount, customer body, provider payload, or direct effect executor through this contract surface.

SupportOS notification contracts add body-free preferences, escalation-pinned intent, and typed delivery settlement evidence. CommunicationOS remains authoritative for rendered content, contact destinations, channel identities, attachments, and provider delivery.

SupportOS OPA handoffs are additive, consent-bound contracts for public profiles and bookings. SupportOS owns only the opaque handoff lifecycle and redacted return evidence; OPA remains authoritative for profile identity, owner scope, links, availability, booking state, calendar data, and provider effects.

SupportOS case search and saved views are additive, contract-only surfaces. They expose strict bounded filters, server-issued watermarks, opaque keyset cursors, redacted operational projections, and revision-fenced idempotent view mutations. Free-text search is restricted to explicitly indexed non-sensitive operational fields. The legacy search port remains unchanged; PostgreSQL, protected API, client, UI, accessibility, and production evidence are not yet claimed.

Workspace topology administration is canonical at v2 with pinned v1 lookup. It records brand/product/host, BCP-47 locale catalog, residency, expected revision, policy, and evidence references. Authenticated server context remains the only tenant/workspace authority. Configuration never implies data movement; isolated/pooled changes use the separate migration planner contract.

Isolated onboarding is a separate tenant-bootstrap contract. A short-lived AuthOS grant supplies the server-derived tenant, new workspace, actor, and principal kind because workspace membership cannot exist before creation. The operation body carries only single-brand topology, locale/residency policy, idempotency, and evidence. Server-side Connect governance authorizes the exact state-bound mutation. The operation atomically creates the workspace and founding administrator or fails without a partial authority.

The workspace migration v2 surface previews an immutable original/target plan, requires policy and evidence references on every mutation, binds start and rollback to an expiring Connect decision, and advances through a revision-fenced PostgreSQL ledger. Exact retries return the original receipt; changed inputs, stale revisions/fences, unresolved blocking collisions, and revoked membership fail closed. Cutover is reauthorized against an unexpired Connect decision. The original workspace configuration command remains available as an explicit v1 compatibility version.

Case merge, split, and link operations retain their original v1 contracts for generated-client compatibility. The explicit v2 relation contracts add stable relation IDs, related-case revision fencing, immutable evidence, and exact idempotent replay. Managed execution derives authority from the server scope and advances both case histories atomically without copying CommunicationOS bodies.

This spec-first flow improves determinism, regeneration safety, and multi-surface consistency.

Package boundary (important)

Use this package for:

  • Contract declarations (defineCommand, defineQuery, defineEvent, defineResourceTemplate, etc.).
  • Agent definition contracts (defineAgent, AgentRegistry, AgentSpec, AgentToolConfig) and optional protocol V1 bindings.
  • Portable Plan–Act–Reflect artifacts via @lssm/lib.contracts-spec/agent/protocol, plus provenance-aware context artifacts via @lssm/lib.contracts-spec/context/agent-context. These strict schemas describe durable plans, checkpoints, reflections, bounded delegation, help, model routes, memory proposals, and opaque owner bindings. They do not grant authority, execute effects, route messages, persist runs, or implement schedulers.
  • Pure Feature Hub protocol contracts via @lssm/lib.contracts-spec/feature-hubs: versioned manifests, capabilities, dependencies, semantic routes, ports, policy declarations, readiness, signed discovery metadata, federation envelopes, leases, replay, and atomic intent records. These contracts never load remote code or own a provider runtime.
  • Agent-platform composition and certification contracts via @lssm/lib.contracts-spec/agent-platform: pinned provider/component plans, stable digests, capability losses, live suite evidence, and explicit enterprise controls.
  • Agentpacks dual-variant guidance-unit contracts (defineAgentpackGuidanceUnit, AgentpackGuidanceUnit) via @lssm/lib.contracts-spec/agentpacks.
  • Agentic interaction safety contracts via @lssm/lib.contracts-spec/agentic-interaction; keep this subpath out of the root barrel so adopters opt into fail-closed AIP mappings explicitly.
  • Portable agent-step observability contracts (AgentStepSpec, AgentStepArtifact, AgentStepEvidencePointer, AgentStepTweakableVariable, AgentStepReplayBundleRef, AgentStepImprovementProposal) via @lssm/lib.contracts-spec/agent-step-observability; this surface links to evidence/replay/approval owners by ref and never stores raw model chain-of-thought.
  • Evidence-backed outcome-claim contracts (OutcomeClaim, ClaimEvidence, ClaimReview, ClaimCorrection) via @lssm/lib.contracts-spec/outcome-claims; no evidence means no valid claim.
  • Marketing page/site narrative contracts (MarketingSiteContract, MarketingPageContract, MarketingSectionContract) via @lssm/lib.contracts-spec/marketing; this additive subpath declares route strategy, narrative intent, density budgets, CTAs, evidence refs, structured card fields/icon keys, and presentation-binding requirements without owning product copy or React rendering.
  • Core registries (OperationSpecRegistry, EventRegistry, FormRegistry, ResourceRegistry).
  • Experience coverage contracts via @lssm/lib.contracts-spec/experience-coverage: stable module, feature, journey, evidence, platform, owner-scope, provider, blocker, and computed status semantics. [email protected] deliberately does not treat route existence or fixture rendering as implementation evidence; actionable features require happy, recovery, and denial journeys, while provider-backed features require reversible production-canary evidence. Security, migration, performance, and resilience are first-class evidence layers so safety proof is not discarded by cross-product projections. Additive structured exposure/auth-mode fields preserve customer, operator, administrator, and service authority in generated journeys; the latest observed evidence result supersedes older results. Optional structured delivery/qualification state prevents a product-health projection from claiming live_verified while canonical promotion is pending or a blocker is open.
  • Managed CompanyOS design-partner readiness operations (designPartnerReadiness.get, decisionPacket.attest, decisionPacket.founderApprove) that reuse evidence.get-receipt, replay.get-packet, specialOps.reviewCard.decide, and specialOps.weeklyReport.approve instead of creating duplicate receipt, replay, or approval systems.
  • Managed CompanyOS organization-bootstrap manifest and durable receipt contracts via the narrow @lssm/lib.contracts-spec/companyos/organization-bootstrap subpath.
  • Managed CompanyOS canonical three-organization seed manifest, family digests, expected counts, and redacted receipt contracts via the narrow @lssm/lib.contracts-spec/companyos/organization-seed subpath. The seed manifest reuses the bootstrap identity tuples, preserves organization-bootstrap:v1, and classifies the new surface as additive and non-breaking. LSSM and CompanyOS carry distinct deterministic profile copy, HTTPS links, and event metadata; events stay inactive with booking unavailable until an approved hybrid destination is materialized by the app-owned seed adapter.
  • Managed CompanyOS public authority composition requirements via @lssm/lib.contracts-spec/companyos: [email protected] and [email protected] require real API/runtime bindings; browser Origins and preflights are exact-trusted while absent Origin is server-transport-only; canonical revalidation bypasses caches; every distinct provider Set-Cookie is preserved; no-active sessions list memberships before selection and have zero workspace authority; active-organization transitions emit one atomic server-owned database-trigger audit event only on change; and production authority repositories are lazy app-lifecycle-owned resources rather than per-request resources.
  • Managed CompanyOS personal and nested authority operations: [email protected], [email protected], [email protected], and [email protected]. The additive context family exposes only opaque personal/company/team/workspace references. Selection uses a signed five-minute one-use token and one atomic compare-and-swap transition; organization, team, workspace, grant, and physical tenant identifiers supplied by a browser are never authority.
  • CompanyOS shell operations [email protected], [email protected], companyos.onboardingPreferences.complete, and companyos.personaPreview.set define the versioned account placement snapshot, tenant-scoped experience preference document, optimistic revision input, tenant-bound experience preference command, and session-scoped presentation-preview result without changing real-role authorization. The onboarding command accepts no browser-selected user or tenant authority.
  • Experimental, versioned graph artifact contracts for contract graphs, codebase graphs, contract-code links, generation plans, drift reports, repair proposals, and provenance.
  • Shared execution/runtime-neutral types (HandlerCtx, policy decision types, telemetry trigger types).
  • Typed success/failure/result contracts (ContractResult, ContractSuccess, ContractProblem, ContractSpecError) via @lssm/lib.contracts-spec/results.
  • Contract installation helpers (installOp, op, makeEmit).

Do not use this package for framework adapters:

  • REST adapters -> @lssm/lib.contracts-runtime-server-rest
  • GraphQL adapters -> @lssm/lib.contracts-runtime-server-graphql
  • MCP adapters -> @lssm/lib.contracts-runtime-server-mcp
  • React runtime rendering -> @lssm/lib.contracts-runtime-client-react
  • Integration provider/secret catalogs -> @lssm/lib.contracts-integrations

Installation

npm install @lssm/lib.contracts-spec @lssm/lib.schema
# or
bun add @lssm/lib.contracts-spec @lssm/lib.schema

Durable Queue V2 contracts

@lssm/lib.contracts-spec/jobs/durable-queue-v2 is the strict, provider-neutral wire boundary for LSSM OS durable admission and broker capability qualification. It exports immutable queue envelopes, exact adapter and broker capability profiles, bounded backpressure and health evidence, plus admission, claim, renewal, acknowledgement, and redrive records.

Queue claims and acknowledgements coordinate delivery; they never authorize an external effect. Every envelope binds tenant, workspace, environment, product, application, operation, order, replay, partition, ordering, dedupe, payload, trace, expiry, attempt ceiling, and sensitivity. Inline JSON is bounded and secret-free; larger payloads use an encrypted blob reference. Broker profiles declare exact ordering, acknowledgement, replay, delay, TTL, lease, fan-out, consumer-group, dead-letter, transaction, dedupe, encryption, placement, and version semantics. Admission must reject requirements the selected profile cannot prove.

The original JobQueue V1 API and @lssm/lib.contracts-spec/jobs/queue remain unchanged as compatibility surfaces. They are not evidence of Durable Queue V2 authority or durability and may be mapped only when mandatory V2 scope, identity, ordering, and evidence can be supplied without fabrication.

Agent protocol V1

AgentSpec.protocol opt-in enables the additive protocol V1 contract without changing legacy agent definitions or compiler output. Protocol V1 forbids full-history subagent delegation and accepts only opaque CommunicationOS, Connect, automation, approval, and Runtime Node references. Context projection validators enforce subset and trust preservation; logical task graphs enforce unique acyclic dependencies and bounded participants; child delegation and model fallback require explicit semantic narrowing checks.

The application manifest pairs with a strict permission summary covering tools, approval-required tools, connection requirements, CommunicationOS bindings, automations, subagents, and evaluations. These content-addressed artifacts let Agent Host prove what was compiled without turning compiler output into a grant. The additive application-signature artifact binds that exact manifest, permission summary, source digest, first-party publisher/key/trust-policy references, evidence time, and release SHA. It defines canonical signed bytes; key custody, signing, trust-root persistence, revocation, and qualification are runtime responsibilities.

Every artifact is strict and versioned. Complete terminal decisions require exact criterion evidence plus immutable Execution Lanes completion and verifier signoff bindings. Run-scoped model selection pins the plan, qualification, version set, route digest, capability-profile digest, and privacy, residency, transport, authentication, capability, latency, and cost constraints; fallback must preserve that same constraint set and its exact qualified model identity. Reflections remain advisory and cannot execute tools, approve effects, expand budgets, or grant authority. Memory is proposal-only. Production runtimes must persist and execute these artifacts through their canonical owners; this package supplies contracts and pure validation only.

Gateway-neutral routing remains inside Protocol V1. Same-family V2 wire artifacts separate model authorship from inference provider, deployment, optional gateway, adapter, commercial policy, region, and sanitized connection identity. Candidate bindings also pin exact route cost/currency and the current production-canary head; deployments, adapters, policies, and price profiles reject floating latest identities. An immutable invocation profile binds executed generation settings, output validation, and provider options; qualification additionally binds the application purpose/optional operation, evaluation decision, dataset, expiry, and revocation. V1 artifacts remain readable, but the one-way migration helper always returns requalification_required and never fabricates strengthened evidence or authority.

The governed memory lifecycle is explicit: the agent emits an immutable proposal, PersonalOS or CompanyOS supplies the independently digest-bound owner decision, and only a promoted proposal can produce an exact CAS mutation receipt. Corrections, revocations, and deletions target an existing memory; cross-scope use requires a separately authorized, expiring projection that can also be revoked. The owner decision and reflection both have effectAuthority: none and therefore cannot substitute for the owning memory service.

Governed automation is likewise explicit. A natural-language request can only produce a preview of one qualified first-party schedule definition. An injected authority materializes that exact preview; Agent Host persists revision-CAS state and claims one deterministic occurrence; a terminal run produces an immutable receipt; and an optional background follow-up is admitted by CommunicationOS only after the final state binds that receipt. Pause, resume, revocation, expiry, lease recovery, retry, and indeterminate reconciliation are digest-bound. Every automation artifact has effectAuthority: "none" and cannot grant tools, approve effects, send a message, or bypass Runtime Nodes.

Enterprise agent-platform contracts

The agent-platform subpath is the portable boundary between agent capabilities and infrastructure. A composition plan pins every selected profile/component and records capability coverage and losses. Certification is fail-closed: the report must bind the exact plan digest and environment, every selected capability must be classified by required suites, timeouts and missing suites fail, and all losses require explicit acceptance.

The complete provider and baseline suite set is part of the plan itself and therefore part of its digest.

Adaptive operations V2

@lssm/lib.contracts-spec/ai-improvement/contracts-v2 adds sanitized operational signals, observation plans/results, deterministic automation-risk decisions, patch-run receipts, and work orders with an explicit observing stage. The V1 contracts remain unchanged. Signals carry metadata and replay evidence only: raw prompts, business payloads, credentials, and personal data are outside the contract.

The canonical certifier itself requires passing, required reports for the governance/security, supply-chain security, observability-export, load/resilience, and clean-consumer-release baselines. Callers cannot bypass them by omitting suite IDs from a runtime composition object.

Production qualification also requires explicit retention, deletion, export, residency, encryption, backup, RPO/RTO, SSO, SCIM, RBAC, break-glass, audit, trace, metric, cost, and budget controls. The contracts deliberately do not claim that a provider supplies or configures these controls; the deployment profile and live evidence must prove the chosen topology.

Managed CompanyOS design-partner readiness operations

The CompanyOS registry now includes three additive operation contracts for the fictive NDconsulting design-partner readiness slice:

| Operation key | Kind | Purpose | | --- | --- | --- | | designPartnerReadiness.get | Query | Read the scoped design-partner readiness projection for tenant/workspace/scenario review. | | decisionPacket.attest | Command | Record expert-reviewer attestation for a decision packet. | | decisionPacket.founderApprove | Command | Record founder approval for a decision packet. |

These contracts reuse evidence.get-receipt, replay.get-packet, specialOps.reviewCard.decide, and specialOps.weeklyReport.approve; they do not create duplicate receipt, replay, or approval systems.

Published subpaths:

  • @lssm/lib.contracts-spec/companyos/organization-bootstrap
  • @lssm/lib.contracts-spec/companyos/organization-seed
  • @lssm/lib.contracts-spec/companyos/organization-seed-profile-manifest
  • @lssm/lib.contracts-spec/companyos/queries/designPartnerReadinessGet.query
  • @lssm/lib.contracts-spec/companyos/commands/decisionPacketAttest.command
  • @lssm/lib.contracts-spec/companyos/commands/decisionPacketFounderApprove.command
  • @lssm/lib.contracts-spec/companyos/production-semantics

Boundary: the original 1.0.0 specs remain unchanged and are still returned by the key-only registry. Explicit 2.0.0 specs are available through companyOsDesignPartnerOperationVersions for production migration:

  • request scope includes tenant, workspace, scenario, and packet version;
  • principal, role, prerequisite attestation, correlation, evidence, and replay authority are server-derived rather than accepted from browser input;
  • mutation outputs carry a durable idempotency receipt committed with business state, audit, and outbox intent;
  • recorded_evidence_pending is explicit until immutable evidence/replay projection completes;
  • readiness output includes replay linkage and fail-closed database, migration, relay, DLQ, and scheduled-snapshot health.

The v2 founder contract explicitly returns a conflict until an accepted expert attestation exists on the exact scoped packet version. This is versioned rather than silently tightening v1 behavior. These remain operation contracts only; they carry no provider dispatch, credential handling, live customer data, or DB execution authority.

Company Intelligence operations and events

@lssm/lib.contracts-spec/companyos/company-intelligence adds canonical contract-only operations for record validation, bounded graph query, grounded answer requests, consented feedback, independent experiment evaluation, promotion decisions, rollback execution, and replay reads. The operations are also added to companyOsOperationRegistry without replacing any legacy key or version.

The same subpath exports reference-only events for canonical record commits, answer verification, feedback capture, promotion decisions, and rollback completion. Event payloads contain tenant-safe ids, fingerprints, evidence receipt ids, replay ids, and correlation metadata only; they contain no raw source body, credential, or secret material. Knowledge results remain evidence, promotion remains approval, and rollback remains execution.

The same subpath exports additive S12 operations/security evidence contracts: the complete threat and kill-switch identifiers, dependency outage identifiers, safe correlated telemetry, audited pre-dispatch kill-switch decisions, bounded backlog-recovery evidence, and the pinned ADR-008 qualification minimums. These contracts describe portable evidence only; the API application owns durable PostgreSQL control and audit execution.

[email protected] is the additive authenticated route descriptor query for the overview, sources, Brain, graph, assistant, learning, and operations surfaces. Its input contains only the logical surface id: tenant, role, and capability authority remain server-derived. The output carries the canonical route, explicit loading/success/empty/error/degraded/unauthorized/ partial state, freshness, safe-read posture, available or blocked actions, and dependency blocks without exposing physical tenant identifiers.

Core concepts

  • defineCommand / defineQuery: typed operation specs with metadata, I/O schema, policy, transport hints, and side effects.
  • @lssm/lib.contracts-spec/marketing: contract-first marketing-site modeling. Shared validation rejects missing dominant questions, primary intents, CTAs, disclosure strategy, unsupported section kinds, missing presentation bindings, unresolved evidence refs, and over-dense homepage contracts before bundle/app renderers consume them.
  • PolicyRequirement and SurfacePolicyRequirement: additive role/permission/flag/policy-ref requirements for operations, presentations, data views, forms, and knowledge access metadata.
  • defineAgent + AgentRegistry: typed agent-definition contracts that runtime packages execute, export, or adapt.
  • defineAgentpackGuidanceUnit + defineAgentpackGuidancePack: typed agentpacks authoring contracts that require Claude and Codex/GPT variants for meaningful guidance units, map OpenCode to the Codex/GPT variant, and carry Connect parity evidence declarations.
  • OperationSpecRegistry: registers specs, binds handlers, and executes with validation/policy/event guards.
  • AgentStepSpec + AgentStepArtifact: portable, artifact-first observability for chained agent steps. The contracts expose step specs, structured artifacts, evidence pointers, confidence, review state, tweakable variables, replay refs, diffs, and improvement proposals without exposing raw hidden reasoning.
  • OutcomeClaim: domain-neutral, reviewable claim kernel for agentic workflow outcomes. Claims require typed subject/source refs, evidence refs, reason, provenance producer/timestamp, review state, and correction history; business projections live outside this package.
  • ContractResult: canonical success/failure envelope used by operation, workflow, job, API, MCP, GraphQL, and React runtimes while preserving raw-response compatibility for adapters.
  • Canonical data-fetching protocol (@lssm/lib.contracts-spec/query): one QueryEnvelope / QueryResultEnvelope / createQueryKey, plus CacheStatus, InvalidationTag, ConflictPolicy, VersionToken, typed QueryConsistency, and the render-ready QueryState. These I/O-free primitives are carried unchanged by every transport (REST/MCP/in-memory) and executed by the in-house engine in @lssm/lib.contracts-runtime-core. They replace the removed data-transmission-{spec,runtime} packages.
  • defineEvent + EventRegistry: typed event contracts and lookup.
  • defineAdaptiveShellSpec / defineAdaptiveShellResolution: additive role-adaptive app-shell contracts for shell regions, navigation, breadcrumbs, layout variants, signals, compatibility posture, fail-closed resolver output, explanations, and invariant evidence.
  • defineResourceTemplate + ResourceRegistry: URI-template-based resource contracts.
  • FormRegistry: contract-first form declarations consumed by UI runtimes, including readonly, email, password, autocomplete, address, phone, number, percent, currency, date, time, datetime, duration, grouped array authoring, semantic legends/descriptions, grid layout hints, progressive layout.flow sections/steps, mobile-safe responsiveFormColumns(...), entity-bound projection/intake guidance, and text/textarea/email input-group addons through @lssm/lib.contracts-spec/forms.
  • installOp: one-call helper to register + bind operation handlers.
  • makeEmit: typed helper for declared event emission in handlers.

FormSpec autocomplete fields support local option filtering or resolver-backed search through resolverKey, dependency paths, debounce, and minimum-query metadata. The contract stays transport-neutral: host renderers provide the resolver/fetcher, and value submission is controlled by valueMapping (scalar, object, or pick).

FormSpec phone fields support first-class country metadata. On a kind: "phone" field, use input to choose a single linked input or split country/national inputs, output to store a PhoneFormValue, one E.164 string, or split linked paths, and display/country to control flags, calling codes, default country, and automatic country detection.

Entity-bound form projections are documented through @lssm/lib.contracts-spec/forms/entity-bound. The guidance keeps canonical identity on entities, treats quick/full/edit/intake/part forms as renderable projections, separates permissive capture from strict readiness, and records skipped fields as completion debt instead of blocking intake. Use EdgeSpec only for true entity-to-entity relations; model form parts with form-specific binding metadata.

ReviewReady app-submission-readiness contracts

@lssm/lib.contracts-spec/app-submission-readiness is the ReviewReady contract surface for auditing mobile app submissions before Apple App Store or Google Play. It exposes 27 typed operation contracts (project/app identity, asset packs, legal links, Apple App Privacy + Google Data Safety disclosures, iOS/Android manifest snapshots, SDK inventory, reviewer access, store integrations, admin rules, audit run, findings/report queries, and rejection-response drafts) plus 3 domain events (app-submission.audit-completed, app-submission.rule-updated, app-submission.integration-connected).

Resolve operations through appSubmissionReadinessOperationRegistry and events through appSubmissionReadinessEventRegistry (both keyed by meta.key). Invariants: reviewer/provider credentials are secret-ref-only (secretRefId / credentialRef) and never carry raw secret values; admin rule contracts require sourceUrl, retrievedAt, effectiveDate, and reviewState; findings/report contracts carry evidence and provenance; and store fields differentiate apple-app-store, google-play, or both. Additive subpaths: ./app-submission-readiness/{contracts,registry,events,constants,fixtures,runtime,types}.

Economic evidence operation seams

Operations may carry optional economicEvidence refs for provider-neutral usage, cost, budget, replay, and projection evidence. Database mutation plan/execute contracts also expose optional economicEvidenceRefs on input and output envelopes so provider adapters can cite evidence without turning usage/cost facts into BillingOS invoices, FinanceOps advice, payment execution, or provider SDK coupling.

Execution effects and scoped approval

Operations may declare execution.effects using the provider-neutral read, write, destructive, cost-bearing, and external-side-effect values. Setting execution.approval.required opts that operation into fail-closed, pre-handler receipt enforcement through OperationSpecRegistry.

Approval receipts bind the subject/tenant, operation key and version, canonical input digest, approved effects, optional cost ceiling, validity window, nonce, issuer, and evidence reference. Runtimes supply an OperationApprovalPort through HandlerCtx; the port validates scope and atomically prevents replay. Operations that omit execution.approval retain legacy behavior. Tags and policy.escalate remain descriptive/advisory and do not silently enable enforcement.

Security-sensitive operations may also declare execution.ceremony. The shared registry then requires a host-bound OperationCeremonyReceipt and an OperationCeremonyPort, atomically claims the receipt before handler entry, and consumes it only after the handler output validates. Failed execution is released according to the host port's bounded-attempt policy. The exported ReferenceOperationCeremonyPort requires a host-owned signature verifier or trusted challenge lookup, binds the trusted record to the server-derived subject/challenge, and provides portable host, expiry, kind, exact-operation, and replay checks. Production hosts must pair it with a durable atomic claim store.

The claimed ceremonyId is projected to the handler as HandlerCtx.ceremonyExecution.ceremonyId. Hosts must use it as the idempotency key for irreversible security transitions and must fail closed when durable claim completion cannot be committed. This keeps handler retries safe when a provider succeeds before an adapter observes the final response.

execution.dataHandling identifies transient top-level input and output fields. The shared executor enforces their telemetry redaction. Its persistence: "forbidden" and evidence: "forbidden" values are explicit obligations for host persistence, replay, and evidence adapters rather than a claim that this contract-only package owns those sinks.

Outcome claim contracts

@lssm/lib.contracts-spec/outcome-claims defines the generic evidence-backed claim kernel for agentic workflows. The package owns only portable refs, evidence, provenance, review state, correction history, validators, and factories; runtime emission belongs in @lssm/lib.ai-agent, and business/product value interpretation belongs in CompanyOS packages.

The invariant is No evidence, no claim: outcomeClaimSchema, defineOutcomeClaim, and validateOutcomeClaim reject an OutcomeClaim when evidenceRefs is empty, when reason is missing, or when provenance lacks a producer and timestamp. Corrections are append-only records that update review/supersession state without silently rewriting the original claim.

import { defineOutcomeClaim } from '@lssm/lib.contracts-spec/outcome-claims';

const claim = defineOutcomeClaim({
  id: 'claim.workflow.completed.1',
  claimType: 'workflow.outcome.completed',
  subjectRefs: [{ kind: 'subject', id: 'workspace.acme' }],
  sourceRefs: [{ kind: 'run', id: 'agent-run-1' }],
  evidenceRefs: [{ id: 'evidence.task-history.1', kind: 'artifact', ref: 'fixture://task-history/1' }],
  confidence: 0.82,
  reason: 'The task history shows the workflow completed with linked evidence.',
  provenance: {
    producer: { kind: 'agent-step', id: 'agent-step.summarize-outcome' },
    producedAt: '2026-05-31T10:01:00.000Z',
  },
  review: { state: 'needs-review' },
  corrections: [],
});

Agent-step observability contracts

@lssm/lib.contracts-spec/agent-step-observability defines the portable kernel for observing and safely tweaking chained agent workflows. It is intentionally additive and package-boundary aware:

  • ContractSpec owns the generic contract types and validators for AgentStepSpec, AgentStepArtifact, evidence pointers, confidence, review state, tweakable variables, replay refs, artifact diffs, and improvement proposals.
  • Runtime execution, telemetry, prompt/tool/model receipts, and approvals remain in @lssm/lib.ai-agent.
  • Workflow graph lifecycle, step transitions, reruns, and lineage remain in workflow-orchestration packages.
  • Durable replay/eval/proof bundles remain in harness and execution-lanes packages; ContractSpec stores AgentStepReplayBundleRef and other refs rather than duplicating evidence stores.
  • CompanyOS owns manager-facing sales workflow projections, review queues, autonomy readiness, and business value interpretation.

The observability invariant is artifacts and refs, not raw chain-of-thought. validateAgentStepArtifact rejects known raw-reasoning field names such as chainOfThought, rawReasoning, stepReasoningText, and contractspec_step_reasoning_text anywhere inside the artifact payload. Verified confidence additionally requires non-empty evidence pointers and evidenceComplete=true.

import {
  validateAgentStepArtifact,
  type AgentStepArtifact,
} from '@lssm/lib.contracts-spec/agent-step-observability';

const artifact: AgentStepArtifact = {
  id: 'artifact.classify-intent.1',
  stepSpecRef: { kind: 'agent-step-spec', id: 'classify_intent', version: '1.0.0' },
  runRef: { kind: 'run', id: 'sales-agent-run-1' },
  attempt: 1,
  artifactKind: 'sales_intent_classification',
  payload: { data: { intent: 'security_review_request' } },
  summary: 'Classified the prospect reply as a security-review request.',
  createdAt: '2026-05-31T23:02:00.000Z',
  producerRef: { kind: 'agent', id: 'sales_agent' },
  evidencePointers: [
    {
      id: 'evidence.prospect-reply.1',
      kind: 'source_message',
      ref: { kind: 'evidence', id: 'prospect-reply-1' },
      sourcePackage: '@lssm/lib.ai-agent',
      observedAt: '2026-05-31T23:01:00.000Z',
      redaction: { status: 'redacted', reason: 'Prospect PII withheld' },
    },
  ],
  confidence: { level: 'medium', evidenceComplete: true },
  review: { current: 'not_required', history: [] },
  redaction: { status: 'redacted', reason: 'Prospect PII withheld' },
};

validateAgentStepArtifact(artifact);

Adaptive shell contracts

@lssm/lib.contracts-spec/adaptive-shell defines the contract/source-of-truth layer for role-adaptive app shells before runtime or UI packages render them. Use it when a bundle or app needs a serializable shell contract that can be validated independently from React, Next.js, provider SDKs, or persistence.

The contract is intentionally additive and platform-neutral:

  • AdaptiveShellSpec declares regions, navigation nodes, breadcrumbs, layout variants, adaptation signals, required invariants, ontology refs, and compatibility classification.
  • AdaptiveShellResolution is the resolver view-model contract: selected layout, visible/disabled/suppressed navigation, action availability, graph drilldown targets, applied/suppressed adaptations, explanations, diagnostics, and invariant statuses.
  • validateAdaptiveShellSpec catches duplicate or unresolved shell refs, missing route/action/graph targets, missing required fail-closed invariants, and breaking compatibility records without migration refs.
  • validateAdaptiveShellResolution proves runtime output preserves workspace intent, has a RoleMorph resolution ref, keeps unsafe actions unavailable, requires evidence-backed adaptations, and keeps graph drilldown routing owned by the app/router layer.

Required invariants are: RoleMorph first, personalization after policy, fail-closed missing RoleMorph, deny/hidden actions, workspace intent preservation, explanation for every adaptation, router-owned graph drilldown, and deterministic output.

import {
  defineAdaptiveShellResolution,
  defineAdaptiveShellSpec,
} from '@lssm/lib.contracts-spec/adaptive-shell';

const shell = defineAdaptiveShellSpec({
  id: 'companyos.shell',
  version: '1.0.0',
  surfaceId: 'managed-companyos',
  title: 'Managed CompanyOS shell',
  regions: [{ id: 'nav', kind: 'sidebar', label: 'Navigation', componentRef: 'shell.nav' }],
  navigation: [{ id: 'cockpit', kind: 'route', label: 'Cockpit', href: '/companyos/cockpit', regionRef: 'nav' }],
  layoutVariants: [{ id: 'sidebar', label: 'Sidebar', regionRefs: ['nav'] }],
  signals: [{ id: 'role', kind: 'role', label: 'Role', sourceRef: 'rolemorph.actor' }],
  invariants: [
    'rolemorph-first',
    'personalization-after-policy',
    'fail-closed-missing-rolemorph',
    'deny-hidden-actions',
    'workspace-intent-preserved',
    'explain-every-adaptation',
    'graph-router-owned-drilldown',
    'deterministic-output',
  ].map((kind) => ({ kind, required: true, description: `${kind} invariant` })),
});

defineAdaptiveShellResolution(shell, {
  specId: shell.id,
  surfaceId: shell.surfaceId,
  roleMorphResolutionRef: 'rolemorph.resolution.founder',
  workspaceIntentRef: 'workspace.intent.operating-cockpit',
  layoutVariantRef: 'sidebar',
  regions: [{ regionRef: 'nav', visible: true, componentRef: 'shell.nav' }],
  navigation: [{ navigationNodeRef: 'cockpit', visible: true, safetyLevel: 'safe' }],
  breadcrumbs: [],
  adaptations: [],
  explanations: [],
  invariants: shell.invariants.map((invariant) => ({
    kind: invariant.kind,
    status: 'passed',
    reason: 'Verified by resolver tests.',
    evidenceRefs: ['adaptive-shell.resolver.test'],
  })),
});

Generative Core Graph Artifacts

Generative Core graph artifacts are additive experimental public surfaces. Import them through subpath-scoped exports such as @lssm/lib.contracts-spec/graph-artifacts rather than broad root-barrel imports.

Use artifact contracts to describe:

  • contract graph nodes/edges and source provenance;
  • codebase graph nodes/edges for packages, files, imports, exports, docs, tests, and generated outputs;
  • contract-code links with confidence, reason codes, hashes, and missing-ref diagnostics;
  • generation plans, drift reports, repair proposals, and Connect evidence refs.

These contracts are runtime-neutral. Workspace analyzers build them, bundle services persist/classify them, and CLI/CI/Builder surfaces consume the schema-versioned JSON. Apply/write workflows remain Connect-gated.

Typed Results

@lssm/lib.contracts-spec/results is the canonical success/failure surface for operations, workflows, jobs, API adapters, MCP tools, GraphQL resolvers, and React clients.

Handlers can keep returning raw output for ordinary OK results. Use contractOk, contractAccepted, contractQueued, contractNoContent, contractPartial, and contractFail when an operation needs explicit status, headers, retry metadata, warnings, partial problems, or typed error args.

import {
  contractAccepted,
  createContractError,
  defineResultCatalog,
  failure,
  standardErrors,
  standardSuccess,
  success,
} from "@lssm/lib.contracts-spec/results";

const results = defineResultCatalog({
  success: {
    ...standardSuccess.pick("OK", "CREATED"),
    QUEUED_FOR_REVIEW: success.queued<{ reviewId: string }>(),
  },
  errors: {
    ...standardErrors.pick("UNAUTHENTICATED", "FORBIDDEN"),
    INTENT_NOT_FOUND: failure.notFound<{ intentId: string }>({
      description: "The referenced intent does not exist.",
      gqlCode: "INTENT_NOT_FOUND",
    }),
  },
});

OperationSpecRegistry.executeResult(...) returns a ContractResult. Legacy execute(...) remains compatible: it unwraps success data and throws ContractSpecError on failure. Custom success and failure codes should be declared in spec.results or io.success/io.errors; undeclared custom failure codes normalize to INTERNAL_ERROR.

Adapter defaults:

  • REST/Fetch keeps raw success bodies by default and emits failures as application/problem+json; set resultEnvelope: true for { ok, data } success envelopes.
  • Next.js can use the injected NextResponse.json(...) helper from the REST runtime.
  • NestJS support is exposed as duck-typed exception filter/interceptor helpers without adding @nestjs/common as a hard dependency.
  • GraphQL keeps field success payloads unchanged by default; enable resultExtensions to collect success metadata, while failures use extensions.contractspec.problem.
  • MCP tools return normal content for success and isError: true with a safe problem payload for failures.
  • React runtime helpers normalize REST, GraphQL, MCP, workflow, job, and legacy error shapes into a ContractResult.

Migration note: prefer ContractSpecError, createContractError, and contractFail over @lssm/lib.error/AppError. @lssm/lib.error is kept as a compatibility bridge.

Experimental graph artifact contracts

The generative-core graph artifact surface is exported through narrow experimental subpaths only; it is not re-exported from the root barrel. Use these versioned contracts for graph, generation-plan, and drift-report DTOs while the analyzer and orchestration layers evolve:

  • @lssm/lib.contracts-spec/graph-artifacts
  • @lssm/lib.contracts-spec/graph-artifacts/contracts
  • @lssm/lib.contracts-spec/graph-artifacts/codebase
  • @lssm/lib.contracts-spec/graph-artifacts/links
  • @lssm/lib.contracts-spec/graph-artifacts/generation
  • @lssm/lib.contracts-spec/graph-artifacts/drift

These schemas are additive and versioned with contractspec.graph-artifacts.v1 / 1.0.0; consumers should persist the schema and artifact versions with every generated artifact.

Validation And Authoring Entry Points

Recent authoring and setup flows use package-level validation APIs directly instead of relying on ad hoc template or registry assumptions.

Multi-design contracts

@lssm/lib.contracts-spec/design-packs exports the additive, serializable contract surface for versioned design packs, app and tenant selection policy, private drafts, immutable publications, certification receipts, and structured safe patches. resolveDesignSelection() is a pure resolver with deterministic fixed, private-user, tenant, app, declared-fallback, and ContractSpec Editorial precedence. Tenant policy can narrow an app catalog or custom-design permission, but cannot widen either boundary. Existing ThemeSpec and ContractSpecEditorialTheme exports remain the theme/token source of truth.

  • @lssm/lib.contracts-spec/app-config/validation
    • validateBlueprint
    • validateTenantConfig
    • validateResolvedConfig
    • assertBlueprintValid
    • assertTenantConfigValid
    • assertResolvedConfigValid
  • @lssm/lib.contracts-spec/features/validation
    • validateFeatureSpec
    • assertFeatureSpecValid
    • validateFeatureTargetsV2
  • @lssm/lib.contracts-spec/themes.validation
    • validateThemeSpec
    • assertThemeSpecValid

These entrypoints are the current public surface for workspace setup, CLI scaffolding, CI, and docs to verify app-config, feature, and theme authoring consistently.

Translation contracts and runtime i18n

@lssm/lib.contracts-spec/translations is the canonical translation contract surface. Keep stable bundle identity in TranslationSpec.meta.key, keep locale variants in TranslationSpec.locale, and use optional metadata such as defaultLocale, supportedLocales, fallbacks, direction, formatter, channels, audience, modality, safety, and rendering to describe runtime behavior without making a UI framework canonical. Managed CompanyOS catalogs can declare those metadata blocks at bundle or message granularity so UI IA, CommunicationOS, workflows, LLM prompts, voice scripts, agent responses, redaction, and degraded-copy paths remain contract-authored.

Production translation resolution lives in @lssm/lib.translation-runtime. That package consumes TranslationSpec[] and provides locale negotiation, BCP 47 canonicalization, fallback chains, override layers, diagnostics, async catalog loading, compiled-message caching, and SSR snapshot serialization. Its default formatter is backed by FormatJS/intl-messageformat behind a small MessageFormatter abstraction so ContractSpec does not implement a custom ICU parser and can adopt MessageFormat 2 later.

import { defineTranslation } from "@lssm/lib.contracts-spec/translations";
import { createTranslationRuntime } from "@lssm/lib.translation-runtime";

const messages = defineTranslation({
  meta: {
    key: "commerce.cart.messages",
    version: "1.0.0",
    domain: "commerce",
    owners: ["platform"],
  },
  locale: "en-US",
  defaultLocale: "en-US",
  supportedLocales: ["en-US", "ar-EG", "zh-Hans"],
  channels: ["ui", "agent"],
  audience: { roles: ["operator"], tiers: ["managed"] },
  modality: { primary: "text", supported: ["voice"] },
  safety: {
    classification: "internal",
    containsSensitiveData: true,
    redaction: "mask",
    degradedFallbackKey: "cart.items.degraded",
  },
  rendering: { surface: "web", target: "cart.summary", richText: "plain" },
  messages: {
    "cart.items": {
      value: "{count, plural, =0 {No items} one {One item} other {{count} items}}",
      placeholders: [{ name: "count", type: "plural" }],
      channels: ["ui"],
      rendering: { target: "cart.summary.count" },
    },
    "cart.items.degraded": {
      value: "Cart summary unavailable.",
      safety: { classification: "public", redaction: "none" },
    },
  },
});

const runtime = createTranslationRuntime({
  defaultLocale: "en-US",
  requestedLocales: ["en-US"],
  specs: [messages],
});

runtime.tUnknown("cart.items", { count: 3 }); // "3 items"

Static translation diagnostics

Static catalog diagnostics are exported from @lssm/lib.contracts-spec/translations/diagnostics for CI tools and downstream consumers that need reusable checks without depending on the CLI shell.

import { analyzeTranslationCatalogGroups } from "@lssm/lib.contracts-spec/translations/diagnostics";

const report = analyzeTranslationCatalogGroups([
  {
    packagePath: "packages/libs/example",
    catalogDir: "packages/libs/example/src/i18n/catalogs",
    catalogs: [enMessages, frMessages, esMessages],
    baseLocale: "en",
    expectedLocales: ["en", "fr", "es"],
  },
]);

if (!report.ok) {
  console.error(report.issues);
}

The report shape is intentionally CI-friendly: { ok, summary, issues }. Issue codes include missing catalogs/keys, extra keys, blank values, invalid ICU messages, placeholder non-parity, invalid shapes, locale non-parity, duplicate bundle identities, unsupported_locale_claim (a catalog's supportedLocales declares a locale with no matching catalog in the group), and manifest_spec_key_missing (a manifest route entry references a specKey absent from the registered catalog set). Use validateManifestCatalogDrift(entries, knownSpecKeys) with a ManifestRouteEntry[] list to surface drift between route shard manifests and the registered catalog. The contractspec i18n check command is the CLI wrapper around this API, and .contractsrc.json can include an optional top-level i18n diagnostics block with catalogGlob, baseLocale, locales, allowExtraKeys, checkPlaceholders, checkIcu, and strict.

Migration notes

  • Prefer meta.key: "bundle.messages" plus locale: "fr-FR" over keys like bundle.messages.fr-FR.
  • Use channels, audience, modality, safety, and rendering metadata for Managed CompanyOS copy selection and policy-aware rendering; keep values descriptive and non-empty so validation can catch unsafe catalog gaps.
  • createI18nFactory now supports SSR snapshot/hydration directly via .snapshot() / .hydrationPayload() on the factory instance and createI18nFactoryFromHydrationPayload(payload) for client rehydration — prefer this over the deprecated createTranslationRuntime for new integrations.
  • resolveLocaleWithin(supportedLocales, defaultLocale, runtimeLocale?, optionsLocale?) is exported for callers that resolve locale outside a factory instance.
  • RouteShardManifest and defineRouteShardManifest live in the bundle/app layer (not contracts-spec) — the contract layer stays route-agnostic. Use validateManifestCatalogDrift to catch drift between manifests and registered catalogs.
  • i18next adapter support lives downstream at @lssm/lib.translation-runtime/i18next. It projects ContractSpec specs/snapshots to i18next resources and metadata manifests, but ContractSpec specs remain canonical.
  • Do not encode locale in i18next namespaces or stable translation keys. Use TranslationSpec.locale for the language and TranslationSpec.meta.key (or an explicit namespace strategy) for the namespace.
  • ICU messages are exported intact for i18next. Configure an ICU-capable i18next format plugin when using i18next to render ContractSpec ICU plural/select/selectordinal messages.
  • For SSR, use the factory-stack snapshot/hydration surface (createI18nFactory → .hydrationPayload() → createI18nFactoryFromHydrationPayload). The deprecated createTranslationRuntime engine is dead-but-present; its removal is a residual follow-up.
  • For React Native, the core runtime uses no DOM APIs; hosts are responsible for locale detection and any required Intl polyfills.
  • Optimization wave (Model A — per-request inline payload): O2+O3 reduce the per-request inline <script> hydration payload by ~61% (en: / 96.6 KB → 37.8 KB; /companyos/founder 93.9 KB → 35.6 KB; fr: ~−60%). Catalogs remain bundled+cached in the JS bundle — this is a per-request inline-HTML reduction, NOT total-transferred-bytes elimination. O4 (@lssm/lib.translation-runtime/precompile subpath) adds a build-time ICU AST precompile step and createIntlMessageFormatter fast-path for formatter-path latency; no payload size change; factory proof routes are unaffected (they use {placeholder} interpolation, no ICU). O5 (@lssm/tool.i18n-prune) is a CI audit tool for dead-key drift, not a payload driver. O5b intersection is wired and fail-safe but currently no-op. The ~90% total-bytes win requires Model B (catalog code-splitting); see .omc/plans/ralplan-translation-catalog-sharding-ssr.md § "Optimization Wave — ARCHITECTURE DECISION: Model A".

Agent Definitions

Agent declarations now live in @lssm/lib.contracts-spec/agent.

import { AgentRegistry, defineAgent } from "@lssm/lib.contracts-spec/agent";

const SupportBot = defineAgent({
  meta: {
    key: "support.bot",
    version: "1.0.0",
    description: "Customer support assistant",
    owners: ["support"],
    tags: ["support"],
    stability: "experimental",
  },
  instructions: "Resolve tickets and escalate low-confidence cases.",
  tools: [{ name: "support.resolve" }],
});

const registry = new AgentRegistry().register(SupportBot);

Runtime execution, exporters, MCP bridges, and provider adapters stay in @lssm/lib.ai-agent.

Workspace Config Notes

@lssm/lib.contracts-spec/workspace-config now includes first-class setup support for:

  • connect configuration
  • connect.adoption configuration for local catalog paths, workspace scan rules, family toggles, and verdict thresholds
  • builder configuration with runtimeMode: "managed" | "local" | "hybrid"
  • canonical Builder bootstrap presets:
    • managed_mvp
    • local_daemon_mvp
    • hybrid_mvp
  • Builder API fields:
    • builder.api.baseUrl
    • builder.api.controlPlaneTokenEnvVar
  • Builder local runtime fields:
    • builder.localRuntime.runtimeId
    • builder.localRuntime.grantedTo
    • builder.localRuntime.providerIds
  • Published typed entrypoints:
    • @lssm/lib.contracts-spec/workspace-config
    • @lssm/lib.contracts-spec/workspace-config/contractsrc-schema
    • @lssm/lib.contracts-spec/workspace-config/contractsrc-types

Those settings are consumed by the shared setup layer used by the CLI, VS Code extension, and JetBrains plugin.

Current Authoring Workflow

  • Use defineTheme(...) plus contractspec create theme for first-class theme scaffolding; keep tokens as the default/light-compatible bag and add modes.dark.tokens for dark-mode overlays.
  • Theme color tokens may carry format metadata such as oklch, with CSS color strings passed through to design-system bridges.
  • Route app-config, feature, and theme checks through the package-level validators above when building setup, editor, or CI automation.
  • Use connect.adoption and the broader authoring-target discovery flows when the CLI or editors should prefer existing workspace or ContractSpec surfaces before scaffolding new code.
  • Use knowledge.mutation.evaluateGovernance when provider-backed knowledge writes need a contracted dry-run, approval, idempotency, audit-evidence, or outbound-send decision surface before runtime mutation.
  • Use optional portable database metadata on DataView, FormSpec, PolicySpec, and KnowledgeSpace contracts to describe table/view/entity bindings, lookups, policy evidence, checkpoints, and provenance before wiring runtime adapters. These descriptors stay adapter-neutral; Drizzle/PostgreSQL imports belong in integration, app, tool, or server packages.
  • Use database.mutation.plan and database.mutation.execute descriptors only as governed, domain-command-owned write envelopes. A valid mutation envelope carries actor, tenant, domain command, policy decision, idempotency key, transaction boundary, expected write set, audit event refs, replay ref, and correlation ref before an integration adapter may execute it. @lssm/lib.contracts-spec defines the portable contract shape; @lssm/integration.provider-database/governed-mutation owns SQL/Drizzle execution.

Migration Note

If you previously imported agent-definition contracts from @lssm/lib.ai-agent/spec, migrate to:

  • @lssm/lib.contracts-spec/agent
  • @lssm/lib.contracts-spec/agent/spec
  • @lssm/lib.contracts-spec/agent/registry

Bundle requires alignment

When using @lssm/lib.surface-runtime, bundle specs declare required features via ModuleBundleSpec.requires (e.g. { key: 'ai-chat', version: '1.0.0' }). These entries should match FeatureModuleSpec.meta from defineFeature. Register features (e.g. AiChatFeature from @lssm/module.ai-chat) in a FeatureRegistry when validating bundle requirements. The bundle runtime can call registry.get(key) to verify each required feature exists before resolution.

Canonical self-contained examples by contract type

Use these example packages when you want one focused, importable reference per contract layer. knowledge and type are covered through the exported knowledge bindings/source configs and schema models. agent definitions now live directly in this package via @lssm/lib.contracts-spec/agent.