libraryPackage manifestv17.3.5

lib.contracts-spec

Spec definitions and registries for ContractSpec

@lssm-tech/lib.contracts-spec
Source, release and verification context

Source snapshot bcc79fcc · Declared package version 17.3.5. This page combines the checked-in package guide and manifest; commands and runtime behavior were not executed in this review.

Package source ↗ Manifest ↗
serverbun
EXPLORE THE PACKAGE

See where this package fits.

Follow a declared connection, inspect an import, then open the source guide when you need the detail.

THIS PACKAGElib.contracts-specplatform

Arrows point from a package to its direct dependency. Each count is derived from the captured manifests.

52 declarations · first 6 shownSELECT TO INSPECT

@lssm-tech/lib.contracts-spec

The PWA manifest registry and semantic-version helpers forward to @lssm-tech/lib.contracts-runtime-kernel/pwa/registry. PWA contract definitions forward to @lssm-tech/lib.progressive-delivery/pwa; legacy imports retain shared definition and registry identity.

The historical model selection and fallback validation v2 leaves forward to the published @lssm-tech/lib.ai-agent/protocol-runtime leaves. Their optional clock evaluation, validation order and exported identities remain unchanged. The removed @lssm-tech/lib.ai alias is no longer a workspace dependency.

Workflow validation and shared workflow/agent task validation now forward to the canonical WorkflowComposer validation leaves. Existing defaults, nominal registry options, error identity, and all validation checks are preserved.

The complete theme and design-pack families forward to @lssm-tech/lib.design-catalog/themes and ./design-packs with their exact leaves. Theme validation, nominal registry identities, Editorial defaults, portable tokens, selection policy, patch safety and inheritance retain their original implementations. The visual-scenarios/spec model also forwards to DesignCatalog's narrow visual-scenario-spec entry; the remaining visual-scenario runtime and platform leaves retain their existing owners.

The historical observability signal, evidence and database-signal entries forward to the same canonical @lssm-tech/lib.observability/signals family. Signal identifiers, evidence tenancy, cost envelopes, schemas, rejection messages and documentation remain unchanged.

./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 existing ./quality entry and source leaves forward to the canonical @lssm-tech/lib.assurance-spec/quality models and deterministic validators. Existing schema versions, digest material, DocBlocks and receipt authority checks remain unchanged. Runtime quality execution stays in execution-lanes.

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.

companyos.calendar-intelligence@2.3.0 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-tech/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-tech/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-tech/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-tech/lib.contracts-spec is the foundation of the split from @lssm-tech/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-tech/lib.contracts-spec/agent/protocol, plus provenance-aware context artifacts via @lssm-tech/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-tech/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-tech/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-tech/lib.contracts-spec/agentpacks.
  • Agentic interaction safety contracts via @lssm-tech/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-tech/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-tech/lib.contracts-spec/outcome-claims; no evidence means no valid claim.
  • Marketing page/site narrative contracts (MarketingSiteContract, MarketingPageContract, MarketingSectionContract) via @lssm-tech/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-tech/lib.contracts-spec/experience-coverage: stable module, feature, journey, evidence, platform, owner-scope, provider, blocker, and computed status semantics. contractspec.experience.coverage@1.0.0 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-tech/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-tech/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-tech/lib.contracts-spec/companyos: organization.list@1.0.0 and organization.set-active@1.0.0 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: personal-context.ensure@1.0.0, personal-context.disable@1.0.0, context.list@1.0.0, and context.set-active@1.0.0. 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 companyos.shellPreferences.get@2.0.0, companyos.shellPreferences.update@2.0.0, 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-tech/lib.contracts-spec/results.
  • Contract installation helpers (installOp, op, makeEmit).

Do not use this package for framework adapters:

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

Installation

Package builds start from the canonical src/index.ts root and the existing manifest compatibility exports. Module-closure emission retains every supported subpath, including declaration-backed aliases, while private helper discovery does not add public exports. Add new public paths deliberately to both source and publication export maps.

The existing production pack workflow owns the four browser-compatible Hook Authority surfaces and their isolated declarations. Source typechecking, packed-consumer verification, and required Connect/runtime approvals retain their respective scopes. Cohort qualification and remaining performance measurements are recorded in docs/refactoring/lssm-ecosystem/STATUS.md.

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

The package does not install the TypeScript compiler. Compiler-backed DocBlock manifest generation is owned by @lssm-tech/lib.typescript-runtime/docs-manifest-builder; import buildPackageDocManifest and extractModuleDocData from there.

The @lssm-tech/lib.contracts-spec/docs/manifest-builder subpath is deprecated. It forwards the same functions (same identities and asynchronous signatures) and is removed, together with the optional @lssm-tech/lib.typescript-runtime peer dependency, at the next major release of this package. Until then it still needs that optional peer, so install it yourself when you import the deprecated subpath:

bash
bun add @lssm-tech/lib.typescript-runtime
ts
// Before (deprecated)
import { buildPackageDocManifest } from "@lssm-tech/lib.contracts-spec/docs/manifest-builder";
// After
import { buildPackageDocManifest } from "@lssm-tech/lib.typescript-runtime/docs-manifest-builder";

Durable Queue V2 contracts

@lssm-tech/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-tech/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-tech/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-tech/lib.contracts-spec/companyos/organization-bootstrap
  • @lssm-tech/lib.contracts-spec/companyos/organization-seed
  • @lssm-tech/lib.contracts-spec/companyos/organization-seed-profile-manifest
  • @lssm-tech/lib.contracts-spec/companyos/queries/designPartnerReadinessGet.query
  • @lssm-tech/lib.contracts-spec/companyos/commands/decisionPacketAttest.command
  • @lssm-tech/lib.contracts-spec/companyos/commands/decisionPacketFounderApprove.command
  • @lssm-tech/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-tech/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.

companyIntelligence.surface.get@1.0.0 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-tech/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-tech/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-tech/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-tech/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-tech/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-tech/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-tech/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-tech/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.

ts
import { defineOutcomeClaim } from '@lssm-tech/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-tech/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-tech/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.

ts
import {
  validateAgentStepArtifact,
  type AgentStepArtifact,
} from '@lssm-tech/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-tech/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-tech/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.

ts
import {
  defineAdaptiveShellResolution,
  defineAdaptiveShellSpec,
} from '@lssm-tech/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-tech/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-tech/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.

ts
import {
  contractAccepted,
  createContractError,
  defineResultCatalog,
  failure,
  standardErrors,
  standardSuccess,
  success,
} from "@lssm-tech/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-tech/lib.error/AppError. @lssm-tech/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-tech/lib.contracts-spec/graph-artifacts
  • @lssm-tech/lib.contracts-spec/graph-artifacts/contracts
  • @lssm-tech/lib.contracts-spec/graph-artifacts/codebase
  • @lssm-tech/lib.contracts-spec/graph-artifacts/links
  • @lssm-tech/lib.contracts-spec/graph-artifacts/generation
  • @lssm-tech/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-tech/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-tech/lib.contracts-spec/app-config/validation
    • validateBlueprint
    • validateTenantConfig
    • validateResolvedConfig
    • assertBlueprintValid
    • assertTenantConfigValid
    • assertResolvedConfigValid
  • @lssm-tech/lib.contracts-spec/features/validation
    • validateFeatureSpec
    • assertFeatureSpecValid
    • validateFeatureTargetsV2
  • @lssm-tech/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-tech/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-tech/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.

ts
import { defineTranslation } from "@lssm-tech/lib.contracts-spec/translations";
import { createIntlMessageFormatter } from "@lssm-tech/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 formatter = createIntlMessageFormatter();
const cartItems = formatter.compile({
  id: "cart.items",
  locale: messages.locale,
  message: messages.messages["cart.items"].value,
});

