# ContractSpec — LLM Guide (Full) > Aggregated content from all packages. For summary, see /llms Generated: stable Packages: 312 --- ## @lssm-tech/lib.accessibility Description: WCAG compliance utilities and validators Path: packages/libs/accessibility URL: /llms/lib.accessibility # @lssm-tech/lib.accessibility Website: https://contractspec.io **WCAG compliance utilities and validators.** ## What It Provides - **Layer**: lib. - **Consumers**: design-system, example apps. - Related ContractSpec packages include `@lssm-tech/lib.design-system`, `@lssm-tech/lib.ui-kit`, `@lssm-tech/lib.ui-kit-web`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.design-system`, `@lssm-tech/lib.ui-kit`, `@lssm-tech/lib.ui-kit-web`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.accessibility` or `bun add @lssm-tech/lib.accessibility` ## Usage Import the root entrypoint from `@lssm-tech/lib.accessibility`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/AccessibilityPanel.tsx` is part of the package's public or composition surface. - `src/AccessibilityProvider.tsx` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/nativewind-env.d.ts` is part of the package's public or composition surface. - `src/next-route-announcer.tsx` is part of the package's public or composition surface. - `src/preferences.tsx` is part of the package's public or composition surface. - `src/styles.css` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./AccessibilityPanel` resolves through `./src/AccessibilityPanel.tsx`. - Export `./AccessibilityProvider` resolves through `./src/AccessibilityProvider.tsx`. - Export `./nativewind-env.d` resolves through `./src/nativewind-env.d.ts`. - Export `./next-route-announcer` resolves through `./src/next-route-announcer.tsx`. - Export `./preferences` resolves through `./src/preferences.tsx`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - WCAG compliance standards must be preserved; changes affect all UI surfaces. - Do not weaken or remove existing validators without coordinating with design-system consumers. --- ## @lssm-tech/lib.ai-agent Description: AI agent orchestration with MCP and tool support Path: packages/libs/ai-agent URL: /llms/lib.ai-agent # @lssm-tech/lib.ai-agent Website: https://contractspec.io **Core AI agent runtime for ContractSpec with tool orchestration, MCP integration, session state, memory, and telemetry.** ## What It Provides - Provides the central agent runtime used by chat, automation, and higher-level orchestration packages. - Supports tools, sessions, memory, approvals, providers, telemetry, and MCP-aware workflows. - Acts as the stable public API for agent execution across multiple runtimes and delivery surfaces. - Consumes agent definitions from `@lssm-tech/lib.contracts-spec/agent`. - `src/providers/` contains provider integrations and provider-facing adapters. ## Installation `npm install @lssm-tech/lib.ai-agent` or `bun add @lssm-tech/lib.ai-agent` ## Usage Define agents in `@lssm-tech/lib.contracts-spec/agent`, then run or export them with `@lssm-tech/lib.ai-agent`. ```ts import { defineAgent } from "@lssm-tech/lib.contracts-spec/agent"; import { createUnifiedAgent } from "@lssm-tech/lib.ai-agent/agent/unified-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 agent = createUnifiedAgent(SupportBot, { backend: "ai-sdk", }); ``` Runtime portability stays adapter-first: - `AgentSpec.runtime` can declare checkpointing, suspend/resume, and approval-gateway capabilities. - `AgentFactory` and `ContractSpecAgent` accept optional runtime adapter bundles for LangGraph/LangChain-style integrations. - Session state now persists workflow, thread, trace, checkpoint, and approval metadata for replay-safe resumes. - Escalation policies can raise approval requests on timeout, tool failure, or confidence thresholds without coupling core contracts to a vendor runtime. ## Architecture - `src/agent/`, `src/session/`, and `src/memory/` contain the runtime core for execution state and persistence hooks. - `src/tools/`, `src.providers/`, and `src.interop/` connect providers, tools, and MCP-aware runtime surfaces. - `src.telemetry/`, `src.approval/`, `src.knowledge/`, and `src.schema/` round out runtime policy and observability surfaces. - `src/telemetry/economic-evidence.ts` captures safe agent-run usage/cost refs without persisting prompts, messages, or tool payloads. - `src/index.ts` is the root public barrel and package entrypoint. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Large multi-subpath library exporting agent runtime, approval, memory, knowledge, providers, schema, telemetry, tools, and types. - Export `.` resolves through `./src/index.ts`. - Export `./agent` resolves through `./src/agent/index.ts`. - Export `./agent/agent-factory` resolves through `./src/agent/agent-factory.ts`. - Export `./agent/contract-spec-agent` resolves through `./src/agent/contract-spec-agent.ts`. - Export `./agent/json-runner` resolves through `./src/agent/json-runner.ts`. - Export `./agent/unified-agent` resolves through `./src/agent/unified-agent.ts`. - Export `./approval` resolves through `./src/approval/index.ts`. - Export `./approval/workflow` resolves through `./src/approval/workflow.ts`. - Export `./exporters` resolves through `./src/exporters/index.ts`. - Export `./exporters/claude-agent-exporter` resolves through `./src/exporters/claude-agent-exporter.ts`. - Export `./telemetry/economic-evidence` resolves through `./src/telemetry/economic-evidence.ts`. - Additional runtime subpaths are published through `package.json`; keep docs aligned with the manifest. ## Economic Evidence Agent runs now emit neutral `@lssm-tech/lib.economic-evidence` refs for token usage, provider receipts, model-cost estimates, budget decisions, lifecycle phases, and redaction decisions. Configure `economicEvidence` on `ContractSpecAgent` to attach provider/model/operation/budget context; generated run results and `agent.step.completed` events carry `economicEvidenceRefs`. `UnifiedAgent` forwards AI SDK provider context and creates external-provider run-completion refs. Budget policy blocks only explicit `pre_execution` gates; post-execution overages and pricing-unavailable paths remain reviewable evidence. Prompt text, messages, tool call arguments, and tool outputs remain redacted/reference-only. ## Migration Note `@lssm-tech/lib.ai-agent` no longer owns the agent-definition contract layer. - Removed: `@lssm-tech/lib.ai-agent/spec` - Removed: `@lssm-tech/lib.ai-agent/spec/spec` - Removed: `@lssm-tech/lib.ai-agent/spec/registry` - Use `@lssm-tech/lib.contracts-spec/agent` for `AgentSpec`, `AgentToolConfig`, `AgentRegistry`, `createAgentRegistry`, and `defineAgent` ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run test` — bun test - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Missing dependencies (thanks to knip). - Replace eslint+prettier by biomejs to optimize speed. - Agentic workflows — subagents, memory tools, and next steps. - Vnext ai-native. - Backend operations + frontend rendering support. - Add latest models and align defaults. - Add first-class agent-run economic evidence capture for usage, cost estimates, provider receipts, and replay-safe redaction refs. ## Notes - High blast radius — used by multiple bundles and libs. - Agent definitions are owned by `@lssm-tech/lib.contracts-spec/agent`. - This package is runtime-focused: execution, exporters, MCP/tool bridges, sessions, memory, approvals, providers, and telemetry. - MCP transport adapters must stay runtime-agnostic (no Node/browser-specific globals). --- ## @lssm-tech/lib.ai-providers Description: Unified AI provider abstraction layer Path: packages/libs/ai-providers URL: /llms/lib.ai-providers # @lssm-tech/lib.ai-providers Website: https://contractspec.io **Unified AI provider abstraction layer.** ## What It Provides - **Layer**: lib. - **Consumers**: ai-agent, content-gen, image-gen, voice. - Related ContractSpec packages include `@lssm-tech/lib.provider-ranking`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.provider-ranking`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.ai-providers` or `bun add @lssm-tech/lib.ai-providers` ## Usage Import the root entrypoint from `@lssm-tech/lib.ai-providers`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/factory.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/legacy.ts` is part of the package's public or composition surface. - `src/models.test.ts` is part of the package's public or composition surface. - `src/models.ts` is part of the package's public or composition surface. - `src/selector-types.ts` is part of the package's public or composition surface. - `src/selector.ts` is part of the package's public or composition surface. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./economic-evidence` resolves through `./src/economic-evidence.ts`. - Export `./factory` resolves through `./src/factory.ts`. - Export `./legacy` resolves through `./src/legacy.ts`. - Export `./models` resolves through `./src/models.ts`. - Export `./selector` resolves through `./src/selector.ts`. - Export `./selector-types` resolves through `./src/selector-types.ts`. - Export `./types` resolves through `./src/types.ts`. - Export `./validation` resolves through `./src/validation.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run test` — bun test --pass-with-no-tests - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Economic Evidence `@lssm-tech/lib.ai-providers/economic-evidence` estimates provider token costs from the model catalog and creates neutral economic cost evidence refs. The helper returns reference-only evidence for downstream metering, billing, observability, and replay surfaces; it does not execute invoices, payments, or finance projections. ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add latest models and align defaults. - Resolve lint, build, and type errors across nine packages. - Add first-class transport, auth, versioning, and BYOK support across all integrations. - Add AI provider ranking system with ranking-driven model selection. - Add first-class mistral provider support. - Add provider/model token cost evidence helpers backed by `@lssm-tech/lib.economic-evidence`. ## Notes - Provider interface is consumed by all AI-powered libs; breaking changes cascade widely. - Adding new providers must not break existing factory signatures. --- ## @lssm-tech/lib.analytics Description: Product analytics and growth metrics Path: packages/libs/analytics URL: /llms/lib.analytics # @lssm-tech/lib.analytics Website: https://contractspec.io **Product analytics and growth metrics.** ## What It Provides - **Layer**: lib. - **Consumers**: bundles, apps. - Related ContractSpec packages include `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.lifecycle`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.lifecycle`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.analytics` or `bun add @lssm-tech/lib.analytics` ## Usage Import the root entrypoint from `@lssm-tech/lib.analytics`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/churn` is part of the package's public or composition surface. - `src/cohort` is part of the package's public or composition surface. - `src/funnel` is part of the package's public or composition surface. - `src/growth` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/lifecycle` is part of the package's public or composition surface. - `src/posthog` is part of the package's public or composition surface. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./churn` resolves through `./src/churn/index.ts`. - Export `./churn/predictor` resolves through `./src/churn/predictor.ts`. - Export `./cohort` resolves through `./src/cohort/index.ts`. - Export `./cohort/tracker` resolves through `./src/cohort/tracker.ts`. - Export `./funnel` resolves through `./src/funnel/index.ts`. - Export `./funnel/analyzer` resolves through `./src/funnel/analyzer.ts`. - Export `./growth` resolves through `./src/growth/index.ts`. - Export `./growth/hypothesis-generator` resolves through `./src/growth/hypothesis-generator.ts`. - Export `./lifecycle` resolves through `./src/lifecycle/index.ts`. - The package publishes 16 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run test` — bun test --pass-with-no-tests - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Event naming conventions must stay consistent with PostHog taxonomy. - Metric calculations affect live dashboards; verify formulas before changing. --- ## @lssm-tech/lib.app-submission-readiness-runtime Description: Pure, deterministic runtime audit engine for mobile app submission readiness (ReviewReady). No network calls; integrations feed it snapshots to audit. Path: packages/libs/app-submission-readiness-runtime URL: /llms/lib.app-submission-readiness-runtime # @lssm-tech/lib.app-submission-readiness-runtime Pure, deterministic runtime audit engine for mobile app submission readiness (ReviewReady). It composes on top of the `@lssm-tech/lib.contracts-spec/app-submission-readiness` contract domain and provides the fuller audit engine described in the ReviewReady PRD (Phase 2). ## No network calls This package performs **no** network I/O. Integrations (App Store Connect, Google Play Developer) are responsible for fetching and handing in submission snapshots; this runtime only audits the materials it is given. Timestamps and ids must be supplied by the caller (no `Date.now()` / `Math.random()`). ## Public API - `normalizeSubmissionInput(materials)` — normalize raw/partial submission materials (assets, legal links, privacy disclosures, manifests, SDK inventory, reviewer access refs) into a canonical `AppSubmissionReadinessAuditInput`. - `buildDisclosureMatrix(materials)` — cross-reference SDK collection, manifest permissions, privacy-policy declarations, Apple App Privacy answers, and Google Data Safety answers; returns a typed matrix with per-cell consistency state and evidence refs. - `runReadinessAudit(materials, policy?)` — orchestrate normalize -> disclosure matrix -> findings -> score -> decision into a full report plus matrix and per-store checklists. Composes the contracts-spec audit primitive. - `scoreReadiness(report)` — readiness score wrapper over contracts-spec scoring. - `buildStoreChecklists(report)` — per-store (Apple / Google Play) ordered blocker/warning/improvement checklists. - `draftRejectionResponse(rejectionMessage, report)` — structured, evidence-cited resubmission draft. Avoids legal-advice and approval-guarantee phrasing. - `redactSubmissionReport(report, policy?)` — canonical redaction entrypoint; never serializes raw secret values. ## Fixtures `@lssm-tech/lib.app-submission-readiness-runtime/fixtures` exports `SampleSubmissionMaterials` (with a known disclosure inconsistency) and `ReadySubmissionMaterials` (a passing baseline). --- ## @lssm-tech/lib.assurance-spec Description: Provider-neutral assurance and compliance evidence correlation contracts for autonomous-company actions. Path: packages/libs/assurance-spec URL: /llms/lib.assurance-spec # `@lssm-tech/lib.assurance-spec` Provider-neutral assurance and compliance evidence correlation contracts for autonomous-company actions. This package closes the P1 assurance gap as a **correlation-only** contract/evidence layer. It does not store audit events, query logs, run anomaly detection, execute providers, evaluate policy, or replace ContractSpec Connect. ## Public entrypoints - `@lssm-tech/lib.assurance-spec` - `@lssm-tech/lib.assurance-spec/types` - `@lssm-tech/lib.assurance-spec/fixtures` - `@lssm-tech/lib.assurance-spec/validation` ## Boundary Adjacent systems are referenced through branded refs only: audit events, observability telemetry/anomalies, ai-agent model/tool/session receipts, integration calls, CompanyOS work/policy decisions, Connect reviews, orchestration workflows, and infra-ops deployment/incident refs. --- ## @lssm-tech/lib.authos-runtime Description: Pure deterministic AuthOS runtime projections and security gates over AuthOS contracts. Path: packages/libs/authos-runtime URL: /llms/lib.authos-runtime # `@lssm-tech/lib.authos-runtime` Pure deterministic AuthOS runtime projections and security gates over `@lssm-tech/lib.authos-spec`. This package does not authenticate users, call Better Auth, access databases, or execute providers. It converts AuthOS contracts into safe runtime-facing projections for RBAC, RoleMorph, personalization, data-transmission, database/form metadata, Connect with LSSM, redaction, and production IdP readiness. The runtime also includes a deterministic domain-command persistence helper. It turns approved or approval-required AuthOS command contracts into immutable local runtime events with governance metadata, while returning `canExecute: false` plans so provider, database, and Better Auth execution remains outside this package. ## Subject providers and subject modes The `./subject` subpath ships the production-grade `SubjectProvider` port implementation consumed by `@lssm-tech/lib.contracts-spec/rich-reference` (S-3) and the per-call subject-mode factories used by the AI-agent surface (S-9): - `createSubjectProvider({ resolve, cache })` — request-scoped resolver with optional dual-key tenant-scoped LRU cache. Returns `undefined` (deny-closed) when the strategy throws or yields a malformed shape. - `createDelegatedSubject({ userSession, agentId, signature }, verifier)` — builds an agent-on-behalf-of-user `Subject` with `kind='user'` and `delegationChain=[userId, agentId]` so the audit record carries both identities. Throws on bad signature; `resolveSubjectMode` turns that into a deny-closed `undefined`. - `createAgentSubject(identity)` — first-class agent identity (`kind='agent'`, no delegation chain). - `resolveSubjectMode(ctx)` — per-call dispatcher selected by the caller via `ctx.mode`. The `createHmacDelegationVerifier(secret)` helper produces a server-side HMAC-SHA-256 verifier; secrets must come from the orchestration boundary that issues delegation contracts. --- ## @lssm-tech/lib.authos-spec Description: Contract-first AuthOS specifications for identity, authentication, federation, and security-gated account surfaces. Path: packages/libs/authos-spec URL: /llms/lib.authos-spec # `@lssm-tech/lib.authos-spec` Contract-first AuthOS specifications for identity, authentication, account federation, and security-gated account surfaces. AuthOS V0 deliberately covers a broad identity/auth surface while staying provider-neutral. Runtime execution is delegated to integrations such as Better Auth; this package defines the contracts, fixtures, maturity tags, and semantic validation that other packages must preserve. ## Scope - identities, accounts, profiles, sessions, credentials, devices, and factors; - organization, team, admin, invitation, and membership references; - OAuth/OIDC, SSO/SAML, SCIM, email/phone verification, OTP, magic-link, passkey, one-tap, and MFA descriptors; - Connect with LSSM account-link federation and LSSM-as-IdP descriptors; - auth events, audit evidence, maturity tags, semantic validation, and agent domain-command authority contracts. ## Non-goals - No bespoke auth engine. - No Better Auth dependency or provider SDK imports. - No production LSSM-as-IdP enablement without security-review evidence. - No credential secret serialization in fixtures, errors, events, command payloads, or replay evidence. ## Domain-command authority Agent-facing AuthOS commands are contracts only: they classify read, draft, approval-required, and reserved-human actions without executing identity, session, credential, organization, or IdP mutations. High-impact commands such as session start, factor verification, LSSM account linking, credential rotation, SSO configuration, organization role changes, and LSSM-as-IdP enablement require explicit approval evidence before any host-owned integration may execute them. ## Public entrypoints - `@lssm-tech/lib.authos-spec` - `@lssm-tech/lib.authos-spec/types` - `@lssm-tech/lib.authos-spec/fixtures` - `@lssm-tech/lib.authos-spec/validation` --- ## @lssm-tech/lib.billing-france Description: France-specific BillingOS readiness contracts and deterministic e-invoicing/e-reporting checks. Path: packages/libs/billing-france URL: /llms/lib.billing-france # `@lssm-tech/lib.billing-france` France-specific BillingOS readiness contracts, deterministic checks, fixtures, exports, and tests. This package may import country-neutral BillingOS contracts from `@lssm-tech/lib.billing-spec`. The reverse dependency is forbidden: France identifiers, routing, e-invoicing, and e-reporting readiness must not leak into `@lssm-tech/lib.billing-spec` or `@lssm-tech/lib.billing-runtime`. ## Scope - French SME, ETI, and enterprise fiscal-profile readiness inputs. - B2B domestic e-invoicing, B2C e-reporting, international e-reporting, public-sector readiness, and out-of-scope flow classification. - 2026/2027 readiness schedule metadata. - Factur-X, UBL, and CII format-readiness metadata only; this package does not generate invoice documents. - PA/PDP/provider routing profiles as deterministic mocks/adapters only. - Financial data-vault evidence contracts for redaction, retention, extraction confidence, evidence chains, and duplicate candidates. - Replayable fixtures for package tests and examples. ## Legal engine The France pack hosts the deterministic legal engine that core/runtime must not contain: - TVA rate table — 20 / 10 / 5.5 / 2.1 plus exemption, autoliquidation, and intra-EU, each carrying `validFrom`/`validTo` and failing closed on an unknown rate. - Per-rate-group half-up rounding of tax totals. - Mandatory-mentions validator for required French invoice legal mentions. - Gapless numbering scoped to a `Europe/Paris` fiscal period. - NF203 inalterability hash-chain computed over the canonical invoice bytes. - Credit-note/avoir derivation with an immutability guard that blocks mutation of issued documents. - `SirenSiretVatValidationPort` for INSEE/VIES identifier validation (adapter supplied by the host; live INSEE/VIES is a documented follow-up). ## Public entrypoints - `@lssm-tech/lib.billing-france` — root barrel. - `@lssm-tech/lib.billing-france/readiness` — France flow, schedule, fiscal identifier, format, and readiness-evidence helpers. - `@lssm-tech/lib.billing-france/provider` — provider-neutral mock routing profile and readiness contracts. - `@lssm-tech/lib.billing-france/data-vault` — redacted evidence, retention, extraction, and duplicate-detection contracts. - `@lssm-tech/lib.billing-france/fixtures` — deterministic fixtures. - `@lssm-tech/lib.billing-france/types` — grouped type-only surface. - `@lssm-tech/lib.billing-france/docs` — package boundary doc metadata. ## Non-goals Readiness and routing metadata are **not** PA accreditation, production PA submission, legal advice, or tax advice. This package contains no provider credentials, network calls, provider SDKs, raw document payload storage, production submission path, or autonomous production billing execution. --- ## @lssm-tech/lib.billing-runtime Description: Pure backend-neutral BillingOS runtime helpers for deterministic quote-to-cash lifecycle projections. Path: packages/libs/billing-runtime URL: /llms/lib.billing-runtime # `@lssm-tech/lib.billing-runtime` Pure, backend-neutral BillingOS runtime helpers over `@lssm-tech/lib.billing-spec`. France readiness metadata is not PA accreditation, production PA submission, legal advice, or tax advice. ## Runtime helpers `@lssm-tech/lib.billing-runtime` provides pure helper engines over `@lssm-tech/lib.billing-spec`: - quote/order/invoice/payment/reconciliation lifecycle projections; - deterministic pricing totals with an injected synchronous tax-calculation port; - local workflow event creation/appending; - payment-state reconciliation hints; - draft accounting export shaping; - deterministic quote-to-cash cockpit projections with lifecycle, approval-packet, surface, and finance-review handoff metadata; and - agent planning guards that produce approval packets instead of executing high-impact billing actions. The package performs no network calls, filesystem access, provider SDK calls, credential handling, persistence writes, PA submission, or autonomous production billing execution. ## Persistence ports (additive) Backend-neutral port interfaces that a host implements against its store; the package defines the contracts, never the adapters: - `InvoiceRepositoryPort` — persist and read issued invoices. - `EventLogAppendPort` — append-only billing workflow event log. - `InvoiceChainAppendPort` — append entries to the per-period invoice hash-chain. - `CreditNoteRepositoryPort` — persist and read credit notes (avoir). ## Observability (additive) - `BillingObservabilityPort` — structured, correlation-id-propagating observability hook for issuance and submission. - Field-level redaction of SIREN/SIRET/VAT identifiers, secrets, and amounts so no sensitive payload is logged; redaction is applied before any sink receives the record. --- ## @lssm-tech/lib.billing-spec Description: Country-neutral BillingOS quote-to-cash contracts, invariants, and agent action governance types. Path: packages/libs/billing-spec URL: /llms/lib.billing-spec # `@lssm-tech/lib.billing-spec` Country-neutral BillingOS contracts for quote-to-cash primitives, lifecycle evidence, policy metadata, and agent-facing operation descriptions. This package is the canonical core contract surface. It intentionally does **not** contain France-only readiness, PA routing, provider credentials, production submission APIs, persistence adapters, UI, or runtime side effects. ## Scope Use this package to model reusable BillingOS concepts before choosing a country pack or runtime implementation: - commercial parties, billing accounts, seller/buyer/vendor/customer roles, and fiscal references; - catalog, price book, offer, quote, order/commitment, invoice, credit-note, payment, reconciliation, and tax-treatment references; - workflow/event/audit/source metadata for quote-to-cash replay; - accounting-export, revenue-memory, connector-profile, financial-data-vault, and product-surface projection contracts when they are country-neutral; - agent operation catalog and safety metadata for read/draft/recommend/approval-only billing actions; - role-aware quote-to-cash cockpit packets, persona-to-managed-role bindings, action availability, and evidence references for downstream bundle/app seams. ## Invoice-issuance contracts (additive) The following additive operation/event contracts describe the France-ready issuance path. They sit alongside the original eight billing contract keys, which are unchanged: - `billing.invoice.issue` — issue an invoice from a quote/order, producing the canonical invoice record. - `billing.invoice.submit` — submit an issued invoice to a PDP (Plateforme de Dématérialisation Partenaire) / e-reporting target. - `billing.invoice.submitted` — event emitted once submission is accepted. - `billing.creditNote.issue` — issue a credit note (avoir) derived from a prior invoice. These contracts stay country-neutral: France legal behavior (TVA, mandatory mentions, gapless numbering, NF203, avoir immutability) lives in `@lssm-tech/lib.billing-france`, and Factur-X/EN16931 generation plus PDP submission live in `@lssm-tech/integration.provider-einvoicing`. ## Boundary BillingOS core remains country-neutral. France e-invoicing/e-reporting readiness lives in `@lssm-tech/lib.billing-france`; deterministic helper behavior lives in `@lssm-tech/lib.billing-runtime`; CompanyOS/operator composition belongs in examples or an explicit module surface. Core contracts may describe high-impact operations, but they must carry authority/autonomy and operator-approval metadata. They must not represent silent authorized execution. ## Public entrypoints - `@lssm-tech/lib.billing-spec` — root barrel - `@lssm-tech/lib.billing-spec/types` — country-neutral BillingOS contract types - `@lssm-tech/lib.billing-spec/validation` — contract validation helpers - `@lssm-tech/lib.billing-spec/fixtures` — safe synthetic quote-to-cash cockpit fixtures ## Production-readiness safety boundaries - No France-specific fields, readiness schedules, PA claims, or provider routing in core. - No provider credentials, API keys, network calls, filesystem/database adapters, or production billing processor behavior. - No production PA submission, e-reporting submission, invoice send, mark-paid, refund, write-off, or VAT/tax-treatment mutation without an explicit approval packet. - No legal advice, tax advice, PA accreditation claim, or full accounting/general-ledger claim. See `docs/billingos-production-readiness.md` and `docs/billingos-v0-release-verification.md` for prompt coverage, release gates, and remaining non-goals. --- ## @lssm-tech/lib.builder-runtime Description: Backend-neutral Builder runtime, ingestion, fusion, readiness, and replay services. Path: packages/libs/builder-runtime URL: /llms/lib.builder-runtime # @lssm-tech/lib.builder-runtime Website: https://contractspec.io Backend-neutral Builder runtime primitives for source ingestion, omnichannel normalization, fusion, planning, previews, readiness, and replay. ## What It Provides - In-memory and interface-based Builder stores. - Omnichannel ingestion pipeline for chat, voice, file, zip, Studio, Telegram, and WhatsApp inputs. - Specs-pack V0 runtime for safe zip/folder import, deterministic file classification, source refs, analysis, readiness, implementation planning, delivery-loop projection, and Connect-gated task-ledger/apply evidence that fails closed before repository writes. - The repository canonical Builder v3 specs pack is covered by runtime regression tests so release evidence proves realistic packs stay read-only, traceable, and fail-closed when their structure needs review. - Pure RoleMorph preview helpers for AirDesk role selectors, policy variant previews, surface inspections, diffs, safe missing-binding suggestions, Workbench packets, preference snapshots, authorization summaries, replay bundles, and assurance/audit evidence checks. - Deterministic precedence-based fusion and blueprint compilation. - Execution-lane plan compilation and lightweight execution lifecycle helpers. - Preview, readiness, replay bundle, automatic economic evidence packet, safe replay sink serialization, and customer-delivery-loop projection helpers. ## Public Entry Points - `.` resolves through `./src/index.ts` - `./builder-intelligence` resolves through `./src/builder-intelligence/index.ts` - `./stores` resolves through `./src/stores/index.ts` - `./ingestion` resolves through `./src/ingestion/index.ts` - `./specs-pack` resolves through `./src/specs-pack/index.ts` - `./fusion` resolves through `./src/fusion/index.ts` - `./planning` resolves through `./src/planning/index.ts` - `./preview` resolves through `./src/preview/index.ts` - `./rolemorph-preview` resolves through `./src/rolemorph-preview/index.ts` - `./readiness` resolves through `./src/readiness/index.ts` - `./replay` resolves through `./src/replay/index.ts` ## Notes - This package stays backend-neutral. Durable database storage belongs in integration and app layers. - Channel dispatch is bridged through an injected outbox adapter so Builder can reuse host messaging infrastructure without depending on app shells. - PDF and OCR extraction are adapter-backed and can be swapped or disabled by hosts. ## Economic Evidence Replay When all production workflow lanes complete, Builder runtime creates `economicReplayPacket` automatically, including explicit packets for workflows with no child economic refs yet. Consumers should send replay packets to logs or replay indexes through `serializeBuilderWorkflowEconomicEvidencePacketForSink()` from `@lssm-tech/lib.builder-runtime/replay`, which exposes safe packet metadata, child ref counts, allowlisted evidence refs, replay bundle metadata, and redaction decisions without raw provider receipts, prompts, operation payloads, or replay payloads. ## Model routing evidence Builder runtime consumes the provider-ranking router during plan compilation and carries routing summaries into readiness and replay. The runtime remains backend-neutral: it records selected provider/model, policy, risk flags, reason codes, review requirements, and evidence references, but host runtimes execute the chosen model. ## Contract Intelligence runtime Builder-runtime exposes the first dry-run Contract Intelligence helpers for fixture-backed brownfield analysis, redacted bundle export/import validation, reconciliation, and selective adoption planning. Apply-capable flows remain blocked until Connect decision and replay evidence exist. ## Builder Intelligence runtime Builder-runtime exposes pure Builder Intelligence helpers for Phase 1 indexing/retrieval and Phase 2 memory/trajectory projection. `buildBuilderIndex()` creates deterministic `BuilderIndexManifestV1` and `BuilderChunkV1` artifacts from caller-provided refs without writing stores. `queryBuilderIndex()` performs in-memory exact lookup, graph-ref expansion, symbol matching, sparse text scoring, stale filtering, reranking, and `BuilderContextPacketV1` packing with selection reasons. `projectBuilderMemoryItems()`, `createStaleMemoryReport()`, `proposeBuilderMemoryConsolidation()`, and `captureBuilderTrajectory()` keep durable memory review-gated, hash-invalidated, provenance-backed, and free of raw hidden reasoning. Later-phase helpers add draft-only ReasoningBank strategy cards, SONA-lite route explanations, non-authoritative GraphRAG community summaries, and neural-adaptation readiness gates without automatic mutation or training. ## RoleMorph preview runtime Builder-runtime exposes `./rolemorph-preview` for backend-neutral RoleMorph preview artifacts. The helpers build AirDesk role/policy selector previews, inspect resolved surfaces, diff default versus VIP policy outcomes, produce safe repair suggestions for missing component/data bindings, create Workbench packets, snapshot host-referenced preferences, summarize authorization, assemble replay bundles, and validate branded assurance/audit evidence. They depend on `@lssm-tech/lib.surface-runtime/rolemorph` and `@lssm-tech/lib.builder-spec` only; they do not render React, write stores, call providers, or bypass Connect-gated apply paths. ## Builder customer-delivery-loop runtime Builder-runtime exposes pure customer-delivery-loop helpers from the root entry point. `createBuilderCustomerDeliveryLoop()` assembles the ref/evidence aggregate, `evaluateBuilderDeliveryReadiness()` projects validation blockers, `projectBuilderDeliveryHandoff()` fails closed until acceptance, release, and customer-handoff evidence exists, and `createBuilderDeliveryReplaySummary()` collects Connect/replay/release refs for audit and release evidence. The helpers do not write repositories, call providers, persist stores, dispatch messages, or send customer communications. Host apps and integrations own durable storage and production delivery. --- ## @lssm-tech/lib.builder-spec Description: Builder control-plane contracts, capabilities, and validation for ContractSpec. Path: packages/libs/builder-spec URL: /llms/lib.builder-spec # @lssm-tech/lib.builder-spec Website: https://contractspec.io Typed Builder control-plane contracts, capabilities, operations, events, and validation for governed omnichannel authoring. ## What It Provides - Builder workspace, conversation, source, directive, blueprint, plan, preview, readiness, and export types. - Specs-pack import, analysis, readiness, implementation-plan, task-ledger, Connect decision, apply receipt, trace, progress, alignment, verifier decision, replay, and customer-delivery-loop types for external product-intent packs. - RoleMorph preview, surface-inspection, policy-diff, policy-variant, missing-binding repair, Workbench packet, preference snapshot/store-port, authorization summary, replay bundle, and assurance/audit evidence types for adaptive operating surfaces. - Full Builder command/query/event surface aligned with the Builder layer spec pack. - Capability specs for chat, voice, ingestion, fusion, planning, preview, harness, and export workflows. - Validation helpers for runtime and host layers, including fail-closed delivery-loop evidence checks. ## Public Entry Points - `.` resolves through `./src/index.ts` - `./capabilities` resolves through `./src/capabilities/index.ts` - `./commands` resolves through `./src/commands/index.ts` - `./events` resolves through `./src/events/index.ts` - `./queries` resolves through `./src/queries/index.ts` - `./types` resolves through `./src/types/index.ts` - `./validation` resolves through `./src/validation/index.ts` ## Notes - This package is a compatibility surface. Additive evolution is preferred. - Builder orchestration reuses execution-lane identifiers and harness evidence references instead of introducing a second runtime taxonomy. - Generated-app runtime channels are out of scope here; this package models the Builder control plane only. ## Builder v2 control-plane records `@lssm-tech/lib.builder-spec` publicly exports the Builder v2 control-plane alignment records from both the root entry point and `./types`: - `BuilderIntentDecisionRecord` captures IntentGate ambiguity classification, selected execution lane, escalation decision, and evidence refs before Builder execution proceeds. - `BuilderToolCapabilityManifest` captures scoped tool availability, supported operations, runtime modes, degraded/blocker state, and evidence refs without depending on a concrete MCP/runtime implementation. - `BuilderToolActivationReceipt` records why a scoped tool was activated, the permissions actually used, produced evidence, and optional Connect review packet refs. - `BuilderTaskLedgerEntry` maps Builder-visible task state to leased/running/blocked/completed/stale ledger entries with heartbeat, recovery-rule, and evidence refs. `BUILDER_V2_CONTROL_PLANE_ARTIFACT_KEYS` lists the canonical artifact keys for these records. ## Contract Intelligence types Builder-spec now includes additive Contract Intelligence types for contractization reports, portable bundle manifests, selective import decisions, and thin portfolio envelopes. These types are dry-run/advisory surfaces and preserve graph/repo-reality/adoption/replay refs instead of defining a second graph. ## Contract Intelligence contracts `@lssm-tech/lib.builder-spec` now includes additive Contract Intelligence types for contractization reports, portable bundle manifests, import reconciliation, selective dry-run adoption, portfolio envelopes, vertical patch notes, and recurrent radar reports. These contracts are additive and dry-run oriented. ## Builder Intelligence contracts `@lssm-tech/lib.builder-spec` now includes additive Builder Intelligence contracts for index manifests, chunks, context packets, durable memory items, trajectories, ReasoningBank-style patterns, SONA-lite routing policies, and stale-memory reports. These contracts are dry-run first: graph refs, source hashes, provenance, `path-only` redaction, review status, and rollback metadata stay authoritative while embeddings, stores, and adaptive routing remain optional later layers. ## RoleMorph preview contracts `@lssm-tech/lib.builder-spec` includes additive RoleMorph Builder contracts for serializable role selectors, policy variants, surface summaries, inspection packets, surface diffs, safe missing-binding repair suggestions, Workbench panel packets, preference snapshots/store ports, authorization summaries, replay bundles, and branded assurance/audit evidence requirements. These contracts describe Builder preview, inspection, replay, and evidence surfaces; rendering, durable storage, provider calls, and production authorization remain in host/runtime layers. ## Builder customer-delivery-loop contracts `@lssm-tech/lib.builder-spec` includes additive interface-first delivery-loop contracts for quote/order/acceptance/account/source refs from BillingOS, customer commitment/work/authority/policy-gate refs from CompanyOS, scoped PRD/test-spec/specs-pack artifacts, implementation plans, task ledgers, Connect/replay refs, acceptance evidence, release capsules, and customer-handoff refs. Validators keep commercial amount-like data in BillingOS refs and block execution-approved, verified, or handed-off states until required evidence exists. These contracts are evidence/ref aggregates only: provider execution, durable storage, repository writes, app shells, and customer sends remain in host/runtime layers. --- ## @lssm-tech/lib.bus Description: Event bus and messaging primitives Path: packages/libs/bus URL: /llms/lib.bus # @lssm-tech/lib.bus Website: https://contractspec.io **Event bus and messaging primitives.** ## What It Provides - **Layer**: lib. - **Consumers**: personalization, bundles. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.bus` or `bun add @lssm-tech/lib.bus` ## Usage Import the root entrypoint from `@lssm-tech/lib.bus`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/auditableBus.ts` is part of the package's public or composition surface. - `src/eventBus.ts` is part of the package's public or composition surface. - `src/filtering.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/inMemoryBus.ts` is part of the package's public or composition surface. - `src/metadata.ts` is part of the package's public or composition surface. - `src/subscriber.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./auditableBus` resolves through `./src/auditableBus.ts`. - Export `./eventBus` resolves through `./src/eventBus.ts`. - Export `./filtering` resolves through `./src/filtering.ts`. - Export `./inMemoryBus` resolves through `./src/inMemoryBus.ts`. - Export `./metadata` resolves through `./src/metadata.ts`. - Export `./subscriber` resolves through `./src/subscriber.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - `EventBus` interface is a core contract; changes affect all event-driven communication. - Do not alter the subscriber/publish protocol without coordinating with all consumers. --- ## @lssm-tech/lib.cockpit-kit-native Description: Native lane for cockpit primitives — React Native implementations with cockpit-kit type contracts Path: packages/libs/cockpit-kit-native URL: /llms/lib.cockpit-kit-native # @lssm-tech/lib.cockpit-kit-native Native lane (React Native / Expo) for cockpit primitives. Implements the `CockpitFrame`, `NavRail`, `GraphCanvas`, and `MetricPanel` contracts from `@lssm-tech/lib.cockpit-kit` using React Native primitives. ## Overview ``` cockpit-kit-native → cockpit-kit (type contracts + variant unions) ``` Variant unions (`Density`, `Expansion`) are owned by `cockpit-kit` and re-exported here for convenience. ## Usage ```tsx import { CockpitFrame } from "@lssm-tech/lib.cockpit-kit-native/ui/CockpitFrame"; function MyCockpit() { const [active, setActive] = React.useState("dashboard"); return ( {/* NavRailNative goes here */} {active === "dashboard" && ( )} ); } ``` ## Subpath exports | Import | Contents | |--------|----------| | `@lssm-tech/lib.cockpit-kit-native` | Type contracts + variant unions | | `@lssm-tech/lib.cockpit-kit-native/variants` | Density + Expansion re-exports | | `@lssm-tech/lib.cockpit-kit-native/types` | Prop interface re-exports | | `@lssm-tech/lib.cockpit-kit-native/ui/CockpitFrame` | Compound layout container | ## Rules - Do NOT import from `@lssm-tech/lib.personalized-presentation` (cycle prevention) - Do NOT use web-only APIs (`div`, `className`, `cva`, `clsx`) - Use `StyleSheet.create` for all styles - Variant types MUST come from `@lssm-tech/lib.cockpit-kit/variants` --- ## @lssm-tech/lib.cockpit-kit-web Description: Web lane for cockpit primitives — re-exports cockpit-kit types with web-specific ui/ subpath convention Path: packages/libs/cockpit-kit-web URL: /llms/lib.cockpit-kit-web # @lssm-tech/lib.cockpit-kit-web Web lane for cockpit UI primitives. Mirrors `@lssm-tech/lib.ui-kit-web` in structure. ## Overview `cockpit-kit-web` provides the web-specific surface for cockpit primitives, re-exporting type contracts from `@lssm-tech/lib.cockpit-kit` and (in Phase 1) adding React/DOM component implementations. ## Subpath exports | Import | What you get | |---|---| | `@lssm-tech/lib.cockpit-kit-web` | All types + variants | | `@lssm-tech/lib.cockpit-kit-web/variants` | `Density`, `Expansion` + schema descriptors | | `@lssm-tech/lib.cockpit-kit-web/types` | Component prop interfaces | Phase 1 will add: | Import | What you get | |---|---| | `@lssm-tech/lib.cockpit-kit-web/ui/CockpitFrame` | Web CockpitFrame component | | `@lssm-tech/lib.cockpit-kit-web/ui/NavRail` | Web NavRail component | | `@lssm-tech/lib.cockpit-kit-web/ui/GraphCanvas` | Web GraphCanvas component | | `@lssm-tech/lib.cockpit-kit-web/ui/MetricPanel` | Web MetricPanel component | ## Usage ```ts // Types (scaffold — Phase 1 adds implementations) import type { CockpitFrameProps } from '@lssm-tech/lib.cockpit-kit-web'; // Canonical variants (owned by cockpit-kit, re-exported here) import { Density, densityVariantSchema } from '@lssm-tech/lib.cockpit-kit-web/variants'; ``` ## Dependency rules - `cockpit-kit-web` depends on `cockpit-kit` — not the reverse - `Density` and `Expansion` unions are owned by `cockpit-kit`; this package re-exports them - Do not add native/React Native code here --- ## @lssm-tech/lib.cockpit-kit Description: Cross-platform type contracts and canonical variant unions for cockpit primitives Path: packages/libs/cockpit-kit URL: /llms/lib.cockpit-kit # @lssm-tech/lib.cockpit-kit Cross-platform type contracts and canonical variant unions for cockpit UI primitives. ## Overview `cockpit-kit` is the shared foundation for the four cockpit primitives: | Primitive | Purpose | |---|---| | `CockpitFrame` | Top-level layout shell for the cockpit surface | | `NavRail` | Vertical navigation sidebar | | `GraphCanvas` | Dependency/workflow graph view | | `MetricPanel` | Metric and KPI display panel | This package ships **type contracts only**. Component implementations land in Phase 1. ## Canonical variant unions Two variant unions are defined and owned here: ```ts import { Density, Expansion } from '@lssm-tech/lib.cockpit-kit/variants'; // Density: 'comfortable' | 'compact' // Expansion: 'collapsed' | 'expanded' ``` **Rule:** `lib.personalized-presentation` imports these FROM here. Never the other way around. ## Subpath exports | Import | What you get | |---|---| | `@lssm-tech/lib.cockpit-kit` | All types + variants | | `@lssm-tech/lib.cockpit-kit/variants` | `Density`, `Expansion` + schema descriptors | | `@lssm-tech/lib.cockpit-kit/variants/density` | `Density` only | | `@lssm-tech/lib.cockpit-kit/variants/expansion` | `Expansion` only | | `@lssm-tech/lib.cockpit-kit/types` | Component prop interfaces | ## Usage ```ts import type { CockpitFrameProps, NavRailProps } from '@lssm-tech/lib.cockpit-kit'; import { densityVariantSchema, expansionVariantSchema } from '@lssm-tech/lib.cockpit-kit/variants'; ``` ## Dependency rules - This package has **no UI framework dependencies** — it is purely types and constants - Web-specific implementations live in `@lssm-tech/lib.cockpit-kit-web` - `lib.personalized-presentation` imports FROM this package, not vice versa --- ## @lssm-tech/lib.communication-runtime Description: Backend-neutral CommunicationOS runtime, governance, lifecycle, state, ingestion, records, and replay helpers. Path: packages/libs/communication-runtime URL: /llms/lib.communication-runtime # @lssm-tech/lib.communication-runtime Backend-neutral CommunicationOS runtime for lifecycle validation, governance decisions, in-memory state, ingestion normalization, records, and replay-oriented helpers. The runtime also exposes `persistAgentCommunicationCommand`, a provider-free domain-command persistence helper. It turns named CommunicationOS commands (for example `communication.reply.send`) into immutable in-memory runtime events with `read_persisted`, `draft_persisted`, or `approval_packet_persisted` status. The helper records the command plan and approval violations only; it does not send messages, call providers, open database connections, or mutate external systems. `createCommunicationCommandInboxItem` projects message-originated commands into a command inbox item with `canExecute: false`, AIP control refs, persisted event evidence, and optional CompanyOS bridge review state. Production-send and high-impact CompanyOS bypass signals fail closed as `blocked`; approval-gated commands remain evidence packets until an external human/policy path acts. ## Public Entry Points - `.` resolves through `./src/index.ts` - `./governance` resolves through `./src/governance/index.ts` - `./ingestion` resolves through `./src/ingestion/index.ts` - `./lifecycle` resolves through `./src/lifecycle/index.ts` - `./records` resolves through `./src/records/index.ts` - `./replay` resolves through `./src/replay/index.ts` - `./state` resolves through `./src/state/index.ts` - `./runtime` includes domain-command planning and persistence helpers - `./command-inbox` exposes the fail-closed command inbox projection helper ## Boundary This package depends on `@lssm-tech/lib.communication-spec` and lower-level libs only. It must not import `@lssm-tech/example.communication-os`, `packages/examples/*`, or module packages. ## Matrix runtime channel The runtime recognizes `matrix` as a backend-neutral channel type with default send capability and human-review expectations for sensitive replies. Matrix SDK behavior belongs in integration provider packages, not in this runtime package. --- ## @lssm-tech/lib.communication-spec Description: Canonical communication contracts, operations, events, and validation helpers for ContractSpec. Path: packages/libs/communication-spec URL: /llms/lib.communication-spec # @lssm-tech/lib.communication-spec Canonical CommunicationOS contracts for threads, messages, participants, reply drafts, handoffs, operations, queries, events, capabilities, and validation helpers. Domain-command helpers classify agent-callable CommunicationOS actions such as reply drafting, reply sending, handoff creation, and escalation requests. These helpers are contract-only: they describe authority, autonomy, approval requirements, and semantic violations without provider adapters, persistence drivers, outbound sends, or runtime side effects. Command-inbox contracts extend domain-command planning with non-executing inbox items, fail-closed status, AIP control refs, and CompanyOS bridge evidence. These contracts describe review/approval state only; they do not grant send or work-execution authority. ## Public Entry Points - `.` resolves through `./src/index.ts` - `./types` resolves through `./src/types/index.ts` - `./types/domain-command` resolves through `./src/types/domain-command.ts` and includes command-inbox contracts - `./commands` resolves through `./src/commands/index.ts` - `./queries` resolves through `./src/queries/index.ts` - `./events` resolves through `./src/events/index.ts` - `./capabilities` resolves through `./src/capabilities/index.ts` - `./validation` resolves through `./src/validation/index.ts` ## Persistence wave CommunicationOS persistence stays contract-first. `communicationOsSchemaContribution`, `communicationOsPersistencePlans`, and `createCommunicationOsMutationDescriptor` expose portable schema and governed `database.mutation.execute@2.0.0` envelopes for managed/BYOK providers. The domain command reference remains the write authority; provider packages execute SQL/Drizzle outside this spec package. Local/PgLite support is compatibility binding metadata, not an ownership mode. ## Boundary This package owns canonical communication contracts. Runtime behavior, examples, fixtures, proof/replay, and product composition live in separate packages. Deprecated module shims may re-export this surface for compatibility only. ## Matrix channel `ChannelTypeEnum` includes `matrix` for deployments that ingest Matrix room events or send governed replies to Matrix rooms. Matrix bridge metadata is owned by integration contracts; this package only owns the canonical channel value. --- ## @lssm-tech/lib.companyos-runtime Description: Pure CompanyOS V0 runtime helpers for authority, autonomy, inbox routing, and operating review projections. Path: packages/libs/companyos-runtime URL: /llms/lib.companyos-runtime # `@lssm-tech/lib.companyos-runtime` Pure, backend-neutral CompanyOS runtime helpers for deterministic V0 replay and V1 operating-loop projections. This package consumes public contracts from `@lssm-tech/lib.companyos-spec` and provides reusable helpers for: - explaining authority for an action proposal - classifying autonomy requests into safe policy decisions - routing approval/reserved-risk decisions into operator inbox items - summarizing a CompanyOS V0 operating review - projecting V1 objectives, temporal memory, operating cadence review packets, agent handoffs, execution readiness/dispatch/receipt evidence, correction/outcome receipt linkage, agent-native operation access, surface profile selection, CompanyOS operating graph views, and evidence-backed outcome value reports ## Positioning Long-term governance/runtime layer behind proofs like CompanyOS VoiceOps. ## Boundary The runtime package has no providers, I/O, modules, bundles, apps, integrations, or UI. It does not execute actions. It only projects deterministic decisions, packets, selections, dispatch drafts, receipts, inbox items, and summaries over CompanyOS spec objects. ## Public entrypoints - `@lssm-tech/lib.companyos-runtime` — root barrel - `@lssm-tech/lib.companyos-runtime/authority` — authority explanation helpers - `@lssm-tech/lib.companyos-runtime/autonomy` — autonomy classification helpers - `@lssm-tech/lib.companyos-runtime/inbox` — operator inbox routing helpers - `@lssm-tech/lib.companyos-runtime/review` — operating review summarization helpers - `@lssm-tech/lib.companyos-runtime/objectives` — V1 objective health and drift projections - `@lssm-tech/lib.companyos-runtime/memory` — V1 temporal memory snapshot projections - `@lssm-tech/lib.companyos-runtime/cadence` — V1 operating cadence review packet builders - `@lssm-tech/lib.companyos-runtime/execution` — V1 execution readiness, dispatch draft, policy-gate, receipt, and inbox projections - `@lssm-tech/lib.companyos-runtime/execution-receipts` — deterministic execution receipt summaries and correction/outcome linkage projections - `@lssm-tech/lib.companyos-runtime/agent-org` — V1 agent delegation and handoff planners - `@lssm-tech/lib.companyos-runtime/operations` — V1 agent-native operation access classifiers - `@lssm-tech/lib.companyos-runtime/surfaces` — V1 dynamic surface profile selectors - `@lssm-tech/lib.companyos-runtime/operating-graph` — deterministic graph snapshot, source-record replay, and idempotent change helpers over CompanyOS spec node kinds - `@lssm-tech/lib.companyos-runtime/identity-resolution` — cross-source identity candidate and link decision projections - `@lssm-tech/lib.companyos-runtime/graph-permissions` — actor-bound graph filtering and required-field redaction projections - `@lssm-tech/lib.companyos-runtime/graph-realtime` — data-transmission-compatible event envelope and replay projections - `@lssm-tech/lib.companyos-runtime/runbooks` — fail-closed runbook readiness projections for stale, conflicted, unauthorized, or low-confidence graph evidence - `@lssm-tech/lib.companyos-runtime/substrate-adapters` — thin adapter-shaped projections for AuthOS/RBAC decisions and data-transmission refs - `@lssm-tech/lib.companyos-runtime/outcome-value-projections` — deterministic business value reports, review queues, readiness signals, sales reports, and prompt/skill influence grouping over ContractSpec outcome claim refs ## Operating graph / AI OS projections The operating graph helpers consume CompanyOS spec-compatible node kinds and stay provider-free. They preserve source-record evidence during realtime replay, bind permission decisions to the requesting actor, and union required redactions before returning graph fields. Permissioned graph query projections filter requested nodes, deny or redline unsafe nodes before agent use, and expose only redacted fields plus evidence refs. Runbook conformance helpers derive pass/fail evidence from procedures, readiness records, and conformance cases without provider execution. Examples should call these runtime helpers and keep deterministic sandbox adapters only at execution boundaries. ## Outcome value projections `projectBusinessValueReport` and `projectSalesValueReport` consume structural ContractSpec outcome claim data without owning the generic claim schema. Claims with no evidence are excluded, low-confidence/high-impact/unreviewed claims enter the review queue, corrections reduce readiness, and prompt/skill attribution groups are reported as correlation unless upstream claims explicitly prove causality. The helpers are deterministic and side-effect-free. ## Safety model Authority and autonomy remain separate. Authority explains whether a principal has a matching capability grant and accountable owner path. Autonomy classifies how far a proposed operation may proceed. Customer-facing, approval-required, and reserved-human-only operations are never escalated to autonomous execution by this package. Execution helpers preserve policy-gate verdicts and only return dispatch drafts or operator inbox projections. ## Policy Runtime Projections `@lssm-tech/lib.companyos-runtime/policy-runtime` provides pure fail-closed projections for CompanyOS policy evaluation packets: readiness, missing evidence, next operator action, reserved-human-only enforcement, dry-run-before-execute state, assurance coverage, and fallback/failure explanations. These helpers are deterministic and side-effect-free. They do not call providers, storage, queues, modules, or adapters. --- ## @lssm-tech/lib.companyos-spec Description: Contract-first CompanyOS V0/V1 specifications for bounded company operations. Path: packages/libs/companyos-spec URL: /llms/lib.companyos-spec # `@lssm-tech/lib.companyos-spec` ## VoiceOps governed-action scenario CompanyOS VoiceOps is represented as a governed-action scenario, not as a provider runtime. The canonical Voice-to-Product-Gap path starts from CommunicationOS voice/transcript evidence, redacts customer identifiers, proposes an internal product-gap work item, blocks the next-day customer promise, routes PM approval for internal work, and emits replay/receipt material with no production-write claim. This package owns the CompanyOS side of that story: action origin, authority explanation, policy verdict, approval gate, governed-action lifecycle, replay trace, and evidence receipt material. CommunicationOS owns the source thread/transcript evidence and proposed-action extraction. Provider STT/TTS adapters, live customer sends, CRM writes, and compliance claims stay outside the spec boundary. Canonical CompanyOS V0 contracts for ContractSpec. CompanyOS models company operations as explicit, inspectable, and bounded contracts: - company identity and operating model - authority, roles, principals, and accountable owners - autonomy policies and approval boundaries - company brain entries and knowledge gaps - decisions, commitments, work items, and graph edges - provider-agnostic operating connector capabilities - operator inbox items and operating review summaries ## Positioning Long-term governance/runtime layer behind proofs like CompanyOS VoiceOps. ## V0 scope This package intentionally implements contracts only. It does not include runtime execution, real providers, UI, app shells, modules, or autonomous customer sends. The V0 fixture proves one deterministic loop: ```txt customer onboarding-confusion conversation -> product feedback item -> customer commitment -> company brain entry / knowledge gap -> work graph decision/work item/edges -> ContractSpec proposal reference -> agent action proposal -> autonomy policy decision -> operator inbox item -> operating review summary ``` ## V1 operating loop The additive V1 surface extends the V0 loop with contract-only operating review primitives: - objectives, metrics, observations, outcomes, and drift signals - temporal company memory snapshots, facts, procedures, policies, and supersession refs - operating cadence specs, review input sets, and review output plans - bounded agent organization: roles, teams, delegation rules, handoff policies, conflict resolution policies, and tool assignments - agent-native operation/tool descriptors with dry-run and approval semantics - dynamic surface profiles for role, locale, risk, data-density, and guidance-mode descriptors - execution lifecycle, claim/lease, idempotency, policy-gate envelope, dispatch, receipt, checkpoint/replay, and outcome descriptors V1 remains provider-free and side-effect-free. It describes executable work semantics and evidence, but does not execute those operations. ## Operating graph / AI OS contracts The additive operating graph surface keeps Company Brain semantics inside CompanyOS without creating a separate package. It includes contract-only schemas for: - source systems and source record refs with evidence, freshness, ACL, and Knowledge fragment refs - graph nodes, edges, conflicts, tombstones, supersession, confidence, and review state - cross-source identity candidates and reviewed link decisions - actor/session/source ACL/policy permission requests, decisions, and redactions - data-transmission-compatible realtime room refs, idempotent change events, replay cursors - runbook procedures, readiness checks, and conformance cases that fail closed for stale, unauthorized, conflicted, or low-confidence evidence The package still does not ingest Knowledge, evaluate AuthOS/RBAC, open realtime transports, execute runbooks, or mutate providers. Those are substrate/runtime responsibilities. ## Agentic Company Brain contract surfaces The V2 operating graph packet also carries additive agentic Company Brain contracts for compiled, versioned skill/runbook artifacts; source/identity/ACL readiness checks; conformance evidence; and correction/outcome receipts. These surfaces prove that a Company Brain procedure can become an agent-readable artifact only when source records, identity decisions, ACL decisions, freshness, runbook readiness, and conformance evidence are explicit. They remain references and receipts only: no runtime execution, provider SDK, credential material, source mutation, or production write is introduced here. ## Managed CompanyOS contract inventory The additive managed CompanyOS surface classifies the public contracts and release anchors needed by managed app/API/worker lanes before those lanes depend on them: tenant profiles, managed/BYOK credential refs, workflow correlation, WebSocket job events, runtime health/degraded state, evidence receipts, package export, and docs-release evidence. The contracts remain provider-neutral, use redacted credential refs only, and fail closed when worker/WebSocket/replay/evidence degradation would otherwise be hidden behind green API health. ## Outcome value projection contracts `@lssm-tech/lib.companyos-spec/types/outcome-value` defines CompanyOS-only business value contracts over ContractSpec outcome claim refs: `BusinessValueEvent`, `OperationalValueClaim`, `BusinessValueReport`, `SalesValueReport`, `ReviewQueue`, `AutonomyReadinessSignal`, and `PromptSkillInfluenceReport`. These contracts do not redefine the generic `OutcomeClaim` kernel. Business meaning stays in CompanyOS, while the source claim, evidence, review, correction, and attribution identity remains a portable ContractSpec claim ref. No evidence means no business value event. ## Public entrypoints - `@lssm-tech/lib.companyos-spec` — root barrel - `@lssm-tech/lib.companyos-spec/types` — schemas and inferred types - `@lssm-tech/lib.companyos-spec/validation` — validation helpers - `@lssm-tech/lib.companyos-spec/fixtures` — deterministic V0 fixture - `@lssm-tech/lib.companyos-spec/docs` — documentation-facing DocBlocks - `@lssm-tech/lib.companyos-spec/types/operating-graph` — operating graph, identity, permission, realtime, and runbook schemas - `@lssm-tech/lib.companyos-spec/fixtures/v2-operating-graph` — deterministic operating graph fixture - `@lssm-tech/lib.companyos-spec/validation/semantic-operating-graph` — semantic validation for graph refs, fail-closed runbook readiness, compiled agentic artifacts, readiness checks, conformance evidence, and correction receipts - `@lssm-tech/lib.companyos-spec/docs/companyos-operating-graph.docblock` — documentation-facing operating graph DocBlock - `@lssm-tech/lib.companyos-spec/types/v1` — V1 operating loop schema/type - `@lssm-tech/lib.companyos-spec/types/objectives` — objective and metric contracts - `@lssm-tech/lib.companyos-spec/types/memory` — temporal memory contracts - `@lssm-tech/lib.companyos-spec/types/cadence` — operating cadence contracts - `@lssm-tech/lib.companyos-spec/types/agent-org` — bounded agent organization contracts - `@lssm-tech/lib.companyos-spec/types/agent-interfaces` — agent-native operation descriptors - `@lssm-tech/lib.companyos-spec/types/agentic-contracts` — compiled skill/runbook artifacts, agentic readiness, conformance evidence, and correction/outcome receipt contracts - `@lssm-tech/lib.companyos-spec/types/dynamic-surfaces` — dynamic surface profile descriptors - `@lssm-tech/lib.companyos-spec/types/execution` — execution lifecycle, policy-gate envelope, dispatch, receipt, and outcome descriptors - `@lssm-tech/lib.companyos-spec/types/managed-companyos` — managed tenant, integration ownership, workflow correlation, WebSocket, health, evidence receipt, and public-surface inventory contracts - `@lssm-tech/lib.companyos-spec/types/outcome-value` — CompanyOS business value projection contracts over ContractSpec OutcomeClaim refs - `@lssm-tech/lib.companyos-spec/fixtures/v1-operating-loop` — deterministic V1 fixture - `@lssm-tech/lib.companyos-spec/fixtures/v1-execution.parts` — deterministic execution/evidence fixture parts - `@lssm-tech/lib.companyos-spec/validation/semantic-v1-execution` — semantic validation for execution refs and fail-closed invariants ## Safety model Authority answers who may act and who is accountable. Autonomy answers how independently the action may proceed. They are related but not interchangeable. Customer-facing sends, legal/financial changes, and production-impacting work should default to approval-required or reserved-human-only until a future runtime explicitly proves stricter policy gates. V1 agent-native descriptors must require dry-run and approval semantics for execute-capable operations. Execution descriptors are evidence contracts, not runtime permission. A later CompanyOS module may coordinate agent, job, integration, human, dry-run, or manual-record lanes only after policy-gate evidence, idempotency, claim/lease, approval, and replay requirements are satisfied. Managed CompanyOS credential refs never carry raw secrets (`secretMaterialAvailable` is contractually false). Managed provider defaults, SDK wiring, procurement, and credential custody claims remain approval-gated outside this spec package. Dispatch authorization is modeled as an explicit substrate contract. `CompanyOsExecutionDispatchAuthorizationSchema` binds a dispatch lane to a policy-gate decision, accountable owner, approvals, and optional fail-closed `CompanyOsDispatchAuthorizationFailureSchema`. `CompanyOsSourceEvidenceRefSchema` records AIP, command-inbox, dry-run, operator, and outcome provenance with `authorizationAuthority: false`; source evidence can explain a request, but it cannot authorize dispatch. `CompanyOsPolicyReplayPacketSchema`, `CompanyOsReplayDeterminismCaseSchema`, `CompanyOsOperatorInboxRouteSchema`, and `CompanyOsOutcomeLinkageSchema` complete the deterministic replay, operator handoff, and outcome trace without introducing provider or module execution. ## Policy Runtime Hardening This package now includes additive policy-runtime contracts under `@lssm-tech/lib.companyos-spec/types/policy-runtime`, fixtures under `./fixtures/v1-policy-runtime`, and validation under `./validation/semantic-v1-policy-runtime`. These contracts extend existing CompanyOS policy gate request/decision semantics with authority, RBAC, risk, budget, tool-scope, dry-run, approval workflow, fallback, explanation, and assurance packet refs. They do not replace autonomy levels, authority graphs, execution plans, receipts, or outcome contracts. --- ## @lssm-tech/lib.content-gen Description: AI-powered content generation for blog, email, and social Path: packages/libs/content-gen URL: /llms/lib.content-gen # @lssm-tech/lib.content-gen Website: https://contractspec.io **AI-powered content generation for blog, email, and social.** ## What It Provides - **Layer**: lib. - **Consumers**: image-gen, voice, video-gen, bundles. - Related ContractSpec packages include `@lssm-tech/lib.ai-providers`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.ai-providers`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.content-gen` or `bun add @lssm-tech/lib.content-gen` ## Usage Import the root entrypoint from `@lssm-tech/lib.content-gen`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/generators` is part of the package's public or composition surface. - `src/i18n` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/seo` is part of the package's public or composition surface. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./generators` resolves through `./src/generators/index.ts`. - Export `./generators/blog` resolves through `./src/generators/blog.ts`. - Export `./generators/email` resolves through `./src/generators/email.ts`. - Export `./generators/landing-page` resolves through `./src/generators/landing-page.ts`. - Export `./generators/social` resolves through `./src/generators/social.ts`. - Export `./i18n` resolves through `./src/i18n/index.ts`. - Export `./i18n/catalogs` resolves through `./src/i18n/catalogs/index.ts`. - Export `./i18n/catalogs/en` resolves through `./src/i18n/catalogs/en.ts`. - Export `./i18n/catalogs/es` resolves through `./src/i18n/catalogs/es.ts`. - The package publishes 17 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run test` — bun test --pass-with-no-tests - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Resolve lint, build, and test failures across voice, workspace, library, and composio. - Add first-class transport, auth, versioning, and BYOK support across all integrations. - Add AI provider ranking system with ranking-driven model selection. - Add full i18n support across all 10 packages (en/fr/es, 460 keys). ## Notes - Generator interface is shared across media libs (image-gen, voice, video-gen); keep it stable. - i18n keys must stay in sync with consuming packages. --- ## @lssm-tech/lib.context-storage Description: Context pack and snapshot storage primitives Path: packages/libs/context-storage URL: /llms/lib.context-storage # @lssm-tech/lib.context-storage Website: https://contractspec.io **Context pack and snapshot storage primitives.** ## What It Provides - **Layer**: lib. - **Consumers**: module.context-storage. - Related ContractSpec packages include `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.context-storage` or `bun add @lssm-tech/lib.context-storage` ## Usage Import the root entrypoint from `@lssm-tech/lib.context-storage`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/in-memory-store.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/store.ts` is part of the package's public or composition surface. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./in-memory-store` resolves through `./src/in-memory-store.ts`. - Export `./store` resolves through `./src/store.ts`. - Export `./types` resolves through `./src/types.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run test` — bun test --pass-with-no-tests - `bun run lint` — bun lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rimraf dist .turbo - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add AI provider ranking system with ranking-driven model selection. ## Notes - `Store` interface is the contract boundary for persistence adapters; do not change its shape without updating all adapters. --- ## @lssm-tech/lib.contracts-integrations Description: Integration contract definitions for external services Path: packages/libs/contracts-integrations URL: /llms/lib.contracts-integrations # @lssm-tech/lib.contracts-integrations `@lssm-tech/lib.contracts-integrations` defines provider-agnostic contracts for integration specs, connection/runtime handling, secret resolution, health and telemetry, and capability-level provider interfaces such as LLM, embeddings, vector stores, email, and storage. Website: https://contractspec.io ## Installation `bun add @lssm-tech/lib.contracts-integrations` or `npm install @lssm-tech/lib.contracts-integrations` ## What belongs here This package owns the contract layer for external integrations: - Integration spec model and registries. - Connection, auth, transport, versioning, and BYOK contracts. - Runtime guards and health/telemetry helpers. - Secret provider abstraction and secret-provider manager. - Capability-level provider interfaces such as `LLMProvider` and `VectorStoreProvider`. - Provider delta contracts for cursor, lease, webhook, replay, dedupe, idempotency, and tombstone state. - Shipped provider/domain spec registrations. - Integration connection operations contracts. Use this package when you need shared integration contracts. Do not use it as the SDK-backed implementation layer or as the integration persistence runtime. ## Core workflows ### Define and register an integration spec ```ts import { defineIntegration, IntegrationSpecRegistry, } from "@lssm-tech/lib.contracts-integrations"; const registry = new IntegrationSpecRegistry(); const spec = defineIntegration({ meta: { key: "payments.example", version: 1, title: "Example Payments", owners: ["@platform.integrations"], tags: ["payments"], category: "payments", }, supportedModes: ["managed", "byok"], capabilities: { provides: [{ key: "payments.process" }], }, configSchema: { schema: { type: "object" }, }, secretSchema: { schema: { type: "object" }, }, }); registry.register(spec); ``` ### Consume runtime contracts with secrets and guards ```ts import { IntegrationCallGuard, } from "@lssm-tech/lib.contracts-integrations/integrations/runtime"; import { EnvSecretProvider, SecretProviderManager, } from "@lssm-tech/lib.contracts-integrations/integrations/secrets"; const secretProvider = new SecretProviderManager({ providers: [ { provider: new EnvSecretProvider(), priority: 100 }, ], }); const guard = new IntegrationCallGuard(secretProvider); const result = await guard.executeWithGuards( "primary-llm", "chat", {}, resolvedAppConfig, async (connection, secrets) => { return llmAdapter.chat(connection, secrets, input); } ); ``` Typical flow: 1. Declare an `IntegrationSpec` that describes config, secrets, auth, transport, and version policy. 2. Register specs in an `IntegrationSpecRegistry` or use `createDefaultIntegrationSpecRegistry()`. 3. Bind tenant connections and secret references outside this package. 4. Resolve secrets and execute guarded runtime calls through `IntegrationCallGuard`. Default shipped provider specs are additive catalog entries. Most providers in `createDefaultIntegrationSpecRegistry()` advertise both `managed` and `byok`, while BYOK-only providers carry explicit credential-manifest exemption metadata for unsupported managed mode. Consumers can still narrow a concrete tenant connection through app-config slot `allowedModes` or connection ownership mode validation. ### Publish and query the integration catalog The production registry is split into two layers: 1. **Static catalog definitions** describe what can appear in an integration catalog: shipped integration specs, integration package wrappers, provider implementation manifests, and explicit exception records for helper modules that are not user-facing integrations. 2. **Tenant overlays** describe runtime state outside this package: catalog availability (`available`, `hidden`, `disabled`, or `exception`) and connection activation (`not-connected`, `active`, `inactive`, `pending`, `disabled`, `error`, or `unknown`). Keep these layers separate. Static definitions must be deterministic metadata only; they must not contain tenant connection state, raw credentials, provider SDK clients, network calls, filesystem discovery, or app/example imports. Apps and bundles should join catalog definitions with overlays through provider-neutral view records before rendering or filtering. When adding a provider: 1. Add or update the `IntegrationSpec` and register it in `createDefaultIntegrationSpecRegistry()` when the contracts package owns the spec. 2. Add package-local catalog contribution metadata in the implementation package when the record represents a provider implementation or package wrapper. 3. Include managed/BYOK support metadata for every user-facing record. If a module is helper-only or a mode is unsupported, add an explicit exception rationale rather than letting guard checks infer intent. 4. Run the registry completeness guard plus the package tests/typecheck before promotion. The expected verification set for registry changes is: ```bash bun test packages/libs/contracts-integrations/src/integrations/catalog.test.ts packages/libs/contracts-integrations/src/integrations/providers/providers.test.ts packages/libs/contracts-integrations/src/integrations/providers/provider-modes-coverage.test.ts bun run --cwd packages/libs/contracts-integrations typecheck bun scripts/check-integration-registry-completeness.ts ``` ### Model provider delta sync state ```ts import type { ProviderDeltaSyncState, } from "@lssm-tech/lib.contracts-integrations/integrations/providers/provider-delta"; const delta: ProviderDeltaSyncState = { lease: { holder: "knowledge-sync-worker", expiresAt: "2026-04-30T13:00:00.000Z", renewalWindowMs: 60_000, }, cursor: { cursor: "gmail-history-123", watermarkVersion: "history-v1", }, webhookChannel: { channelId: "google-channel-1", resourceId: "google-resource-1", expiresAt: "2026-04-30T14:00:00.000Z", }, providerEventId: "provider-event-1", dedupeKey: "gmail:provider-event-1", idempotencyKey: "tenant:gmail:provider-event-1", replayCheckpoint: { checkpointId: "replay-1", }, }; ``` Delta-aware providers should attach this state before runtime sync starts so callers can renew leases, resume from provider cursors/watermarks, preserve webhook expiry, dedupe provider events, run idempotently, replay from checkpoints, and skip tombstoned source records. ## API map ### Spec model and registries - `IntegrationSpec`: provider-agnostic contract for a shipped or custom integration. - `IntegrationSpecRegistry`: registry for integration specs with category-based lookup. - `defineIntegration`: helper for authoring specs. - `makeIntegrationSpecKey`: canonical key formatter for spec identity. - `createDefaultIntegrationSpecRegistry`: registry builder for shipped provider specs. - `filterByTransport`, `filterByAuthMethod`, `filterVersioned`, `filterByokRotatable`: spec filtering helpers. ### Newly registered AI and web-research providers - `ai-voice.slng`: SLNG API-key HTTP/WebSocket contract for TTS, STT, and voice-agent infrastructure. Public docs do not currently expose official MCP or OAuth app support. - `ai-voice.gradium`: Gradium REST/WebSocket contract for realtime TTS/STT. Public docs expose API-key access and Python SDK; no public JS SDK, MCP, or OAuth app surface is documented. - `ai-voice.fal`: Fal generative-media contract with official `@fal-ai/client`, REST, hosted MCP, queue, realtime, storage, and media capabilities. Public MCP auth is API-key based. - `web-research.tavily`: Tavily search/extract/crawl/research contract with official `@tavily/core`, REST, local/remote MCP, and OAuth-enabled remote MCP. ### Connections, auth, transport, versioning, and BYOK - `IntegrationConnection` and `ConnectionStatus`: tenant-bound connection shape and readiness state. - `IntegrationAuthConfig`, `findAuthConfig`, `supportsAuthMethod`: auth contract and helpers. - `IntegrationTransportConfig`, `findTransportConfig`, `supportsTransport`: transport contract and helpers. - `IntegrationVersionPolicy`, `resolveApiVersion`, `getVersionInfo`, `isVersionDeprecated`, `getActiveVersions`: API-version policy helpers. - `ByokKeyLifecycle` and BYOK metadata/result types: key validation and rotation contracts. - `IntegrationCredentialManifest` and helpers from `./integrations/credentials`: managed/BYOK credential requirements, env aliases, validation strategy, rotation policy, and compatibility mapping from legacy schemas. ### Runtime, health, and telemetry - `IntegrationCallGuard`: guarded execution with secret resolution, retries, and telemetry. Exported from `./integrations/runtime`. - `IntegrationCallResult`, `IntegrationCallError`, `IntegrationTelemetryEvent`: runtime result/telemetry contracts. - `IntegrationHealthService`: structured health checks and telemetry emission. - `resolveIntegrationRequestContext`, `resolveAuthMethod`, `DefaultTransportResolver`, and related helpers: runtime resolution utilities. ### Secrets - `SecretProvider`: provider-agnostic secret backend interface. Exported from `./integrations/secrets/provider`. - `SecretProviderManager`: priority-ordered composite secret provider. Exported from `./integrations/secrets` or `./integrations/secrets/manager`. - `SecretProviderError`: structured secret-provider error. - `parseSecretUri`: parse `provider://path?...` references. - `normalizeSecretPayload`: normalize text/binary/base64 payloads before writes. ### Operations and provider interfaces - Integration connection operations: `CreateIntegrationConnection`, `UpdateIntegrationConnection`, `DeleteIntegrationConnection`, `ListIntegrationConnections`, `TestIntegrationConnection`. - Frequently consumed provider contracts: - `LLMProvider` - `EmbeddingProvider` - `VectorStoreProvider` - `EmailInboundProvider` - `EmailOutboundProvider` - `GoogleDriveProvider` - `ObjectStorageProvider` - Delta-aware provider contracts: - `ProviderDeltaSyncState` - `ProviderDeltaEnvelope` - `isProviderDeltaTombstoned` ## Public surface The root barrel re-exports common integration contracts from: - spec and registry helpers - auth, binding, BYOK, connection, transport, and versioning - health helpers - operations contracts - provider interfaces - selected domain contracts such as `health`, `meeting-recorder`, and `openbanking` Runtime and secret-management helpers live under `./integrations/runtime` and `./integrations/secrets*`. The exhaustive public surface lives under `./integrations/*` in `package.json`. Use the README as a guide to the main clusters. Use `package.json` as the authoritative export map for all subpaths, including the many provider and domain-specific entrypoints. ## Operational semantics and gotchas - `IntegrationCallGuard` fails fast when a slot is missing or a connection is not ready. - `IntegrationCallGuard` defaults to `3` attempts with `250 ms` backoff. - Retry only happens when `shouldRetry()` returns true; the default implementation looks for a truthy `retryable` field on the error. - `IntegrationSpec` carries config and secret schemas, but raw secrets live behind `secretRef` and `SecretProvider`. - `SecretProviderManager` delegates in descending priority order and preserves registration order for ties. - `resolveApiVersion()` uses connection override first, then policy default. - `IntegrationHealthService.check()` returns structured results instead of throwing health failures upward. - Registry filters only match specs that explicitly declare auth methods, transports, version policies, or BYOK support. - Credential manifests describe required config and secret references per ownership mode; they do not carry raw credential values. - `ProviderDeltaSyncState` is the shared contract for sync leases, provider cursors/watermarks, webhook channel expiry, replay checkpoints, dedupe/idempotency keys, provider event IDs, and tombstones. - Gmail and Google Drive specs advertise `provider.delta.watch`; Drive also advertises `knowledge.ingestion.drive`. - This package defines contracts and shipped spec registrations. SDK-backed implementations live elsewhere. ## When not to use this package - Do not use it as a provider SDK implementation layer. - Do not use it as the secret storage backend itself. - Do not use it as the integration persistence database layer. - Do not use it as the app-config slot/binding resolver. ## Related packages - `@lssm-tech/lib.contracts-spec`: upstream spec system consumed by integration contracts and operations. - `@lssm-tech/lib.schema`: schema types used by operation and config shapes. - `@lssm-tech/integration.runtime`: runtime composition layer built on top of these contracts. - `@lssm-tech/integration.providers-impls`: SDK-backed provider implementations for many of these interfaces. - `@lssm-tech/lib.knowledge`: major consumer of embedding, vector-store, email, storage, and LLM provider interfaces. ## Local commands - `bun run lint:check` - `bun run typecheck` - `bun test` ### Matrix and bridge-aware messaging `messaging.matrix` models Matrix as an additive managed/BYOK messaging integration. It declares `matrix-js-sdk` as the preferred SDK transport with REST/WebSocket hints, Matrix homeserver and room configuration, bearer token secrets, and optional bridge metadata. Bridge metadata is descriptive and provider-agnostic: it can explain that Matrix rooms bridge to Slack, Telegram, WhatsApp, Discord, email, SMS, IRC, XMPP, or other channels, but it must not replace direct provider specs when first-party integrations are configured. This package does not provision homeservers, automate hosted provider signup, install bridges, or endorse a hosting provider. --- ## @lssm-tech/lib.contracts-library Description: (none) Path: packages/libs/contracts-library URL: /llms/lib.contracts-library # @lssm-tech/lib.contracts-library **Contract definitions for library templates and local runtime.** ## What It Provides - **Layer**: lib. - **Consumers**: `bundle.library`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.contracts-library` or `bun add @lssm-tech/lib.contracts-library` ## Usage Import the root entrypoint from `@lssm-tech/lib.contracts-library`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/index.ts` is the root public barrel and package entrypoint. - `src/templates` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./templates` resolves through `./src/templates/index.ts`. - Export `./templates/messaging` resolves through `./src/templates/messaging.ts`. - Export `./templates/recipes` resolves through `./src/templates/recipes.ts`. - Export `./templates/todos` resolves through `./src/templates/todos.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun run lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rm -rf dist - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Template contracts define the shape consumed by bundle.library — breaking changes cascade to all template renderers. - Keep contract schemas additive; avoid removing or renaming fields without a migration path. --- ## @lssm-tech/lib.contracts-runtime-client-react Description: React runtime adapters for ContractSpec contracts Path: packages/libs/contracts-runtime-client-react URL: /llms/lib.contracts-runtime-client-react # @lssm-tech/lib.contracts-runtime-client-react **React runtime adapters for ContractSpec contracts.** ## What It Provides - **Layer**: lib. - **Consumers**: design-system, presentation-runtime-react, bundles. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.contracts-runtime-client-react` or `bun add @lssm-tech/lib.contracts-runtime-client-react` ## Usage Import the root entrypoint from `@lssm-tech/lib.contracts-runtime-client-react`, or choose a documented subpath when you only need one part of the package surface. The form renderer supports the expanded FormSpec field set: readonly inputs, email, autocomplete, address, phone, date, time, datetime, semantic groups, repeated grouped arrays, grid layout hints, progressive `layout.flow` sections/steps, and text/textarea/email input groups. Drivers are expected to provide dedicated slots for rich widgets plus shadcn/Radix-style `Field*` and optional `InputGroup*` slots. Email fields render through the standard input slot with native email input behavior. When input-group slots are absent, text, email, and textarea fields fall back to plain controls. Autocomplete fields support local filtering and resolver-backed search. Resolver calls receive the current query, watched dependency values, field name, and an `AbortSignal` through the existing resolver args object; stale responses are ignored and selected remote options remain visible when later searches return a different result set. Custom autocomplete driver slots can read optional `loading`, `error`, `emptyText`, `loadingText`, and `errorText` props to expose async state. ### PWA update checks `usePwaUpdateChecker` from `@lssm-tech/lib.contracts-runtime-client-react/pwa-update-client` checks the `pwa.update.check` API, exposes required/blocking versus optional update state, supports polling, and delegates actual service worker activation to a host-provided `onApply` callback. ### Adaptive form support `resolveAdaptiveFormExperience` from `@lssm-tech/lib.contracts-runtime-client-react/adaptive-form` maps `ResolvedAdaptiveExperience` into generic form guidance, density, control, and recovery defaults. It is a lightweight adapter for form renderers and vertical applications that want adaptive behavior without coupling forms to analytics or product-specific labels. Use the result as an editable runtime recommendation. It should not override permissions, validation, authorization, or business rules. ### Query and mutation hooks `useContractQuery(envelope, options?)` and `useContractMutation(options?)` are **thin bindings over the in-house engine** in [`@lssm-tech/lib.contracts-runtime-core`](../contracts-runtime-core) — no `@tanstack/*`. Wrap the surface in `ContractDataEngineProvider` with a `createDataEngine({ transport })`, then: - `useContractQuery` returns the canonical `QueryState` verbatim (`status`, `fetchStatus`, `data`, `error`, `cacheStatus`, `isStale`, `isOffline`, `conflict`, `versionToken`) plus `refetch` — so it flows straight into the I/O-free design-system `QueryState` components with zero adapter. - `useContractMutation` returns the canonical mutation state (`status`, `data`, `problem`, `conflictOutcome`, `isPending`) plus `mutate(request, { optimistic? })`. The engine owns the cache, request dedup, durable offline queue + replay, etag conflict resolution, optimistic apply/rollback, and recoverable auth-expiry. This package no longer ships cache-key/storage/policy helpers or a `./query-client` subpath — they were removed in the data-fetching ecosystem reset (the engine owns all of it). `parseContractResponse` (structuredContent-first MCP/GraphQL decode) remains for non-engine response interpretation. ## Architecture - `src/adaptive-form.ts` is part of the package's public or composition surface. - `src/drivers` is part of the package's public or composition surface. - `src/feature-render.ts` is part of the package's public or composition surface. - `src/form-render.impl.tsx` is part of the package's public or composition surface. - `src/form-render.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./adaptive-form` resolves through `./src/adaptive-form.ts`. - Export `./drivers/rn-reusables` resolves through `./src/drivers/rn-reusables.ts`. - Export `./drivers/shadcn` resolves through `./src/drivers/shadcn.ts`. - Export `./feature-render` resolves through `./src/feature-render.ts`. - Export `./form-render` resolves through `./src/form-render.ts`. - Export `./form-render.impl` resolves through `./src/form-render.impl.tsx`. - Export `./pwa-update-client` resolves through `./src/pwa-update-client.tsx`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun run lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rm -rf dist - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add generic adaptive form experience helpers for runtime guidance defaults. ## Notes - Driver interface must stay compatible with both shadcn and RN Reusables. - Form rendering pipeline is a critical path; test thoroughly before changing. --- ## @lssm-tech/lib.contracts-runtime-core Description: Framework-neutral in-house query/cache/offline engine and Transport port for ContractSpec data fetching Path: packages/libs/contracts-runtime-core URL: /llms/lib.contracts-runtime-core # @lssm-tech/lib.contracts-runtime-core Framework-neutral, in-house runtime for the canonical ContractSpec data-fetching protocol. It depends only on [`@lssm-tech/lib.contracts-spec`](../contracts-spec) — the frozen protocol primitives (`QueryEnvelope`, `QueryResultEnvelope`, `ContractResult`, `CacheStatus`, `InvalidationTag`, `ConflictPolicy`, `VersionToken`, `QueryConsistency`, `QueryState`). ## Scope This package hosts: - the `Transport` port (`execute()` + optional `subscribe()` realtime seam), - the in-house query/cache engine (`createDataEngine`: store, dedup, retry/backoff, background revalidation, GC) — **no `@tanstack/*` dependency**, - the durable offline mutation queue + replay-on-reconnect, - the conflict-resolver registry (server-wins default, field-merge, client-wins, surface, CRDT-via-injection, custom), - the storage port + shipped platform defaults (IndexedDB `.web` / AsyncStorage `.native`), - the reachability **input** port (the engine never imports `integrations/*`), - tag-invalidation runtime, observability, persisted-state redaction, - `economic-evidence-attached` engine events and observability bindings that carry provider-neutral usage/cost/budget/replay/projection refs without importing billing, finance, provider, or analytics SDKs, - the re-homed `Collaboration*` envelopes (consumed by `integration.crdt-loro`). ## Usage Native apps can wire durable storage through the published Expo/React Native subpath: ```ts import AsyncStorage from "@react-native-async-storage/async-storage"; import { createAsyncStorage } from "@lssm-tech/lib.contracts-runtime-core/storage/async-storage"; const storage = createAsyncStorage(AsyncStorage); ``` `createDataEngine({ transport })` returns a `DataEngine` exposing `query`/`getState`/`subscribe`/`invalidateTags`/`refresh`/`emitConflict`/ `mutate`/`drain`/`resume`/`dispose` over one shared cache. The React binding (`useContractQuery`/`useContractMutation` in `@lssm-tech/lib.contracts-runtime-client-react`) is thin; this core stays framework-neutral and is also consumed by the realtime worker and the provider resolver. ## Local/offline capability mode `createDataEngine` now owns the semantic local/offline toggle through `localOffline`. The safe default is `online-only`: online queries and direct online mutations work, but the engine does not persist local data, serve prior local data while offline, or enqueue offline mutations. | Mode | Cache/read behavior | Offline mutations | | --- | --- | --- | | `online-only` | No local/offline cache; offline reads return the canonical offline/no-data state. | Disabled; returns `OFFLINE_QUEUE_DISABLED` without queueing. | | `memory-cache` | Same-engine in-memory cache only; nothing persists across engine instances. | Disabled while offline. | | `offline-capable` | Uses the supplied storage/cache seams for warm offline reads, queue/replay, conflicts, and maintenance. | Queued and replayed when reachability returns. | Use the pure resolver when policy comes from env/config/feature flags: ```ts import { createDataEngine, createMemoryStorage, resolveLocalOfflinePolicy, } from "@lssm-tech/lib.contracts-runtime-core"; const localOffline = resolveLocalOfflinePolicy({ env: process.env.CONTRACTSPEC_LOCAL_OFFLINE, flag: featureFlags.localOffline, }); const engine = createDataEngine({ transport, localOffline, advanced: localOffline.mode === "offline-capable" ? { storage: createMemoryStorage() /* use IndexedDB/AsyncStorage in apps */ } : undefined, }); ``` `localOffline` is the source of truth. Low-level composition seams now live under `advanced`; `online-only` rejects `advanced.storage` and `advanced.cacheStore`, while `advanced.reachability` remains valid in every mode. `offline-capable` requires an explicit `advanced.storage` so durable local persistence is never enabled accidentally. ## Economic Evidence Observability `attachObservability()` consumes `economic-evidence-attached` events automatically. It increments `contracts_runtime_economic_evidence_refs_total` and logs `economic.evidence.attached` with only operation key, latency, ref count, and allowlisted ref fields (`id`, `kind`, optional `source`). Raw provider receipts, prompts, database payloads, replay payloads, and unsafe ref IDs containing PII/secret-shaped values are rejected or dropped before logs consume the event. ## Status Engine landed (B1a synchronous + B1b offline/conflict). Full WebSocket realtime delivery on `subscribe()` is a follow-on; the seam is defined and the realtime worker runs on it. This package absorbed the former `@lssm-tech/lib.data-transmission-{spec,runtime}` concepts. --- ## @lssm-tech/lib.contracts-runtime-server-graphql Description: GraphQL server runtime adapters for ContractSpec contracts Path: packages/libs/contracts-runtime-server-graphql URL: /llms/lib.contracts-runtime-server-graphql # @lssm-tech/lib.contracts-runtime-server-graphql **GraphQL server runtime adapters for ContractSpec contracts.** ## What It Provides - **Layer**: lib. - **Consumers**: bundles, apps with GraphQL. - Related ContractSpec packages include `@lssm-tech/lib.contracts-runtime-server-rest`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-runtime-server-rest`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.contracts-runtime-server-graphql` or `bun add @lssm-tech/lib.contracts-runtime-server-graphql` ## Usage Import the root entrypoint from `@lssm-tech/lib.contracts-runtime-server-graphql`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/graphql-pothos.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./graphql-pothos` resolves through `./src/graphql-pothos.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun run lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rm -rf dist - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Pothos builder integration must stay compatible with graphql-core and graphql-prisma. - Do not introduce direct schema mutations outside the Pothos pipeline. --- ## @lssm-tech/lib.contracts-runtime-server-mcp Description: MCP server runtime adapters for ContractSpec contracts Path: packages/libs/contracts-runtime-server-mcp URL: /llms/lib.contracts-runtime-server-mcp # @lssm-tech/lib.contracts-runtime-server-mcp **MCP server runtime adapters for ContractSpec contracts.** ## What It Provides - **Layer**: lib. - **Consumers**: bundles, CLI, VS Code extension. - `src/mcp/` contains MCP handlers, tools, prompts, and resources. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.logger`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - `src/mcp/` contains MCP handlers, tools, prompts, and resources. ## Installation `npm install @lssm-tech/lib.contracts-runtime-server-mcp` or `bun add @lssm-tech/lib.contracts-runtime-server-mcp` ## Usage Import the root entrypoint from `@lssm-tech/lib.contracts-runtime-server-mcp`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/index.ts` is the root public barrel and package entrypoint. - `src/mcp/` contains MCP handlers, tools, prompts, and resources. - `src/provider-mcp.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./mcp/createMcpServer` resolves through `./src/mcp/createMcpServer.ts`. - Export `./mcp/mcpTypes` resolves through `./src/mcp/mcpTypes.ts`. - Export `./mcp/registerPresentations` resolves through `./src/mcp/registerPresentations.ts`. - Export `./mcp/registerPrompts` resolves through `./src/mcp/registerPrompts.ts`. - Export `./mcp/registerResources` resolves through `./src/mcp/registerResources.ts`. - Export `./mcp/registerTools` resolves through `./src/mcp/registerTools.ts`. - Export `./provider-mcp` resolves through `./src/provider-mcp.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun run lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rm -rf dist - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add changesets and apply pending fixes. ## Notes - MCP protocol compliance is critical; transport layer must stay spec-compliant. - Do not introduce runtime-specific (Node/browser) dependencies in the transport layer. --- ## @lssm-tech/lib.contracts-runtime-server-rest Description: REST server runtime adapters for ContractSpec contracts Path: packages/libs/contracts-runtime-server-rest URL: /llms/lib.contracts-runtime-server-rest # @lssm-tech/lib.contracts-runtime-server-rest **REST server runtime adapters for ContractSpec contracts.** ## What It Provides - **Layer**: lib. - **Consumers**: bundles, all REST apps. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.contracts-runtime-server-rest` or `bun add @lssm-tech/lib.contracts-runtime-server-rest` ## Usage Import the root entrypoint from `@lssm-tech/lib.contracts-runtime-server-rest`, or choose a documented subpath when you only need one part of the package surface. ### PWA update checks `createPwaUpdateCheckHandler` from `@lssm-tech/lib.contracts-runtime-server-rest/pwa-update` turns a manifest resolver into a handler for the `pwa.update.check` contract. It merges app defaults with release overrides and returns `none`, `optional`, or `required` update decisions. ## Architecture - `src/contracts-adapter-hydration.ts` is part of the package's public or composition surface. - `src/contracts-adapter-input.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/rest-elysia.ts` is part of the package's public or composition surface. - `src/rest-express.ts` is part of the package's public or composition surface. - `src/rest-generic.ts` is part of the package's public or composition surface. - `src/rest-next-app.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./contracts-adapter-hydration` resolves through `./src/contracts-adapter-hydration.ts`. - Export `./contracts-adapter-input` resolves through `./src/contracts-adapter-input.ts`. - Export `./rest-elysia` resolves through `./src/rest-elysia.ts`. - Export `./rest-express` resolves through `./src/rest-express.ts`. - Export `./rest-generic` resolves through `./src/rest-generic.ts`. - Export `./rest-next-app` resolves through `./src/rest-next-app.ts`. - Export `./rest-next-pages` resolves through `./src/rest-next-pages.ts`. - Export `./pwa-update` resolves through `./src/pwa-update.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — bun run prebuild && bun run build:bundle && bun run build:types - `bun run lint` — bun run lint:fix - `bun run lint:check` — biome check . - `bun run lint:fix` — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write . - `bun run typecheck` — tsgo --noEmit - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run clean` — rm -rf dist - `bun run build:bundle` — contractspec-bun-build transpile - `bun run build:types` — contractspec-bun-build types - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - High blast radius — all REST APIs depend on this package. - Framework adapters (Elysia, Express, Next.js) must stay independent of each other. - Do not introduce cross-adapter coupling. --- ## @lssm-tech/lib.contracts-spec Description: Spec definitions and registries for ContractSpec Path: packages/libs/contracts-spec URL: /llms/lib.contracts-spec # @lssm-tech/lib.contracts-spec Core contract declarations, registries, and shared execution primitives for ContractSpec. 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. 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`). - 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, and presentation-binding requirements without owning product copy or React rendering. - Core registries (`OperationSpecRegistry`, `EventRegistry`, `FormRegistry`, `ResourceRegistry`). - 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 ```bash npm install @lssm-tech/lib.contracts-spec @lssm-tech/lib.schema # or bun add @lssm-tech/lib.contracts-spec @lssm-tech/lib.schema ``` ## 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. ## 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. - `@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 { createTranslationRuntime } 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 runtime = createTranslationRuntime({ defaultLocale: "en-US", requestedLocales: ["en-US"], specs: [messages], }); runtime.tUnknown("cart.items", { count: 3 }); // "3 items" ``` ### Static translation diagnostics Static catalog diagnostics are exported from `@lssm-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/libs/example", catalogDir: "packages/libs/example/src/i18n/catalogs", catalogs: [enMessages, frMessages, esMessages], baseLocale: "en", expectedLocales: ["en", "fr", "es"], }, ]); if (!report.ok) { console.error(report.issues); } ``` The report shape is intentionally CI-friendly: `{ ok, summary, issues }`. Issue codes include missing catalogs/keys, extra keys, blank values, invalid ICU messages, placeholder non-parity, invalid shapes, locale non-parity, duplicate bundle identities, `unsupported_locale_claim` (a catalog's `supportedLocales` declares a locale with no matching catalog in the group), and `manifest_spec_key_missing` (a manifest route entry references a specKey absent from the registered catalog set). Use `validateManifestCatalogDrift(entries, knownSpecKeys)` with a `ManifestRouteEntry[]` list to surface drift between route shard manifests and the registered catalog. The `contractspec i18n check` command is the CLI wrapper around this API, and `.contractsrc.json` can include an optional top-level `i18n` diagnostics block with `catalogGlob`, `baseLocale`, `locales`, `allowExtraKeys`, `checkPlaceholders`, `checkIcu`, and `strict`. ### Migration notes - Prefer `meta.key: "bundle.messages"` plus `locale: "fr-FR"` over keys like `bundle.messages.fr-FR`. - Use `channels`, `audience`, `modality`, `safety`, and `rendering` metadata for Managed CompanyOS copy selection and policy-aware rendering; keep values descriptive and non-empty so validation can catch unsafe catalog gaps. - `createI18nFactory` now supports SSR snapshot/hydration directly via `.snapshot()` / `.hydrationPayload()` on the factory instance and `createI18nFactoryFromHydrationPayload(payload)` for client rehydration — prefer this over the deprecated `createTranslationRuntime` for new integrations. - `resolveLocaleWithin(supportedLocales, defaultLocale, runtimeLocale?, optionsLocale?)` is exported for callers that resolve locale outside a factory instance. - `RouteShardManifest` and `defineRouteShardManifest` live in the bundle/app layer (not `contracts-spec`) — the contract layer stays route-agnostic. Use `validateManifestCatalogDrift` to catch drift between manifests and registered catalogs. - i18next adapter support lives downstream at `@lssm-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`). The deprecated `createTranslationRuntime` engine is dead-but-present; its removal is a residual follow-up. - For React Native, the core runtime uses no DOM APIs; hosts are responsible for locale detection and any required `Intl` polyfills. - **Optimization wave (Model A — per-request inline payload):** O2+O3 reduce the per-request inline `