cartItems.format({ count: 3 }); // "3 items"

Static translation diagnostics

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

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

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

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

catalogDir is relative to packagePath: issue paths join the two, so a root-relative catalogDir would repeat the package path.

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 supports SSR snapshot/hydration directly via .snapshot() / .hydrationPayload() on the factory instance and createI18nFactoryFromHydrationPayload(payload) for client rehydration.
  • 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-tech/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).
  • 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-tech/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-tech/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-tech/lib.contracts-spec/agent.

ts
import { AgentRegistry, defineAgent } from "@lssm-tech/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-tech/lib.ai-agent.

Workspace Config Notes

@lssm-tech/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-tech/lib.contracts-spec/workspace-config
    • @lssm-tech/lib.contracts-spec/workspace-config/contractsrc-schema
    • @lssm-tech/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-tech/lib.contracts-spec defines the portable contract shape; @lssm-tech/integration.provider-database/governed-mutation owns SQL/Drizzle execution.

Migration Note

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

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

Bundle requires alignment

When using @lssm-tech/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-tech/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-tech/lib.contracts-spec/agent.

  • operation, feature, example, type: @lssm-tech/example.minimal†
  • event, presentation, capability, test-spec: @lssm-tech/example.workflow-system†
  • data-view: @lssm-tech/example.data-grid-showcase†
  • visualization: @lssm-tech/example.visualization-showcase†
  • agent: @lssm-tech/example.agent-console†
  • harness-scenario, harness-suite: focused reference @lssm-tech/example.harness-lab† covering sandbox, Playwright, agent-browser, auth refs, and visual evidence; product/business proof @lssm-tech/example.agent-console†
  • knowledge, knowledge-space, lightweight app-config: @lssm-tech/example.knowledge-canon†
  • integration, workflow, integration-oriented app-config: @lssm-tech/example.integration-stripe†
  • policy, form, translation: @lssm-tech/example.locale-jurisdiction-gate†
  • product-intent: @lssm-tech/example.product-intent†
  • experiment, theme: @lssm-tech/example.personalization†
  • job: @lssm-tech/example.openbanking-powens†
  • migration: @lssm-tech/example.versioned-knowledge-base†
  • telemetry: @lssm-tech/example.pocket-family-office†

Data table contract example

The canonical data-table example lives in @lssm-tech/example.data-grid-showcase† and starts with a declarative DataViewSpec in this package:

DataView filters now distinguish user-editable filters from scoped constraints. Use view.filterScope.initial to seed removable filters and view.filterScope.locked for constraints that always apply but are not serialized into URL state. Locked filters render as disabled chips by default so embedded views, such as a category-scoped posts list, stay explainable while reusing the same base DataView contract.

DataView source.database can declare a portable read binding with a source key, table/view/entity ref, field-to-column mapping, pagination, policy refs, and provenance. DataViewQueryGenerator preserves the existing operation input and also emits an optional database.query.readonly descriptor for provider adapters; it does not emit SQL or import database runtimes.

Table fields and columns can declare overflow as truncate, wrap, expand, hideColumn, or none. Column overflow overrides field overflow, and unspecified values use type-aware defaults: markdown wraps, while text, badges, numbers, currency, percentages, dates, times, durations, and booleans truncate. expand keeps the compact cell but adds the field to row expansion; hideColumn starts the column hidden when column visibility is enabled.

Collection data views (list, grid, and table) can now share production listing defaults under view.collection. Use collection.viewModes to declare which modes a renderer may project between, collection.pagination.pageSize to seed query generation, collection.toolbar to describe search/filter/view-mode controls, collection.density for cross-mode spacing defaults, and collection.dataDepth for summary/standard/detailed/exhaustive field projection. Fields can declare visibility.minDataDepth so richer fields are available to detailed experiences without forking the base spec. The authored view.kind remains the canonical shape; renderers derive alternate collection projections without mutating the source spec. Table density remains supported as a permanent compatibility alias.

ts
import { defineDataView } from '@lssm-tech/lib.contracts-spec/data-views';
import { ListDataGridShowcaseRowsQuery } from '@lssm-tech/example.data-grid-showcase/contracts/data-grid-showcase.operation';

export const DataGridShowcaseDataView = defineDataView({
  meta: {
    key: 'examples.data-grid-showcase.table',
    version: '1.0.0',
    entity: 'account',
    title: 'Data Grid Showcase Table',
    description:
      'Declarative DataViewSpec for the ContractSpec table showcase.',
    domain: 'examples',
    owners: ['@platform.core'],
    tags: ['examples', 'table', 'data-grid'],
    stability: 'experimental',
  },
  source: {
    primary: {
      key: ListDataGridShowcaseRowsQuery.meta.key,
      version: ListDataGridShowcaseRowsQuery.meta.version,
    },
  },
  view: {
    kind: 'table',
    collection: {
      viewModes: {
        defaultMode: 'table',
        allowedModes: ['list', 'grid', 'table'],
      },
      pagination: { pageSize: 20 },
      toolbar: {
        search: true,
        viewMode: true,
        filters: true,
        density: true,
        dataDepth: true,
      },
      density: 'comfortable',
      dataDepth: 'standard',
      personalization: {
        enabled: true,
        persist: {
          viewMode: true,
          density: true,
          dataDepth: true,
        },
      },
    },
    executionMode: 'client',
    selection: 'multiple',
    columnVisibility: true,
    columnResizing: true,
    columnPinning: true,
    rowExpansion: {
      fields: ['notes', 'renewalDate', 'lastActivityAt'],
    },
    initialState: {
      pageSize: 4,
      hiddenColumns: ['notes'],
      pinnedColumns: {
        left: ['account'],
      },
      sorting: [{ field: 'arr', desc: true }],
    },
    fields: [
      { key: 'account', label: 'Account', dataPath: 'account', sortable: true },
      { key: 'owner', label: 'Owner', dataPath: 'owner', sortable: true },
      { key: 'status', label: 'Status', dataPath: 'status', sortable: true },
      { key: 'notes', label: 'Notes', dataPath: 'notes', overflow: 'expand' },
    ],
    columns: [
      { field: 'account' },
      { field: 'owner' },
      { field: 'status', overflow: 'truncate' },
      { field: 'notes', overflow: 'hideColumn' },
    ],
  },
});

See the live example in /docs/examples/data-grid-showcase and the browser sandbox in /sandbox?template=data-grid-showcase.

OSINT v0 contracts

@lssm-tech/lib.contracts-spec/osint is the provider-neutral contract surface for evidence-first company, job, and person intelligence. It defines additive operations and events for datasets, programs, grants, source discovery, qualification, explicit activation, ingestion, revalidation, entity retrieval, research, evidence, graph traversal, export, correction, curation, subscriptions, and replay.

Sources use an explicit lifecycle: discovered → qualified → active, with independent revalidating, degraded, quarantined, and retired states. Discovery never grants ingestion authority. Every fact is a bitemporal assertion with at least one immutable source snapshot and locator. Requests carry tenant, dataset, deployment, jurisdiction, and purpose scope.

osint.source.activate, osint.source.qualify.governed, osint.source.revalidate.governed, osint.source.quarantine, and osint.source.retire bind the authenticated actor, overlay_write grant, scope, purpose, source revision, policy decision, contract fingerprint, evidence, and canonical request digest. The original generic qualify/revalidate V1 contracts remain available for compatibility and are not the durable-worker contract. Lifecycle receipts bind the exact claim key, owner, and monotonic attempt used by the canonical transition so expired workers can be fenced and replayed exactly.

Rights submission, get/list, verification, decision, and completion operations are projected through the same REST, SDK, MCP, and CLI registry. Submission is effect-free. Verification and decisions require evidence and an expected revision; suppression and deletion work begin only after the separately authorized decision operation.

Use @lssm-tech/lib.osint-spec for executable Zod validation. OSINT extends the existing knowledge, workflow, agent, policy, and Company Intelligence capabilities; it does not create competing kernels. V0 may emit sanitized observations and evaluation evidence, but cannot generate/apply patches, deploy itself, bypass access controls, or automate hiring decisions.

The additive ./osint/job-sources surface defines the 17 named France and ATS source descriptors, installation records, acquisition plans, observations, revalidation results, and seven-cell connector qualification vocabulary. Its operation map reuses the governed OSINT lifecycle; it does not create a second source state machine. La Bonne Alternance and Indeed France remain permission-bound until an applicable live authorization receipt exists. JobSourceLiveQualificationReceiptV1 binds an exact release SHA and complete OSINT scope to the installation, policy authorization, capability, request and response digests, immutable evidence, and observation window. Deterministic fixtures never satisfy this receipt.

Governed operational recovery adds dead-letter list and exact-attempt replay, durable webhook delivery status and replay, and separate job-listing revalidation and closure reconciliation operations. Each mutation binds the complete deployment scope, idempotency key, expected revision and attempt, authority, policy and contract fingerprints, and authorized evidence. Closure reconciliation never treats a failed crawl as proof that a listing closed.

Candidate job application V1

@lssm-tech/lib.contracts-spec/job-application is the privacy-isolated candidate-side contract boundary. It defines immutable mandates, encrypted profile and verified-answer references, form snapshots, field proposals, external account bindings, opaque Resend inbox aliases, verification challenges, authorization receipts, and fenced effect receipts. Its 25 operations and 13 events project through REST, SDK, MCP, CLI, signed webhook, SSE, and WebSocket delivery metadata.

Every mutation requires candidate scope, an expected revision, idempotency key, authorization receipt, contract fingerprint, trace, and evidence references. Unknown material questions and CAPTCHA, MFA, device-attestation, or other access challenges fail closed to candidate or authorized-operator takeover. Credentials, cookies, codes, links, and candidate values remain opaque references and never enter OSINT, prompts, logs, analytics, or portable contracts.

Governed self-improving system V1

@lssm-tech/lib.contracts-spec/self-improving-system adds the reusable contract boundary that turns sanitized AI-improvement V2 signals into goal-, budget-, policy-, gate-, observation-, rollback-, and replay-bound programs and candidates. It composes existing Builder, Connect, LSSM plan, and Runtime Node V2 authorities by immutable reference; it does not introduce another authorization or work-order kernel.

Runtime artifacts can become eligible for explicitly delegated qualified automation. Repository work items, contracts, schemas, RLS, retention, legal policy, restricted fields, credentials, networks, provider qualification, code, and infrastructure stay approval-bound. Repository work items never self-apply, and every execution envelope binds exactly one existing execution authority: a signed runtime work order or a Builder patch receipt.

Full contract inventory (explicit map)

The package currently exposes 1,687 total exports in package.json, including the root . barrel and 1,686 subpath exports. Almost every subpath forwards to a canonical owner package; see AGENTS.md for the owner map.

1) Registry-level contract types (semantic model)

CONTRACT_SPEC_TYPES (owned by @lssm-tech/lib.contracts-spec-core, re-exported from @lssm-tech/lib.contracts-spec) currently has 32 values:

  • agent
  • app-config
  • capability
  • data-view
  • design-pack
  • edge
  • entity
  • event
  • example
  • experiment
  • feature
  • form
  • harness-scenario
  • harness-suite
  • integration
  • job
  • knowledge
  • knowledge-space
  • migration
  • operation
  • policy
  • presentation
  • product-intent
  • pwa-app
  • telemetry
  • test-spec
  • theme
  • translation
  • type
  • visual-scenario
  • visualization
  • workflow

2) Export artifact kinds (suffix-based, subpaths only)

These are the contract artifact kinds visible in package export names. .d subpaths forward legacy declaration modules; everything else is counted as plain.

  • .capability: 19
  • .feature: 17
  • .command: 127
  • .event: 31
  • .query: 76
  • .form: 6
  • .presentation: 6
  • .dataView: 11
  • .contracts: 13
  • .d (declaration): 356
  • plain: 1024

3) Category -> kinds matrix

  • acp: capability(1), feature(1), command(7), plain(5)
  • adaptive-shell: plain(3)
  • adoption-catalog: plain(1)
  • agent: capability(1), feature(1), command(9), event(4), query(2), form(1), presentation(1), dataView(1), plain(54)
  • agent-platform: plain(6)
  • agent-step-observability: plain(3)
  • agentic-interaction: plain(3)
  • agentpacks: plain(10)
  • ai-improvement: plain(7)
  • analytics: plain(2)
  • app-config: capability(1), feature(1), contracts(1), declaration(5), plain(9)
  • app-submission-readiness: contracts(12), plain(11)
  • capabilities: declaration(8), plain(8)
  • cli: plain(2)
  • companyos: command(26), query(29), plain(35)
  • content-analysis: plain(6)
  • content-generation: feature(1), plain(9)
  • context: capability(1), feature(1), command(1), event(1), query(2), form(1), presentation(1), dataView(1), plain(12)
  • contract-registry: plain(3)
  • contracts-spec.feature: feature(1)
  • control-plane: capability(5), feature(1), command(15), event(10), query(8), plain(28)
  • creative-intelligence: plain(6)
  • creator-operations: plain(16)
  • customer-support: feature(1), plain(225)
  • data-views: declaration(16), plain(20)
  • database: capability(1), feature(1), command(2), query(5), dataView(1), plain(15)
  • decisioning: feature(1), declaration(27), plain(26)
  • delivery: declaration(1), plain(1)
  • design-packs: declaration(15), plain(15)
  • docs: capability(1), feature(1), command(2), event(2), query(2), form(1), presentation(2), dataView(3), declaration(29), plain(15)
  • editions: plain(31)
  • entities: declaration(4), plain(6)
  • events: declaration(1), plain(1)
  • examples: plain(6)
  • experience-coverage: plain(4)
  • experiments: declaration(2), plain(3)
  • feature-hubs: plain(11)
  • features: declaration(6), plain(6)
  • forms: form(1), declaration(24), plain(24)
  • graph-artifacts: plain(7)
  • harness: capability(4), feature(1), command(3), event(8), query(5), presentation(1), dataView(3), plain(11)
  • install: declaration(1), plain(1)
  • job-application: plain(9)
  • jobs: declaration(2), plain(5)
  • jsonschema: plain(1)
  • knowledge: capability(1), feature(1), declaration(4), plain(14)
  • llm: plain(4)
  • markdown: plain(1)
  • marketing: plain(5)
  • migrations: plain(1)
  • model-registry: plain(1)
  • navigation: plain(4)
  • notifications: capability(1), feature(1), plain(2)
  • observability: plain(4)
  • onboarding-base: plain(1)
  • ontology: plain(12)
  • openapi: plain(1)
  • operations: command(59), query(19), declaration(104), plain(35)
  • osint: plain(24)
  • outcome-claims: plain(4)
  • ownership: declaration(1), plain(1)
  • policy: declaration(3), plain(9)
  • presentations: declaration(4), plain(4)
  • product-intent: plain(16)
  • prompt: plain(1)
  • promptRegistry: plain(1)
  • provider-ranking: capability(1), feature(1), command(3), event(3), query(3), form(2), presentation(1), dataView(2), plain(10)
  • pwa: capability(1), feature(1), event(3), query(1), plain(8)
  • quality: plain(1)
  • query: declaration(10), plain(10)
  • regenerator: plain(7)
  • registry: declaration(1), plain(1)
  • registry-utils: declaration(1), plain(1)
  • release: plain(1)
  • resources: declaration(1), plain(1)
  • results: declaration(12), plain(12)
  • rich-content: plain(5)
  • rich-reference: declaration(26), plain(33)
  • runtime-adapters: declaration(1), plain(1)
  • schema-to-markdown: plain(1)
  • self-improving-system: plain(8)
  • serialization: plain(3)
  • shared: declaration(5), plain(6)
  • shared-entities: declaration(1), plain(7)
  • sop: feature(1), plain(5)
  • structured-data: declaration(4), plain(5)
  • telemetry: declaration(8), plain(5)
  • tests: declaration(1), plain(3)
  • themes: declaration(1), plain(1)
  • themes.platform-validation: declaration(1), plain(1)
  • themes.validation: declaration(1), plain(1)
  • translations: declaration(10), plain(10)
  • types: declaration(1), plain(1)
  • utils: plain(1)
  • versioning: declaration(7), plain(7)
  • visual-scenarios: declaration(2), plain(6)
  • visualizations: declaration(3), plain(4)
  • workflow: declaration(2), plain(16)
  • workspace-config: plain(15)

4) DocBlock coverage map (for AI context retrieval)

DocBlocks are authored as same-file exports in their canonical owner modules and loaded through generated manifests, not standalone *.docblock package exports.

The entity-bound forms guidance is available as a package subpath, @lssm-tech/lib.contracts-spec/forms/entity-bound, and as a generated DocBlock route at /docs/tech/contracts/forms/entity-bound.

End-to-end quick start

1) Define schema models and specs

ts
import { SchemaModel, ScalarTypeEnum } from "@lssm-tech/lib.schema";
import {
  defineCommand,
  defineEvent,
  defineQuery,
} from "@lssm-tech/lib.contracts-spec";

const WorkspaceInput = new SchemaModel({
  name: "WorkspaceInput",
  fields: {
    workspaceId: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
  },
});

const WorkspaceOutput = new SchemaModel({
  name: "WorkspaceOutput",
  fields: {
    workspaceId: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
    name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
  },
});

const WorkspaceCreatedPayload = new SchemaModel({
  name: "WorkspaceCreatedPayload",
  fields: {
    workspaceId: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
  },
});

export const WorkspaceCreated = defineEvent({
  meta: {
    key: "workspace.created",
    version: "1.0.0",
    title: "Workspace created",
    description: "Emitted after a workspace is created.",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["workspace", "event"],
  },
  payload: WorkspaceCreatedPayload,
});

export const GetWorkspace = defineQuery({
  meta: {
    key: "workspace.get",
    version: "1.0.0",
    title: "Get workspace",
    description: "Returns workspace metadata for the current tenant.",
    goal: "Expose read-only workspace state to the UI.",
    context: "Used by dashboard bootstrap.",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["workspace", "query"],
  },
  io: { input: WorkspaceInput, output: WorkspaceOutput },
  policy: { auth: "user" },
});

Operations can also declare stronger policy requirements without replacing the legacy `auth`, `flags`, or `pii` fields:

```ts
export const ReadInvoice = defineQuery({
  // ...meta and io...
  policy: {
    auth: "user",
    permissions: { any: ["invoice.read"] },
    roles: { any: ["billing.viewer", "billing.admin"] },
    fieldPolicies: [
      { field: "internalNotes", actions: ["read"], permissions: ["invoice.notes.read"] },
    ],
  },
});

OperationSpecRegistry.execute() normalizes those requirements and passes them to ctx.decide with subject, resource, tenant/workspace, policy refs, and field-policy context before the handler runs. UI surfaces may reuse the same requirement shape for adaptation, but authoritative enforcement belongs in the runtime decider or server-side RBAC engine.

export const CreateWorkspace = defineCommand({ meta: { key: "workspace.create", version: "1.0.0", title: "Create workspace", description: "Creates a new workspace.", goal: "Provision a workspace for a tenant.", context: "Triggered by onboarding flows.", stability: "stable", owners: ["platform.core"], tags: ["workspace", "command"], }, io: { input: WorkspaceInput, output: WorkspaceOutput }, policy: { auth: "admin" }, sideEffects: { emits: [{ ref: WorkspaceCreated.meta, when: "after_create" }] as const, }, });

code

### 2) Register specs and bind handlers

```ts
import {
  EventRegistry,
  installOp,
  makeEmit,
  OperationSpecRegistry,
} from "@lssm-tech/lib.contracts-spec";
import {
  CreateWorkspace,
  GetWorkspace,
  WorkspaceCreated,
} from "./workspace.spec";

export const events = new EventRegistry().register(WorkspaceCreated);
export const operations = new OperationSpecRegistry();

installOp(operations, GetWorkspace, async (input) => ({
  workspaceId: input.workspaceId,
  name: "Acme Workspace",
}));

installOp(operations, CreateWorkspace, async (input, ctx) => {
  const result = {
    workspaceId: input.workspaceId,
    name: "Acme Workspace",
  };

  const emit = makeEmit(CreateWorkspace, ctx);
  await emit.ref(WorkspaceCreated, { workspaceId: input.workspaceId });
  return result;
});

3) Execute from runtime context

ts
import type { HandlerCtx } from "@lssm-tech/lib.contracts-spec";
import { operations, events } from "./registry";

const ctx: HandlerCtx = {
  actor: "admin",
  channel: "web",
  eventSpecResolver: events,
  eventPublisher: async (envelope) => {
    console.log("published", envelope.key, envelope.version);
  },
};

const output = await operations.execute(
  "workspace.create",
  "1.0.0",
  { workspaceId: "wk_123" },
  ctx
);

console.log(output);

Execution behavior (why this is AI-friendly)

OperationSpecRegistry.execute(...) runs predictable steps:

  1. Resolve spec/version.
  2. Parse input.
  3. Apply policy hooks when provided (ctx.decide, ctx.rateLimit).
  4. Guard event emission against declared side effects.
  5. Execute handler.
  6. Parse output when output is a schema model.
  7. Emit telemetry when configured.

This deterministic contract -> runtime flow is a strong base for code generation and AI-driven refactors.

AI assistant guidance

When writing code:

  • Start here when asked to "add a new operation/event/form/resource contract".
  • Keep meta.key stable and increment versions for behavior changes.
  • Define spec first, then bind handler, then expose transport.

When reading code:

  • Treat <meta.key, meta.version> as the canonical identity.
  • Expect one operation contract to project into multiple transports.

Split migration from deprecated monolith

  • @lssm-tech/lib.contracts -> @lssm-tech/lib.contracts-spec
  • @lssm-tech/lib.contracts/operations/* -> @lssm-tech/lib.contracts-spec/operations/*
  • @lssm-tech/lib.contracts/events -> @lssm-tech/lib.contracts-spec/events
  • @lssm-tech/lib.contracts/resources -> @lssm-tech/lib.contracts-spec/resources
  • @lssm-tech/lib.contracts/forms/* -> @lssm-tech/lib.contracts-spec/forms/*

Runtime packages moved out:

  • REST runtime -> @lssm-tech/lib.contracts-runtime-server-rest
  • GraphQL runtime -> @lssm-tech/lib.contracts-runtime-server-graphql
  • MCP runtime -> @lssm-tech/lib.contracts-runtime-server-mcp
  • React runtime -> @lssm-tech/lib.contracts-runtime-client-react
  • Integration contracts -> @lssm-tech/lib.contracts-integrations

PWA Update Contracts

Use @lssm-tech/lib.contracts-spec/pwa to declare app-level PWA update policy and the pwa.update.check query. defaultUpdatePolicy sets the application behavior, while each release can override it for required/blocking updates or heavily offline-compatible optional updates.

The contract standardizes update decisions and prompt telemetry; host apps still own service worker registration and activation.

Monorepo environment configuration

Use @lssm-tech/lib.contracts-spec/workspace-config/environment to declare logical environment variables for monorepos before framework-specific materialization.

  • EnvironmentVariableDefinition separates logical keys, sensitivity, lifecycle, allowed surfaces, defaults, value sources, and aliases.
  • AppEnvironmentTarget maps a logical app/package target to a framework such as Next, Expo, Node, or worker runtimes.
  • EnvVariableAlias maps one logical variable to concrete names such as NEXT_PUBLIC_API_URL or EXPO_PUBLIC_API_URL.
  • Validation rejects secret/sensitive variables exposed through public client aliases or Next config bundle env.

Raw secrets still belong behind secret references and providers, never in .contractsrc.json.

Ontology-led Company Work Graph

@lssm-tech/lib.contracts-spec/ontology is the canonical semantic graph surface for CompanyOS work, surfaces, resources, actors, adaptation, and safety evidence. It is intentionally the semantic spine for graph authoring; existing entity, DataView graph, CompanyOS, control-plane, policy, AI-improvement, RoleMorph, and personalization contracts should project to or from ontology refs instead of defining competing taxonomies.

The Autonomous Work Order proof slice uses six node domains:

  • actor — human, agent, team, customer, role, permission, and authority-scope nodes.
  • work — goals, orders, workflows, commands, queries, mutations, decisions, blockers, and outcomes.
  • resource — specs, documents, records, files, pages, memories, evidence, and external resources.
  • surface — apps, pages, navigation, menus, panels, DataViews, actions, routes, and feature surfaces.
  • adaptation — preferences, behavior signals, RoleMorph decisions, adaptive hints, analytics signals, and explanations.
  • safety — policy decisions, approvals, rejections, audit receipts, redaction, replay, risk, and consent.

High-impact orders and mutates edges are fail-closed by contract: a committed transition must include a policy decision ref, authority scope ref, actor ref, approval-or-refusal ref, audit receipt ref, redaction status, replay-or-evidence ref, risk tier, and timestamp. Low-risk query/render/adaptation edges may be policy-optional, but they still need to remain audit/evidence-addressable when emitted into the Autonomous Work Order slice.

Migration note: the ontology release is a breaking semantic alignment. Prefer @lssm-tech/lib.contracts-spec/ontology and ontology-aware projections for new graph work. Treat older unconstrained CompanyOS graph type strings, DataView graph mutation refs without safety requirements, and local RoleMorph/personalization taxonomies as migration targets rather than new authoring patterns.

Experimental graph artifacts

@lssm-tech/lib.contracts-spec exposes additive, versioned graph artifact contracts through narrow subpaths:

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

These schemas are experimental public additions for read-only graph inspection, generation planning, drift reporting, and future Connect-gated repair workflows. They default to path-only provenance and preview-first generation plans; apply/repair flows must remain gated by Connect policy.

AI Improvement Envelope

AI-improvement declarations are canonical in @lssm-tech/lib.orchestration-spec/ai-improvement. The existing imports below remain compatibility forwards to the same types, version constants and V2 DocBlock. Policy helpers, evidence helpers and validation remain here.

@lssm-tech/lib.contracts-spec/ai-improvement provides the neutral evidence, policy, replay, risk, and kill-switch envelope for AI self-improvement workflows. Pioneer and future vendors must adapt to this surface rather than owning core domain types.

The additive V2 surface adds sanitized operational signals, explicit observation plans/results, deterministic automation-risk decisions, patch-run receipts, and an observing work-order stage. Existing V1 types and runtime behavior remain unchanged. Import the contracts from @lssm-tech/lib.contracts-spec/ai-improvement/contracts-v2 and their strict Zod schemas from @lssm-tech/lib.contracts-spec/ai-improvement/validation-v2.

Rich code and diff content

@lssm-tech/lib.contracts-spec/rich-content defines the portable model used by governed CodeBlock and DiffBlock surfaces. It represents rich text segments, references, sensitivity, visibility, explanations, action boundaries, code lines, and diff hunks without depending on a renderer.

Use redactRichCodeBlock and redactRichDiffBlock on the server before serializing payloads to clients. Redaction replaces denied segment text, strips reference values/hrefs, and preserves safe labels/explanations so UI surfaces can explain what was hidden without leaking the original value.

RichReference (canonical reference surface)

@lssm-tech/lib.contracts-spec/rich-reference is the canonical transport for governed, kind-typed references rendered across REST, GraphQL, MCP, and agent surfaces.

  • defineReferenceKind({ id, schema, sensitiveFields, defaultPreview, defaultPanel, icon, parser? }) registers one kind. sensitiveFields is Required at the type level (Required<…>) and at runtime — a missing or non-array value throws. Kinds with no sensitive fields must pass an explicit [] with the // confirmed: no sensitive fields comment (enforced by @lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields).
  • ReferenceKindRegistry (registerKind / getKind / listKinds) is process-global with zero side-effects on import; apps opt in via registerBuiltInReferenceKinds() from ./rich-reference/kinds.
  • DenialToken is a TypeScript-branded string (not a Symbol — Symbols don't survive JSON). Wire form: redacted:{kindId}:{hex(hmacSha256(message=kindId, key=salt))}. Mint and verify through createDenialTokenSigner(createSessionSalt()); the per-resolve-request salt prevents forgery via markdown re-ingestion (invalid signatures fail closed via verify() returning undefined).
  • Four governance ports live under ./rich-reference/ports: SubjectProvider (implemented by authos-runtime, fail-closed on missing subject), CoarsePreferencesProvider (implemented by personalization, tenant-scoped cache key), KindPolicyProvider (implemented by surface-runtime's RoleMorph adapter), and AuditSink (payload-free audit records). DurableAuditSink extends the final port with bounded claim, acknowledgement, retry/dead-letter, recovery, and health contracts for governed production decisions; a successful record() means the minimized decision was durably accepted before authority proceeds.
  • applyKindRedaction(kind, instance, decision, signer) walks the kind's sensitiveFields at read-time (not detector-time) so schema-evolution events honor new sensitive fields on the next read.
  • Six built-in kinds ship out of the box: database-record, object, link, file, media, code-symbol.

The runtime (./rich-reference/runtime — added by S-2) enforces post-handler redaction so handlers cannot ship a RichReference whose payload contains undeclared fields or unredacted sensitive fields.

AI-agent surface (S-9)

  • ./rich-reference/agent-export — toAgentJson(ref, prefs?) is a strict passthrough of the canonical serializer (body === canonicalJsonString(serializeRichReference(ref))). Preferences only affect envelope meta (request id, redaction-state summary, issued-at); they never reshape the wire body. There is exactly one serialization pipeline (P-3).
  • ./rich-reference/markdown-envelope — symmetric markdown round-trip. toMarkdown(block, prefs?) renders reference segments as [label](rich-ref:{kindId}/{refId}); denied refs render as [redacted:{kindId}]({hmac-wire-form}). fromMarkdown(md, ctx) re-validates every redacted: token via DenialTokenSigner.verify and FAILS CLOSED on forged HMAC (the link is dropped and replaced with an [invalid-redaction] marker; the function never auto-unredacts). The detector is re-applied to text regions so freshly pasted ref-like patterns become annotations again on read. defaultCopyMarkdownHandler is the wire used by <RichBlock onCopyMarkdown> in ui-kit-web / ui-kit.

Graph & Timeline Primitives

@lssm-tech/lib.contracts-spec ships the spec layer for graph and timeline data views as part of the graph-timeline-primitives milestone.

Data view spec authoring

Three new DataViewKind values — "graph", "timeline", "timeline-graph" — extend the existing spec system. defineDataView accepts a DataViewGraphSpec (sibling type to DataViewSpec) via overload. Source variants:

  • "inline-op" — single operation returns { nodes, edges }
  • "two-op" — separate node and edge operations
  • "entity-declarative" — driven by EntityRegistry (C12: must be loaded before renderer)

Entity contract authoring (Layer 1 and Layer 2)

defineContractEntity supports two authoring layers:

Layer 1 — declare an entity key and version without a schema:

ts
import { defineContractEntity } from "@lssm-tech/lib.contracts-spec";

const UserEntity = defineContractEntity({
  meta: { key: "user", version: "1.0.0", description: "User entity", owners: ["team-auth"] },
});

Layer 2 — pair with defineEntity from @lssm-tech/lib.schema to add typed fields:

ts
import { defineContractEntity } from "@lssm-tech/lib.contracts-spec";
import { defineEntity, field } from "@lssm-tech/lib.schema/entity/defineEntity";

const UserEntity = defineContractEntity({
  meta: { key: "user", version: "1.0.0", description: "User entity", owners: ["team-auth"] },
  entity: defineEntity({
    name: "User",
    fields: { id: field.id(), email: field.email(), name: field.string({ isOptional: true }) },
  }),
});

Use defineContractEdge to declare typed graph edges (from, to, relation, cardinality, directed). Load entities and edges into EntityRegistry before the renderer mounts.

See AGENTS.md for the full exported symbol list and import rules.

Translation diagnostics

@lssm-tech/lib.contracts-spec/translations/diagnostics exposes static catalog analysis helpers for CI and CLI consumers. Use analyzeTranslationCatalogGroup or analyzeTranslationCatalogGroups to produce { ok, summary, issues } reports for missing catalogs/keys, extra keys, invalid catalog/message shapes, blank values, ICU syntax, placeholder parity, and duplicate bundle identities.

Harness keyed browser reads

Connect Hook Authority V1

@lssm-tech/lib.contracts-spec/control-plane/hook-authority provides the additive, runtime-neutral authority boundary for host hooks. A decision envelope binds issuer service/key/signature, exact tenant and workspace authority refs, filesystem workspace, actor, SHA, event, path, command, evidence, ownership, and lease generations. A durable host generates the random session capability before session-start, places only its SHA-256 commitment in the signed decision, and delivers the raw bearer separately for the one commit attempt. Exact retries reuse that caller-held bearer; adapters retain only the commitment and never return it in receipts or replay output. The envelope has the fixed contractspec.hook-authority.decision.v1 signature domain and canonical 64-byte unpadded base64url Ed25519 encoding. HookAuthorityPort.transition() owns atomic authorization, terminalization, handoff checkpoint, merge verification, receipts, outbox, audit, and replay results. Stop receipts include completed per-lease release records (receipt, status, and release time), not only requested lease refs. The trusted verifier, clock, and live ownership/lease/revocation/key resolver are installed in the adapter composition—not supplied by callers. hook-authority-reference-adapter is an executable conformance adapter; real adapters must derive durable session, replay, and terminal lease-release keys from the complete decision, tenant, workspace, session, and lease refs (including IDs, generations, and digests), enforce (session,replayKey) uniqueness, and persist verified active lease rows with the session. A stop must match those exact active rows (including their generation and digest) and flip them to released in the same transaction as terminalization, receipt, outbox, audit, and replay state; it must not perform a fallible external lease-release call between authorization and final compare-and-swap.

pack:production, pack:verify, and package publication use the same disposable production staging tree and exact tar artifact. The pack keeps every declared public export, including ./tests and public fixture modules, while removing compiled test bodies, unexported fixtures, build state, source, and private Hook Authority JavaScript. Hook Authority entries are bundled independently for Bun, Node, and browser use; only the declaration files required by their public type closure remain private implementation files. Production packing fails when an export target or relative declaration dependency is missing. It never rewrites the workspace manifest, and two packs of unchanged output are byte-identical. The reusable artifact policy also preserves exact advertised generated JavaScript and required declarations beneath compatibility dist/src paths. Raw TypeScript, compiled tests, build state and unadvertised source-path artifacts remain rejected.

Use bun run pack:production --pack-destination <directory> to create the same tarball consumed by dry-run and live publication. pack:verify installs that untouched tar, runs npm ls, imports every concrete export in Node and Bun, and resolves and bundles every explicitly browser-conditioned export.

Browser get actions accept an optional stable key. A non-empty key opts the action into structured step output; legacy unkeyed get declarations remain valid and output-neutral. Runtime adapters preserve authored key order, do not coerce returned values, and fail before execution for empty or duplicate keys and invalid selector/target combinations.

  • text, html, and value keyed reads require a selector.
  • title and url keyed reads reject a selector.
  • Successful text reads may return null; other values remain strings.
  • Harness json-match assertions use exact deep equality for structured output.

The feature-hubs/social-scheduling and social-scheduling-operations subpaths define additive LinkedIn/X scheduling contracts and eight governed operations. The canonical tenant-bound SocialMediaIntentPort now lives in feature-hubs/social-intent-ports; the module's prior interface remains structurally compatible. Publication still requires current grants and retains its revision/account idempotency semantics.

feature-hubs/social-provider-v2 owns the versioned tenant-bound publication/status port. It carries the canonical local key even when the native API has no idempotency support. Legacy provider interfaces remain available through the existing social module.

content-generation/rights defines scoped creator/media rights grants, immutable asset revision uses, revocation evidence and tracked withdrawal states. Revocation and publication removal are distinct: a pending or unavailable withdrawal is not confirmation.

Durable media status

The additive content-generation.media.status v1 query exposes persisted generation state, revision, artifact references and expected output count through POST /marketing/media/status and MCP media_generation_status. It never polls providers or dispatches generation. Installations supply an authorized reader; the marketing host mounts it only when configured. Tenant, workspace and generation ownership are checked before returning progress. Provider URLs, connection keys and payment reservation references stay private. Existing draft generation operations retain their behavior.

External agent Markdown migration

The agent protocol exports a restricted, digest-bound Markdown archive for selected Hermes memory files and OpenClaw workspace memory, plus skill definitions and Markdown references. Contents remain unreviewed and inactive. Hosts must authorize source selection and storage; this contract does not scan home directories, write runtime files, promote memory, install plugins, or schedule actions. Credentials, configuration, executable skill assets, schedules, channels and external memory databases require separate migration implementations and qualification.

Format references: Hermes memory and OpenClaw memory, inspected September 5, 2026. These current references do not establish the September 4 frozen capability matrix.

agent.memory.import.submit is the additive fleet-management operation for submitting a referenced import proposal through Runtime Node. It requires user authentication and agent.fleet.manage, explicit tenant/workspace/environment, archive/proposal digests, idempotency and a Runtime Node work-order reference. The executor must independently verify authority; references are not permissions. It creates review candidates only and does not promote or share memory. Runtime handler binding and product endpoint qualification remain pending.

Memory import scope is server-bound: the authenticated workspace must match both request and verified Runtime Node operation. Transports refresh session permissions after input consumption before dispatching the review proposal.

An owner-authorized local development gate override remains separate from CI. The build cache includes the override and CI/GitHub Actions markers, and the gate rejects skipping in GitHub Actions even when the general CI variable is changed. Runtime and publication authority are not supplied by this local build setting.

Package-level Turbo configuration extends the shared build task. Its Connect environment settings preserve dependency ordering and cached declaration outputs; do not replace the task with an environment-only root override.

Personal Microsoft calendar OAuth

Personal connection contracts expose POST /api/v2/opa/personal-calendar/microsoft/authorize and GET /api/v2/opa/personal-calendar/microsoft/callback. Ownership comes from the authenticated personal context. PKCE state and encrypted credentials use the Microsoft-only owner-scoped storage; callbacks pin verified Microsoft identity. These operations do not yet provide calendar discovery or qualify booking/planning integration. Production activation requires configured Microsoft credentials/callback, migrations and least-privilege grants, followed by real account acceptance.

Compilation and qualified preparation

bun run build compiles existing source into disposable JavaScript and declaration outputs without regenerating tracked DocBlocks or rewriting package exports. It is usable with uncommitted source and does not issue a Connect permit. Run bun run build:qualified to gate tracked preparation and then compile; build:prepare still requires Connect before documentation regeneration and export preparation. A successful local compile does not qualify source edits, PR acceptance, signing, publication, or promotion. Those authority checks remain independent and fail closed when trusted authority is unavailable. The release artifact-preparation workflow may explicitly use diagnostic report mode before immutable-artifact permit issuance; report mode is not a permit.

Portable primitive owner

The query, result, operation approval-port and versioned-reference primitives are owned by @lssm-tech/lib.contracts-spec-core at packages/foundation/contracts-spec. Existing ContractSpec leaf imports retain their export names and forward to those canonical implementations. Constructors, constant objects and functions share identity across old and new import paths. Existing declaration aliases and published export mappings remain supported.

New consumers of these four primitive families can use the core package root or its deliberate query, results, operations/approval and versioning/refs subpaths. Core's intentional entries share one module closure. Schema and Zod remain declared model dependencies. Its results root includes seven explicit compatibility helpers needed by existing result leaf imports; this package's results root keeps its original namespace. Domain definitions, populated registries and runtime authorization bindings retain their existing owners.

FeatureModuleSpec, defineFeature and their portable ownership/reference vocabulary now share the Core features model owner. Existing feature imports and declaration aliases remain supported; installation, validation and registries still use this compatibility distribution. The linking DocBlock remains declared once in the features/types facade until the existing manifest builder can discover its canonical Core declaration without losing or duplicating its ID.

The existing economic reference validators now have one canonical owner at @lssm-tech/lib.contracts-spec-core/operations/economic-evidence. This package's existing economic-evidence leaf and operations barrel forward the same five functions, preserving supported seam kinds, rejection grammar, parser defaults, count-only errors, input-array identity and ordered merging. The Core root namespace remains unchanged. Supplied-input validation grants no budget, ledger or runtime authority; clean packed and strict consumer qualification remains pending for this owner change.

Canonical durable AgentProtocol models

The provider-neutral help, uncertainty, escalation and common protocol models are owned by @lssm-tech/lib.agent-protocol-spec at packages/platform/agents/agent-protocol-spec. Prefer its root, /help or /common imports when only these models and deterministic structural/binding checks are required. Existing Legacy root and protocol leaves preserve the canonical schema singletons, literal types and namespace readonly modifiers. Evidence-pointer implementation stays private; remaining protocol execution, providers, approvals, review and learning retain their current owners.

See docs/refactoring/lssm-ecosystem/AGENT-PROTOCOL-COMPATIBILITY.md for the source split, import compatibility and rollback boundary. Package metadata and local qualification do not grant live runtime authority or establish registry publication status.

Portable generic declaration ownership

The existing entity/edge constructors, DataView declarations, translation spec, ontology types and physical graph artifact schemas forward to the explicit @lssm-tech/lib.contracts-spec-core leaves documented in its README. Historical public paths, declaration shapes, constructor behavior and schema aliases remain supported. Registry, translation/runtime, rendering, codec and domain ontology implementations retain their existing owners. Metadata does not grant runtime authority. Clean declarations and actual packed consumers still require campaign qualification before release.

Outcome claim declarations and pure correction helpers retain every existing ./outcome-claims* entrypoint while forwarding to the canonical @lssm-tech/lib.contracts-spec-core/outcome-claims definitions. Review records do not replace trusted runtime approval or authorization.

The historical delivery chain and primitives paths now forward to the canonical @lssm-tech/lib.lssm-os-spec/delivery-chain and ./delivery-primitives leaves. Schema identity, SHA-256 material, wire versions, risk checks and effect-authority restrictions remain unchanged.

Job application contract ownership

The existing job-application export and its eight public leaves forward to @lssm-tech/lib.job-application-runtime/contracts and its matching leaves. The domain owns the original V1 operations, events, schemas and transport bindings; contract keys, candidate privacy, authorization, revisions and exact effect fences are unchanged. Existing consumers can keep their supported compatibility imports. Execution approval, rejection and trace operation declarations retain all historical ControlPlane paths through canonical BuilderSpec leaves. Operation keys, singleton schemas, admin policy and evidence/authority requirements remain unchanged; runtime authority is enforced by the existing trusted host.

Managed CompanyOS semantic definitions retain all historical paths while forwarding to @lssm-tech/lib.companyos-spec/managed-companyos/*. Concrete host profiles and mixed runtime/transport composition remain with their host-facing compatibility paths; no production binding or authority is moved into Core. The supported Forms leaf uses exact named reexports from private modules for field/layout/projection models, normalization, completion/intake, relation refinement and the existing nominal registry. These modules add no published subpaths. FormSpec and its DocBlocks share one owner; registry and relation runtime behavior remains in this compatibility package. Module organization does not authorize effects or alter host safety requirements.

The existing ontology/ref and ontology/companyos paths forward to Core pure format helpers and the CompanySpec ontology spine respectively. This preserves all existing constructor/parser behavior and CompanyOS graph values without turning references or safety descriptions into runtime authority.

Generic registry and registry utility imports retain their paths and forward the canonical RuntimeKernel class, functions and grouping object. The contract-kind tuple and guard retain their existing execution-types paths through canonical Core bindings.

Portable Connect and Harness contracts

@lssm-tech/lib.assurance-spec/connect/types owns the unchanged Connect verdict and review threshold declarations. Connect retains policy evaluation, approvals, and runtime authority.

@lssm-tech/lib.assurance-spec/harness/types owns the unchanged Harness evidence, scenario, suite, target, and execution declarations and the identity declaration factories. It does not execute a harness. The supported Legacy paths forward these declarations. The nominal Harness registry classes retain their existing Legacy implementation and superclass identity until the coordinated runtime ownership cut.

Portable visualization and presentation descriptors

Pure visualization models and the identity factory live at @lssm-tech/lib.contracts-spec-core/visualizations/spec and /visualizations/types. Portable presentation descriptors, their identity factory and original DocBlocks live at @lssm-tech/lib.contracts-spec-core/presentations/spec; the framework-independent block configuration model lives at /presentations/block-config. Historical descriptor paths forward these exact implementations. Mutable registries and rendering stay with their existing owners. Graph and timeline documentation remains beside its declaration models.

Portable policy models and decision receipts

@lssm-tech/lib.contracts-spec-core/policy/spec owns the original declarative PolicySpec family and its source DocBlocks. @lssm-tech/lib.contracts-spec-core/policy/decision owns the original FieldLevelDecision and PolicyDecision receipt declarations. Legacy policy/spec and types paths forward the same declarations and DocBlock array. All fields, optionality, vocabulary and documented defaults are preserved. PolicyEngine, OPA adapters, deciders, policy registration and runtime authorization remain outside Core.

Portable Form declarations and the exact identity-preserving defineFormSpec now live in Core's narrow forms/* leaves. Legacy named contract files forward to the same canonical declarations. The projection compatibility shim retains its original formKey value import and initialization. Normalization, registries, relation execution and UI remain at their current owners. This Source extraction grants no runtime or resulting-tree acceptance.

Operation registry imports retain the same canonical RuntimeKernel constructor specialized with the original HandlerCtx, including full telemetry, integrations, knowledge and app configuration models. The existing installer source and execution guards are unchanged. Host policy, approval and ceremony authority remains required.

The rich-field form showcase retains its existing form export through a forward to the canonical DesignCatalog fixture, preserving the model and form singleton.

Canonical telemetry tracking, anomaly monitoring and registry implementations belong to Observability. Legacy telemetry leaves forward to the same constructors; privacy masking, sampling, defaults, provider dispatch and anomaly callback ordering are preserved. Clean declarations and physical consumers remain to be qualified.

CustomerSupport CSAT response and survey contracts, server authority scope, and synchronous input digest forward to the canonical CustomerSupport runtime leaves. These forwards preserve the existing definitions and function identity.

The ./customer-support/* leaves forward with identical identity to their canonical owner @lssm-tech/lib.customer-support-spec (the runtime contracts/* leaves forward there too); only the platform-authority composition helpers remain implemented here until the decisioning definitions have an owner. Shared schemas, error classes, validators, and operation definitions retain single-instance ownership.

The /observability/signal-spec and /observability/evidence-record compatibility leaves forward directly to the complete portable models in @lssm-tech/lib.observability-spec.

Knowledge binding/source/spec imports retain all original models and canonical key/helper documentation identities through Core. The supported spec leaf also retains its existing KnowledgeSpaceRegistry reexport.

Feature and presentation registry imports keep their supported paths and forward the exact canonical RuntimeKernel constructors. Portable feature and presentation models remain with their existing Core owners; registry behavior and class identity are preserved.

Translation catalog model ownership

The unchanged Locale, MessageKey, TranslationEntry, TranslationCatalogMeta, PlatformTranslationCatalog and BlueprintTranslationCatalog declarations are canonical at @lssm-tech/lib.translation-runtime/contracts/catalog. Historical @lssm-tech/lib.contracts-spec/translations/catalog imports forward these same declarations. The model move adds no loading, formatting or runtime initialization behavior; Core continues to own TranslationSpec.

The supported workspace-config/lssm-os-types leaf forwards the complete canonical LSSMOSSpec configuration family and the same scope-order tuple. Configuration schema, inheritance and waiver behavior retain their original implementations.

The six portable built-in rich-reference kind paths forward to their canonical Core leaves. Existing registration and consumers retain the same kind objects and schemas.

Marketing operation paths forward to canonical Growth contract objects, including all original models, operation policies and DocBlocks.

Marketing site types and generic lead/estimate/billing FormSpecs now forward to the complete canonical Growth model and singleton families.

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.

Navigation implementation ownership

Generic navigation contracts, validation and NavRegistry now belong to @lssm-tech/lib.surface-runtime/navigation; the concrete capability registry belongs to its ./capabilities/registry entry. Existing ./navigation, ./navigation/nav-surface, ./navigation/nav-graph, ./navigation/registry and ./capabilities/capabilities imports retain their exports through compatibility forwards. Class identity, registry defaults, validation and version selection remain unchanged.

Workflow runner, state, DAG, expression and persistence-adapter leaves retain their historical paths as exact forwards to WorkflowComposer. No callback, authority, default, class identity or persistence behavior changes.

The 356 historical .d subpaths keep their export conditions. Their declaration forwards preserve generic constraints, nominal types, interface/class and function-overload augmentation, and original runtime imports/reexports. The package-local scripts/forward-legacy-declarations.mjs recipe reconstructs the 331 rewritten sources from the recorded historical commit; use its --check mode and the declaration signature/runtime verification scripts before changing these compatibility declarations. See DECLARATION-FORWARDING-2026-10-11.md† for exact scope, commands and the remaining clean published NodeNext gate.

Declared capabilities.

Lib Contracts Spec

Spec definitions and registries for ContractSpec

Use it to

  • Adopt spec definitions and registries for contractspec

Requires

  • TypeScript

Choose another boundary when

  • The @lssm-tech/lib.contracts-spec package constraints do not match the target runtime or platform.

@lssm-tech/lib.contracts-spec

@lssm-tech/lib.contracts-spec/acp

@lssm-tech/lib.contracts-spec/acp/acp.feature

@lssm-tech/lib.contracts-spec/acp/capabilities

@lssm-tech/lib.contracts-spec/acp/capabilities/acpTransport.capability

@lssm-tech/lib.contracts-spec/acp/commands

@lssm-tech/lib.contracts-spec/acp/commands/acpFsAccess.command

@lssm-tech/lib.contracts-spec/acp/commands/acpPromptTurn.command

@lssm-tech/lib.contracts-spec/acp/commands/acpSessionInit.command

@lssm-tech/lib.contracts-spec/acp/commands/acpSessionResume.command

@lssm-tech/lib.contracts-spec/acp/commands/acpSessionStop.command

@lssm-tech/lib.contracts-spec/acp/commands/acpTerminalExec.command

Imports and export paths.

1687 entries

These are package-manifest entry points. Named symbols listed above come from the capability catalogue; this is not an exhaustive TypeScript symbol reference.

1,687 imports · showing 35

Dependencies and related packages.

Runtime dependencies 52
@formatjs/icu-messageformat-parser
catalog:i18n
compare-versions
catalog:data
zod
catalog:
Peer dependencies 1
Development dependencies 4
typescript
catalog:

Package scripts.

Commands declared by this package. Review its setup requirements before running them; no command here was executed by this review.

publish:pkgbun scripts/publish-hook-authority-package.ts
publish:pkg:canarybun scripts/publish-hook-authority-package.ts --tag canary
publish:pkg:dry-runbun scripts/publish-hook-authority-package.ts --dry-run
pack:productionbun scripts/pack-production-package.ts
cleanrm -rf dist
lintbun run lint:fix
lint:fixnode ../../../../scripts/biome.cjs check --write --unsafe --only=nursery/useSortedClasses . && node ../../../../scripts/biome.cjs check --write .
lint:checknode ../../../../scripts/biome.cjs check .
buildbun scripts/build-package.ts
build:qualifiedbun scripts/build-package.ts --qualified
build:bundlecontractspec-bun-build transpile
build:typescontractspec-bun-build types
build:preparebun run connect:gate && bun run docs:manifest && contractspec-bun-build prebuild
connect:gatebun ../../../../scripts/contractspec-connect-pr-gate.ts
typechecktsgo --noEmit
testbun test
pack:verifybun run build && bun scripts/verify-packed-consumer.ts
devcontractspec-bun-build dev
docs:manifestbun run scripts/build-docblocks-manifest.ts
registry:buildbun run scripts/build-registry.ts
readme:inventorybun scripts/update-readme-contract-inventory.ts
Your view

Make room for your context.

Shape the presentation around this moment. You can change it whenever you need.

Your context

The different parts of you

Choose a starting point

A useful mix of context, visuals and gentle guidance.

Tune each dimension
Each dimension can change independently. Product permissions and available actions stay unchanged.

Support the way you begin and return

Tune your support

Reading comfort

Choose your language

Interface language changes text only. Markets, prices and workflows keep their own settings.

Translation coverage

Original source

Navigation151
Graph616
Categories378
Portfolio833
Examples2,035
Source preview1,542

More translations will be added as content is reviewed.

This preference is saved on this browser.

Search the website

Useful starting points

No results. Try a shorter phrase, an operation name or another search area.

A LITTLE ROOM TO EXPLORE

Find something to explore.

Open a closer look on this page, try a different perspective, or follow the detail into its own page.

How previews and controls work
01

Look before you leave

Hover a link or focus it with Tab to see a preview. Clicking the original link or pressing Enter always opens its destination.

02

Stay with the context

Move into the preview to explore its sections. Use Alt + ↓ from a focused link to enter it with the keyboard. Escape closes it.

03

Open the possibilities

Disclosure rows, perspective choices and highlighted controls reveal more. Your view changes reading comfort and the context you explore.

A separate button for a closer look

Show small preview buttons beside links where there is room. Tap the eye to inspect, or tap the link to go straight there. This choice stays in this tab.

No browsing history is collected. Reduced motion follows your device and Your view.