# ContractSpec — LLM Guide (Full) > Aggregated content from all packages. For summary, see /llms Generated: stable Packages: 561 ## Agent notes - Changelog data is available at `GET https://contractspec.io/api/changelog` returning JSON. Append `?version=` or `?slug=` for detail. Before modifying any `@lssm-tech/*` package, check the changelog API for recent releases affecting that package and review associated migration instructions or upgrade steps. --- ## @lssm-tech/bundle.alpic Description: Alpic MCP server and ChatGPT App hosting bundle Path: packages/bundles/alpic URL: /llms/bundle.alpic # @lssm-tech/bundle.alpic Website: https://contractspec.io **Re-exports the Alpic module to provide MCP server and ChatGPT App hosting helpers as a single bundle entry point.** ## What It Provides - **Layer**: bundle - **Consumers**: `apps/alpic-mcp` ## Installation `npm install @lssm-tech/bundle.alpic` or `bun add @lssm-tech/bundle.alpic` ## Usage Import the root entrypoint from `@lssm-tech/bundle.alpic`, or use one of the documented subpaths when you want a narrower surface area. ## Public Entry Points - `.` — `./src/index.ts` ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Package exports - Make workspace tests pass without local test files ## Notes - No business logic lives here; all implementation is in `module.alpic`. - Changes to exports must stay in sync with the module's public API. --- ## @lssm-tech/bundle.career-experience Description: Brand-neutral focused career workspace experience (shell, profile facts editor, documents entry, session boundary, binding-required panel and application-setup building blocks) composed over native job-application owners; the six-step onboarding closure is exported; the acquisition and activation-screen journeys stay deferred until their native owners land. Path: packages/bundles/career-experience URL: /llms/bundle.career-experience # @lssm-tech/bundle.career-experience Private, brand-neutral focused career workspace experience (E layer, LSSM consolidation CL-24 / CAREER-UI-IMPORT-G4). It ports the selected focused B2C donor UI (source `a5c7d6a8`) as reusable React composition over the native job-application owners. Every career brand reuses it through its own brand composition bundle, which supplies copy and presentation only. - Composition only. Behavior, writers, stores and migrations stay with the job-application domain owners (`lib.job-application-runtime`, `bundle.job-application`, `integration.job-application-store`); provider effects stay in integrations. This bundle never creates an identity, grant, fact writer, profile store or document store. - No brand names, brand copy, pricing or hostnames. Brand copy (for example the focused workspace, profile, documents, onboarding and application-setup French dictionaries) lives in the brand composition bundle and reaches components through props or `ApplicationSetupCopyProviderV1`. - Unported source routes stay visible but disabled; a slot is enabled only when the host mounts a real native client. Disabled or binding-required controls never claim completion. ## Entrypoints - `./shared/contracts`: route/slot/navigation contracts (`CareerRouteV1`, `CareerWorkspaceSlotsV1`, `FOCUSED_CAREER_NAVIGATION_V1`). - `./shared/document-client`, `./shared/document-workspace`, `./shared/documents-entry.web`: bounded documents entry and checkpoint recovery over the native document store (HF12 entry only). - `./shared/documents/contract`, `./shared/documents/workspace.web`, `./shared/documents/documents.css`: the documents workspace (focused layout): library cards per version family, editor beside a paper preview (Edit/Preview switch on small screens), a guided review with highlighted critique statements, one privacy confirmation and one Approve, version history and comparison, approved-only downloads and CV import. The host binds `CareerDocumentsPortV1` to request-bound actions and supplies copy and file URLs; child routes are `/documents/` and `/documents//versions/` (`/documents/cv` is the library). - `./shared/session-boundary.web`: session display boundary used by the host; a principal is never converted to a candidate by the UI. - `./shared/navigation`: per-epoch navigation/recovery controller (pure); `href` maps a route to the host URL. - `./shared/private-profile-editor`, `./shared/profile-workspace`, `./shared/profile-editor.web`, `./shared/native-panels.web`: per-fact private profile editor controller (materialized byte-identically from the profile UI relocation candidate f4cd0fab), the presentation aggregation, the facts editor and the native profile+documents panels. Native ports are host-supplied; nothing here holds a writer or store. - `./shared/binding-required.web`: a mounted route whose native client is not bound; every action renders disabled. - `./focused/shell.web`, `./focused/history.web`, `./focused/workspace.css`: focused workspace shell, history binding (optional host-supplied `basePath`; the bundle never names one) and source design tokens (HF29). `workspace.css` and `focused/fonts.css` reference the bundled Inter files in `src/focused/assets/fonts/` (SIL OFL 1.1, see `LICENSE.txt`, `PROVENANCE.md` and `SHA256SUMS.txt`). - `./focused/jobs/*`: brand-neutral jobs kit ported from the focused donor (FeedOffer, JobBrief, FeedQuickFilters, saved searches, skipped review, monitoring, swipe; feed-v3.css as `./focused/jobs/jobs.css`). `contracts` defines the serializable `FocusedJobCardV1`/`FocusedJobDetailV1` props a host projects; `format`, `routes`, `search-controller`, `saved-searches-controller`, `swipe-controller` and `monitoring` are pure and unit-tested; the `.web` screens render them. FR/EN/ES copy (`copy`). Hosts bind `search`/`get`/`prepare`; dispositions, saved-search commands and the application policy are optional and their controls stay hidden or report `binding_required` when unbound. Links keep real hrefs and never intercept modifier clicks. ## Deferred closures The profile workspace/editor/experience fields (HF09) and native panels are no longer deferred (TAFIO-HOST-COMPOSITION-G4): their native owner (`contracts/profile-editor*`) landed in train 1 and the controller is materialized here. The six-step onboarding closure is no longer deferred either (g6 train, TAFIO-WORKSPACE-BIND-G5 request): its native owners (`contracts/candidate-activation`, `contracts/candidate-search*`) landed in train 2, so `./focused/onboarding/six-step-controller`, `six-step-contract`, `six-step-screen.web`, `native-field`, `native-activation-adapter.server` and `native-search-adapter.server` are exported and typechecked with their local closure (`contracts`, `controls.web`, `profile-sections.web`, `source-field.web`), and `six-step-controller.test.ts` runs again. No host binds them yet. The synthetic browser fixture and the onboarding acquisition and activation-screen journeys (HF14) still do not resolve, so they are not exported, are excluded from `tsconfig.json`, and the acquisition controller test is skipped by the `test` script (`--path-ignore-patterns`). The kept, typechecked application-setup building blocks (contract, controller, values, fields, availability, neutral copy provider) have no export yet. `src/focused/browser-fixture.web.tsx` takes the brand label and every visible fixture label through props (`brand`, `fixtureCopy`); the Tafio values live in `@lssm-tech/bundle.tafio/copy/career-workspace` as `focusedCareerBrowserFixtureFr`. No D-117 exception applies. The fixture stays excluded with the profile closure until that closure resolves. `src/shared/private-profile-editor.ts` and its test are the byte-identical profile_ui_relocation sources from f4cd0fab; they are the editor the deferred profile workspace imports. ## Integration prerequisites The deferred closures depend on sibling Career candidates that are not merged in this package's branch: - profile owner / profile UI relocation (`refs/handback/career-core/profile_ui_relocation/f3981b6dfd80`, integrated on the CAREER-PROFILE lane): runtime `contracts/profile-editor` and `contracts/profile-editor-values` exports, `contracts/profile-evidence#CandidateProfileDisclosurePurposeV1`, and `src/shared/private-profile-editor.ts`. - profile activation (`refs/handback/career-core/profile_activation/6202face41a0`): runtime `contracts/candidate-activation` and `headless/candidate-activation`. - search owner (`refs/handback/career-core/search_owner/c6427ccf08bd`): runtime `contracts/candidate-search*`, `headless/candidate-search-draft-policy` and `bundle.job-application/search-owner/client`. When they land, remove the matching `tsconfig.json` excludes and test ignore patterns, then add each export with a catalog entrypoint and release capsule. `development.focusedTests` lists the tests whose closure resolves today. ## Sectioned profile and D-240 sharing (G8 P5) - `./shared/profile-sections`: the fact sections, the five editing groups (`/profile/`: identity, experience, education, skills, situation) and the section-level sharing choice (general CV, targeted CV, cover letter, application forms, AI processing). The choice is recorded only as the approved disclosures of each adopted fact (native adoption) and read back from them; employer disclosure stays a per-destination decision. - `./shared/profile-workspace` aggregates the per-fact editors: structured section entries (`updateEntry`), typed field issues, `setSharing`, and a Save scoped to groups and sections (`publish(groups, sections)`). - `./shared/profile-overview.web`, `./shared/profile-section-editor.web`, `./shared/profile-onboarding.web` (first-run sharing choice and recap), `./shared/profile-completeness` (published facts only) and `./shared/profile-copy` (typed copy supplied by brand compositions). - The six-step journey hides unbound controls and skips steps with nothing to fill in (`focused/onboarding/six-step-steps.ts`). - The criteria editor is exported (`./shared/criteria-editor.web`, form model `./shared/criteria-form`, typed copy `./shared/criteria-copy`, keyless commune suggestions `./shared/commune-lookup` and `./shared/commune-input.web`). A chosen commune stores its plain name (the native matcher compares it as a substring of the posting location); saved fields the editor does not show are carried through unchanged. Tafio mounts `/criteria` over its saved-search owner (revise or first create). - `setSharing` with no purposes is the explicit "keep private" choice; `sharingChosen()` holds the first-run review until a choice is made (facts adopted before any choice carry no purposes and never count as one). ### Reusable application answers, criteria and profile layout (G8 round 2) - `shared/application-answers`: the typed write port of the reusable application answers (`createCareerApplicationAnswersV1`). Each question is backed by the profile fact that owns its concept (work authorization per country, availability, mobility) or by the native `applicationAnswers` fact; `set` edits a draft (`null` clears a question back to "never answered"), `publish` is the workspace's own Save, and `complete` records the candidate's explicit review, refused while any question asked has no disposition. An explicit "I don't know yet" is kept as a reviewed answer (on the answers fact, `unknownQuestionIds` for questions another fact owns). Questions follow focused applicability (notice when employed, studies when studying, licence categories with a licence, nationality only when a form lawfully requires it). No second profile store exists. - `shared/application-setup-client`: the focused `ApplicationSetupClient` over that port (question set, versioned answer writes, completion), for the post-paywall first-use questions. `requiredQuestionIds` are every question asked, `reviewedQuestionIds` those with a disposition, and the status is `completed` only while the first is a subset of the second; completing with open questions throws `application_setup_incomplete`. - `shared/application-answers.web`: the `/application-setup` and `/profile/answers` screen (progress, important questions still open, section sharing, Save, "I checked my answers" held with its reasons). Standalone it asks one question at a time ("Question x of y", Previous / Next) and resumes at the first unanswered question. - Skill and language sections take several comma-separated names at once (`shared/profile-list-batch`); each becomes its own entry on a free slot the host offers, adopted by the section's one Save. - `shared/profile-layout.web` and `shared/profile.css`: the focused profile layout with a persistent section navigation (`aria-current="page"`). - `shared/country-names`: localized country names (`Intl.DisplayNames`, keyless) for the country pickers and per-country questions. - Section editors keep unsaved edits as a private draft (a native checkpoint, never a publication) when focus leaves the section or the page is hidden. ## Activation funnel (G8 parity, activation lane) The mounted port of the focused activation funnel is `./shared/activation/*` (hub, acquisition with the Gateway mapping proposal and the embedded CV picker, preview, paywall framing and the first-use questions), composed by the host over the current owners (saved search, CV owner, settings, profile writer, application-setup owner, billing). Decision (round 3): the earlier donor screens `focused/onboarding/acquisition-screen.web.tsx`, `activation-screen.web.tsx`, `application-setup.web.tsx` and `optional-cv.web.tsx` stay excluded from `tsconfig.json` and unexported, as donor reference only; they are not a second implementation and no host may bind them. They are deleted once the activation funnel qualifies at an integrated cohort (their native owners differ from the ones the shared screens use). `./shared/activation/mapping` holds the brand-neutral, pure part of the acquisition mapping (focused `ACQUISITION_MAPPING_SYSTEM` and patch validation): the prompt, the source wrapped as data, and the extractive validation of a model answer into a criteria proposal. The host performs the model call (AI Gateway routes, cost caps) and falls back to the deterministic rules of `./shared/activation/funnel`. --- ## @lssm-tech/bundle.communication-os Description: Shell-neutral CommunicationOS application kit for standalone and embedded messaging products. Path: packages/bundles/communication-os URL: /llms/bundle.communication-os # `@lssm-tech/bundle.communication-os` Reusable CommunicationOS application kit for Next.js, Expo, Tauri, and in-app feature-hub hosts. `createHcircleMeetingIntelligence` provides the hCircle meeting projection: optional connection-focused preparation, consent-led sharing, no productivity scoring, no clinical inference, and public links disabled by default. The bundle composes the canonical v2 messaging contracts, deterministic journal projections, revocable principal authority, normalized channel adapters, semantic navigation, and contextual embed slots. It is framework-neutral and provider-neutral. `communicationOsCanonicalRoutes` and `resolveCommunicationOsRoute` derive from the 23-route hub catalog. Standalone, embedded, Expo, and Tauri hosts use this registry to validate list/detail paths instead of treating unknown URLs as an inbox or room fallback. Navigation derives every non-detail canonical destination from the same catalog and then adds explicitly owned product routes. `resolveCommunicationOsRoutePresentation` gives each canonical destination the same purposeful title, description, and empty-state contract on web, Expo, and Tauri. Thread and message deep links retain their opaque conversation reference instead of silently falling back to the previously active room. Hosts that only need the Forms experience should import the focused `@lssm-tech/bundle.communication-os/forms-ui` subpath so meeting/provider runtime code does not enter the same browser chunk. Detail identifiers remain opaque, but the shared resolver rejects traversal segments, encoded path separators, control characters, malformed encoding, repeated interior separators, and decoded identifiers longer than 256 characters before any host selects or fetches a conversation. Contextual slots use the same canonical `communication-os.*` identifiers as the route catalog. This keeps standalone web, CompanyOS embedding, Expo, and Tauri from showing an action that the canonical route authority would deny. Legacy CommunicationOS adopters remain draft-only. Standalone and embedded hosts opt into `membership_grants` only after supplying membership, grant, policy, journal, and channel ports. ## Forms The bundle exports the shared Forms management and public respondent surfaces. CommunicationOS mounts management at `/communications/forms`, public forms at `/f/{opaqueToken}`, and the versioned API at `/api/forms/v1`. The same governed operations are registered for web, Expo mobile, Tauri desktop, and MCP; creator scope still comes from the authenticated CommunicationOS grant. --- ## @lssm-tech/bundle.creator-platform Description: Headless reusable creator platform foundation with governed optional surfaces. Path: packages/bundles/creator-platform URL: /llms/bundle.creator-platform # @lssm-tech/bundle.creator-platform Headless reusable creator-platform foundations with governed design selection, gamification helpers, operations ports, server composition, Studio composition, and deterministic fixtures. The optional `./creator-operations` entrypoint now binds the canonical reusable campaign, agreement, submission, accrual, wallet and settlement module. Inject a transactional creator store, current authority and qualified settlement provider. This additive scope follows `specs/marketing-creator-operations-v1/REPO-OWNERSHIP.md`; application records, credentials, accepted agreements and migration ownership remain with the host. Existing creator APIs and the earlier draft/human-only surfaces keep their previous behavior. Full Hirly parity and live payment qualification are pending. Import the root only for the manifest and readiness report. Use `./design`, `./gamification`, `./operations`, `./server`, `./studio`, and `./testing` explicitly. Optional React surfaces live at `./ui/design-picker`, `./ui/analytics`, `./ui/auth`, `./ui/gamification`, and `./ui/review`; governed publishing composition lives at `./publishing`. Recommendations never persist or activate a design. Applications own creator data, routes, persistence, campaign rules, payouts, provider credentials, copy, schedules, and experiments. AI-native operations are exposed only through optional subpaths: `./analysis`, `./intelligence`, `./learning`, `./coaching`, and `./authority`. The authority resolver composes system, workspace, campaign, consent, and request constraints; lower scopes can narrow authority but cannot broaden it. Consequential creator, campaign, publication, communication, ranking, and money actions are human-only. `./readiness` exposes the executable end-to-end capability matrix and validation helpers. `./experience` resolves explicit RoleMorph presentation hints, creator role lenses, and design-catalog selections without granting authority. `./ui/experience` provides the responsive, accessible Creator Operations Cockpit: next actions, campaigns, evidence-backed signals, coaching, momentum, gamification, and system coverage in one role-aware home. It uses Design System primitives, Creator design packs, Design Studio composition, and synchronized English, French, and Spanish operator copy. The gamification UI composes `@lssm-tech/module.gamification`; review uses the product-neutral `@lssm-tech/module.human-review` rather than the CompanyOS review queue. A credential-free complete composition is available in `@lssm-tech/example.creator-platform-foundation`. Stable release additionally requires the visual matrix, clean canary install, and credentialed official-provider smoke tests listed by `creatorPlatformReadiness()`. `learning/native-training` provides a pure compatibility adapter for existing app-owned creator-training records. It maps native Date/null fields and reset notices into the shared snapshot, and produces a DB update patch using the shared transition engine. The native boundary retains French/English locales and existing output keys. Existing transactions, request receipts, authorization and canonical write ownership stay in Hirly. This adapter does not migrate data or install a second writer. Run `bun scripts/check-creator-training-compatibility.ts --source-root ` from the ContractSpec root to compare the adapter against the current native pure transition block. The report records source hashes and explicitly excludes database, authorization, request-receipt and deployment behavior from its compatibility claim. `learning/posting-streak` maps the shared timezone-explicit calendar projection to native Sunday–Saturday slot labels and numbering. Supply participant timezone and current ISO instant explicitly. This adapter does not mutate XP, streak records or compensation. `learning/native-quiz-key` maps existing native quiz definitions into private versioned keys, preserving the native 67-percent fallback. Use only in server-owned scoring configuration and bind revision to immutable source content. The mapper omits prompts and labels but still contains correct answers; never return it to learners. `learning/native-quiz-view` explicitly projects localized titles, questions and choices from a native definition while omitting correct answers and incidental metadata. Run the mapper server-side and send only its validated result to learners; do not ship the source definition or private key mapper in a learner bundle. `learning/native-quiz-loader` composes enrollment-authorized course lookup with private native content loading and learner-safe projection. It verifies course scope, quiz/module membership, requested locale and exact quiz revision before returning public content. Enrollment and native content sources remain app-owned ports. `./tracking/connected-accounts`, `./tracking/disconnect-impact`, `./tracking/connection-outcome` and `./tracking/brand-social-accounts` present host-supplied, nonsecret connection projections; they never grant posting, publishing or payout authority. `./publishing/queue` and `./publishing/queue-presentation` parse the creator publishing queue fail-closed (viewer/creator binding, `manual_only`, at most 50 items, no duplicates or unknown states, unlisted fields dropped) and present its seven checks in English and French; a test-only account is never provider qualified and nothing grants posting, publishing or payout authority. `./publishing/queue-assembly` assembles that queue as a pure function over records the host has already authorized (source exclusion counts, approved-version de-duplication, rights/licence-start mapping, 50-item page and cursor); duplicate or foreign records refuse the whole assembly and authorization stays the host's precondition. `./ui/experience/PublicOverview.web` renders an explanatory public overview from brand-supplied copy, locale links, logo and CSS classes. Its data-only model is available at `./ui/experience/public-overview`. The screen is web-only and is not re-exported by the root or generic experience/native entries. It uses the existing MarketingLandingPage, HStack, Box and Text exports and grants no workspace access. --- ## @lssm-tech/bundle.founder-suite Description: Provider-neutral standalone Tendframe Founder Intelligence Suite composition. Path: packages/bundles/founder-suite URL: /llms/bundle.founder-suite # Founder Suite Bundle `createPactenaMeetingIntelligence` projects OPA's shared meeting capability into Tendframe with an adaptive profile, explicit rationale and confidence, founder override state, and human-only approval, publication, and dispatch. Composes the standalone Tendframe Founder Intelligence product boundary: Founder Intelligence, Executive Intelligence, Talent, fourteen domain doors, four operating archetype packs, route contracts, and en/fr/es copy. CompanyOS is an external peer, not a host or authority shortcut. Missing persistence and providers must remain explicitly degraded; fixtures are never labelled live. Shared Forms is an additive founder-suite capability at `/forms`, with public responses at `/f/{opaqueToken}`. OPA may be referenced as a typed profile or booking destination but is not the owner of Forms. The founder live room (`./live-room`, `./live-room-screen`) is the reusable CommunicationOS conversation screen: an explicit founder-private/company scope switch, bootstrap load, realtime subscription with a 15 s poll fallback and single-flight send (`useFounderLiveRoom`), rendered by `FounderLiveRoomScreen` with en/fr/es copy (`./live-room-copy`). Hosts inject a `FounderLiveRoomPortV1` (load/send/subscribe) and keep the CommunicationOS client binding and API origin; the bundle never imports a provider client. --- ## @lssm-tech/bundle.job-application Description: Headless candidate and operator job-application controllers. Path: packages/bundles/job-application URL: /llms/bundle.job-application # Job application bundle Reusable candidate/operator controllers and redacted projections for application lists, lifecycle detail, profile provenance, form review, external account and inbox state, challenges, effects, takeover, submission, reconciliation, cancellation, and deletion. The controller projects only reference-safe metadata. Candidate answers, credentials, inbox addresses, verification links, codes, cookies, and form values are never included. Executable actions are projected from server-returned descriptors; hosts cannot infer an action from a status. Review, submit, takeover/resume, reconcile, cancel, application deletion, and account deletion all require exact-resource confirmation. Concurrent execution of the same descriptor shares one in-flight effect. --- ## @lssm-tech/bundle.job-application-demo-content Description: Brand-neutral demo workspace content for job applications: reviewed French market packs and the deterministic workspace builder. Path: packages/bundles/job-application-demo-content URL: /llms/bundle.job-application-demo-content # @lssm-tech/bundle.job-application-demo-content Content of demo accounts for job applications. - Six reviewed French market packs, one per job family: tech, product and design, marketing, sales, finance, operations. Each pack holds employers, posting templates, a persona, a CV, a cover letter, inbox threads and notifications. - `buildDemoContentWorkspaceV1` turns a combination (family, seniority, location, density) into a deterministic seeded workspace: feed, application history, inbox with interview invitations, documents, saved searches. - `demoWorkspaceContentV1` is the content port to bind to the demo operator and workspace services of `@lssm-tech/integration.job-application-effects-demo`. - `src/cli.ts` is the operator command line with this content bound, plus the persona commands of `src/seed-cli.ts`. ## Scenario versions - Version 1 is the ported donor workspace, unchanged (pinned by digest in `workspace-v2.test.ts`). - Version 2 (new accounts) adds, on top of version 1: CV and cover-letter version history and targeted letters, the exact document versions each application was sent with, an offer story (final interview held, offer received), employer stages on every confirmed application, simulated automatic runs per monitored saved search (scanned, matched, skipped with reasons, running or completed), automatic-application settings on saved searches, and an activity history. Accounts seeded with version 1 keep version 1 so retakes stay identical. - Version-2 timeline rules, checked for every seed weekday and hour: a scheduled run starts at 08:00 (Paris) on a weekday and paces its requests over the working day; a run whose requests fall in the evening, at night or on a weekend is a manual run started a few minutes before its first request; a run never starts before its saved search existed (the primary search is dated before the first run); the offer thread's messages arrive on weekdays during business hours, the offer on the latest weekday afternoon before the seed. Request times themselves come from version 1 and are not moved. - Hosts show the current version of each document (`current !== false`); older versions stay in the workspace for a history view. - Interface labels for the new codes (`labels.ts`) and the new story content (`story-copy.ts`) exist in French, English and Spanish. ## Content languages (D-251) The seeded text exists in French (the reviewed source), English and Spanish. `packs/en-*.ts` and `packs/es-*.ts` hold only the text of each French pack, keyed like it (posting and thread keys, array positions); `packs/{en,es}-employers.ts` hold the sector and pitch of the shared employers. `localizeContentPack` puts that text on the French structure and refuses a translation that is missing a string, adds one, or changes a placeholder (`validateContentLocales`). The market stays France: cities, euro amounts, French contracts and real French employers. A build input's `contentLocale` (`fr`, `en`, `es`, or any tag of those languages; French otherwise) selects the language. Only text changes: ids, dates, statuses, ranks, scores and counts are identical in every language (`locale.test.ts` compares every persona in both scenario versions), so a reader can switch language without losing a simulated application. Renderers take the pack's language for headings, amounts (`52 000 €` / `52,000`), interview slots and the country name. ## Personas `src/personas.ts` names ten reviewed combinations, at least one per job family (for example `tech-confirmed-paris`, `marketing-apprentice-bordeaux`, `operations-manager-nantes`), with a default purpose and labels in French, English and Spanish. Not yet at donor parity: the donor's operator-managed presets (`preset add|list|remove` backed by its `demo_presets` table, global and per-account) are not ported; personas here are code-owned only. Families match the donor's shipped packs (six, its decision D3); the four further families of its spec list (data, HR, health, hospitality) are authored in neither. Employers are real company names; every posting is fictional and every link and address uses the reserved `.invalid` domain. Review brand use of the employers visible in a video before publishing it. ## Operator command line ```bash JOB_APPLICATION_DATABASE_URL=... bun packages/bundles/job-application-demo-content/src/cli.ts create --candidate --operator --purpose sales --family tech --seniority confirmed --location paris --label "Sales demo" --responsible "" ``` Commands: `create`, `switch`, `reseed`, `revoke`, `extend`, `erase`, `status`, `audit`, `list`. Scope defaults come from `JOB_APPLICATION_DEMO_SCOPE_*` variables. Persona commands: ```bash bun packages/bundles/job-application-demo-content/src/cli.ts personas JOB_APPLICATION_DATABASE_URL=... bun packages/bundles/job-application-demo-content/src/cli.ts seed --persona tech-confirmed-paris --candidate --operator --responsible "" [--purpose P] [--label TEXT] [--refresh] JOB_APPLICATION_DATABASE_URL=... bun packages/bundles/job-application-demo-content/src/cli.ts reset --candidate --operator ``` `seed` is idempotent: it creates a fresh scope with the persona, switches an active demo account on another combination, and leaves an account already on the persona unchanged (`--refresh` re-seeds it with fresh relative dates). A frozen account is refused. An existing account keeps its purpose, label, expiry and own first name: `--purpose`, `--label`, `--expires` and `--own-first-name` are only read at creation, and the result lists them in `ignoredFlags` and reports `purposeMismatch` when the account's purpose differs from the requested or persona purpose. A switch keeps the account's own first name on screen. `reset` re-seeds the current combination of an active demo account and refuses every other scope before writing. The person signs up first; the operator never handles a password. ## Provenance The content engine and the packs are ported from the focused donor repository (`integrations/b2c-demo/src/content`, commit `9283bcd99110b895a7e58e9df677b9dd3faf1aea`) by the deterministic transform `demo-content-debrand-v1`. `provenance.json` lists each file with its donor sha256 and its sha256 after the transform and formatting. --- ## @lssm-tech/bundle.jobrally Description: Jobrally brand composition (JR-02, D-112a, D-122 B layer): active-search tempo composition over the shared career experience; no domain or experience logic. Path: packages/bundles/jobrally URL: /llms/bundle.jobrally # `@lssm-tech/bundle.jobrally` Jobrally brand composition (`JR-02`, B layer under D-112a / D-117 / D-122 / D-211). Composes the shared ContractSpec career candidate product (`@lssm-tech/bundle.job-application` and `@lssm-tech/bundle.career-experience`) with Jobrally's active-search (`tempo`) starting experience, `career-base.jobrally-tempo` design pack, hosts (`www.jobrally.app`, `app.jobrally.app`, `beta.jobrally.app`, 308 aliases `jobrally.{me,run,work}`), commercial offers (`app_jobrally`), five-locale legal documents, Dev Day `04-tempo` marketing copy, and workspace/billing/settings/activation/email copy. Both `jobrally*` exports and brand-neutral `tempo*` host aliases are provided so consuming hosts satisfy `source-scan` zero-brand-literal gates while indexing compositions by `productApplicationId`. --- ## @lssm-tech/bundle.library Description: Composable ContractSpec library bundle for documentation, MCP, and runtime consumers. Path: packages/bundles/library URL: /llms/bundle.library # @lssm-tech/bundle.library **Shared library bundle that composes docs, templates, integrations, MCP implementations, and reusable presentation surfaces.** ## What It Provides - Provides the reusable product-facing bundle consumed by API, web, and documentation surfaces. - Aggregates docs pages, integration marketplace UI, templates, example showcase pages, and library-side MCP implementations. - Includes reusable managed/BYOK credential setup UI for integration manifests and monorepo-aware env alias previews. - Acts as the main composition layer between lower-level libraries and app-specific delivery shells. - `src/presentation/` contains presentation-layer components and renderers. ## Installation `npm install @lssm-tech/bundle.library` or `bun add @lssm-tech/bundle.library` ## Usage Import the root entrypoint from `@lssm-tech/bundle.library`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/application/` contains application services including MCP implementations and cross-surface orchestration. - `src/components/` contains reusable docs, integrations, legal, shell, and template presentation code. - `src/components/docs/agents/` contains the canonical public Agent Ecosystem hub and guides for multi-agent execution, self-improvement, durable runtime, self-maintaining APIs, deployment, and production qualification. - `src/components/docs/examples/` derives showcase links from the discoverable example catalog and leaves preview rendering to the shared `@lssm-tech/module.examples/runtime` host. - `src/features/`, `src.config/`, `src.infrastructure/`, and `src.libs/` hold bundle-local composition helpers. - `src/presentation/` contains feature-specific UI composition exported to consuming apps. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Large multi-subpath bundle exporting docs, integrations, templates, shell layout, email helpers, and MCP application surfaces. - Export `.` resolves through `./src/index.ts`. - Export `./application` resolves through `./src/application/index.ts`. - Export `./application/context-storage` resolves through `./src/application/context-storage/index.ts`. - Export `./application/mcp` resolves through `./src/application/mcp/index.ts`. - Export `./application/mcp/cliMcp` resolves through `./src/application/mcp/cliMcp.ts`. - Export `./application/mcp/common` resolves through `./src/application/mcp/common.ts`. - Export `./application/mcp/contractsMcp` resolves through `./src/application/mcp/contractsMcp.ts`. - Export `./application/mcp/contractsMcpResources` resolves through `./src/application/mcp/contractsMcpResources.ts`. - Export `./application/mcp/contractsMcpTools` resolves through `./src/application/mcp/contractsMcpTools.ts`. - Export `./application/mcp/contractsMcpTypes` resolves through `./src/application/mcp/contractsMcpTypes.ts`. - Export `./components/docs/agents` exposes the public Agent Ecosystem page components consumed by the website delivery shell. - Exports under `./components/docs/{areas,packages,source-guides,source-examples,migration}/*` (WEB-01-DOCS) render the converged source docs: the authored guides and `/docs/core` hub, the 22 areas and their directory, the regenerated package manuals and directory (`package-manual-loader` verifies the docs-generator hashes and refuses private packages), the example walkthroughs, and the docs-tree redirects. - The package publishes many generated export subpaths; treat `package.json` as the source of truth for the current subpath list and keep public-surface docs aligned when exports change. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `bun run test` — bun test - `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. - Package exports. - Vnext ai-native. - Add latest models and align defaults. - Standardize tool naming to underscore notation. - Add changesets and apply pending fixes. ## Notes - This bundle is consumed by multiple apps — breaking export changes cascade widely. - MCP server implementations must stay transport-agnostic (the app layer wires the transport). - Keep side effects behind explicit adapters; do not perform I/O at import time. Cross-platform UI documentation and the customer markdown kit now cover translation-bound data-view filters and active chips. Standalone declaration exports keep their existing public subpath names. The shared builder preserves their original declaration suffix and copies checked source declarations into dist, without overwriting emitted implementation types. The 355 retained declaration-named implementation aliases select the existing canonical TypeScript module and its compiled JavaScript artifact. Public keys, condition keys and type targets remain unchanged. Eight historical test declarations derive through the existing TypeScript 5 compiler from their canonical test sources without evaluating those tests. Run `bun run generate:mcp-test-declarations` to regenerate them; prebuild checks that their exact compiler outputs remain current. The owning configuration freezes the reviewed map so source discovery cannot retire compatibility keys. The declaration generator resolves the package's `catalog:testing` TypeScript 5.9.3 dependency. The existing `tsgo` typecheck and mandatory TypeScript 7 consumer qualification remain separate gates. --- ## @lssm-tech/bundle.lifecycle-managed Description: Lifecycle management bundle with analytics and AI advisor Path: packages/bundles/lifecycle-managed URL: /llms/bundle.lifecycle-managed # @lssm-tech/bundle.lifecycle-managed Website: https://contractspec.io **Lifecycle management bundle with analytics and AI advisor.** ## What It Provides - **Layer**: bundle. - **Consumers**: `examples/lifecycle-cli`. - `src/services/` contains business logic services and workflows. - Related ContractSpec packages include `@lssm-tech/lib.analytics`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.lifecycle`, `@lssm-tech/lib.observability`, `@lssm-tech/module.lifecycle-advisor`, `@lssm-tech/module.lifecycle-core`, ... - `src/services/` contains business logic services and workflows. ## Installation `npm install @lssm-tech/bundle.lifecycle-managed` or `bun add @lssm-tech/bundle.lifecycle-managed` ## Usage Import the root entrypoint from `@lssm-tech/bundle.lifecycle-managed`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/services/` -- assessment service (lifecycle evaluation logic). - `src/agents/` -- AI lifecycle advisor agent. - `src/events/` -- lifecycle domain events. - `src/api/` -- REST handler adapters. - `src/__tests__/` -- unit tests. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Resolve lint, build, and type errors across nine packages. - Add first-class transport, auth, versioning, and BYOK support across all integrations. ## Notes - Depends on six workspace packages (`lib.analytics`, `lib.contracts-spec`, `lib.lifecycle`, `lib.observability`, `module.lifecycle-advisor`, `module.lifecycle-core`); changes to those APIs propagate here. - Events must remain serializable for cross-service consumption. - Keep REST handlers thin; domain logic belongs in services. --- ## @lssm-tech/bundle.lssm-ecosystem Description: LSSM ecosystem product bundle: non-company atlas nodes, perspectives, public copy and the ecosystem graph explorer composition over the CompanyOS portfolio records. Path: packages/bundles/lssm-ecosystem URL: /llms/bundle.lssm-ecosystem # @lssm-tech/bundle.lssm-ecosystem Private LSSM ecosystem product bundle (WEB-01, D-100 and D-103). It composes the LSSM company portfolio, brand pages and ecosystem atlas served by `packages/apps/lssm-ecosystem-web`. - Company, holding, brand and product nodes are `lib.companyos-spec` enterprise topology and portfolio records; they are not duplicated here. - This bundle owns the non-company atlas nodes, perspectives and public copy (English, French and Spanish), and the ecosystem graph explorer composition over `lib.ui-kit-web` graph primitives. - Dependency direction: `bundle.lssm-ecosystem` depends on `bundle.patio`; `bundle.patio` never depends on this bundle. - It must never import `packages/apps/lssm-board` or the founder-intelligence private Board store. `./catalog` (CompanyOS topology, atlas, series, graph projection) and `./schema` (atlas lib.schema models) are owned by WEB-01-CATALOG; see `docs/provenance.md` and `docs/atlas.md`. `./page` (public page model, documents, fragments, islands, render context; `./page/server` is `verifyPublicRender`), `./interactions` (global public provider, studio journey, public composition and the interactive islands), `./navigation`, `./search` (released search index), `./previews` (released page previews) and `./preferences` (preferences store, provider and panel) are owned by WEB-01-PAGE, in `src/page`, `src/interactions`, `src/navigation`, `src/search`, `src/previews` and `src/preferences`. Hosts compose pages inside `LssmLocaleProvider` → `PreferencesProvider` → `GlobalPublicProvider` → `StudioJourneyProvider` → `PublicCompositionProvider` (the composition provider is where experiences and documents register). --- ## @lssm-tech/bundle.managed-companyos Description: Provider-neutral composition helpers for the managed CompanyOS application ecosystem. Path: packages/bundles/managed-companyos URL: /llms/bundle.managed-companyos # Managed CompanyOS Bundle The OPA Planner renders persisted Work-backed proposals and unscheduled reasons separately from committed focus time. Proposal generation does not apply calendar effects. History and idempotent replays remain scoped to the active workspace. OPA Settings includes localized per-action automation defaults/ceilings across organization, workspace, team, and user targets. Effective inherited modes and the inactive-background-execution status remain visible. The Planner offers an explicit reviewed Add to calendar action, with pending synchronization kept distinct from completed writes. The CommunicationOS screen contract accepts an explicit `dataMode`. Authenticated managed routes use `live`; deterministic previews retain `preview`, preventing production workspaces from presenting fixture counts or demo disclosures. The meeting-intelligence projection makes decision and workshop meetings written-first: preparation is required unless an explicit urgent override is recorded. Private playbooks stay separate from shared pre-reads, and publication and follow-up dispatch require current human approval. The bundle can now render contract-validated live readiness, context, artifacts, and work-session counts for a server-selected meeting while keeping refresh authority host-owned. OPA Settings includes the CompanyOS Briefings 2.0 personal control plane: Google connection health, calendar selection, explicit authorized-workspace mapping, locale, timezone, recap time, preparation lead, enablement, recent privacy-safe delivery evidence, and separate one-to-one morning/preparation previews through the current user's real personal pipeline. The surface displays `setup_required` until the current user completes their own personal setup and does not offer a workspace-calendar fallback. The native OPA Booking hub lets an authorized owner edit each active booking link's exact HTTPS embed-origin allowlist after creation. Saving uses the current link revision, refreshes the scoped ledger, and keeps hosted-only mode available by saving an empty list. Embed snippets remain disabled until at least one origin is persisted. `@lssm-tech/bundle.managed-companyos` is the provider-neutral composition boundary for Managed CompanyOS, the invite-led AI operating system for companies built on the ContractSpec substrate. ## CompanyOS design pack (`./design`) `./design` exports two CompanyOS-scoped designs. Neither is a built-in catalog pack, so sibling products do not inherit them. ### Calm pack: the workspace default `CompanyOsCalmDesignPack` (`companyos.design.calm-assistant@1.0.0`) is the CompanyOS-scoped default design: warm paper, pine actions, rust focus, certified light and dark modes. - `createCompanyOsDesignRegistries()` returns theme and design-pack registries with the CompanyOS pack first and every built-in pack after it (multi-theme selection keeps working). - `COMPANYOS_DESIGN_PACKS` / `COMPANYOS_DESIGN_THEMES` list what CompanyOS hosts offer; `COMPANYOS_CALM_DESIGN_PACK_REF` is the default for app policies and SSR hydration fallbacks. - `COMPANYOS_CUSTOM_DESIGN_BASES` is the `catalog` passed to `materializeCustomDesign`, so tenant custom designs may start from the CompanyOS pack. - `listCompanyOsDesignChoices()` maps `COMPANYOS_DESIGN_PACKS` to picker options (key, version, title, light-mode background/primary/accent swatches), and `toDesignPackRef()` turns a choice back into a `DesignPackRef`. ### Campaign pack: public site only, never a user choice `CompanyOsCampaignDesignPack` (`companyos.design.room-for-work@1.0.0`, theme `CompanyOsCampaignTheme`, `companyos.theme.room-for-work`) is the "Room for the real work" campaign design: mineral white canvas, deep ink, restrained cobalt and a warm worklight accent, IBM Plex Sans and an editorial style profile. `COMPANYOS_CAMPAIGN_PALETTE` holds its light and dark palettes and `COMPANYOS_CAMPAIGN_DESIGN_PACK_REF` its reference. It is marked `experimental`. The campaign pack is not in `COMPANYOS_DESIGN_PACKS`, so it is never offered by `listCompanyOsDesignChoices()`, never registered in the workspace design picker and never persisted as a user selection. Do not add it to the `designs` passed to `AppearanceMenu`. The web app applies the campaign theme to its public pages only. `CampaignThemeScope` (`packages/apps/web-application-monolith/src/lib/campaign-theme.tsx`, app-internal) wraps the `(marketing)` layout in `DesignSystemThemeProvider` with `CompanyOsCampaignTheme`, `mode="light"` and CSS variables applied. Marketing routes are forced light by the route theme. The scope never calls the design selection adapter, so a visitor's or user's saved design is untouched. ## AppearanceMenu (`./ui/appearance`) `AppearanceMenu` is the header control for light/dark/system mode and the design pack. Choices are a transient preview scoped to the open menu. Only "Apply" calls `onCommit`; closing the menu or "Cancel" restores the committed design and mode. `AppearanceMenuProps` (`ui/appearance/types.ts`): | Prop | Meaning | | --- | --- | | `labels` | `AppearanceMenuLabels`: trigger, mode names, design, studio, preview, apply, cancel, saving, saved, error | | `committed` | The persisted `AppearanceSelection` (`mode`, optional `designKey`); previews never change it until a commit succeeds | | `designs` | The offered `AppearanceDesignOption` list (key, version, title, swatches) | | `onCommit` | `(selection) => Promise`: persists then applies; must reject when persistence fails | | `systemMode` | Optional resolved OS scheme used to preview `system` (default `light`) | | `scopeKey` | Optional workspace/tenant scope; a change discards any transient preview | | `onOpenStudio` | Optional link to the full design studio | A rejected `onCommit` keeps the menu open, shows `labels.error` as an alert and leaves the committed selection unchanged. Hosts build `onCommit` with `createAppearanceCommit(ports)`: it persists a changed design first (`APPEARANCE_DESIGN_UNKNOWN` for a key not in `designs`), and only after that succeeds applies the mode and refreshes the server-resolved design. The web app composes it in `src/lib/use-appearance-control.tsx` with `listCompanyOsDesignChoices()`. This contract replaced the earlier `mode`/`onModeChange`/`activeDesignKey`/`onDesignChange`/`pending`/`error` props (`.changeset/companyos-visual-growth.md`). ## Feature Hub composition `./feature-hubs` now consumes the canonical module-owned Integration, Auth User, Auth Admin, Agent System, Agent Network, Workflow, CommunicationOS, and CompanyOS Hubs through `composeFeatureHubs()`. The bundle keeps opinionated CompanyOS route aliases and compatibility re-exports, but the modules remain the canonical owners. Provider adapters, secrets, schedulers, databases, and deployment topology stay host-supplied. Social Media remains independently installable and can be added by verticals that opt into that feature. It is intentionally safe for app packages to import while keeping lower layers pure: - Apps may compose this bundle plus approved modules/libs. - This bundle must not import app packages, example packages, provider SDKs, or raw provider credentials. - Managed and BYOK integration ownership modes must expose equivalent admin affordances while using different support/accountability copy. - Secret material is represented only as redacted references, never raw values. - Public managed CompanyOS surfaces are inventoried with compatibility intent and verification evidence. - Executable proof helpers must stay tied to runnable code and tests, not PRD-only narrative. ## Experience coverage ledger `./experience-coverage` exports the governed CompanyOS, OPA, CommunicationOS, and SupportOS feature/journey manifest plus its redacted product-health projection. Callers can pass explicit `productIds` to produce a scoped report; its totals and completion denominator are recomputed from only those products. Empty or unknown product scopes fail closed instead of producing a misleading empty report. Status and completion are computed from verified evidence gates; route existence and fixture rendering do not count as implementation. The web application exposes the projection through the authenticated, read-only `/api/companyos/admin/product-health` endpoint and renders it at `/companyos/admin/product-health`. Both surfaces use the exported `managedCompanyOsProductHealthScope`, so SupportOS cannot alter the CompanyOS, OPA, and CommunicationOS denominator. The UI filters by product, module, persona, platform, status, provider, and blocker. Run the completeness and report loop with: ```bash bun test packages/apps/web-application-monolith/src/product-health/route-inventory.test.ts bun run --cwd packages/apps/web-application-monolith experience:coverage ``` The generated Markdown and JSON reports live under `generated/experience-coverage/`. The `companyos-opa-communicationos-1.0.0` artifact intentionally excludes SupportOS, which retains its own capability matrix. Generation fails when an in-scope route has no feature classification or an out-of-scope product enters the report. ## Tenant-aware workspace shell `./view-models/workspace-shell` accepts an optional provider-neutral `workspaceIdentity` presentation override. Apps may use server-authoritative tenant composition to replace fixture display name, domain, and industry in workspace summaries, breadcrumbs, command headings, adaptive context, and graph labels. Fixture ids, source anchors, records, navigation, and evidence ids stay unchanged. When the requested RoleMorph role is absent from a presentation fixture, the projection preserves that requested role and derives presentation defaults from the fixture. It never silently substitutes the fixture's first role. Tenant resolution, membership, capabilities, and provider authority remain app and runtime responsibilities. The web shell may hydrate its switcher with a server-verified active context so the current organization and workspace are visible on first paint while the authoritative context list refreshes. Only optional OPA and CommunicationOS route families are module-entitlement gated; authenticated core CompanyOS routes continue to rely on their own persona and capability guards. ## UI surface (`./ui`) The G006 profile surface exports provider-neutral profile DTOs, projection and health helpers, an optimistic revision reducer, and typed `en`/`fr`/`es` catalogs. Its admin and public templates accept persisted API projections only; provider connections, authentication, transport, and secrets remain outside the bundle. Profile analytics are limited to `destinationMode` and `revisionBucket`. G006 browser projections and copied local drafts strip tenant, profile, link, event, scheduling, connection, avatar, and public-booking references. A new hybrid event may be persisted with an approved HTTPS Calendly destination; a new unprovisioned owned-live event fails closed and uses the locale catalog for its validation feedback. The final size gates are 235 lines for the catalog, 90 for `ProfileEventList`, and 150 for `ProfileAdminEditor`. Apps may attach an opaque `contextFingerprint` to the admin load DTO. The template uses it only to remount local editor state; the browser sends it in the authoritative preview header and echoes it on initialize, draft, publish, and revoke commands. The bundle never interprets it as tenant or provider authority, and it must not contain a raw tenant, organization, session, token, profile, calendar, or provider reference. The same UI barrel exports responsive Company Intelligence and Organization Planning dynamic templates. They consume request-backed, tenant-free snapshots, render all seven canonical route states in `en`, `fr`, and `es`, and keep blocked actions and dependency health visible without inventing executable client authority. Browser transport, authentication, persistence, and provider effects remain app/runtime responsibilities. The Organization Planning surface now resolves a canonical adaptive experience from server authority, RoleMorph, policy ceilings, explicit preferences, accepted suggestions, and safe role/job defaults—in that order. It exposes Today, Scheduling hub, and Module dashboard modes only when the current role may use them; auditors remain evidence-first and AI operators remain proposal-only for accountable actions. The mode toolbar persists only a user’s explicit, tenant-scoped home choice through the app BFF. Runtime adaptation remains non-persistent and includes visible “why” and reset controls. Public booking projects six explicit steps—event, date, time, details, review, and outcome—and distinguishes draft, pending approval, processing, durable confirmation, and repair states. Unsafe or stale availability never becomes a selectable slot. Tenant branding is presentation-only and cannot hide the CompanyOS trust mark or lifecycle truth. `OPA_VISUAL_MATRIX` freezes 2,448 governed cases across 320/375/768/1280px, light/dark, en/fr/es, every role-permitted home mode, host/company/neutral branding, and standard/expanded copy. It is the canonical input for visual baseline generation; generated screenshots and human approval remain promotion evidence rather than source contracts. All 427+ shared React components from the app shell have been migrated into this bundle under `src/ui//` via PR series `chore/migration/slice-*` (Slices 1–13). The `./ui` subpath is the **canonical UI surface** for managed CompanyOS. **Import patterns:** ```ts // Barrel (all domains) import { GovernancePolicyPanel } from '@lssm-tech/bundle.managed-companyos/ui'; // Per-domain (tree-shakeable, preferred) import { GovernancePolicyPanel } from '@lssm-tech/bundle.managed-companyos/ui/governance'; ``` **UI domains available:** `agents`, `analytics`, `audit`, `auth`, `autonomy`, `brain`, `cockpit`, `composition`, `finance`, `governance`, `graph`, `inbox`, `integrations`, `knowledge`, `landing`, `lifecycle`, `onboarding`, `policy`, `replay`, `shared`, `special-ops`, `status`, `team`, `threads`. - SSR by default — all components are React Server Components unless they carry an explicit `"use client"` directive. - App shells must not import from `src/ui/` by filesystem path; use the subpath exports only. ## Integration Hub reusable surfaces The bundle is the canonical source for the reusable Integration Hub view-models and templates consumed by examples and app shells. **Provider-neutral view-models**: - `buildIntegrationHubViewModel` from the root export or `./view-models/integration-hub` builds the searchable catalog summary, managed/BYOK counts, health counts, recommended tiles, screen-state matrix, and redacted credential references. - `normalizeManagedCompanyOsIntegrationCatalog` and `normalizeManagedCompanyOsIntegrationConnections` convert workspace integrations into reusable catalog/connection records without app-local catalog rebuilding. - `buildIntegrationHubViewModelFromCatalog` accepts normalized `IntegrationHubCatalogRecord[]` and `IntegrationHubConnectionRecord[]` input, so examples and app shells can pass provider-neutral records through the bundle instead of forking list/detail behavior. - Public helper types (`IntegrationHubCatalogRecord`, `IntegrationHubConnectionRecord`, `IntegrationHubFilterState`, `IntegrationHubHealthSummary`, and `IntegrationHubActionDescriptor`) are exported with the catalog seam and remain pure data contracts. - `buildIntegrationDetailViewModel`, `buildIntegrationConnectionsViewModel`, `buildIntegrationSyncsViewModel`, `buildIntegrationCredentialsViewModel`, `buildIntegrationSecretsViewModel`, `buildIntegrationConfigViewModel`, and `buildIntegrationAuditViewModel` live under their `./view-models/integration-*` subpaths and stay pure: no provider SDKs, network calls, persistence, filesystem reads, or secret access. - `buildIntegrationHubRegistryCatalog` (root export) maps host-joined registry catalog records (for example `joinIntegrationCatalogView` output) into healthy catalog entries with the view-support-boundary affordance; hosts keep loading the definitions. - The legacy `./integration-hub-view-model` shim is source-compatible for one release cycle; new consumers should import from `./view-models/integration-hub`. **Reusable UI**: - Catalog and detail templates are exported from `@lssm-tech/bundle.managed-companyos/ui/templates` (`IntegrationHubTemplate`, `IntegrationDetailTemplate`, `ConnectionsTemplate`, `SyncsTemplate`, `ConfigTabTemplate`, `IntegrationAuditTabTemplate`, `CredentialsTabTemplate`, and `SecretsTabTemplate`). - `DeploymentTopologyTemplate` renders the EN/FR/ES topology passport: nine independent deployment axes, RoleMorph-resolved authority copy, non-activating reference postures, and a provider-proof ledger. New consumers supply a canonical `providerReceipt`, exact `receiptScope`, and trusted time; missing, stale, failed, cross-scope, or digest-mismatched proof never renders as verified. The legacy display-only `receipt` input remains deprecated for source compatibility. - `IntegrationHubTemplate` owns the health overview/details CTA, Info links, search/category/status/mode filters, recommended row, explicit managed/BYOK install wizard, and read-only configure affordance for denied personas. - Capability atoms and integration-domain design primitives are exported from `@lssm-tech/bundle.managed-companyos/ui/integrations`. - `CredentialsTabTemplate` and `SecretsTabTemplate` are security-class templates. App routes that render them must be `force-dynamic` and must re-resolve session/persona per request. **Ownership and redaction contract**: - Every catalog entry must expose managed/BYOK support metadata or an explicit exception rationale. - Turn-on/configuration flows must require an explicit managed vs BYOK choice; do not silently default to managed. - View-models, fixtures, rendered HTML, snapshots, logs, and evidence packets may show only redacted credential references such as `********` or `secretref://...`; raw credential-like values block promotion. **Registry projection contract**: - Managed CompanyOS consumes provider-neutral catalog view records only. Bundle source must not import Integration Hub examples, implementation packages, concrete provider SDKs, provider clients, network adapters, or raw credential fixtures to build catalog tiles. - Preserve the registry two-state model in view-models: catalog availability is a policy/display overlay, while connection activation is derived from tenant/workspace connection records. Filtering one state must not mutate or erase the other. - Displayed tile counts, recommended tiles, and health summaries should be based on the same filtered provider-neutral tile set unless a helper explicitly documents a global/unfiltered summary. - `requiresModeChoice` remains `true` for install/configure affordances so the user/operator selects managed or BYOK before any connection flow starts. - Promotion evidence for catalog changes should include: ```bash bun test packages/bundles/managed-companyos/src/view-models/integration-hub/__tests__/integration-hub-normalized.test.ts bun run --cwd packages/bundles/managed-companyos typecheck bun run managed-companyos:provider-safety ``` ## Public composition helpers - `createManagedCompanyOsWorkspace` creates the deterministic reference workspace with tenant, policy, graph, workflow, replay, evidence, and health projections. - `createManagedCompanyOsReadinessReport` proves required app surfaces, dual-mode integrations, fail-closed approvals, evidence receipts, and runtime health. - `createManagedCompanyOsGovernanceReport` classifies managed public surfaces, S0 inventory row refs, and evidence refs before risky implementation changes. - `createManagedCompanyOsExecutableProof` proves this bundle exposes runnable managed CompanyOS behavior and test-backed evidence. - `buildManagedCompanyOsIntegrationOwnershipViewModel` keeps managed and BYOK integration UX at affordance parity with redacted credentials. - `evaluateManagedCompanyOsProviderCandidate` fails closed for raw secrets and requires explicit approval before concrete provider SDK wiring. - `createReferenceManagedCompanyOsIntegrationPort` provides a deterministic provider-neutral port for app layers. Concrete provider defaults, managed-provider SDK wiring, credential-handling authority, persistence adapters, and production queue choices remain approval-gated follow-up work. ## Managed Builder navigation The bundle registers `/companyos/builder` as a bundle-backed navigation surface for the managed Builder Workbench. It links to integration setup and evidence surfaces, but it does not replace or relabel the existing agent/workflow route families. App shells should consume `managedCompanyOsNavRegistry` and `managedCompanyOsNavGraph` rather than duplicating Builder route copy locally. ## I18n-ready product surface copy The bundle owns Managed CompanyOS business display copy so app shells do not fork route labels, route descriptions, or degraded-state wording into app-local dictionaries. Product surface snapshots and route builders accept an optional locale input and resolve copy through the bundle translation runtime: ```ts import { createManagedCompanyOsProductSurfaceSnapshot } from '@lssm-tech/bundle.managed-companyos/product-surfaces'; const snapshot = createManagedCompanyOsProductSurfaceSnapshot({ locale: 'fr', }); ``` The `./product-surfaces` subpath is the preferred app/mobile import because it exposes only the RN-safe pure route/view-model snapshot seam and avoids pulling SSR/web UI barrels into Expo. Current catalog coverage for the product-surface route group is `en`, `fr`, and `es`; unsupported or partial requests fall back through the deterministic bundle translation runtime to `en`. The localized fields are display-only: route ids, API paths, web paths, capability refs, evidence refs, health statuses, policy/evidence reason fields, tenant ids, and correlation ids remain stable machine values. App adapters should pass a negotiated locale or preference context into the bundle helpers instead of duplicating Managed CompanyOS business copy locally. Web and mobile shells remain responsible for host-specific locale detection, document metadata, React/React Native boundaries, and hydration/snapshot handling. ## Capability graph `src/capability-graph/` exposes the production-owned, pure shape contracts and view-model projections for the Special Ops capability graph. It is the SHAPE source-of-truth — repository (T4), API (T7), worker (T8), and web (T9) surfaces must match these types. - Types: `CapabilityNodeKind`, `CapabilityStatus` (`enabled | blocked | degraded | disabled`), `CapabilityNode`, `CapabilityEdge`, `CapabilityGraph`. - Pure builders: `createSpecialOpsCapabilityGraph()`, `createSpecialOpsWorkspaceProfile()`, `createSpecialOpsSeedRunReceipt()`, `attachSpecialOpsCapabilityGraph()` (clock is injectable; no `Date.now()`). - Projection selectors: `selectCockpitProjection`, `selectOpsSprintProjection`, `selectWorkGraphProjection` — tenant/workspace-scoped, redaction-aware. Disabled or restricted nodes surface a `[redacted-capability]` label and a `disabled` effective status with no raw secret material. - View-models that consume these projections live in `src/view-models/special-ops`, `src/view-models/ai-ops-sprint`, and `src/view-models/work-graph`. Each output carries a deterministic `locale` (default `en`) and an optional `displayCopy` map keyed by `ManagedCompanyOsI18nKey`, ready for T7/T9 to hydrate localized strings without forking builders. - Major-version cleanup removed legacy `Managed*` capability aliases; use `CapabilityNodeKind`, `CapabilityStatus`, and `CapabilityGraph` directly. ## Repository ports and deterministic adapters (`./repositories`) `@lssm-tech/bundle.managed-companyos/repositories` owns the reusable, driver-free repository layer that the API host composes: - `WorkspaceCapabilityRepository` port, `WorkspaceRow` / `CapabilityNodeRow` / `CapabilityEdgeRow` / `SeedRunInput` row contracts, `TenantMismatchError`, and the row-to-capability-graph projections (`workspaceRowToProfile`, `nodeRowToNode`, `edgeRowToEdge`). - `InMemoryRepository` (fail-closed `assertTenantAccess` on every call, idempotent dry-run aware mutations), the seeded `create*Repository()` factories, and `InMemoryWorkspaceCapabilityRepository`. - `MutationLedgerRepository` port, `mutationResultFromLedger`, and the in-memory and injected-SQL (`DrizzleMutationLedgerRepository`) ledgers over `managed_companyos_mutation_ledger`. - `RepositoryQueryFn` / `RepositoryExecFn` / `RepositorySqlParam`: the minimal injected SQL seam. The bundle ships no driver; hosts bind these to their own pool and keep env-based repository selection. ```ts import { createInMemoryWorkspaceCapabilityRepository, InMemoryMutationLedgerRepository, } from '@lssm-tech/bundle.managed-companyos/repositories'; ``` ## Special Ops domain (`./special-ops`) `@lssm-tech/bundle.managed-companyos/special-ops` owns the Special Ops lifecycle over the bundle-declared `managed_companyos_special_ops_*` tables: - Row contracts (`SpecialOpsMissionRow`, `SpecialOpsDraftRow`, `SpecialOpsReviewCardRow`, `SpecialOpsWeeklyReportRow`, `SpecialOpsGovernanceAssessmentRow`, `SpecialOpsEvidenceReceiptRow`, `SpecialOpsAuditEventRow`) and the `SpecialOpsRepository` port. - Role mutation policy (`assertCanMutate`; `SpecialOpsLifecycleRole` is `ManagedCompanyOsRole`), scope/redaction guards, typed errors carrying HTTP status, and deterministic receipt/audit builders shared by every adapter. - `InMemorySpecialOpsRepository` (deterministic test/dev authority) and the weekly report Markdown export (`composeWeeklyReportMarkdown`). - `DrizzleSpecialOpsRepository`: the SQL adapter over those tables. It takes an injected `SpecialOpsQueryFn` (statement, params, access); the host binds it to its driver, applies the RLS GUCs, and hydrates jsonb columns. - `createSpecialOpsFacade(resolveRepository)`: the command/query facade. Hosts pass a resolver so env-based adapter selection and database driver binding stay in the host composition root. ```ts import { createSpecialOpsFacade, InMemorySpecialOpsRepository, } from '@lssm-tech/bundle.managed-companyos/special-ops'; const repository = new InMemorySpecialOpsRepository(); const specialOps = createSpecialOpsFacade(() => repository); ``` ## Evidence ledger adapter (`./evidence-ledger`) `@lssm-tech/bundle.managed-companyos/evidence-ledger` exports `EvidenceLedgerRepository`, the driver-free adapter for the `@lssm-tech/lib.observability` `EvidenceAppendPort` / `EvidenceLedgerReadPort` over the bundle-declared `managed_companyos_evidence_outbox` and `managed_companyos_evidence_ledger` tables. `appendEvidence` is idempotent (`ON CONFLICT (idempotency_key) DO NOTHING`), `drainOutbox` returns `EvidenceOutboxRow`s for the worker relay, and `readEvidence` clamps reads to 1000 rows. Hosts construct it per transaction with the active tenant-scoped `EvidenceQueryFn` so outbox rows commit atomically with the producing mutation. ## Observability and behavior signals (`./observability`) `@lssm-tech/bundle.managed-companyos/observability` is node-free and owns the PostHog wire names (`POSTHOG_EVENTS`, `POSTHOG_PROPS`, `POSTHOG_LIBS`) plus the CompanyOS behavior-signal vocabulary shared by the web and native hosts: `CompanyOsSurfaceId`, `CompanyOsBehaviorSignal`, `hashTenantRef` (FNV-1a `tenant_ref_`), `COMPANYOS_BEHAVIOR_SIGNAL_PROHIBITED_CONCLUSIONS` and the builders `createCompanyOsBehaviorSignal`, `createCompanyOsBehaviorSignalEvent`, `createCompanyOsBlockedActionEvent` and `createCompanyOsBehaviorSignalCaptureProperties`. Hosts call `createCompanyOsBehaviorSignalRecorder({ emitter, transport, sink })` and inject only their adaptive-experience emitter and capture sink (posthog-js or posthog-react-native). Every signal carries the non-overridable `tenant-identity-inference` prohibited conclusion (on the signal model and in event `metadata.prohibitedConclusions`) and only a pre-hashed `tenant_ref`. ## RoleMorph action contracts (`./rolemorph-action-contracts`) `createManagedCompanyOsActionContracts({ workflowId, componentKey, displayActionIds, governedActionIds, namespace, governedImpact, governedSafetyRefs })` classifies display-only and governed actions and builds their ontology refs under `namespace` (default `companyos`). `governedImpact: 'mutate'` marks governed actions high-impact (policy and evidence required); their safety refs come only from the caller's `governedSafetyRefs`, so a host without evidence is blocked by RoleMorph. `createManagedCompanyOsAuthorityDecisions(workflowId, actionIds, policyDecisions, { namespace, allowReason })` is bound to resolved policy: an action is authorized only when exactly one policy decision resolves it, and is denied otherwise (fail closed). `createManagedCompanyOsPermissionDecisions` and `governedManagedCompanyOsActionIds` derive explicit permissions from a component registry. ## Superapp shell (`./superapp-shell`) The CompanyOS superapp catalog (`SUPERAPP_PERSONAS`, workspace/surface types, `SUPERAPP_ACTION_LABEL_KEYS`, `createSuperappComponentRegistry`), the per-persona RoleMorph policy (`createSuperappPolicyDecisions`) and the pure `resolveSuperappShell({ config, workspaceId, personaId, translate, roleMorph })` resolver. Hosts inject the workspace config, their translator (which must know `SUPERAPP_SHELL_MESSAGES_EN` / `_FR` / `_ES`, spread into the host catalogs; each persona declares its `labelKey` and `objectiveKey`) and the RoleMorph binding (`namespace`, `governedSafetyRefs`, decision copy). Governed actions are high-impact; without host evidence they are blocked and their surfaces are removed (fail closed). ## Tenant-safe read projections (`./read-projections`) `projectCompanyBrain`, `projectTemporalGraph`, `projectExperimentOutcome` and `projectProviderHealth` gate every read through the authenticated tenant actor, `assertTenantAccess` and the injected `authorize` port, failing with `AUTHENTICATION_REQUIRED`, `TENANT_ACCESS_DENIED` or `AUTHORIZATION_DENIED`, and project only redacted, read-only fields. Hosts (for example the MCP server) keep the resource-registry glue. ## Worker supervision (`./worker-supervision`) `createManagedWorkerSupervisionHealth(run, nowMs)` derives the canonical `ManagedWorkerSupervisionHealth` from a narrow structural run view (`stale`, `degradedReasons`, `jobs[].kind/status/stale`). ## Company Intelligence snapshot projection (`./view-models/company-intelligence`) `projectCompanyIntelligenceSnapshot(descriptor, results, surface)` maps the companyos-spec surface descriptor and API results into the `CompanyIntelligenceSnapshot` view model (401/403 → `unauthorized`, 503-only → `degraded`, mixed → `partial`); hosts keep their HTTP transport. ## Design-partner readiness view-model The bundle owns the pure design-partner readiness projection for the Managed CompanyOS private-pilot path. The fixture remains fictive and test/demo only; the activated path must receive persisted API data and follow the shared [`private-pilot contract`](../../../docs/managed-companyos-private-pilot.md). Import from the root bundle export or the narrow subpath: ```ts import { buildDesignPartnerReadinessViewModel, createNdconsultingDesignPartnerFixture, evaluateDesignPartnerReadinessProof, } from '@lssm-tech/bundle.managed-companyos/view-models/design-partner-readiness'; ``` The view-model exposes the deterministic tenant/workspace/scenario identifiers, mission command cycle, decision packet, expert attestation, founder approval, weekly report draft, evidence/replay links, known gaps, blocked/degraded reasons, role-gated affordances, and `aiCannotDispatch: true`. Design-partner fixture boundary: | Field | Value | | --- | --- | | Tenant ID | `tenant_ndconsulting_design_partner_demo` | | Workspace ID | `workspace_ndconsulting_desliance_demo` | | Scenario ID | `scenario_atlantique_industrie_mission_retournement` | | Scenario title | `Atlantique Industrie — mission retournement` | `expert_reviewer` is now part of `ManagedCompanyOsRole`. It may attest the decision packet, but cannot founder-approve or dispatch. `founder_approver` may founder-approve but not attest. `operations_manager` prepares only; `auditor` is read-only; AI proposes only; `frontline_staff` cannot mutate; `enterprise_admin` is not accepted as founder approval. The fixture readiness proof can reach `ready_for_design_partner_review` only for the design-partner review boundary. It still carries `noProductionReadinessClaim`, `noProviderDispatch`, and fictive-only assertions. Production activation is a separate operator decision and remains blocked until the private-pilot contract's tenant, data, domain, ownership, support, restore, kill-switch, and deferred-surface decisions are approved. ## Special Ops production cutover The Special Ops monolith production slice is documented in [`docs/runbooks/special-ops-monolith-production.md`](../../../docs/runbooks/special-ops-monolith-production.md). The bundle owns only pure, provider-neutral contracts for Special Ops, AI Ops Sprint, work graph, capability graph, replay, evidence, redaction view models, and deterministic database lifecycle artifacts. Live tenant/workspace persistence and provider dispatch remain app-layer approval-gated work; do not import example packages, provider SDKs, or raw fixture/customer data to satisfy the production cutover. ## Managed CompanyOS production-path boundary The authenticated workspace shell accepts persisted workspace module entitlements in addition to RoleMorph authority. LSSM, CompanyOS, and newly provisioned personal workspaces enable only `opa` and `communicationos`; the sidebar omits all other module screens and the API host independently rejects disabled authenticated OPA operations before storage or provider work. Seed selection is explicit: live commands accept `core-workspaces` or `all` (the live `lssm` and `companyos` organizations). Hirly and NDconsulting were decommissioned on 2026-10-20 ([evidence](../../../docs/evidence/authos/decommission-hirly-ndconsulting-2026-10-20.md)); the deprecated `legacy-reference` profile keeps NDconsulting available in source for local/reference fixtures only and is refused live. The retired `lssm-hirly` profile is refused by every bootstrap and seed path and stays exported by the company spec only until its next major. The broader Managed CompanyOS production path is coordinated by [`docs/runbooks/managed-companyos.md`](../../../docs/runbooks/managed-companyos.md). For this bundle, the production-path review has one hard boundary: keep schema, manifests, pure builders, view-models, redaction helpers, capability graph contracts, replay, and evidence receipts deterministic and provider-neutral. Production runtime concerns belong outside bundle module-load/helper execution: - live DB repositories/connections (the bundle only prints deterministic migrate/seed SQL artifacts); - session cookies, headers, and protected-route guards; - concrete provider SDK dispatch, webhook calls, queues, or filesystem state; - external production credentials or customer data. The bundle exposes pure SQL/manifest/contract artifacts for app-owned tooling to execute through `bun run --cwd packages/bundles/managed-companyos database:cli `. The deterministic seed includes tenant/workspace, capability graph, Special Ops proof rows, replay/evidence rows, and AuthOS fixture-backed projections in `managed_companyos_authos_projections`; it must not open connections, mutate persistence, read secrets, or import app/example/provider packages during import or helper calls. Attach static import-guard, redaction-scan, `database:verify`, database CLI artifact, test, typecheck, lint, and build evidence before treating a boundary change as complete. ## Host-bound behavior subpaths These subpaths hold behavior that app hosts previously duplicated. They stay pure or take explicit host bindings; fetch origins, cookies, browser storage, navigation, digests and session lookup remain in the host. - `./access-policy` — fail-closed mutation predicates shared by hosts: `authorizeManagedCompanyOsSessionRole` (a request acts only with its session role), `authorizeManagedCompanyOsSessionRevoke` (enterprise_admin, siblings only), `authorizeManagedCompanyOsIntegrationConfigure` (enterprise_admin with an explicit managed/BYOK choice), `authorizeManagedCompanyOsWorkflowDecision` (auditors read-only, approval_required steps only, AI-operator steps fail closed) and `toManagedCompanyOsActorKind`. - `./profile-drafts` — the OPA profile trust boundary: `redactProfileAdmin` strips server refs and `OPA_PROFILE_PROTECTED_AUTHORITY_KEYS` before the browser and derives owned-live readiness; `restorePrivateDraft` re-binds server refs by client id from a host-computed opaque digest; `buildDefaultIntroEventDraft` appends the default 30-minute Google Meet intro event to a schema-validated mutation draft. - `./public-booking` — v2 public booking client over an injected `PublicBookingTransport`: availability parsing (on the shared `@lssm-tech/opa-booking-react/availability` parsers), the lifecycle client implementing `PublicBookingLifecyclePorts`, status mapping, and the latest-request refresh guard. Status exchange tokens stay in memory; only the safe manage model is persisted through the host callback. - `./ui/public-booking` — `PublicBookingTemplateClient`, the smart container for `PublicBookingTemplate` over a stable `PublicBookingHostBinding`. - `./ui/organization-workspace` — `OrganizationWorkspaceSwitcher` and `useOrganizationWorkspaceSwitcher` over a host `OrganizationWorkspaceTransport` with en/fr/es copy (`resolveOrganizationWorkspaceSwitcherCopy`). ## Agent/Workflow Command Center readiness The production-path Agent/Workflow Command Center slice is tracked by [`docs/agent-workflow-command-center-production-readiness.md`](../../../docs/agent-workflow-command-center-production-readiness.md). Treat that packet as the gate for agent lifecycle, tool registry/permissions, workflow builder/run execution, review/governance/audit/replay, and cross-surface UX parity. The bundle remains the reusable product surface; web/mobile hosts and examples must consume module/bundle APIs rather than owning command-center domain behavior. The command-center view-model now exposes explicit Atomic CRUD coverage through `buildAgentWorkflowCommandCenterViewModel().atomic`: - domains: `tool`, `agent`, and `workflow`; - modes: `list`, `create`, `update`, and `detail` for every domain; - states: loading, empty, error, denied, read-only, allowed, dirty-invalid, review-required, and blocked; - per-surface `capabilities`, `policy`, `auditRefs`, `replayRefs`, redaction mode, app-relative `pillarRoute`, and optional host-prefixed `hostRoute`. `AgentWorkflowCommandCenterTemplate` renders that matrix with CVA-backed state variants. Keep it client-safe: do not import database, provider SDK, app, or example code into the view-model or template. ## S6 release and operations readiness The S6 handoff for this bundle is evidence-first and provider-neutral. A release candidate is ready only when the acceptance matrix, operator runbook, release copy guardrails, and final evidence packet all point to runnable checks. ### Vercel-only Managed CompanyOS readiness seam The bundle is the pure source of truth for production readiness snapshots. App shells should consume `createManagedCompanyOsProductSurfaceSnapshot()`, `createManagedCompanyOsWebShell()`, and status view-model helpers to expose `vercelSnapshot` manual-refresh semantics: - `vercelSnapshot.mode` is `manual-refresh`. - `vercelSnapshot.transport` is `request-time-http`. - scheduled work is represented through API/Vercel Cron evidence, not a browser realtime channel. - retained realtime exports are legacy/future VPS compatibility only and must not be used as Vercel production readiness requirements. ### Acceptance matrix | Gate | Required proof | Stop condition | | --- | --- | --- | | Managed/BYOK parity | Integration ownership and product-composition tests show equal admin affordances with redacted refs. | Any raw credential preview or asymmetric managed/BYOK affordance blocks release. | | Tenant/redaction safety | Implementation proof and workspace tests show tenant-scoped graph, replay, and evidence receipts. | Cross-tenant graph nodes, unredacted customer-sensitive payloads, or raw secret-like strings block release. | | Fail-closed approval | Readiness and product-composition tests show unknown or reserved actions are blocked or approval-required. | Financial, customer-facing, dispatch, legal, or reserved-human actions cannot run without accountable human evidence. | | Provider-neutral smoke harness | Provider approval and product-composition tests use deterministic reference providers and expect no SDK instantiation. | Concrete provider SDK imports, defaults, credentials, or dispatch paths require a separate approval decision. | | Provider catalog parity | App-layer provider catalog evidence shows managed/BYOK support metadata for each provider or a documented exception. | Bundle/libs/modules stay provider-neutral; live provider dispatch fails closed when deployment secret-manager values are missing. | | CRDT disabled by default | `crdt-disabled-default.test.ts` scans managed bundle/app/runbook surfaces for Loro CRDT imports and CRDT enablement env defaults. | CRDT/Loro stays disabled until the root baseline plus focused CRDT typecheck, lint, and tests are green together. | | Runtime health runbook | Product surface tests expose Vercel snapshot, scheduled work, replay, and evidence degraded states. | API-only green health cannot hide scheduled snapshot/replay/evidence degradation; realtime worker/WebSocket checks are future VPS-only. | | Support lifecycle | Operator runbook names intake, acknowledgement, severity classification, mitigation, customer status updates, post-incident evidence, closure, and ownership handoff. | Managed support availability, contracted response times, or uptime commitments remain blocked until support owner and coverage model approval exists. | | Release copy guardrails | `createManagedCompanyOsReleaseReadinessPacket` and release-readiness tests scan release-facing copy. | Copy cannot claim formal-attestation guarantees, raw credential-handling authority, live provider execution without approval, or autonomous reserved-action execution. | | Final evidence packet | Task handoff lists exact tests, typecheck, lint, build, secret scan, static import guard, and known gaps. | No release candidate is complete without command output and explicit known gaps. | ### Provider-neutral smoke harness Use `createManagedCompanyOsOrchestrationFacade` and `createManagedCompanyOsReleaseReadinessPacket` for bundle-level dry-run proof. Smoke inputs must use deterministic reference providers, redacted credential previews, and `expectedSdkInstantiation: false`. App-layer provider catalog smoke may cover approved live/reference adapters only when each provider has managed/BYOK support metadata or an explicit exception rationale. Live Resend, Slack, PostHog, database, or webhook dispatch may be validated only from deployment secret-manager values after provider approval; missing values must fail closed. Raw values must not appear in git, snapshots, logs, release copy, or evidence receipts. ### Environment validation and runbook Support evidence is part of the same release gate: the operator packet must show how an incident or customer escalation moves from intake to acknowledgement, severity classification, mitigation, customer status updates, post-incident evidence capture, closure, and ownership handoff. P0/P1 communication expectations may be documented as reference-mode operating guidance, but the bundle must not claim managed support availability, contracted response times, or uptime commitments until a support owner and coverage model are separately approved. Before promotion, operators validate these non-secret runtime variables: - `LSSM_STUDIO_DATABASE_URL` The Vercel API must not use `MANAGED_COMPANYOS_STATE_FILE`: Vercel Function storage is ephemeral, so PostgreSQL is the production state authority. - `MANAGED_COMPANYOS_DEFAULT_TENANT_ID` Provider env vars such as `MANAGED_COMPANYOS_RESEND_API_KEY`, `MANAGED_COMPANYOS_SLACK_WEBHOOK_URL`, and `MANAGED_COMPANYOS_BYOK_SLACK_WEBHOOK_URL` are optional until the approved provider dispatch smoke is enabled, and must be configured only through the deployment secret manager. Before any approved provider smoke begins, validate the filled G006 decision artifact. The command is intentionally fail-closed: exit `0` means all mandatory provider categories are ready for adapter smoke, exit `1` means the artifact parsed but remains blocked, and exit `2` means malformed JSON or an invalid decision shape. Artifacts marked `not_real_approval` also fail closed unless the operator passes `--allow-example`, which is reserved for synthetic command-path evidence and must not be used as customer authorization. ```bash bun run --cwd packages/bundles/managed-companyos provider-approval:validate \ .omx/plans/evidence/g006-provider-approval-decision-template.json ``` Recommended S6 evidence commands: ```bash bun run --cwd packages/bundles/managed-companyos test bun run --cwd packages/bundles/managed-companyos typecheck bun run --cwd packages/bundles/managed-companyos lint:check bun run --cwd packages/bundles/managed-companyos build bun scripts/check-managed-companyos-production-hardening.ts ``` The final release handoff should also include the executable `scanManagedCompanyOsReleaseSurface` secret/redaction scan, a provider-catalog parity guard, and a static import guard proving this bundle has no app, example, provider SDK, or CRDT/Loro enablement imports. Do not add a Managed CompanyOS CRDT flag, env var, or adapter import until `docs/data-transmission-crdt-v0.md#crdt-promotion-criteria` has green root baseline and focused CRDT evidence. ### UX states The managed bundle keeps the canonical UI states visible instead of collapsing them into a single healthy/failed binary: - `healthy` surfaces the normal operator and product views. - `degraded` keeps the degraded banner and degraded reason copy visible across the status and communication screens. - `down` blocks promotion and keeps replay, scheduled snapshot, or evidence failures explicit instead of hiding them behind an API-only green check. Realtime worker/WebSocket failures are explicit future-VPS signals, not Vercel production requirements. - `active` / `inactive` remain the auth-capability states for role and session affordances. - Blocked or approval-required actions use explicit guard copy rather than provider, compliance, or credential claims. These states are already exercised by the managed CompanyOS status, communication-screen, and product-surface tests; the S6 docs should describe them as UX contracts, not as new runtime modes. ### Operator docs and evidence packet Operators should use this bundle README together with: - `docs/companyos-ai-os-release-verification.md` for the central evidence packet and verifier checklist. - `docs/release-workflow.md` for the broader release-capsule and `/llms*` guardrails. - The bundle tests that prove health, redaction, provider-neutral smoke, and release-copy guardrails. The final evidence packet must list the exact commands that were run, the expected guardrail outcomes, and any known gaps that remain intentionally out of scope. ## Integration with Custom Applications This bundle is intended to be composed by the three official app monoliths (web, API, worker). If you need to integrate Managed CompanyOS into a custom application, use this bundle to build your own app composition: ```typescript import { createManagedCompanyOsWorkspace, createManagedCompanyOsReadinessReport, buildManagedCompanyOsIntegrationOwnershipViewModel } from '@lssm-tech/bundle.managed-companyos'; // Build deterministic workspace const workspace = createManagedCompanyOsWorkspace({ tenantId: 'custom_tenant_id' }); // Verify readiness const ready = createManagedCompanyOsReadinessReport(workspace); if (!ready.allGatesPass) { console.error('Not release ready:', ready.failures); } // Get dual-mode integration models const managed = buildManagedCompanyOsIntegrationOwnershipViewModel('managed'); const byok = buildManagedCompanyOsIntegrationOwnershipViewModel('byok'); ``` **Important:** Do not import this bundle at runtime in `examples/*`, `packages/foundation/*`, `packages/platform/*`, or `packages/domains/*`. The three official apps are the only supported composition boundary. ## Provider Approval This bundle is provider-neutral. All concrete provider integrations (Slack, Resend, PostHog, database/webhook adapters, AWS, etc.) are intentionally wired via approval-gated adapters in app/integration/provider packages, not in the bundle. Provider SDKs and credentials belong at the app composition layer, not here. Each catalog entry should expose managed and BYOK support by default; any managed-only or BYOK-only exception must name the operational reason and the approval/evidence path needed to close it. The root export now includes `parseManagedCompanyOsProviderApprovalDecision`, `evaluateManagedCompanyOsProviderApprovalDecision`, `assertManagedCompanyOsProviderApprovalReady`, and `createManagedCompanyOsLiveAdapterSmokePlan` so approval artifacts can be parsed, evaluated, and converted into the per-category smoke checklist required before live adapter work starts. These helpers do not select a provider, open credentials, or authorize live dispatch; they only convert a filled decision record into `approval_blocked` or `ready_for_smoke` readiness and required smoke assertions. ## Agent/workflow command center view-model `buildAgentWorkflowCommandCenterViewModel()` exposes the production walking skeleton for the Agent + Workflow pillar. The model is deterministic and client-safe: it uses simulator-only tool bindings by default, records review-required workflow state, includes correlated audit/replay evidence, and never requires provider credentials or external side effects. ```ts import { buildAgentWorkflowCommandCenterViewModel } from '@lssm-tech/bundle.managed-companyos'; const commandCenter = buildAgentWorkflowCommandCenterViewModel(); ``` Use `mode: 'blocked_tool'` to render the fail-closed authorization-required state for tool registry and audit/replay screens. ## Public comms + booking hub MVP Managed CompanyOS now owns a provider-neutral public communications and booking hub for founder/design-partner workflows. The public profile and booking templates use the Executive Ledger composition: an editorial identity panel, compact ledger-marked booking surfaces, a visible localized step state, responsive date/time selection, and semantic light/dark tokens. Internal labels such as `Event Type:` are stripped at the public projection boundary without changing stored administrative names. - Public profile route: `/u/nd-consulting` renders configured profile copy, a social icon row (links with `kind: "social"`, icon chosen from the link host, `mailto:` opens in place), list links grouped under their section headings with optional descriptions, and booking entry points. - Public booking route: `/book/founder-design-partner-call` renders a public scheduler with date-first selection, duration chips, timezone viewing, and user-facing confirmation/trust copy; final confirmation still stays fail-closed until an approved app/integration calendar adapter is bound. - Protected admin route: `/companyos/admin/public-comms` configures profile fields, link ordering, event type/duration, availability summary, calendar connection metadata, confirmation copy, evidence, and safety posture. Its desktop/mobile preview is revision-bound and request-backed; unsaved local edits are never presented as the persisted publication candidate. - Calendar semantics reuse `@lssm-tech/lib.organization-planning-spec` public booking primitives and the app/integration calendar adapter seam; the bundle does not import provider SDKs or write calendars directly. - Evidence/replay projections are redacted (`evidence:companyos-public-booking:redacted`, `replay:companyos-public-booking:deterministic`) and keep booker PII out of logs. - The Organization Planning template provides an en/fr/es responsive smart-meeting form backed by the same-origin authenticated BFF. It renders fresh/cached/unavailable availability, distinct runtime-unavailable and role-blocked states, durable pending approval, replay, and explicit no-event-created states without receiving tenant or provider authority. Enterprise admins and founder approvers receive approval, denial, cancellation, rescheduling, manual status-refresh, and ready Google Meet affordances; operations managers can prepare and monitor without receiving mutation controls they cannot use. - OPA uses one global CompanyOS shell plus contextual planning tabs. Its Today surface prioritizes the time ribbon, recommended action, setup gaps, and smart meeting preparation; personalization explanations and reset controls no longer compete with primary work in the page header. - Planner and Focus are distinct request-backed Executive Ledger workbenches. Focus creates, reschedules, and cancels owner-calendar blocks with localized synchronization evidence; Planner groups committed time by day, generates a seven-day plan run, and exposes current workspace, write calendar, protected hours, and conflict count without leaking provider identifiers. - MVP defers payments/tipping, public marketplaces, and workforce analytics. Verification runbook: ```bash bun test --cwd packages/bundles/managed-companyos src/view-models/public-comms-booking-hub/__tests__/public-comms-booking-hub.test.ts src/view-models/public-comms-booking-hub/__tests__/public-comms-booking-seam.test.ts src/view-models/public-comms-booking-hub/__tests__/public-comms-evidence.test.ts bun test --cwd packages/apps/web-application-monolith src/proxy.test.ts bun test --cwd packages/apps/web-application-monolith src/next-app.test.tsx -t "public-comms|public CompanyOS profile" ``` Verification runbook: ```bash bun test --cwd packages/bundles/managed-companyos src/view-models/public-comms-booking-hub/__tests__/public-comms-booking-hub.test.ts src/view-models/public-comms-booking-hub/__tests__/public-comms-booking-seam.test.ts src/view-models/public-comms-booking-hub/__tests__/public-comms-evidence.test.ts bun test packages/apps/web-application-monolith/src/next-app.test.tsx -t "public CompanyOS profile|runtime-configured public booking adapter" ``` Operator runbook: [`docs/runbooks/opa-public-booking.md`](../../../docs/runbooks/opa-public-booking.md) covers adapter readiness modes, provider/vault safety, outbox replay evidence, smoke evidence, degraded states, rollback, and public-safe communication boundaries. Keep `MANAGED_COMPANYOS_PUBLIC_BOOKING_ADAPTER_STATUS` unset/invalid for fail-closed dry-run mode, `sandbox_only` for non-live provider proof, and `adapter_ready` only after approved app/integration adapter, vault, idempotency, outbox, route-policy, and Connect evidence are attached. Smart-meeting operator runbook: [`docs/runbooks/opa-smart-meeting.md`](../../../docs/runbooks/opa-smart-meeting.md). The additive `forms` workspace module mounts at `/companyos/forms`; public forms use `/f/{opaqueToken}`. Forms storage and authorization remain owned by CompanyOS and do not mutate OPA tables. Native OPA demonstration view models use `organization-planning-proof-runtime.native.ts` over the pure manual-loop engine. The server seam retains the installed runtime. A parity test verifies identical deterministic output and blocked external effects, avoiding server database/Node imports in the native proof. This does not qualify the whole Expo application or native recording. Meeting intelligence opens on My private preparation and offers an explicit Shared meeting workspace view. Each view has its own mounted client state and uses the matching server owner selector for reads and mutations. Switching views disposes private transcript state. Graph-context refresh is offered in the private view; shared notes/artifacts remain accessible separately. The selector is localized in English, French and Spanish and does not grant server permissions. The private meeting view now offers **Create private meeting** when no meeting is selected. It reuses the canonical owner-bound creation API, retains ambiguous retry identities in tab session storage, and opens the returned private workspace with a resumable `meetingRef` URL. Creation does not start recording or invite participants. Capacity, denied authority and unavailable creation stay explicit. This web entry requires the private-meeting API to be deployed; browser audio capture/import is not added by this change. ## Private meeting notes CompanyOS exposes one private human-authored notes draft per meeting through additive `opa.meeting_artifact.get_note` and `opa.meeting_artifact.save_note` operations at `GET/POST /api/v2/opa/smart-meetings/:meetingRef/notes`. Existing meeting-work-session management permission authorizes this personal authoring surface; recording, transcript generation and model credentials are not prerequisites. Saves use `expectedRevision` (zero for creation), at most 100000 characters and a stable idempotency key. Notes remain `live_notes/private_user/draft`, persisted in the existing encrypted aggregate. Empty content clears the draft. Revision conflicts preserve the local draft and show the latest saved notes before an explicit choice to continue. Saving notes creates no Work task and sends no message. Private meetings include a gated audio-file import panel (MP3/MPEG, MP4, WAV, OGG or WebM, up to 32 MiB). It requires server-advertised processing readiness and explicit consent/participant notice, rechecks owner/policy context and recovers using the exact original file plus tab-scoped digest checkpoints. No raw file or filename is persisted in browser storage. Missing capture configuration leaves private notes usable. This adds file import, not microphone recording, and activates no provider. Recent private meetings are available through additive `opa.meeting_workspace.recent` (`GET /api/v2/opa/private-meetings?expectedOwnerScopeDigest=...`). Use the existing private creation-context digest; it prevents stale scope selection and grants no authority. The fixed latest-twenty view uses stored timestamps/readiness and optional 160-character canonical manual-note previews. Current authority is reproven before and after the encrypted owner read, and no caller scope or limit is accepted. CompanyOS renders snippets as plain text and reopens the existing meetingRef URL. Selected meeting workspaces expose **All private meetings** (English/French/Spanish) to return to the recent list without reloading. The control clears only `meetingRef`, preserves other URL state and does not let an unchanged host prop restore the old selection. Actual incoming meeting-reference changes remain synchronized. Pending planner placements expose a localized Check synchronization action that refreshes the live schedule and resolves only the matching focus block. Placement button state is scoped to the plan-run identity so a replacement proposal does not inherit an earlier accepted state. A bounded observer refreshes at most twelve times with five seconds between completed checks, stops when the pending reference clears or unmounts, and retains manual recovery afterward. Signed-client and browser acceptance remain separate qualification work. Placement refresh shares an immediate in-flight guard with the apply action, and schedule reads time out after twenty seconds so manual recovery remains possible. Schedule refreshes carry a local revision so late responses cannot overwrite newer planner state; unmount invalidates pending view updates. Task split preferences use the existing scheduling proxy and opa.work_split_preference.get/save operations. Owner identity is server-derived; saves use revision CAS plus an idempotency receipt and enqueue replanning atomically. Apply migrations 0088/0089 and verify runtime grants before deploying this workflow. Absent/null preference remains unsplit, and saving never changes the Work estimate or applies calendar effects. Production acceptance remains pending. The composition build explicitly targets Node-compatible server hosts (including Bun), matching the package runtime scope and default server rendering model. Existing `./ui` entry points, client directives, and Node/Bun export targets are preserved; the composition root does not advertise a browser condition. UI helpers import their existing implementations directly rather than re-entering the server composition barrel. This keeps presentation dependencies narrower without changing role affordances, evidence verification or public exports. UI projection imports use existing domain-specific view-model subpaths to avoid loading unrelated server domains through the all-domain barrel. Reusable sign-in config accepts optional emailOtpEnabled, magicLinkEnabled and passwordResetEnabled flags. Explicit false removes the related control; omitted values preserve legacy defaults. These presentation flags never grant authentication authority. OPA usability corrections: mobile booking exposes Change date from time selection; committed planner blocks group and display their saved timezone with both endpoints. Private notes identify unsaved edits and require explicit discard before Reload. Browser unload protection applies where supported; SPA navigation and meeting switching are not yet covered. Recent private-note filtering is local to authorized previews, and proposed-plan summaries distinguish sessions from distinct unscheduled Work tasks. Focused tests do not qualify deployed browser or signed-native journeys. OPA interaction recovery preserves unsaved private notes when the meeting workspace itself changes meeting or private/shared view: users can continue editing or explicitly discard. This guard does not intercept unrelated SPA links or external authority/workspace changes, and it does not persist private drafts. Planner mutation retries retain the exact pending request and idempotency key while the mounted sender remains alive; ambiguous responses block a different mutation until the original intent is resolved. Refreshing or unmounting does not provide durable client recovery. Public booking date/time transitions move keyboard focus into the visible panel. These UI protections do not establish browser-wide, native or production release qualification. OPA setup distinguishes booking configuration from calendar connection and keeps unknown readiness explicit. Private note navigation preserves the draft when anchor navigation is cancelled and restores appropriate focus. These client corrections do not grant server authority or qualify production readiness. Private briefing consent reads and draft operations reject superseded UI responses. Refresh clears stale consent settings, and consent changes clear the displayed draft immediately. This client fencing does not establish durable model retry recovery or provider cancellation. Private draft generation suppresses concurrent clicks and retains command identity for same-kind retries after failure. Keys are memory-only and clear after a validated successful result; page reload recovery and retrieval of a previously consumed command result remain outstanding. Processing consent can be revoked while private draft generation is pending. The client aborts its old request and rejects late generated content; server-side cancellation/preemption remains subject to the documented admission and locking behavior. Private briefing requests enforce browser deadlines across headers and JSON decoding: 15 seconds for consent and 60 seconds for drafts. Cancellation releases the UI even if a transport stalls; it does not prove that remote model work was cancelled. Canonical portable composition declarations use narrow `@lssm-tech/lib.contracts-spec-core` leaves. The original package i18n factory and hydration stack are owned by `@lssm-tech/lib.translation-runtime/contracts/i18n-factory`; historical facade paths remain compatible. This import migration does not qualify providers or authorize host actions. ## Autonomous Work Order fixture source projection Managed CompanyOS owns the complete semantic authoring modules under `generation/rolemorph/`. They are source-generation inputs with the original Surface module context, outside the bundle TypeScript `src` include and builder entry patterns. They are never compiled or imported as a second runtime. SurfaceRuntime retains its published fixture paths, barrel and singleton instance. Its contributor `fixture:generate` workflow parses the canonical ontology source and Core constructor source without importing either runtime module, then emits the complete original fixture bodies and a private typed six-reference binding. `fixture:check` rejects stale projections. Input SHA256 provenance covers both whole fixture sources, ontology/Core source and generator code; changed inputs are rejected before writing and after completion. Preparation, development, checks and publication inputs include the higher authoring source directly, without a bundle-build prerequisite or platform-to-domain dependency. The bundle exposes `./fixtures/autonomous-work-order` and `./fixtures/autonomous-work-order-helpers` as exact forwards to the same Surface instance. The generator admits only the existing six literal ontology records and the known import projection. It does not evaluate product policy or emit approvals. Generated outputs and their qualification are pending the controlled owning workflow; Source implementation alone is not resulting-tree acceptance. The canonical build retains its Node entry selection and emits the two fixture forwarding entries through `build:browser:fixtures`. Intentional published maps remain fixed, including all existing aliases and conditions. The full published surface and both new browser targets still require owning producer and consumer qualification. ## Founder canary and executive cockpit (G1) `src/founder-canary/` composes the G1 one-mailbox canary: a read-only mailbox adapter bound to one connection and driven by S03's history-based `createGmailMailboxSync` (so mail after a traversal is admitted), Knowledge `OriginalDocumentCustody` and readability extraction, S02 account→context routing mapped to server-resolved Work scopes (an account default stays a candidate until an item classifier or the founder confirms it, and the binding revision is re-verified before any Work write), read-time withdrawal of cited originals, an evidence-keyed adapter over `WorkManagementService`, and `PostgresFounderCanaryStore` (`founderCanaryMigrationStatements`, tenant RLS). `createFounderCanaryService` implements the four `founder.canary.*` contracts. `ui/founder-executive` renders Today, Needs you, Brief, Evidence and Recovery through contract data views with EN/FR/ES catalogs; `view-models/founder-executive` projects canary status, briefs and the S06 morning/EOD model, never upgrading stale or partial sources to success. All five surfaces are in the experience-coverage ledger as `implemented_local` with missing evidence until verified. ### Founder canary item classification policy Recorded owner decision (2026-10-15): until an item classifier is qualified, every canary message's concerned context is reviewed by the founder in Needs you, even when the receiving account has a default context. Hosts bind no `classifier` to `createAccountContextResolverPort`, and the API readiness reports `item_classifier: "manual_review_policy"`. Readable canary originals are recorded in the Knowledge evidence ledger (`createKnowledgeEvidenceRecorder`) once the context is confirmed, so a Gmail source or thread withdrawal also withdraws them; briefs drop withdrawn citations when read. Today renders the owner's newest validated S06 morning/EOD brief (`founder.dayBrief.read`) or states that the day context is not connected. --- ## @lssm-tech/bundle.marketing Description: Marketing surface bundle built from ContractSpec modules and design-system components. Path: packages/bundles/marketing URL: /llms/bundle.marketing # @lssm-tech/bundle.marketing **Marketing composition bundle for the public ContractSpec site: category-defining substrate narrative, technical product/templates/examples pages, support pages, and email-facing marketing helpers.** ## What It Provides - Marketing page bodies consumed by `@lssm-tech/app.web-landing` - Platform-neutral landing story, navigation, page, and examples-entry data consumed by web and Expo shells - Scenario/template browsing and preview surfaces used on `/templates` - Support and program pages such as contact, contribute, cofounder, and design-partner - Email/contact helpers and marketing-adjacent utilities ## Architecture - `src/components/marketing/` owns the public marketing narratives, section composition, and page-level stories. - `src/content/` owns React-free story data shared by web and mobile shells. - `src/content/companyos-marketing-contracts.ts` owns the CompanyOS marketing `MarketingSiteContract` instances consumed by the web app. It imports the shared `@lssm-tech/lib.contracts-spec/marketing` validators, keeps CompanyOS copy in the bundle, and declares the route narrative, section sequence, density, deep-dive routes, CTAs, and evidence refs for `/`, `/product`, `/solutions`, `/solutions/ai-ops-automation-sprint`, `/platform/managed-contractspec`, `/autonomous-companies`, and `/pricing`. - `src/components/templates/` owns template browsing, preview, and template-to-CLI/Studio flows. Preview content uses the shared example preview host from `@lssm-tech/module.examples/runtime` so UI-backed and fallback examples stay aligned with docs and sandbox. - `src/libs/email/` owns contact/newsletter/waitlist actions and helpers used by marketing surfaces. - `src/index.ts` is the root public entrypoint. The important boundary: - `@lssm-tech/lib.design-system` owns reusable marketing atoms, molecules, sections, and the typed landing-page section sequence. - `bundle.marketing` owns story/content mapping, icon lookup, and product-specific page composition. - Existing `./components/marketing/sections/*` subpaths remain compatibility shims over design-system components. - CompanyOS contract pages use one render path: `MarketingPageContract` → design-system `MarketingPageSection[]` adapter → existing marketing landing primitives. The bundle supplies content and page contracts; the design system adapts generic presentation props; apps retain route metadata, structured data, canonical URLs, and Next.js shell concerns. - App packages own routing, metadata, OG, shell, and public delivery. ## Template preview workflow `bundle.marketing` stays a thin consumer of `@lssm-tech/module.examples` preview metadata: - `/templates` actions should be derived from `supportsInlineExamplePreview()` and the shared preview surface, not bundle-local allowlists. - Rich preview content belongs in the example package `./ui` export or an explicitly approved module/examples adapter; marketing should not duplicate domain preview implementations. - Keep fallback CTAs to docs, sandbox, LLMS, and source links for examples that are discoverable but not inline-preview enabled. - Preview data must remain deterministic and provider-free; no marketing preview should require live backends, provider credentials, or network execution. ## Public Entry Points - Root export `.` through `src/index.ts` - `./content` for platform-neutral landing story data and CTA helpers - `./content/companyos-marketing-contracts` for CompanyOS marketing page/site contracts and validation helpers - `./i18n` for a small marketing copy runtime used by app metadata and locale-provider composition - `./components/marketing/*` for landing, product, pricing, contact, contribute, cofounder, and design-partner surfaces - `./components/marketing/NewsletterSignup` for the localized newsletter form (`marketing.newsletter.*` keys); hosts inject the `NewsletterSignupAction` server action and keep its binding - `./components/templates/*` for templates browsing and preview surfaces - `./libs/email/*` for marketing contact/newsletter/waitlist helpers ## Marketing route contract system `src/content/marketing-route-contracts.ts` exposes exact, generated, and runtime-family `MarketingPageContract` registries for the CompanyOS and ContractSpec public marketing route groups. Adapter-rendered pages keep using the full contract renderer; bespoke pages consume the same route contract system through an inert design-system boundary so existing page copy stays owned by the current components. ## CompanyOS "Room for the real work" campaign pages Three audience landing pages, rendered by `@lssm-tech/app.web-application-monolith` under its marketing layout. That layout applies `CampaignThemeScope` (the `companyos.design.room-for-work` campaign theme from `@lssm-tech/bundle.managed-companyos/design`, fixed light mode) to every marketing route. A visitor's saved workspace design is never read or changed. - `./content/companyos-campaign`: React-free en/fr/es page content. `COMPANYOS_CAMPAIGN_ROUTES` maps each `CampaignAudience` to its route: `owners` → `/for-owners`, `trades` → `/for-trades`, `intake` → `/for-client-intake`. `getCompanyOsCampaignPage(audience, locale)` resolves the content for a normalized locale and throws for an audience without registered content. All three audiences have registered content in en, fr and es; each file is still marked `draft_for_native_review` from `specs/companyos-visual-growth`. The audience and content types are exported as types. - `./components/companyos-campaign`: the page compositions `CompanyOsOwnersPage`, `CompanyOsTradesPage` and `CompanyOsIntakePage`, the shared sections (`CampaignComparison`, `CampaignEvidencePanel`, `CampaignFaq`, `CampaignClose`, `CampaignFilm`, `CampaignFilmView`, `CampaignSplitSection`, `CampaignStoryBand`, `CampaignWalkthrough`, `CampaignStill`) and the design atoms (`CampaignCta`, `CampaignHeading`, `CampaignLabel`, `HandoverFrame`). - Route contracts: `createCompanyOsOwnersContract`, `createCompanyOsTradesContract` and `createCompanyOsClientIntakeContract` (`src/content/companyos-assistant/contracts-campaign.ts`) build each page's `MarketingPageContract` from the same content, with `route` taken from `COMPANYOS_CAMPAIGN_ROUTES`. They are composed into the CompanyOS marketing site contract. - Campaign films: `src/content/companyos-campaign/media.ts` lists each film and locale explicitly. A locale without media is `null` and the player renders a text alternative, never another language. `videoSrc` stays `null` until an approved export is on first-party storage. Audience routing is a presentation and copy choice only. `CampaignAudience` is never persisted as a role, permission or preference and never changes what a visitor may access. The owner experience is publicly named **Fellowhand** (`fellowhand.com`, `app.fellowhand.com`); the expert-network experience is **Briefhand** (`briefhand.app`, `app.briefhand.app`). Their existing EN/FR/ES content, `companyos.owners` and expert-network contracts, route IDs, and component exports stay under CompanyOS. The web host chooses the composition by an exact hostname allowlist and owns canonical metadata. `getCompanyosBrand(locale, publicName)` and the footer accept the selected public name while retaining CompanyOS and its existing contact channels. Default callers still render CompanyOS. The app host enters `/companyos` with the same verified session, workspace, persona and capability policy. A public brand name never grants access or qualifies a new Better Auth origin; deployment must qualify new app origins against the existing production topology before advertising working sign-in. Do not add prices, dates, SLAs, certifications or early-stage offer labels to campaign pages without an approved claim-ledger entry. ## CompanyOS v2 assistant site The CompanyOS public site (`companyos.run`, hosted by `@lssm-tech/app.web-application-monolith`) presents CompanyOS as the company's personal assistant installed under the customer's control (spec: `specs/companyos-restyle-v2`). - `./content/companyos-assistant`: React-free en/fr/es story data for `/`, `/on-premises`, `/content-assistance`, `/pricing` and `/example`; `COMPANYOS_ASSISTANT_ROUTES`; `withCompanyOsLocaleHref`; contract builders (`contracts-home.ts`, `contracts-pages.ts`, `contracts-pricing.ts`) composed into `companyos.marketing.site`. Editorial strings use ` ` for line breaks and `*text*` for the serif emphasis. - `./components/companyos-assistant`: page compositions (`CompanyOsAssistantHomePage`, `CompanyOsOnPremisesPage`, `CompanyOsContentAssistancePage`, `CompanyOsPricingPage`, `CompanyOsExampleWorkspacePage`) and shared sections. Every section carries `data-marketing-section` equal to its contract section id; page tests assert the match. - Styling uses semantic design tokens only, so pages follow the active design pack (CompanyOS defaults to `companyos.design.calm-assistant`). - Examples are illustrative: no account, inbox, model or calendar is connected and nothing is sent or published. Do not add prices, dates, SLAs, certifications or early-stage offer labels without an approved claim-ledger entry. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 ## Notes - Keep the bundle focused on page storytelling and marketing interaction flows. Do not move shell/routing concerns here. - Public positioning in this package must stay aligned with root docs and `@lssm-tech/app.web-landing`. - If the page story changes materially, update the package docs and the public LLM-facing docs so human-facing and agent-facing descriptions do not drift. ## Design-system marketing foundation split Generic full-page marketing UI now lives in `@lssm-tech/lib.design-system`. The marketing bundle keeps product story/content ownership and exposes compatibility wrappers for existing section subpaths such as `CtaButtonRow`, `MarketingHero`, `MarketingCtaBand`, `ProseSection`, and `IconGridSection`. Consumers can keep using the bundle section subpaths while new product pages should compose content into design-system `MarketingPageSection` objects when they need full landing-page foundations. --- ## @lssm-tech/bundle.marketing-operations Description: Shared governed marketing operation server composition. Path: packages/bundles/marketing-operations URL: /llms/bundle.marketing-operations # Marketing Operations composition The data-only root describes implemented capabilities and required host ports. `./server` exposes `createMarketingOperationsServer` and `./mcp` exposes `registerMarketingMcpTools`. Both use the same canonical operation registry. `./site-mcp` owns the public marketing site MCP surface that the contractspec.io and CompanyOS hosts serve at `/api/marketing-mcp`. It binds the three Growth site operations (`marketing.product.get`, `marketing.plans.compare`, `marketing.demo.book`) from `lib.growth-spec` to their `lib.growth-runtime` handlers, and exposes the framework-neutral JSON gateway (`executeMarketingTool`, bounded `SlidingWindowRateLimiter`), the MCP 2024-11-05 JSON-RPC dispatcher (`handleMcpJsonRpc`) and the embedded-agent config (`createMarketingChatConfig`). Product facts and plan comparison are public reads; `demo.book` is default-deny without an authenticated user (UNAUTHENTICATED at the MCP transport gate, FORBIDDEN from the PDP) and limited to its contract `rpm`. Hosts keep the request body cap, trusted client IP, session lookup and feature flag. The `./site-mcp/marketing-agent-config`, `./site-mcp/marketing-mcp` and `./site-mcp/marketing-registry` subpaths expose the individual modules. This `registerMarketingMcpTools` takes a tool-context factory for the public site tools; the `./mcp` export of the same name mounts the authenticated operations registry. The surface replaces the deprecated `@lssm-tech/lib.contracts-runtime-server-mcp/marketing*` subpaths with the same exports. `./ui/MarketingWorkspace` exposes the localized goal-to-plan interface. It displays questions, assumptions and proposed actions, with host-owned detailed action review. It does not execute a model's suggestions. `onPropose` binds to authenticated host transport; the optional controlled `proposal` prop can be refreshed by the host. Supply `planning` dependencies to the server to enable durable, contract-validated goal proposals at `/marketing/plans/propose` and `/marketing/plans/get`. Inference requires scoped approval and idempotent cost authorization. A proposal request ID is reserved before calling the model, so retries do not buy another generation. Every step must match a registered/allowed operation and pass host resource validation. The full composition now exposes 39 REST/MCP operations with every optional service configured. `scripts/preview.ts` serves a synthetic browser QA fixture on loopback only. It is not a production deployment and never invokes a model or payment/ad provider. Supply a durable `MarketingExecutor`, `MarketingCopyGenerator`, and an authorized brief loader through `MarketingOperationsDependencies`. The host context resolves the authenticated actor, tenant, workspace, PDP, and shared approval runtime. Execution and copy generation declare cost-bearing effects and require scoped approval receipts before their handlers run. The executor independently checks the plan digest, mandate, current rights, provider qualification, and provider state. There is no default authority, credential, in-memory production store, or advertising provider. Hosts must mount this with the same isolation controls in managed and self-hosted deployments. This package is a server composition foundation; a complete standalone UI, creator migration, campaign-provider certification, and production deployment are not yet delivered. The new API endpoints are declared in `lib.growth-spec/marketing/operations`: - `POST /marketing/executions` - `POST /marketing/executions/reconcile` - `POST /marketing/executions/continue` - `POST /marketing/copy` Supply the optional `editorial` host dependency to bind thirteen standard operations under `/marketing/editorial`: create, revise, submit, review, schedule, reschedule, unschedule, associate (refused without an `editorial.context` port), archive, publish, reconcile, get and due. List, history, recovery and preparation resume are additional operations when the store or publisher supports them. Their declarations live in `lib.growth-spec/marketing/editorial-operations`; every editorial operation is version 2.0.0. Editorial and advertising authority are independent. REST tests cover authentication, tenant/workspace substitution, storage effects and publication/copy approval gates. ### Editorial record v2 (TS-01-EDCORE) - **Record:** editorial records are `schemaVersion: 2`, stored in the `editorial_record` and `editorial_record_history` tables from `integration.growth-persistence`. Content is a payload discriminated over the eight content kinds, plus field-addressed claims, public author/contributor/sender/recipient bindings and a pinned `briefRevision`. Summaries filter and report `kind`. - **Policy evaluator required:** pass `editorial.policy` (an `EditorialPolicyEvaluator`, for example `createEditorialPolicyEvaluator` from `lib.growth-runtime/marketing/editorial-policy`). Without it the server installs `refusingEditorialPolicy`, so submit, review approval, scheduling and publication are refused (`POLICY_UNAVAILABLE`) rather than allowed. The fingerprint bound at submit must still match at review, schedule, publish and due execution. - **Scheduling:** schedule and reschedule need an IANA `timeZone` and the three acknowledgements (exact content and identity, unattended publication, informational and non-duplicative) plus the temporary-images flag. The server computes the 15-minute window and refuses past or over-30-day times. - **Admission bridge:** `growth.editorial.admit` is not registered on this registry, so REST and MCP return 404 for it. Studio hosts call `createEditorialAdmissionBridge` from `module.editorial` with an authenticated actor and a rights check reference. - **Native kinds:** the editor and the site compiler handle long-form kinds only; `createNativeEditorialGitCompiler` refuses native kinds with `EDITORIAL_NATIVE_KIND_UNSUPPORTED`. The record detail data view still shows only the long-form Markdown body, so native fields are not rendered there yet. A native-kind editor is not provided. Supply optional `creators` dependencies to bind eleven canonical creator operations under `/creator-operations`. This brings the combined registry to 24 operations. The creator store is transactional, agreements are immutable, and every settlement rail consumes the same wallet reservations. Runtime approval and provider evidence are still required; mounting the module does not enable production payouts. See the repository Marketing Operations implementation status for remaining work. `./advertising` composes Meta, Google and TikTok HTTP providers with the durable recipe executor and marketing reservation engine. Supply recipe/receipt stores, current request and recipe authority, a reviewed compiler and a read-only reconciler. No constructor sends requests or enables spend. Launch compilation supports typed Meta, Google Search/Display/Demand Gen/Performance Max and TikTok plans; campaign controls support pause/resume against a checked provider-state digest. The continuation operation reauthorizes pending work without reserving the same budget again. The advertising compiler composition also supports reviewed budget adjustments and creative replacement. Configure `AdvertisingCampaignCompiler` with the launch, control, budget and creative compilers. The host loads immutable change documents and exact native resource mappings; the execution plan must reference their digests in reviewed evidence. Use `createMarketingConversions` from `./advertising` to compose the conversion service with scoped providers, durable storage, current consent authority and read-only recovery. Supply it as the server's optional `conversions` dependency to mount three operations at `/marketing/conversions/deliver`, `/reconcile` and `/get`. Delivery requires its own approval. The original registry remains unchanged when the optional service is absent. `createMarketingObservations` from `./advertising` composes native read providers with a required evidence store, current scope authority and immutable snapshot storage. Supply it as the optional `observations` server dependency for `/marketing/observations/refresh` and `/get`. Results separate review/eligibility/configuration and include a stable state digest. Source mappings must verify each native resource belongs to the scoped campaign. `./social` exports `createMarketingSocialScheduling`, which composes durable schedules with the existing social publication runtime. Its default remains draft-only. Configure SQL schedule/intent/lease ports, current signed grant verification, policy/audit ports, qualified LinkedIn/X providers and an explicit publication autonomy mode. Pass the result as optional `socialScheduling` to mount eight schedule operations. Register the worker with the existing lifecycle scheduler and persist each batch result. Live LinkedIn/X publishing, account access and media formats still require qualification; the local scheduling tests use simulated provider effects. Configure the optional scoped LinkedIn publisher under `publicationPorts.providersV2.linkedin`. The SQL scheduling composition preserves its creation URN and confirms through tenant/account/author-bound reads. Hosts supply approved materialization, ready assets, qualified LinkedIn contexts and credentials. Provider qualification and media upload pipelines remain installation work. Configure the scoped X publisher in `publicationPorts.providersV2.x` with a durable `SqlXPublicationStore`, qualified materialization, current per-part grant/metering checks and exact-request recovery evidence. The scheduler reconciles uncertain thread parts before resuming only unsent work. Configure the native upload composition below for new media; live account qualification remains separate from mocked transport tests. For X media, compose `XNativeUploadProvider` with `SqlXUploadStore` before materializing reviewed publication. The uploaded-asset projection returns the native ID/key only after processing succeeds and before expiry. SQL integration tests cover uploaded video through scheduling and native attachment confirmation. Live qualification remains host-owned. LinkedIn image/video uploads can use `LinkedInMediaJobRuntime`, `SqlLinkedInMediaJobStore` and `LinkedInSecretSessionVault`. Supply a versioned secret backend, exact native recovery receipts and authorized immutable asset reads. Project ready media into the existing publication materializer with current rights checks. Standalone worker wiring and live qualification remain separate requirements. `./installation` exposes `createMarketingOperationsInstallation` for both deployment modes. Supply the canonical server, explicit worker mode and readiness checks. Concurrent starts/stops share lifecycle work, partial startup rolls back registrations, and failed cleanup can be retried. Public probes reveal only liveness/readiness. Mutations from a foreign browser origin are rejected; canonical operation approval checks remain intact. `./workers` adapts the existing durable social scheduler into a registration that stops new callbacks and drains active batches. Registrations must clean up resources they create if startup fails before returning a stop handle. The thin `app.marketing-operations` shell binds HTTP before starting workers and loads trusted deployment composition from a module. A turnkey installation, standalone frontend and managed provisioning remain incomplete. `./ui/planning-client` exposes `createMarketingPlanningBrowserClient`; use it with `./ui/ConnectedMarketingWorkspace`. The host supplies an authenticated actor/scope/brand binding, same-origin fetch and an exact-input approval callback. The browser binding is a cache partition, never server authorization. No receipts or goal text are persisted in browser storage. Identical actor/intent/goal/context produces the same durable request ID, including after a lost response or client recreation. Set a new intentRef only for an explicitly separate generation. Check progress calls the canonical read operation without inference approval. Responses must match the original request before rendering; switching scope remounts the workspace and clears previous visible results. Detailed review/execution remains host-owned. The standalone authenticated bootstrap and approval experience are not yet wired by default. Supply optional `workspace` to register the authenticated `/marketing/workspace` query. Its brand selector is resolved against the current actor, tenant and workspace; the loader must authorize access and return the approved brand revision. Bootstrap returns no credentials or execution grants. The full optional composition exposes 40 operations. `BootstrappedMarketingWorkspace` loads that query before creating the planning client. Change its sessionKey on login/logout or session changes to clear the previous view. The optional server `approvalReceipt` callback adapts transport evidence; the existing context approvalPort still decides whether that evidence authorizes execution. `PlanningApprovalReview` displays a host-issued exact-input planning quote, maximum cost and expiry. Its controlled callback invokes the existing issuer; the component never mints receipts. Expired quotes cannot be approved, duplicate clicks are locked, and uncertain callback failures require status resolution rather than blind retry. The quote issuer and production approval workflow remain installation requirements. `ReviewedMarketingWorkspace` composes authenticated bootstrap, planning and quote review. Provide a `MarketingPlanningApprovalGateway` backed by the existing server authority; quote/issue/status must bind the actor, exact input, maximum cost and expiry. Issuance must be idempotent by quote ID. The UI controller resumes the waiting planning call only with the returned receipt, rejects quote substitution and uses read-only status recovery after uncertain issuance. Change sessionKey on principal changes; unmount discards local waiting without claiming to revoke durable receipts. Production gateway routes and issuer configuration remain required. Configure optional `planningApproval` to mount quote, issue and status operations at `/marketing/planning-approvals/*` (43 operations with all optional services). The injected authority must authorize brand access, persist quotes, verify explicit human review and issue scoped receipts idempotently by quote ID. Authentication alone is insufficient. `createMarketingPlanningApprovalGateway` implements the browser transport; supply host CSRF/step-up handling through its fetch callback. Issuance/status receipt outputs are marked transient and redacted by operation contracts. No permitting issuer is supplied. The planningApproval host port can now use MarketingPlanningApprovalService with SqlPlanningApprovalStore. Configure pricing, brand authorization and explicit human review verification. Wire createOperationApprovalPort with the service's verifyEvidence and the SQL store as nonceStore; never use the verifier's permissive evidence default. Human authentication, quote pricing and reviewer evidence still require host integration. Use `withMarketingPlanningApproval(host, {service, nonceStore})` from `./planning-approval-host` to install the durable planning verifier and receipt decoder. It requires both persisted evidence and the supplied nonce store, rejects malformed or unrecognized receipt headers, and preserves existing approval handling for other operations. The resulting host can be passed directly to createMarketingOperationsServer. Supply `metricReports` to expose `/marketing/metrics/report` and the matching MCP query. The loader must authorize brand/campaign access, authoritative source and freshness policy. The module rejects foreign tenant/workspace scope before loading observations. The complete optional registry now contains 44 operations. Missing periods remain unavailable in the returned report, with provenance and explicit reasons. `./optimization` wraps the existing self-improvement lifecycle effect port for acquisition economics or creator performance. Configure the exact program and marketing scope plus an authorized immutable evidence loader. Promotion requires matching candidate artifact, program revision and experiment scope, then an eligible marketing assessment. Existing authority/gates still decide whether the effect may run. Inconclusive evidence and guardrail failure block promotion; rollback/kill behavior remains available. This does not qualify statistical methods or install autonomous provider effects by itself. Marketing optimization composition also requires `recordEvidence`: persist the exact readout/assessment document idempotently and return its SHA-256 artifact reference. The wrapper verifies that reference before effects and appends it to the lifecycle receipt. A failed or mismatched evidence write blocks promotion. Lifecycle integration tests drive acquisition and creator programs through shadow, canary, observation, an inconclusive promotion hold, qualified promotion, replay and regression rollback. Assessment artifacts use the SQL store; candidate lifecycle state and effects remain simulated. This is not live statistical or production qualification. The optimization lifecycle scenarios now use SqlMarketingOptimizationLifecycleStore for candidate state/history and SqlMarketingOptimizationEvidenceStore for assessments. Both initial programs pass shadow/canary/observation/promotion/replay/rollback paths with durable SQL state. External effect transports remain simulated and require qualification. `createMarketingWithdrawalWorker` from `./withdrawal-worker` binds withdrawal processing to the installation worker lifecycle. Supply authorized durable pending-use discovery and a durable result observer; scope-bound scheduler IDs isolate installations. Batches are bounded, overlapping local ticks are skipped, and shutdown stops new work and drains active callbacks. The ContentWithdrawalWorker retains provider claims/reconciliation. The scheduled withdrawal integration test now uses SqlContentWithdrawalQueue for both discovery and result tracking. Completed uses disappear from subsequent batches without manual queue edits, while unresolved items retain fair attempt ordering. Provider effects and installation authorization remain simulated in this test. Supply `contentRights` to expose grant/use/revoke/get/withdraw operations at `/marketing/rights/*`, bringing the full optional registry to 49 operations. Scope checks precede service access; grant recording and provider removal require operation approval. Rights service authorization and durable native withdrawal remain independently required. `withMarketingRightsPreflight` wraps existing advertising authority with current rights checks for declared grants. The resolver must bind the exact reviewed plan/assets to registered-use IDs and the authorized actor. Every grant must be covered by an active use on the advertising channel with paid-amplification permission. Existing budget, provider-state and qualification checks still run. Pause remains available after revocation; this wrapper is not a lease over later provider dispatch. Supply `creatorTraining` to mount `/creator-operations/training/open` and `/update`. The full optional registry now exposes 51 operations. The injected service owns course access, quiz evidence validation and transactional request replay; mounting does not migrate Hirly records or replace its current training writer. Optional creatorTrainingProgress mounts the read-only training summary query at `/creator-operations/training/progress` and MCP. Missing state returns `not_started` without progress initialization. Full optional composition now has 52 operations. Optional creatorQuizCompletion mounts `/creator-operations/training/quiz/complete` and its MCP command. Input contains answers and expected training version, never a claimed score. Private-key authorization/scoring and durable progress replay remain in the injected completion service. Full optional composition now contains 53 operations. Optional creatorQuizView mounts the authorized public quiz-read operation at `/creator-operations/training/quiz/get`. Strict response validation rejects private answer-key fields and mismatched revisions. Full optional composition has 54 operations. The loader must enforce creator/course enrollment and requested locale. `createMarketingEditorialWorker` invokes due discovery and publication through the canonical registry. Its host context callback supplies exact-input approval evidence for each publication; no background authority is inferred. Result observation is required, local overlapping ticks are suppressed, and shutdown drains the active batch. Unknown publication reconciliation remains a separate existing operation, not a blind retry. Configure a separate editorial worker with `mode: "reconcile"` to discover and reconcile persisted unsettled publications. `minimumAgeSeconds` defaults to 60 (30–86400 allowed); publication remains the default worker mode. Recovery requires the optional store-backed recovery operation and current reconcile authority. Both modes drain on stop, and explicit stop closes dispatch before scheduler unregistration. `editorial-restart.test.ts` rehearses interrupted terminal persistence and database reopening through the recovery scheduler. It preserves publication identity and provider receipt without redispatch; provider responses remain simulated. `createNativeEditorialGitCompiler` adapts an existing strict native compiler and its application readiness function to the shared Git compiler port. Supply an authorized approved-source loader, `compileNative`, and `publicationState`. It binds the exact requested title/body/locale/canonical URL to one compiled edition, verifies the returned receipt against native edition digests and configured locales, then packages unchanged Markdown sources and the approved publication manifest. The Hirly rehearsal script exercises its current compiler and source-derived readiness projection without changing its deployment. `createGitEditorialModule` from `./git-editorial` composes the editorial publication service, durable Git publisher, native GitHub transport and HTTP deployment verifier. Assign its result to the marketing server’s optional `editorial` host field. Supply migrated editorial/Git stores, native compiler, IDs/clock, and separate domain/artifact/repository/deployment authorization functions; construction performs no network activity. The composition test uses both SQL stores and native GitHub/HTTP adapters with simulated HTTP responses, retaining unknown state until deployment readiness is confirmed. Feed `GitHubEditorialSourceLoader.load(record)` into the native compiler’s approved-source callback, adding installation-native compiler options and its returned `publicationManifest`. The returned target preserves the reviewed `sourceCommitSha`. The Hirly rehearsal now covers the loader, native compiler and readiness projection together using simulated pinned GitHub reads. The native compiler always receives the complete source snapshot. Optional approved `commitPaths` control only the emitted mutations, must include the requested edition, and cannot name unrelated files. Tests cover a 145-edition cohort, its initial 146-file artifact, and a six-file incremental artifact. Git editorial installations expose `editorial_resume_preparation` through the canonical registry. Operators must approve the exact claim and expected revision; supported recovery preserves the claim and cannot repeat an existing Git dispatch. The clean packed-consumer check now installs the complete marketing bundle dependency closure and runs on Bun and Node without source aliases. It exercises Git editorial composition, exact-input preparation-resume approval and durable compiler rejection. `docs/evidence/marketing-operations/packed-consumer.json` records the tested archive and projected-manifest fingerprints; this is not an npm publication claim. Editorial-capable SQL installations expose paginated summary discovery. HTTP tests verify no-store responses, scope rejection and unavailable-capability behavior. `./ui/EditorialWorkspace` provides a connected, read-only editorial workspace with contract-driven filters, cursor pagination and localized EN/FR/ES chrome. Supply an authorized scope, a non-secret sessionKey that changes with the actor session, and optionally onOpen for a custom host detail route. Fetching defaults to the same-origin API. Late responses are ignored after filters or sessions change; errors never masquerade as empty results. Keyboard pagination moves focus into newly loaded records. Schedules are explicitly displayed in UTC. `EditorialWorkspaceView` is available for controlled hosts. `loadEditorialRecord` from `./ui/editorial-detail-client` fetches the current revision through the canonical same-origin detail endpoint. It checks tenant/workspace/brand, record identity and the content digest before returning data; callers must still use the returned revision for subsequent mutations. EditorialWorkspace now opens its verified read-only record panel by default; an optional onOpen callback preserves custom host navigation. Selection/session changes cancel prior detail requests. Opening focuses the record heading; returning preserves collection state and focuses the workspace heading. Loading and denied states hide prior content. EditorialRecordPanel and EditorialRecordView are separately available for host composition. The clean-consumer probe includes current-record retrieval and French detail rendering from built exports, including the Markdown block-nesting regression check. `saveEditorialRevision` submits one expected-revision edit attempt, verifies the returned draft/digest and invalidated approvals, and never retries uncertain writes. After an unknown outcome, load the current record before another save. `EditorialEditorController` preserves local draft text during save conflicts and uncertain outcomes. It blocks another write until recovery reads current state and the operator explicitly adopts a conflicting revision. Disposal ignores late responses. The controller is not yet mounted in editor controls. `EditorialEditFields` renders the canonical long-form (blog and landing page) title/Markdown form through the design-system form renderer and EN/FR/ES translation context. It merges edited text with host-supplied verified provenance. Mount it only during editable controller phases; save/recovery controls remain host composition. Editable record states now expose the integrated editor. Save/recovery phases preserve local text, show remote conflicts before explicit adoption, and block closing during active saves. Returning with unsaved text requires an explicit discard choice. Unknown saves recover via a verified read; the form never retries the write automatically. Editor state guards also reject terminal publications when invoked directly. Recovery cannot reopen a record that became published elsewhere; local text remains available for comparison. A 375px browser rehearsal verified direct saving without overflow or console warnings. Draft and changes-requested detail panels now offer Submit for review. The client sends the expected revision once, verifies the returned in_review state and unchanged content, and requires a refresh after an uncertain result. This action does not approve or publish content. Submission qualification includes a REST/SQL concurrency test (one accepted revision, one conflict) and a browser lost-response rehearsal that recovers in_review via refresh without resubmitting. `recordEditorialReview` records an explicit supplied review decision/evidence against the current in-review digest and revision. It never mints authority receipts, retries uncertain writes or treats a returned approval with altered evidence as success. Pass optional prepareReview to EditorialWorkspace/EditorialRecordPanel to expose two-step review decisions. The installation supplies reviewer identity, digest- and policy-fingerprint-bound evidence, a note for changes_requested and the authority receipt; the UI displays those before an explicit confirmation. Preparing evidence performs no mutation. Unknown writes remain held until record refresh; installations without the callback do not expose review decisions. Disposed review controllers now discard prepared evidence and refuse confirmation. Shared controller lifetime handling tolerates React StrictMode effect replay while disposing actual unmounts and replaced controllers. Review REST/SQL qualification verifies denied evidence authority, mismatched reviewer identity and concurrent opposing decisions. One decision is persisted with its evidence; the competing request receives a revision conflict and no publication is created. Review browser qualification covers prepare/cancel, explicit changes-requested/approval decisions, mobile evidence inspection and heading focus after the persisted revision changes. Test authority is synthetic; installations still supply production review evidence. `scheduleEditorialRecord` schedules one approved revision through the canonical API with an IANA time zone and the three acknowledgements, preserving review evidence and verifying exact destination/time in the response. The server owns clock and destination authority; unknown outcomes require read recovery rather than write retries. Scheduling REST/SQL qualification verifies destination denial, server-clock rejection of past schedules, concurrent-request exclusion, review preservation and appearance in due discovery only at the scheduled time. Supply optional loadDestinations to the workspace/panel to expose scheduling for approved records. The callback receives the verified record and returns authorized destination IDs/labels. The form rejects ambiguous local time strings and sends explicit UTC. Server time and current destination authority remain authoritative; uncertain saves require refresh. Scheduling browser checks verify destination option labels, controlled initial fields and the exact saved UTC timestamp/destination in record details. The supplied destination label is mapped to the form renderer labelI18n property. `publishEditorialRecord` requires an opaque exact-input approval receipt supplied by the installation. `reconcileEditorialPublication` uses the separate recovery endpoint without implying new publication authority. Both verify scope/content/claim/destination bindings; publication success requires provider receipt and public URL. Clients never retry writes automatically. Publication-client qualification now exercises canonical REST approval validation and SQL claim persistence: unrecognized receipts fail before dispatch, a reused nonce permits one attempt, and a lost provider response recovers through reconciliation without publishing again. Supply optional approvePublication to expose two-step publication on scheduled records. The installation receives the canonical operation/input plus the reviewed record, and returns an opaque execution receipt. The UI keeps the receipt out of rendered state, requires explicit confirmation and never retries an uncertain write. Publishing/unknown records expose reconciliation separately. Publication browser qualification covers cancel-before-dispatch, explicit confirmation to an uncertain result, and separate reconciliation to visible provider proof. The preview uses synthetic state responses; real clock, approval and SQL dispatch checks are covered separately. Publication response validation also requires lifecycle/claim-status agreement and definitive failure receipts. An unchanged revision may only return the identical record; contradictory or unversioned state changes remain uncertain. `createEditorialDraft` requires a stable caller-owned ID and verified content/provenance input. It sends one create request and checks the returned initial draft. After uncertainty, read the same ID; repeated creation returns conflict rather than allocating another draft. `EditorialCreateController` owns one immutable creation intent, coalesces creation attempts and resolves uncertainty with a read of the original ID. Recovery checks content and assignee before adopting the record; conflicting content remains a conflict and no automatic replacement ID is allocated. Optional prepareDraft enables workspace creation. The installation returns a complete creation intent with stable ID and provenance. Operators inspect the title/body/ID before confirming. Uncertain creation remains attached to that ID with read recovery; opening is offered only after confirmed or matching recovered creation. Creation browser qualification verifies prepared-content preview, original-ID retention after a lost response, read recovery and opening revision 1 with no console warnings. The preview backend is synthetic. The clean-consumer probe now exercises create → revise → submit → review → schedule → approved publication → reconcile using public clients, the canonical REST handler, and SQL history. Bun and Node both finish at revision 8 with eight history rows, one provider dispatch and one recovery read. `archiveEditorialRecord` retires an unpublished revision without deleting content/history. The client rejects published and uncertain publication states, validates schedule removal and retained review evidence, and never retries uncertain writes. Eligible record details now offer archival with a separate confirm/cancel step explaining schedule removal and retained history. Published, publishing, uncertain and already archived records show no archive action. Unknown writes stay held until refresh. Archive browser qualification confirms cancellation leaves the draft unchanged, confirmed archival preserves inspectable content, and editing/publication actions disappear in archived state. Focus returns to the record heading. Returning from integrated record details refreshes the collection from its first cursor while preserving selected filters. Records changed by review/scheduling/archival no longer remain visible under stale filter membership. `loadEditorialHistory` validates each historical revision, identity, digest and continuation cursor before returning it. Missing or skipped revisions are reported as unavailable rather than silently shown as complete history. Record details include on-demand revision history. The history panel fetches bounded authorized pages and opens a clearly labeled read-only historical detail without mutation actions. It only selects revisions present in the fetched page and discards late responses after disposal. History browser checks verify original content after edits, read-only inspection and focused historical headings. Revision rows use compound record/revision identities and record action/history sections have distinct React keys. ### Durable media status The additive `content-generation.media.status` v1 query exposes persisted generation state, revision, artifact references and expected output count through `POST /marketing/media/status` and MCP `media_generation_status`. It never polls providers or dispatches generation. Installations supply an authorized reader; the marketing host mounts it only when configured. Tenant, workspace and generation ownership are checked before returning progress. Provider URLs, connection keys and payment reservation references stay private. Existing draft generation operations retain their behavior. --- ## @lssm-tech/bundle.mission Description: Brand-neutral mission experience bundle (D-122 E layer): mission, recruitment and contribution surfaces composed over the mission domain owners, reused by every mission brand composition. Path: packages/bundles/mission URL: /llms/bundle.mission # @lssm-tech/bundle.mission Private, brand-neutral mission experience bundle (D-122 E layer, TAFIO-APP-00). It composes mission, recruitment and contribution surfaces over the mission domain owners (planned by D-112d); every mission brand reuses it through its own composition bundle. - Behavior stays in the mission domain owners and persistence in their integration owner; this bundle composes, it does not store. - No brand names, brand copy, pricing or hostnames: those belong to brand composition bundles and the G-layer registries. - Compensation observations are not payment execution. Skeleton only (TAFIO-APP-00): the package exports nothing yet. --- ## @lssm-tech/bundle.osint Description: Composable OSINT provider routing and operator view models Path: packages/bundles/osint URL: /llms/bundle.osint # `@lssm-tech/bundle.osint` Reusable composition for all supported web-access providers and OSINT operator view models. Explicit provider plans can use Serper search, Linkup or Tavily deep research, Bright Data or Massive collection/proxy methods, and Browserbase rendered sessions. API, SDK, MCP, webhook, WebSocket/SSE, browser, and proxy capabilities remain visible in provenance rather than being flattened away. Each router is pinned to one deployment, credential namespace, and provider allowlist; bounded requests persist evidence before distinct-provider corroboration. Reusable controllers and responsive design-system screens cover loading, empty, ready, degraded, unauthorized, conflict, stale, review, and evidence states. ## Operator command center `normalizeOsintCommandCenterResultV1` projects untrusted service responses into deduplicated, redacted records. It exposes only operational metadata needed for source health, acquisition, evidence, freshness, recovery, and review; unknown fields such as credentials, tokens, cookies, and personal payloads never enter the view model. Partial-provider health remains an explicit presentation state. Mutations are rendered only from a server-returned action descriptor containing an exact operation, immutable input, authorization reference, and idempotency key. The reusable coordinator enforces an optional exact confirmation phrase and coalesces concurrent invocations with the same idempotency key. The host may further narrow operations for a route, but it never constructs an action or decides whether an effect is allowed. `GovernedDataViewV1` (`./governed-data-view`) is the reusable load/act container: it loads the view operation (optionally keyed by a resource parameter), keeps only allowlisted operation keys (`limitGovernedActionsV1`), runs actions through the coordinator and maps failures to command-center states. The host injects the `call` transport. `./governed-transport` supplies typed failures: wrap the SDK fetch with `createGovernedTransportFetchV1` so non-OK responses reject with `GovernedTransportErrorV1` (`401`/`403` → unauthorized, `409` → conflict or stale by structured error code, `412` → stale, otherwise degraded); `governedErrorModelV1` maps only typed errors to states and treats anything else as degraded. --- ## @lssm-tech/bundle.patio Description: Patio product bundle: the seven Patio product identities with a typed product stage, authored EN/FR/ES copy, the Patio atlas and the MailPatio website inquiry surface over customer-support. Path: packages/bundles/patio URL: /llms/bundle.patio # @lssm-tech/bundle.patio Private Patio product bundle (WEB-01, D-100 and D-103), hosted by the single host-aware, fail-closed `packages/apps/patio-web`. - The seven Patio product identities (MailPatio, PhonePatio, LetterPatio, SocialPatio, VoicePatio, HealthPatio, InfraPatio) carry a typed product stage (`development` or `proposed`, with evidence refs). A stage is not an availability claim. - Authored copy ships in English, French and Spanish. - MailPatio website inquiries are an additive customer-support website-inquiry operation (persisted by `customer-support-postgres`, operator view in SupportOS). This bundle only composes that surface; the donor operator lookup route is not carried over. - Dependencies stay limited to schema, contracts, translation, design catalog, the web UI kit and the customer-support spec and module. No `module.osint`, no `data-exchange-core`, and never `bundle.lssm-ecosystem`. Exports `./catalog`, `./atlas`, `./i18n`, `./visuals` and `./visuals/styles.css` (WEB-01-PATIO-CAT), and `./intake`, `./intake/route`, `./sites/mailpatio` and `./sites/mailpatio/styles.css` (WEB-01-PATIO-INTAKE: `src/intake` is the website inquiry browser client and its server route over the SupportOS website-inquiry handler; `src/sites/mailpatio` is the ported MailPatio site). See `src/catalog/README.md` (catalog, stages, workflows), `src/visuals/README.md` (atlas explorer, workflow lab, styles) and `docs/README.md` (ported Patio docs, provenance and composition). --- ## @lssm-tech/bundle.personal-os Description: Evidence-scored PersonalOS product composition and requirements coverage. Path: packages/bundles/personal-os URL: /llms/bundle.personal-os # `@lssm-tech/bundle.personal-os` Canonical cross-domain composition for PersonalOS and the personal/non-work product portfolio. The bundle preserves 103 exact needs across PersonalOS, Personalization, RoleMorph, personal agency, learning, health and wellbeing, HCircle, Pactena, life administration, personal finance, and platform quality. The server-only `./runtime` entrypoint composes typed mission/goal, productivity, household, health-connection, goal-scoped support, governed coach-lifecycle, private progress-celebration, and rights commands. It recomputes the domain-separated payload digest before authority, requires an exact fully bound receipt and authorized encrypted-state digest, hydrates one subject-scoped snapshot, runs pure reducers, and commits the snapshot, receipt, event, idempotency result, and outbox atomically. It then projects a minimized workspace cursor with bounded planning, delegation, goal-scoped support, non-clinical health, reversible coach, and private progress-policy summaries. Consent summaries populate a bounded subject-facing dashboard window with purpose, known downstream consumers, expiry, and granted/expired/revoked state. Counts remain exact when the window is truncated, active records are prioritized, and raw evidence plus authority receipts stay server-only. The server runtime also composes subject-owned support incidents through a separate exact-subject transaction port. It parses the command, loads current state, computes the before and proposed semantic state digests, obtains server-side authority for that exact transition, independently verifies the receipt, and only then commits. Confirmation and denial create a digest-bound no-effect audit; exact replays do not reacquire authority. Public reads expose only minimized status, revision, channel, timestamps, and accessibility need identifiers. The bundle does not accept client-issued authority receipts. Support grant preflight recomputes current household membership, active goals, consent, evidence, and source revision before authority. Grant, revoke, block, and categorical report events enter a separately leased outbox destination. That worker validates the complete content-free audience plan before delivery and exact event, subject, recipient, window, intent digest, and distinct assurance receipts before acknowledgement. Concrete provider credentials, callback reconciliation, manual delivery acceptance, and production canaries remain host qualification rather than bundle evidence. Coach proposal and activation are presentation-only, expiry- and consent-bound, default to human authority, and retain explanation, evidence, authority receipt, undo, and compensation references. Proposal, activation, inspect, undo, and reset validate their hydrated revisions and exact feature/task policy scope before authority; raw behavioral signals, measurements, provider payloads, and credentials never enter the projection. The runtime subpath has no browser condition and is excluded from fresh browser artifacts. The same server-only entrypoint now composes the Personal Life Administration module through the shared two-phase authority and encrypted atomic state port. It recomputes the complete command and semantic state digests, rejects self-consistent idempotency substitutions before authority, persists only AES-GCM ciphertext under exact subject/version AAD, and commits the finalized receipt, immutable event, snapshot, idempotency result, and minimized provider effect destinations in one forced-RLS PostgreSQL transaction. A local on-disk PGlite E2E closes and reopens the database mid-rights-plan, completes a portable export, proves cross-subject isolation and ciphertext privacy, and rejects cipher-integrity tampering. A forced outbox failure proves the snapshot, event, receipt, idempotency result, and effects all roll back. Real export/deletion processors, legal-hold policy and UX, cache/index/analytics/backup propagation, managed KMS/PostgreSQL recovery, product accessibility, acceptance, and canary evidence remain unqualified. The server-only runtime also owns durable Personal Finance execution. Five canonical finance commands are parsed and exact-bound to the authenticated subject/version, consent, expected aggregate revision, action risk, evidence, idempotency key, and domain-separated action digest. The runtime hydrates only an AES-GCM subject snapshot, runs the pure append-only reducer, prepares and finalizes authority against exact before/proposed semantic digests, verifies an independent draft/proposal/receipt proof, and atomically commits ciphertext, event, receipt, idempotency result, and projection/audit outbox entries. An on-disk PGlite journey completes record, correction, scenario, connection, and provider-page operations across restart; RLS isolation, ciphertext privacy, replay, digest tampering, verified no-effect denial, and forced-outbox rollback are covered. Live regulated providers, managed credential/KMS/PostgreSQL operations and recovery, finance product UI/accessibility, regulatory review, manual acceptance, and canaries remain external qualification gates. The finance host also projects the decrypted exact-subject ledger only after restart into three minimized views: an integrity-bound wealth snapshot with no cross-currency total, aggregate cash-flow and budget metadata with no item-level payloads, and an expiring family-office view containing opaque encrypted document references. The projection recomputes the semantic source digest, requires independent source and receipt binding, excludes rejected provenance, and never exposes provider payloads or credentials. A second on-disk PGlite journey persists an owner-assigned household care item, reopens the database, and projects it only to the exact current delegated actor. Actor-version substitution and revoked delegation return no care data, the stored snapshot contains ciphertext rather than the care title, and the owner can complete the item after restart. Broader household invitations, abuse-safe exit UX, real notifications, manual accessibility, and production canaries remain separate qualification gates. The workspace runtime also owns subject-controlled guardrails and goal conflicts. It validates exact goal scope, consent, evidence, revision, digest, and authority receipt before persisting definitions, triggers, resolutions, or decisions. Active pause/block responses immediately pause affected goals and deny later progress before authority. Revoke-sharing immediately blocks scoped support and denies replacement grants. Legacy encrypted snapshots are accepted only after their original semantic digest verifies and only allowlisted empty domains are hydrated. Workspace projections expose bounded counts and no guardrail descriptions or evidence. The server runtime also derives `PersonalExperienceProjectionV1` from the hydrated workspace plus explicit host-owned consent, sharing, and completed rights facts. Pending, failed, revoking, or revoked health records never count as connected sources. Export and deletion journey completion is never inferred from a pending counter; the host must supply verified completion facts. The same server projection now composes the RoleMorph-first presentation cursor: all six areas retain authority boundaries, Personalization is presentation-only, preferences are attributed and resettable, and delegated actors require the exact active `view_shared_projection` grant and one unambiguous current member role. The contract recomputes its domain-separated resolution digest. No policy reason, evidence path, component payload, raw behavior, or credential enters the public cursor. Hosts may also provide the minimized `personalizationIdentity` cursor: an opaque tenant digest plus one current consent reference/status. The bundle never derives raw tenant labels or consent evidence, and surface clients bind this cursor to the exact outer subject and actor before any scoped buffer can collect. The server-only runtime applies the current RoleMorph presentation as a DataView boundary before returning workspace summaries. It strips every domain summary when presentation is missing, invalid, stale, differently bound, or denies any canonical area view or summary component. Only schema-valid cursor metadata remains; the DataView spec and resolution never enter browser builds. The runtime owns the legal peer-module composition for Personal Learning. Its `createPersonalLearningJourneyAdapterV1()` adapter projects the existing learning-journey engine into the consent-aware Personal Learning port while rechecking exact subject versions, journey and command revisions, idempotency, step cardinality, evidence, locale, and bounded due-card reads. The host still owns the authoritative catalog, entitlements, export/deletion propagation, and production UI qualification. `PersonalLearningDurableRuntimeV1` now owns the server-side durable command path: it hydrates the exact encrypted subject snapshot, rejects command-binding and revision drift before authority, invokes only a pure learning transition planner, finalizes two-phase authority against the proposed semantic state digest, and atomically commits the encrypted state, immutable event, receipt, idempotency result, projection work, and minimized telemetry work. Planner failures and consent denials preserve the last durable checkpoint without committing partial progress. The exact local adapter run is recorded in a dated, SHA-256-bound qualification artifact; it contributes only contract, implementation, unit, and integration evidence and cannot qualify the remaining host or product gates. The server-only runtime also composes the HCircle projection consumer through the actual `@lssm-tech/module.personal-community` service. Compiled packets now carry exact subject and community-grantee references. The consumer recomputes a canonical packet or revocation digest, checks every grant, source-consent, field, projection, expiry, actor, and subject-version binding, and acknowledges only an applied or idempotently replayed encrypted community transaction. Revocation clears locally readable values and emits the five required purge scopes for the host outbox. The injected issuer remains the authority boundary: it must resolve the current source grant and issue a fully command-bound human receipt. Real key custody, durable delivery workers, purge-SLA completion, HCircle UI/accessibility, provider deployment, and production canaries remain unqualified. The exact local consumer run is recorded in `generated/qualification/hcircle-consumer-local-qa-2026-08-10.json`; its SHA-256-bound contract, implementation, unit, and integration evidence is scoped to the local service composition and cannot qualify those remaining host gates. The server-only `@lssm-tech/bundle.personal-os/projections/governed` entrypoint exports `PersonalGovernedProjectionTransportV1`, a `PersonalProjectionTransportPort` over the data-exchange governed gateway. Publication requires an exact authority binding (subject, grantee, destination, consumer application, field mapping) before it builds the access request, sealed materialization authorization and dispatch; revocation dispatch requires exact revocation bindings and acknowledgement watermarks. It is not emitted for browsers and is not yet composed by a production host. The server runtime now also composes Pactena projection packets through the actual `@lssm-tech/module.personal-founder-support` reducer and encrypted atomic store port. One canonical packet can create idempotent, purpose-bound founder handoffs for an explicitly configured cockpit/portfolio/room destination; the handoff omits subject identifiers, provenance references, and free-form outcome narratives. Exact packet, subject, product-grantee, grant, consent, projection, domain-door, destination, revision, receipt, and digest bindings are rechecked before storage. Revocation enumerates the exact grant projection ids, marks each handoff revoked, and emits the downstream delivery plus five-scope purge plan. Real KMS custody, Pactena delivery/reconciliation, product routes, accessibility, managed databases, E2E, purge-SLA proof, and canaries remain unqualified. The exact local consumer run is recorded in `generated/qualification/pactena-consumer-local-qa-2026-08-10.json`; its SHA-256-bound contract, implementation, unit, and integration evidence covers the actual founder-support service composition without widening those host qualification claims. The server-only workspace projector also emits bounded outcome summaries from encrypted mission-goal state. Each metric exposes its explicit baseline, target, unit, window, collection mode, current observed value, confidence, minimized evidence identifiers, and correction/removal counts. Prior values and correction reasons remain inside the immutable encrypted observation history. ```ts import { PersonalWorkspaceRuntime } from '@lssm-tech/bundle.personal-os/runtime'; const runtime = new PersonalWorkspaceRuntime({ store: subjectBoundPostgresStore, crypto: kmsEnvelopeCrypto, authority: connectBackedPersonalAuthority, authorityReceiptVerifier: connectReceiptTrustRoot, decisionAudit: subjectBoundDecisionAudit, ids: monotonicPersonalIds, }); ``` Provider credentials, raw health payloads, and export artifacts remain behind injected integration ports. Local runtime tests qualify deterministic command and persistence boundaries only; they do not qualify a production KMS, provider, AuthOS deployment, restore drill, browser E2E, or canary. The PostgreSQL store supplied here must be constructed with an `authorityReceiptVerifier`; production atomic commits fail closed when the authority receipt lacks independent canonical verification evidence. `preparePersonalHealthAuthorizationDispatch()` recomputes the immutable receipt, authority-proposal, and dispatch digests before exposing a command to effects. `runPersonalHealthAuthorizationDispatchCycle()` then leases a durable, secret-free broker dispatch, executes the normal runtime path, and atomically acks, retries, or supersedes it with a freshly issued revision-bound command. `createPersonalHealthAuthorizationConnectCommand()` builds that issued or reissued `connect_provider` command (high risk, human-required, online-only, bound to the request, active consent policy and evidence, and digest-bound to its payload); hosts only resolve the active consent. OAuth code/state and PKCE material are deleted before this delivery boundary; the workspace reducer retains connection/category/status metadata only. Browser and public consumers use the privacy-safe entrypoint: ```ts import { projectAcceptedPersonalScope, projectPersonalProductHealth, } from "@lssm-tech/bundle.personal-os/experience-coverage"; const acceptedP0 = projectAcceptedPersonalScope({ priority: "P0" }); const important = projectPersonalProductHealth({ criticality: "important" }); ``` Trusted Bun or Node operators explicitly opt into the operator-only entrypoint: ```ts import { listPersonalGaps, projectPersonalOperatorHealth, } from "@lssm-tech/bundle.personal-os/experience-coverage/operator"; const gaps = listPersonalGaps({ acceptedScope: true, criticality: "essential" }); const operatorHealth = projectPersonalOperatorHealth(); ``` The public and browser artifacts contain only audience-safe rows. They neither import operator modules nor contain repository source references, qualification references, or internal blocker text. The build classifies the operator entrypoint as server code and excludes it from browser transpilation. Source discovery is inventory, not readiness. The matrix classifies discovered artifacts as `source`, `reference`, or `fixture`. Only qualification evidence with observation and expiry dates, producer/run provenance, and SHA-256 integrity can contribute to a requirement score. Mandatory evidence is the additive union of the exact need kind, quality gates, provider canaries, and any declared layers; exceptions require an explicit approved, expiring waiver. For local evidence, operator validation also hashes the referenced artifact and checks its run schema, producer, environment, observation time, source commit, qualified layer allowlist, commands, and passed package results. Evidence can credit only a layer named inside the hashed replay artifact, so a unit run cannot be relabelled as accessibility or canary proof by an overlay. A well-formed but invented digest cannot qualify a row. The current generated snapshot contains 103 requirements: 90 are `implemented_unverified`, four are `fixture_only`, and nine remain `blocked_external`. None remain `stub` and none are `live_verified`. Qualified completion is **0 percent**. Existing implementations and historical local proofs do not supply current qualification credit unless their source, provenance, integrity, expiry and required-layer checks pass. Regenerate this projection with `coverage:generate`; never repair its score by editing receipts or report totals. The inventory includes the bounded projection publisher and delegated-household support runtime. Rows that still lack managed host composition, browser or device E2E, accessibility, manual acceptance, provider, regulatory, or production-canary layers retain those gaps explicitly rather than inferring them from source or route existence. The core, health, and golden-journey rows map the exact first-release surface set: standalone web, PWA, Expo iOS/Android, and Tauri macOS/Windows/Linux. This scope declaration does not substitute for the still-missing dated device, accessibility, manual-acceptance, provider, or canary evidence. The bounded composite native qualification run is recorded in `generated/qualification/presentation-surfaces-source-bound-composite-local-qa-2026-08-15.json`. It covers the exact presentation contract and composer plus current shared contracts, API, web, mobile, and desktop lint, type, unit, integration, mobile production export, desktop production build, package-inventory, Cargo, and Clippy checks. Unchanged package scopes are carried only after an exact byte-identity comparison to the prior replay; the changed web scope and its API dependency were replayed at the current source commit. Web lint, typecheck, unit, browser-artifact privacy, zero-exit Webpack production build, seven browser-contract journeys, and the actual API-backed production journey passed. The matrix credits contract, implementation, unit, and integration evidence for the bounded RoleMorph and Personalization rows. Browser E2E and automated accessibility remain governed by their separate source-bound artifacts rather than being inferred from this package replay. Expo simulator and physical-device runs, VoiceOver/TalkBack, signed installers, Windows/Linux packaging, provider accounts, restore drills, manual accessibility, and canaries remain unqualified. The current automated cross-surface accessibility composite replay is recorded in `generated/qualification/cross-surface-accessibility-source-bound-composite-local-2026-08-15.json`. It credits only the accessibility layer for platform accessibility, localization, responsive/native presentation, offline continuity, privacy and consent, profile runtime, delegated-support recovery, explicit presentation preferences, and the exact RoleMorph resolution, suppression, canonical preference, and fail-closed data-view boundaries consumed by the three apps. It also credits the automated accessibility layer for the executable mission, goal, Today plan, habit, check-in, missed-day recovery, and weekly-review journeys that each surface builds from the shared command contracts. The health connection consent control and non-clinical minimized wellness view also receive only this automated accessibility credit; live providers and provider canaries remain external blockers. The same bounded credit covers the localized activity, sleep, biometrics, and nutrition history categories rendered without raw provider payloads. The human-only export and deletion controls shared by all three apps likewise credit accessibility for the life-administration rights row, while external processor propagation, manual acceptance, and canaries remain open. Web, mobile, and desktop semantic, label, focus/live-region, localized catalog, RTL-readiness, reduced-motion, offline recovery, native-property, production build/export, package-inventory, and Rust host checks passed. Chromium was blocked before test execution by the managed macOS Mach bootstrap sandbox, and the desktop strict TypeScript command was obstructed by unrelated duplicate exports in the concurrently dirty main-worktree dependency. Browser/native E2E, screen-reader, zoom, contrast, switch/voice, visual regression, professional localization review, real devices, signed installers, manual acceptance, and production canaries remain open. The identity and authentication row credits the integrated source-bound AuthOS chain in `generated/qualification/identity-auth-source-bound-local-qualification-2026-08-14.json`. It covers AuthOS contracts/runtime, reusable lifecycle UI, the Better Auth and PersonalOS bridges, health identity binding, and authenticated API composition through 1,279 tests and 4,049 assertions. Reusable sign-in, verification, MFA, passkey, recovery, session, security, audit, and sign-out screens reject critical or serious Axe findings and invalid React nesting while preserving focusable landmarks under reduced motion. The shared-worktree type/declaration obstructions are recorded in the artifact rather than reported as passing. Managed identity/provider delivery, manual assistive-technology, recovery and account-closure drills, real devices, acceptance, and canaries remain unqualified. The identity-cohesion E2E composes the real Personal Experience identity session with the real Personalization tracker, in-memory store, and scoped signal emitter. It proves account-switch drain ordering, tenant/consent/sign-out discard, exact subject/actor/version scope rejection, and fail-closed sign-out when delivery fails. This local replay does not qualify the separately owned CommunicationOS host, manual acceptance, or production canaries. This artifact uses `personal-qualification-run.v2`: its exact source scopes are bound to a full Git commit, and local validation rejects the evidence if that commit is missing, a scope is unsafe, or any declared source changed afterward. All credited local artifacts now use v2. Legacy v1 artifacts fail closed because they do not bind exact source scopes or qualified evidence layers. The evidence inventory test also rejects orphaned qualification files that no current requirement credits; superseded runs are removed instead of lingering as ambiguous release evidence. The health and platform qualification is recorded in `generated/qualification/health-platform-source-bound-composite-local-qa-2026-08-15.json`. Its source-continuous 313-test replay binds the provider-neutral health contracts and runtime, strict provider adapter, health module, and current web, mobile, and desktop packages to one full commit. It credits only local implementation, unit, and integration layers. Simulated providers and automated semantic checks do not qualify live providers, manual accessibility, real devices, signed installers, restore drills, regulatory status, or production canaries. The Personal Operations qualification is recorded in `generated/qualification/operations-source-bound-local-qa-2026-08-10.json`. It is freshly replayed against the entire operations module and uses the same v2 source-scope check. It remains bounded to local contracts, pure evaluators, tests, and multi-runtime builds; managed RUM, load, restore, support, accessibility, manual acceptance, and production-canary evidence remain open. The support-incident row separately credits its encrypted host E2E and the current web source accessibility suite from `generated/qualification/support-incident-source-bound-composite-local-qa-2026-08-15.json`. The browser process could not be launched in this environment, so browser Axe, staffed accessible-channel acceptance, incident drills, response objectives, manual acceptance, and production canary evidence remain required. The core foundation qualification is recorded in `generated/qualification/foundation-source-bound-composite-local-qa-2026-08-24.json`. It binds the subject/command contracts, authority runtime, encrypted Postgres state, authenticated API, RoleMorph, Personalization, Personal Calm composer, goals, productivity, household, and their canonical digest prerequisite to one source-continuous 906-test/3,560-assertion replay. Every declared package passed lint, strict typecheck, its full test suite, and its production build on the bound commit. That current replay also resolves only the exact superseded implementation blocker IDs it proves; deployment, provider, manual, canary, real-device, and deferred CommunicationOS blockers remain open. The Personalization slice includes collection-time consent and retention, ciphertext-only behavior evidence, correction, export, deletion, expiry purge, and durable retry/dead-letter delivery. The current 227-test encrypted E2E composite is recorded in `generated/qualification/personalization-e2e-source-bound-composite-local-qa-2026-08-15.json`. It additionally proves exact scoped queries, minimized telemetry, preference lifecycle, receipt policy, advisory aggregate analysis, and identity-buffer retirement. A separate receipt-policy E2E run proves exact request/evidence-bound receipt issuance, consent and redaction denial, raw-payload exclusion, and durable digest-only audit without claiming deployed training or canary evidence. The outcome slice includes authenticated record, substitution denial, correction, removal, immutable encrypted history, and a minimized current-value projection. It credits only local implementation, unit, and integration layers; accessibility labs, real devices, provider qualification, restore drills, manual acceptance, and canaries remain open. The current private progress-celebration qualification is recorded in `generated/qualification/progress-celebration-source-bound-composite-local-qa-2026-08-15.json`. The host rejects missing or abandoned target goals before authority. Its on-disk PGlite E2E configures an exact owned goal, closes and reopens the encrypted workspace, projects deterministic capped private XP with exact evidence and authority receipt references, proves RLS subject isolation and ciphertext privacy, replays idempotently, and disables the policy without deleting the goal or policy history. Automated web accessibility contracts and the production build pass, but no browser process launched in this replay. Browser E2E, manual assistive-technology acceptance, real-device and longitudinal behavior, managed KMS/PostgreSQL recovery, and canary evidence remain open and prevent `live_verified` status. The host artifact also uses v2 source-scope binding, so later changes to its contract, digest, reducer, encrypted hydration, or minimized projection paths invalidate the credited evidence until the run is refreshed. Delegated household support qualification is recorded in `generated/qualification/sharing-agency-source-bound-local-qa-2026-08-10.json`. It binds the household authority reducer and minimized projection compiler, publisher, acknowledgement, and revocation paths to one fresh local replay. The additional `generated/qualification/support-delegation-postgres-source-bound-local-e2e-2026-08-12.json` run executes the subject-owned household, consent, mission, goal, and support sequence through two-phase authority and the encrypted Postgres adapter, then rehydrates the minimized grant after an on-disk restart. Exact replay and RLS isolation pass while private purpose, consent, evidence, and goal text remain outside ciphertext inspection and projections. Provider reconciliation, product-device acceptance, manual accessibility, incident operations, and production canaries remain open. The package test command keeps deterministic non-PGlite tests on a 15-second ceiling and runs stateful PGlite tests serially with a 60-second functional ceiling. This prevents local resource contention from masquerading as a domain failure; it does not qualify latency, throughput, load, or production SLOs, which remain governed by separate performance evidence. Learning host qualification is recorded in `generated/qualification/learning-host-source-bound-composite-local-qa-2026-08-14.json`. It binds the Personal Learning module and bundle host boundary to a source-bound local replay. The durable runtime additionally has a restartable PGlite journey covering real learning-engine progress, AES-GCM snapshots, exact replay, revision conflict, RLS subject isolation, minimized outbox work, plaintext exclusion, and cipher-integrity failure. Authoritative catalog entitlements, product UI, manual accessibility, device E2E, rights propagation, managed restore drills, and production canaries remain open. Breadth qualification is split across exact source-bound artifacts for `life-admin-source-bound-local-qa-2026-08-13.json`, `personal-finance-host-source-bound-local-e2e-2026-08-14.json`, `community-source-bound-local-qa-2026-08-14.json`, and `founder-support-source-bound-local-qa-2026-08-14.json`. The split prevents a change in one domain from refreshing or invalidating another domain's evidence. The additional `life-admin-organize-postgres-source-bound-local-e2e-2026-08-14.json` run credits only local E2E for calendar, encrypted personal files, and knowledge: it persists through an on-disk restart, projects/searches metadata without the content reference, archives safely, replays idempotently, and enforces subject RLS. Provider, blob-custody, accessibility, device, manual, managed-restore, and canary evidence remain open. Household care now also reaches the authenticated organizer through an exact-actor, bounded metadata projection. Local contract/runtime/API/web tests cover delegated capability scope, expiry and version denial, cardinality, private-purpose exclusion, translated empty copy, and semantic list rendering. Manual assistive-technology acceptance, live providers, managed restore, and production canaries remain open and are not inferred from this automated run. Life-administration rights and restore qualification are refreshed separately in `life-admin-rights-postgres-source-bound-local-e2e-2026-08-13.json` and `postgres-restore-rehearsal-source-bound-local-qa-2026-08-13.json`. The rights replay binds 48 module tests, 42 forced-RLS PostgreSQL tests, and three exact bundle PGlite scenarios to their current source scopes. The PostgreSQL suite passed its declared serialized 15-second qualification profile; a contended five-second default run timed out two denial-audit cases and is explicitly not counted as passing evidence. Managed recovery, downstream deletion processors, manual acceptance, accessibility certification, and canaries remain open. Provider credentials, production encrypted stores, UI, manual accessibility, devices, moderation and support operations, restore drills, formal regulatory qualification, and canaries remain open as applicable. Pactena and HCircle integrations use the `./projections` entrypoint. It derives allowed destinations from the founder-domain and CommunicationOS read-only inventories, compiles only fields named by an active PersonalOS sharing grant, and emits no profile, provenance, provider payload, protected trait, or consequential-use authority. The publisher binds acknowledgements to the exact grant, grantee, consumer, and destination. Revocation invalidates local access before attempting remote delivery; an unavailable remote remains pending and cannot reopen access. The cross-product projection E2E publishes one exact subject through both the actual Community and Founder Support services, replays without duplicate writes, and revokes both consumers with the complete five-scope purge plan. Post-revocation recreation fails closed. The replay remains local: durable cross-service delivery, managed key custody, purge-SLA completion, manual acceptance, and production canaries are still unqualified. Every requirement has an explicitly authored journey-semantics catalog entry; there is no generic fallback. Actionable needs require distinct happy, recovery, and denial variants with concrete state transitions and actions. Recovery declares resume, repair, rollback, or an alternative plus durable no-data-loss and idempotency guarantees. Denial identifies the exact rejected authority, consent, dependency, policy, or validation condition. Non-actionable needs use an observation-only qualification path that cannot mutate personal state. Validation rejects missing, unknown, interpolation-only, and duplicated boilerplate entries. Priorities follow the agreed product program: P0 trust foundation, P1 killer product, P2 game changers, and P3 breadth. Current out-of-program rows are marked `deferred` with retained blockers as their rationale and resume conditions; the ledger does not leave an unmapped stub silently planned. Run `bun run coverage:generate` to refresh the deterministic, operator-only JSON/Markdown ledger and the safe public catalog. The dated web production-composition qualification run exercises the actual API/runtime path through the ordered household, mission, goals, simulated health authorization, offline Today replay, habits, check-in, recovery, review, coach reversal, delegation/revocation, and rights journey. Its SHA-256-bound artifact credits only the exact contract and E2E layers that ran. The final-page Axe scan remains a supporting signal rather than a complete accessibility layer. It does not claim a deployed host, live provider, PostgreSQL, manual WCAG review, device coverage, restore drill, or production canary. ### Health requalification — 2026-09-05 Four health records have fresh source-bound local proofs for history, revocation, wellbeing goals and safe insights. The replay passed clean builds, lint, typechecks, package dry runs and 75 tests across three health packages. Previous artifacts remain intact. These records credit only their declared local layers; other stale foundation/accessibility evidence and live provider/device acceptance remain open. Coverage generation retains those gaps rather than restoring old completion percentages. ### Foundation and personalization replay — 2026-09-05 A new foundation record binds 48 passing checks and 908 tests (3,565 assertions) across 12 package scopes. Four personalization records reuse the same current-source package checks and add clean builds, package inspection and explicit PGlite receipt-policy replay. These five records provide 125 current local layer refs. Historical artifacts remain immutable. Accessibility, device/runtime-specific E2E, manual acceptance and production canaries keep their independent gates. ### Automated surface accessibility — 2026-09-05 Current-source automated accessibility now covers the web, native mobile build and desktop host checks: 264 tests, eight browser journeys with Axe checks, iOS/Android exports, and locked Rust fmt/check/test/clippy. The record binds the native Babel pin and credits 26 accessibility references. It does not claim physical-device, manual screen-reader, visual-regression or production acceptance. Other stale E2E records retain their independent completion gates. ### Qualification archive and current web/analyzer proofs Superseded qualification records live in `generated/qualification/archive` with unchanged bytes and listed hashes. The active directory contains referenced records only. September 5 web and analyzer records bind actual local replays; foundation, web and inventory qualification tests pass. This does not certify the remaining product matrix or grant production authority. --- ## @lssm-tech/bundle.product-intent Description: Product intent bundle with AI runner and evidence retriever Path: packages/bundles/product-intent URL: /llms/bundle.product-intent # @lssm-tech/bundle.product-intent Website: https://contractspec.io **Product intent bundle with AI runner and evidence retriever.** ## What It Provides - **Layer**: bundle. - **Consumers**: not yet wired into an app (standalone bundle). - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.product-intent-core`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.product-intent-core`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/bundle.product-intent` or `bun add @lssm-tech/bundle.product-intent` ## Usage Import the root entrypoint from `@lssm-tech/bundle.product-intent`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/` -- AI runner and product-intent service. - `src/__tests__/` -- unit tests. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Uses the Vercel AI SDK (`ai`) for LLM interactions; keep provider-agnostic patterns. - Depends on `lib.contracts-spec` and `module.product-intent-core`; spec changes upstream affect this bundle. - AI runner prompts and tool definitions should remain deterministic and testable. --- ## @lssm-tech/bundle.sarla Description: Sarla brand composition (D-112a, D-122 B layer): composition only over the shared hiring experience; no domain or experience logic. Path: packages/bundles/sarla URL: /llms/bundle.sarla # @lssm-tech/bundle.sarla Private Sarla brand composition (D-112a, D-122 B layer, SARLA-02a), served by `packages/apps/sarla-web` by hostname. - Composition only: `defineBrandComposition`, route map, copy and i18n overrides, design patch, entitlement map and assets. - The shared hiring experience lives in `@lssm-tech/bundle.talent`; behavior lives in the talent domain owners. A brand selects and configures them; it never branches on itself. - A composition grants no authority: admission comes from AuthOS with a trusted `productApplicationId`. ## Entrypoints (SARLA-02a) - `.`: `sarlaBrandComposition` (family `hiring`, markets FR and EU, FR default with en/es/de/it, consumes `career.candidate-disclosure@1` and `company.offering@1`, no hosts here), `sarlaBrandFacts` (operator, legal and support facts, all `null` until reviewed), the mark assets, and neutral aliases (`composition`, `brandFacts`, `brandAssets`) for the host. - `./route-map`: the route table as data over the `bundle.talent/shell` model: one row per donor page/route file, the donor public slugs, legal pages, private prefixes and the `/confidentialite` legacy redirect. A later slice ports a journey by flipping its row from `unported` to `shell`. - `./i18n`: brand copy overrides (product name, wordmark, home label, tagline, service scope) in five locales. Against the real catalogs the composition is refused until its pending records exist (see `sarlaCompositionDocBlocks`). --- ## @lssm-tech/bundle.self-improving-system Description: Headless controllers and operator view models for governed self-improvement Path: packages/bundles/self-improving-system URL: /llms/bundle.self-improving-system # `@lssm-tech/bundle.self-improving-system` Reusable headless controllers and operator view models for governed self-improvement programs, signals, candidates, evaluations, gates, reviews, shadow and canary comparisons, observations, promotion, rollback, kill, and exact replay. The injected data source is the only transport boundary. Commands require an idempotency key, expected revision, compatible contract fingerprint, trace reference, and at least one evidence reference. The bundle never authorizes or executes changes; it exposes durable server decisions and evidence to hosts. `createSelfImprovementControllersV1(dataSource, { locale })` titles each operator panel from the bundle's `self-improving-system.messages` catalog in `en`, `fr` or `es`; without a locale the titles stay English. --- ## @lssm-tech/bundle.tafio Description: Tafio brand composition (D-112a, D-122 B layer): composition only over the shared career experience; no domain or experience logic. Path: packages/bundles/tafio URL: /llms/bundle.tafio # @lssm-tech/bundle.tafio Private Tafio brand composition (D-112a, D-122 B layer, TAFIO-APP-00), served with the other career brands by `packages/apps/tafio-web` by hostname. - Composition only: `defineBrandComposition`, copy and i18n overrides, design patch, entitlement map and assets. - The shared career experience (variants, First Chance, acquisition, assistant, audio, billing gate) lives in `@lssm-tech/bundle.job-application`; behavior lives in the domain owners. A brand selects and configures them; it never branches on itself. - A composition grants no authority: admission comes from AuthOS with a trusted `productApplicationId`. Exports `tafioBrandComposition`; pending catalog rows listed in its DocBlock. --- ## @lssm-tech/bundle.taketide Description: Private Taketide public composition for the reviewed first release. Path: packages/bundles/taketide URL: /llms/bundle.taketide # Taketide public composition The `./composition` data-only entry provides reviewed French and English copy, locale validation, visible metadata and `composeTaketidePublicOverview`. `@lssm-tech/bundle.creator-platform/ui/experience/PublicOverview.web` owns the reusable web screen. The thin host passes the selected composition to that screen. The host owns trusted host admission, browser-language negotiation, private-route refusal, responsive styling and release selection. This initial release keeps discovery closed and workspace access unavailable. Shared creator, tracking and financial capabilities retain their existing owners and qualification gates. --- ## @lssm-tech/bundle.talent Description: Brand-neutral hiring experience bundle (D-122 E layer): employer-side talent surfaces composed over the talent domain owners, reused by every hiring brand composition. Path: packages/bundles/talent URL: /llms/bundle.talent # @lssm-tech/bundle.talent Private, brand-neutral hiring experience bundle (D-122 E layer, TAFIO-APP-00). It composes the employer-side talent surfaces over the talent domain owners; every hiring brand reuses it through its own composition bundle. - Behavior stays in the talent domain owners (`lib.talent-spec`, `module.talent`) and persistence in `integration.talent-store`; this bundle composes, it does not store. - No brand names, brand copy, pricing or hostnames: those belong to brand composition bundles and the G-layer registries. - Candidate-private data reaches employers only through approved disclosure projections. ## Entrypoints (SARLA-02a) - `./experience`: the hiring family experience registry (`hiringExperienceRegistryEntry`, one `baseline` experience; presentation-only). - `./shell`: the route-map model (`ShellRouteMap`, statuses `shell` | `unported` | `not-shipped`, access `public` | `session` | `area-authority`), the pure resolver (`resolveShellRoute`: serve, not-available, not-found, sign-in, access-denied), `safeReturnPath`, `decideShellAccess` (an absent session resolver or area decision is a denial), the runtime health seam (`probeShellRuntime`) and design-system shell components (`AppShell`, `LanguageSwitcher`, `NotAvailableState`, `DegradedNotice`, `AccessDeniedBody`, `NotFoundBody`, `ErrorStateBody`, `LegalDraftGap`, `ShellIntro`). - `./i18n`: `SHELL_MESSAGES` as a talent-spec `MessageCatalog` (fr source; en, es, it, de authored drafts, all `draft` in `SHELL_CATALOG_STATUS`); language names reuse `LOCALE_NATIVE_NAMES`. The root `.` entry still exports nothing. --- ## @lssm-tech/bundle.tellshift-studio Description: Tellshift Studio product bundle: studio engine, hosts, public site, workspace UI and server composition over the growth owners. Path: packages/bundles/tellshift-studio URL: /llms/bundle.tellshift-studio # @lssm-tech/bundle.tellshift-studio Tellshift Studio product bundle (D-086): the verbatim studio engine and browser layer, the public and private hosts, the public site, the workspace UI and the server composition over the converged growth owners. Reserved subpaths (D-028 spelling kept by D-098j): `./engine`, `./react`, `./hosts-public`, `./hosts-private`, `./public-site`, `./workspace-ui`, `./server`. The integration owner adds each export entry when the slice that owns it merges. Verbatim exemption: `src/engine/**` and `src/react/**` hold donor code imported verbatim until parity. Only those two folders are excluded from Biome, the i18n hard-coded string scan and the layout Stack/Box scan; every other folder (for example `src/server/**`) is checked normally. Delivered subpaths (TS-01-STUDIO, integrated by TS-01-DEPS): `./engine` (the verbatim studio engine), `./react` (the browser layer and authenticated shell) and `./hosts-public` (the same-origin public embed), plus `./hosts-public/runtime` (the public runtime, kept apart so the embed entry loads no engine) and `./hosts-public/styles.css` (copied to `dist/` at build). Their files are pinned by `SOURCE-MANIFEST.json`. A hosting document for the browser layer must import `src/react/index.css` itself (Tailwind 4 is a peer dependency); `./react` does not import it. The root `.` entry still exports nothing. `./public-site` (TS-01-PUBSITE) holds the public marketing interactions WS-005/006/007 (start experience, source-story demo and content-studio preview). It makes no network calls and owns no routing; hosts mount its components on their own routes and import `src/public-site/styles.css` (copied with its `@import` targets to `dist/public-site/` at build, also exported as `./public-site/styles.css`). Its message catalogs (`src/public-site/i18n/**`) are allowlisted for the hard-coded string scan. Verbatim strictness: `tsconfig.json` checks the package-owned folders with the repository settings, and `tsconfig.verbatim.json` checks `src/engine/**` and `src/react/**` with `noUncheckedIndexedAccess` off until parity; `typecheck` runs both. The ported regressions under `tests/*/canonical/**` and `docs/provenance/**` share the verbatim Biome exemption. The public-host message catalogs (`src/hosts-public/i18n/catalogs/**`) are allowlisted for the hard-coded string scan. `./server` (TS-01-GEN) currently re-exports `server/generation`: Tellshift's copy-run configuration and wiring only. It pins the route (`TELLSHIFT_GENERATION_ROUTE`, through provider-llm `GatewayLLMProvider` with EU inference, zero data retention, no prompt training and OpenAI only), the limits (`TELLSHIFT_GENERATION_LIMITS`: one provider attempt, a 60 000 ms deadline), the prompt pack, the deterministic fixture (refused in production), and `createTellshiftUsageReservation`, which reserves `kind: 'generation'` usage on the TCORE ledger with a lease ending at the deadline and settles once. `createTellshiftGenerator` reads `APP_MODE` (`fixture` or `live`) and fails on a conflicting `AI_MODEL_ID` or a missing key. The brand-neutral run owner is `MarketingCopyRunService` in lib.growth-runtime; hosts bind it with `registerMarketingCopyRuns` from module.growth-os. `evals/bounded-generator.ts` is the evals port; it reports `liveModelVerified: false`, and `tsconfig.evals.json` typechecks it as part of `typecheck`. No live model call is qualified. --- ## @lssm-tech/bundle.workspace Description: Workspace utilities for monorepo development Path: packages/bundles/workspace URL: /llms/bundle.workspace # @lssm-tech/bundle.workspace Website: https://contractspec.io **Core workspace bundle for ContractSpec validation, code generation, and repository setup.** ## What It Provides - Provides the service layer behind the CLI, editor integrations, drift detection, diagnostics, and setup flows. - Retains dependency-free AI ports used to inject optional capabilities. - Acts as the main orchestration bundle for repository lifecycle, graph inspection, drift reporting, regeneration planning, and codegen workflows. - `src/adapters/` contains runtime, provider, or environment-specific adapters. - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/services/` contains business logic services and workflows. - Generative Core orchestration is exposed as `services.generativeCore` for graph artifact persistence, dry-run generation plans, drift reports, and Connect/path policy classification. ## Local capability lookup `can-help` discovers local package manifests from the root `workspaces` authority (array or `workspaces.packages`), including nested foundation/platform/domain groups, explicit bridges, root examples and exclusions. Overlapping patterns are deduplicated; undeclared folders and conflicting package identities are not promoted as reusable workspace packages. Classic projects use their root manifest. Current manifest capability IDs, constraints and canonical imports/exports remain `workspace` / `workspace-scan` evidence. They do not establish registry publication or replace the shipped catalog. Mirrored catalog observations retain their source, degraded warnings and staleness, bound to the exact document including observation dates. Legacy embedded mirrors stay explicitly degraded; verified registry or installed catalog evidence remains distinct from local workspace content. No live authorization decisions are cached. For a focused machine-readable result, use `contractspec can-help "@lssm-tech/lib.contracts-spec-core/features" --scope workspace --limit 1 --json`. The separate published catalog may remain unavailable while the current workspace implementation is discoverable. ## Release file portability Release discovery reads Changeset frontmatter with LF or CRLF line endings without rewriting files. Package bump metadata, summaries and capsule fallback packages retain their existing meaning. Lone CR and unrecognized headers remain opaque summaries with no parsed package releases; ignored `none` or invalid bump rows and filesystem errors preserve their existing behavior. This is local, deterministic parsing and grants no provider or publication authority. Direct capsule validation and YAML-path repair preserve supplied POSIX absolute paths and Windows drive-absolute, UNC or rooted paths. Relative paths, including Windows drive-relative paths, keep the adapter/workspace resolution behavior. Returned capsule and quarantine paths use the adapter's native spelling. Validation remains read-only; repair writes still require the existing explicit write option. Selected Changeset/capsule paths retain paired owning-workspace slug selection and deduplication; bare repair slugs still select canonical workspace capsules. ## Installation `npm install @lssm-tech/bundle.workspace` or `bun add @lssm-tech/bundle.workspace` Concrete AI SDKs are optional peers with development mirrors; installing the workspace bundle alone does not force provider SDKs into a consumer lockfile. Hosts that enable AI behavior must supply compatible implementations through the exported ports. ```bash bun add @lssm-tech/integration.workspace-ai ``` Use `createNodeAiAdapter(config)` from the integration and pass it as the `ai` option to `createNodeAdapters`. Concrete agents and prompts are imported from the integration package rather than the workspace bundle root. ## Usage Import the root entrypoint from `@lssm-tech/bundle.workspace`, or choose a documented subpath when you only need one part of the package surface. ### Self-maintaining API adapters `@lssm-tech/bundle.workspace/maintenance` composes the module lifecycle with production-oriented adapters: - digest-bound OpenAPI, GraphQL, protobuf, SDK-manifest, and changelog source ingestion; - signed, declarative, language-scoped migration packs that cannot execute arbitrary provider code; and - GitHub App installation authentication, bounded repository snapshots, atomic branch commits, fail-closed check observation, draft pull requests, webhook verification/deduplication, and exact-ref rollback. `GitHubGovernedChangeAutomationAdapter` supplies the optional V2 ready-for-review and native auto-merge port. It re-reads the PR and check runs, requires the exact head SHA, and delegates merge completion to GitHub branch protection; it never invokes the direct merge endpoint. The existing maintenance adapter continues to create draft-only PRs. The host remains responsible for tenant-to-installation authorization, secret resolution, deployment scheduling, policy, and live qualification. ## Architecture - `src/services/` contains the core use-cases for build, validate, doctor, diff, setup, examples, and CI flows. - `src/adapters/` and `src/ports/` isolate filesystem, git, AI, and workspace integration boundaries. - `src/maintenance.ts` exposes the self-maintaining API adapter composition. - AI-facing services depend on workspace ports; concrete provider selection is an optional host concern. - `src/templates/`, `src/contracts/`, `src/formatters/`, `src.types/`, and `src.utils/` support generated outputs and reporting. - `src/index.ts` is the root public barrel and package entrypoint. - `src/types.ts` is shared public type definitions. ## Generative Core Responsibilities - Compose discovery, graph-building, artifact persistence, drift classification, and regeneration-plan services behind ports/adapters. - Keep graph and drift operations deterministic and JSON-schema-versioned so CLI, CI, Builder, and coding agents can replay evidence. - Enforce preview-first generation: generated writes require provenance hashes and manual-edit guards; protected/apply paths require Connect verification before mutation. - Keep Connect impact and drift verification read-only: temporary generation must override every configured docs/runtime output root and must never materialize handlers into the consumer workspace. ## Public Entry Points - Root bundle export with namespaced services, adapters, ports, formatters, templates, contracts, AI helpers, and utilities. - `services.generativeCore` exposes guarded JSON-artifact helpers for `generated/contractspec/graphs/**`, `generated/contractspec/generation/**`, and `generated/contractspec/drift/**`; dry-run planning remains the default for mutation workflows. - Export `.` resolves through `./src/index.ts`. - Export `./maintenance` resolves through `./src/maintenance.ts`. - Environment templates can generate root and app-target `.env.example` content from the shared logical environment contract while preserving per-framework aliases such as `NEXT_PUBLIC_*` and `EXPO_PUBLIC_*`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `bun run test` — bun test --isolate - `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 - Share one semver-accurate compatibility plan across Update and Doctor, with Expo SDK evidence, registry provenance, sticky prerelease channels, peer widening, and deterministic rollback waves. - Replace eslint+prettier by biomejs to optimize speed. - Add table capabilities. - Stability. - Package exports. - Add latest models and align defaults. - Standardize tool naming to underscore notation. - Add signed source/codemod and GitHub App adapters for self-maintaining APIs. ## Notes - Largest bundle in the monorepo (~280 source files); prefer editing existing services over adding new top-level directories. - Adapters must implement port interfaces; no direct infrastructure calls from services. - AI agent definitions must stay provider-agnostic via the `ai` SDK abstraction. - Template changes affect generated code across all consumers; test thoroughly. ### Builder delivery draft storage Loop IDs are portable single components: 1–128 letters, digits, underscores or hyphens, beginning with a letter or digit. Reserved Windows device names and path-like IDs are rejected before I/O. Existing malformed or mismatched records now fail instead of being treated as missing; restore a verified record before retrying. Missing ledgers cannot restart an existing loop at `release_ready`, and malformed idempotency records cannot silently forget earlier effects. This filesystem adapter remains workspace-local draft storage. It is not an atomic multi-writer ledger or a tenant isolation boundary against local filesystem writers. Production admission, durable approval/receipt persistence and provider reconciliation require the authoritative runtime composition. Draft evidence append persists primary and related references in the loop artifact catalog without rewriting its transition ledger. Exact retries reuse stable IDs; restarting the service retains the references. Entries are labeled unverified and do not create acceptance verdicts, approvals or permission grants. Hosts with a custom storage adapter may supply the optional `updateLoop` method; without it, evidence append fails explicitly. The adapter remains single-writer. Production mode rejects the local simulated approval, receipt, transition and handoff operations. Authoritative production operations must be composed through Connect and Runtime Nodes before enabling shipping in a host. Simulation receipt recording persists a loop/key-bound draft record before returning success. Exact retries replay it; changed actor, outcome or payload under the same key is rejected. Draft IDs are explicitly prefixed `draft_` and no ledger transition is claimed. These records use single-writer local storage and are not provider execution evidence. Handoff preview remains blocked until a verified receipt/replay resolver is composed; it never invents those references. The root build targets Node-compatible server execution (including Bun). It requires filesystem, process, or native compiler facilities and does not advertise a browser export condition. Browser applications should use the relevant browser-safe contracts or UI entry points instead of importing this server root. Tests isolate each file so Connect service mocks cannot replace spec discovery in the contract-first policy checks run by other files. Exact duplicate workspace identities are blocking conflicts: their package and import-subpath lookup cannot fall back to an older catalog entry. Distinct prefix-suffix package identities remain independent; `./` workspace patterns and exclusions normalize to the same authority as unprefixed patterns. # CLI composition `./cli` owns the existing reusable ContractSpec command composition. Delivery hosts retain bootstrap, blueprint and version glue; registry distributions call `./cli` with their explicit snapshot bindings. `./cli/run` remains an executable entry for hosts that need no optional snapshot supplier. Optional AI, Builder and examples registrations remain lazy and are bound to the exact Commander program through `@lssm-tech/lib.cli-runtime`. Their handlers are canonical here rather than copied into integrations or imported from a delivery host. `contractspec.cliRuntime.version` retains the original CLI version fallback for registry wrappers. Release updates must keep it aligned with the CLI distribution version; the existing explicit `CONTRACTSPEC_CLI_VERSION` override still wins. The app's original program construction signatures remain compatibility wrappers. Golden traffic generation accepts an explicit typed synchronous or asynchronous snapshot-client factory. The app host retains its original optional database module lookup, deferred until the production-snapshot action is selected. Registry hosts bind their same original lookup through `./cli/snapshot-client`; the shared helper accepts a host loader and never imports a database app itself. The old database CLI lookup requested a factory absent from the current source. No production snapshot adapter is supplied here; without a binding the existing warning and no-output behavior remain. Injecting an adapter does not grant database or production authority. The bundle prebuild owns offline MCP knowledge regeneration. App prebuild keeps its contract-source schema generation; registry consumers build the same owning bundle rather than relying on a previously generated app artifact. ## Connect host hook authority `connect hook ...` host hooks (`--host claudecode|codex|cursor`) run through the dedicated entry `src/cli/connect-hook-run.ts`. Durable authority for governed host edits comes from an explicit local operator grant: `contractspec connect hook authority grant --path [--command ] [--ttl ] [--host-session ] --confirm-workspace ` (interactive terminal only), with `revoke` and `status`. The grant signs a one-shot Hook Authority V1 decision bound to the workspace root and current HEAD, starts its session in the `@lssm-tech/integration.lssm-os-state-sqlite` adapter under the gitignored `.contractspec/connect/hook-authority/`, and keeps only the public key and the session capability there. When that store exists, before-file-edit, after-file-edit and before-shell-execution commit a V1 transition before Connect policy; revoked, expired, other-workspace or other-session grants deny. The grant follows the agent's own commits on its branch while every commit since the grant stays inside its prefixes and leaves hook, autonomy and grant control files alone (`--pin-head` binds one commit); a HEAD that left the grant denies. Lifecycle authority V1 (`@lssm-tech/lib.contractspec-connect/lifecycle-authority`) lets the grant establish session-start, stop and handoff without ever ending it; merge is never delegated. Hooks deny agent tool calls that run the grant command or touch the store. Without an active grant the recorded exception `connect-hook-authority-port-unwired` keeps the ask / Codex warning path. ## Connect host hooks and run modes This bundle owns `contractspec connect hook` and `contractspec connect mode`. Shell payloads that supply only a command are governed through the same current canonical roots as file edits, including the contracts-spec core and compatibility facade. Raw and analyzed shell forms are checked, retaining legacy command recognition. Canonical path hints can only tighten Connect policy assessment and raise action criticality for governance, protected or immutable targets; they never expand the paths, prefixes or exact commands covered by a durable authority grant. Immutable policy denial applies before every host run mode, including full. Relative shell targets are resolved against the live working directory and workspace root, so leaving and re-entering the same workspace cannot skip governance; external sibling paths do not acquire its policy. - While no operator hook authority grant exists, hooks evaluate Connect policy first; policy deny and rewrite always block. The run mode then decides instead of a blanket ask. - The run mode follows the host `permission_mode`: `bypassPermissions`/`dontAsk` run `autonomous` (never asks; critical actions are denied with a reason), `auto`/`acceptEdits` run `assisted` (asks only for high-criticality actions or review verdicts), `default` stays `supervised`, and `plan` is `readonly`. - Operators grant bounded autonomy with `contractspec connect mode set --for 8h [--scope ]`, inspect it with `connect mode show` and remove it with `connect mode clear`. Grants are bound to the worktree, not a git SHA. - `.contractsrc.json` `connect.runModes` sets `default`, `hostModes`, `maxLevel` and extra `highCriticalityPaths`. `durableAuthorityRequired: true` caps every run mode at `supervised`. - Agent writes to hook and grant control files and agent-run `connect mode set|clear` are operator-only, so an agent cannot raise its own autonomy. - Actions a run mode decides without asking are appended to `run-mode-decisions.ndjson` in the Connect storage root (`.contractspec/connect/` by default) for after-the-fact review. --- ## contractspec Description: CLI tool for creating, building, and validating contract specifications Path: apps/contractspec URL: /llms/contractspec # contractspec Website: https://contractspec.io **npm-published CLI entry point for ContractSpec. Thin wrapper that delegates to `@lssm-tech/bundle.workspace/cli` via `bin/contractspec.mjs`.** ## What It Does - **Layer**: apps - **Consumers**: end-users installing `npx contractspec` or `bun x contractspec` ## Installation `npm install contractspec` or `bun add contractspec` ## Usage ```bash npx contractspec --help # or bunx contractspec --help ``` ## Public Entry Points - `contractspec` -> `./bin/contractspec.mjs` ## Local Commands - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run test:packed` — packed-artifact clean install: packs this package and its built workspace closure into local tarballs (no publish), installs them into an isolated consumer pinned to the single-version `bun.lock` versions and runs `contractspec`. Build the closure first with `bun run build --filter='contractspec...'`. ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Stability - Refactor contracts libs to split them reducing bundle size and load ## Notes - This package is a shim; all logic lives in `@lssm-tech/bundle.workspace/cli` - Do not add dependencies beyond the shared CLI composer workspace reference - Changes to `bin/contractspec.mjs` affect every user -- test locally before publishing --- ## @lssm-tech/app.cursor-marketplace Description: Cursor marketplace catalog for ContractSpec product and core libraries Path: apps/cursor-marketplace URL: /llms/app.cursor-marketplace # @lssm-tech/app.cursor-marketplace Website: https://contractspec.io **Cursor marketplace catalog containing publishable plugin artifacts for ContractSpec's IDE integrations.** ## What It Does - **Layer**: apps - **Consumers**: Cursor IDE users, marketplace publishing pipeline - Hosts derived plugin artifacts generated from reusable `packs/*` sources of truth ## Running Locally From `apps/cursor-marketplace`: ## Local Commands - `bun run validate` — node ../../scripts/validate-contractspec-plugin.mjs ## Catalog Structure - Root catalog manifest: `.cursor-plugin/marketplace.json` - Publishable plugin artifacts: `plugins/*` - Reusable source packs live outside this package under `packs/*` and are exported here ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Expose contract management via CLI and MCP - Add Cursor marketplace catalog for core ContractSpec libraries ## Notes - Each plugin must have a valid `.cursor-plugin/plugin.json` - Do not add runtime code; this package contains only declarative metadata - Customer-facing runtime behavior is produced through `agentpacks` generation and hook/MCP configs, not custom code in this package - Validate changes with `bun run validate` before publishing - Logo assets in `assets/` must remain stable (referenced by marketplace) --- ## spec-driven-development Description: CLI tool for creating, building, and validating contract specifications Path: apps/spec-driven-development URL: /llms/spec-driven-development # spec-driven-development Website: https://contractspec.io **npm-published CLI alias for ContractSpec under the `sdd` / `spec-driven-development` binary names. Thin wrapper that delegates to `@lssm-tech/bundle.workspace/cli`.** ## What It Does - **Layer**: apps - **Consumers**: end-users installing `npx sdd` or `npx spec-driven-development` ## Installation `npm install spec-driven-development` or `bun add spec-driven-development` ## Usage ```bash npx sdd --help # or bunx sdd --help ``` ## Public Entry Points - `sdd` -> `./bin/contractspec.mjs` - `spec-driven-development` -> `./bin/contractspec.mjs` ## Local Commands - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary - `bun run test:packed` — packed-artifact clean install: packs this package and its built workspace closure into local tarballs (no publish), installs them into an isolated consumer pinned to the single-version `bun.lock` versions and runs `sdd` and `spec-driven-development`. Build the closure first with `bun run build --filter='spec-driven-development...'`. ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - PublishConfig not supported by bun ## Notes - This package is a shim; all logic lives in `@lssm-tech/bundle.workspace/cli` - Do not add dependencies beyond the shared CLI composer workspace reference - Changes to `bin/contractspec.mjs` affect every user -- test locally before publishing --- ## @lssm-tech/app.action-drift Description: GitHub Action for ContractSpec drift detection Path: packages/apps/action-drift URL: /llms/app.action-drift # @lssm-tech/action.drift Website: https://contractspec.io **GitHub Action that detects contract drift between specs and implementation. Runs in CI to flag when generated code diverges from its source contracts.** ## What It Does - Uses `@lssm-tech/lib.contracts-spec` for contract definitions - Uses `@lssm-tech/bundle.workspace` for workspace analysis - Configured via `action.yml`; no `src/` — logic lives in workspace bundle ## Usage ```yaml name: ContractSpec Drift on: pull_request jobs: contractspec: runs-on: ubuntu-latest permissions: contents: read packages: read steps: - uses: actions/checkout@v6 - uses: lssm-tech/contractspec/packages/apps/action-drift@main with: github-packages-token: ${{ secrets.CONTRACTSPEC_PACKAGES_TOKEN }} generate-command: 'bun contractspec generate' ``` For affected private GitHub Packages dependencies, `github-packages-token` must be a GitHub token that can read the ContractSpec packages granted to the consuming repository, bot, or GitHub App. ## Inputs - `package-manager` (default: `bun`) — Package manager to use (bun|npm|pnpm|yarn) - `working-directory` (default: `.`) — Working directory for running commands - `generate-command` (default: `bun contractspec generate`) — Command to regenerate artifacts - `on-drift` (default: `fail`) — Behavior when drift is detected (fail|issue|pr) - `drift-paths-allowlist` — Comma-separated glob patterns to check for drift - `token` (default: `${{ github.token }}`) — GitHub token for issues/PRs - `github-packages-token` — Optional token used to configure private GitHub Packages auth before dependency installs ## Outputs - `drift-detected` — Whether drift was detected ## Key Files - `action.yml` — GitHub Action definition - `fixtures/` — Test report data for drift scenarios ## Local Commands - `bun run test` — bun test ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Stability - Stability improvements ## Notes - Do not change `action.yml` inputs/outputs without updating downstream workflow consumers - Fixture JSON files are used for CI testing — keep them valid --- ## @lssm-tech/app.action-pr Description: GitHub Action for ContractSpec PR checks Path: packages/apps/action-pr URL: /llms/app.action-pr # @lssm-tech/action.pr Website: https://contractspec.io **GitHub Action that runs ContractSpec validation checks on pull requests. Posts drift reports, validation results, and product views as PR comments.** ## What It Does - Uses `@lssm-tech/lib.contracts-spec` for contract definitions - Uses `@lssm-tech/bundle.workspace` for workspace analysis - Configured via `action.yml`; no `src/` — logic lives in workspace bundle ## Usage ```yaml name: ContractSpec PR on: pull_request jobs: contractspec: runs-on: ubuntu-latest permissions: contents: read packages: read pull-requests: write steps: - uses: actions/checkout@v6 - uses: lssm-tech/contractspec/packages/apps/action-pr@main with: github-packages-token: ${{ secrets.CONTRACTSPEC_PACKAGES_TOKEN }} generate-command: 'bun contractspec generate' ``` For affected private GitHub Packages dependencies, `github-packages-token` must be a GitHub token that can read the ContractSpec packages granted to the consuming repository, bot, or GitHub App. ## Inputs - `package-manager` (default: `bun`) — Package manager to use (bun|npm|pnpm|yarn) - `working-directory` (default: `.`) — Working directory for running commands - `report-mode` (default: `summary`) — Report output mode (summary|comment|both|off) - `enable-drift` (default: `true`) — Run drift detection after generate - `fail-on` (default: `any`) — Fail on breaking, drift, any, or never - `generate-command` (default: `bun contractspec generate`) — Command to regenerate artifacts (required when enable-drift=true) - `validate-command` — Override validation command - `contracts-dir` — Directory containing contract specs - `contracts-glob` — Glob pattern for contract specs - `token` (default: `${{ github.token }}`) — GitHub token for PR comments - `github-packages-token` — Optional token used to configure private GitHub Packages auth before dependency installs ## Outputs - `drift-detected` — Whether drift was detected - `breaking-change-detected` — Whether breaking changes were detected - `validation-failed` — Whether validation failed ## Key Files - `action.yml` — GitHub Action definition - `fixtures/` — Test report data and validation fixtures - `.contractspec-ci/contracts.json` — CI contract configuration ## Local Commands - `bun run test` — bun test ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Stability - Standardize tool naming to underscore notation ## Notes - Do not change `action.yml` inputs/outputs without updating downstream workflow consumers - Fixture files are used for CI testing — keep them valid --- ## @lssm-tech/action.validation Description: GitHub Action for running ContractSpec CI checks Path: packages/apps/action-validation URL: /llms/action.validation # @lssm-tech/action.validation Website: https://contractspec.io **ContractSpec GitHub Action for CI/CD integration. Wraps the `contractspec ci` CLI command as a composite action.** ## What It Does - **Layer**: app (GitHub Action) - **Consumers**: external CI/CD pipelines via `lssm/contractspec-action@v1` ## Usage ```yaml name: ContractSpec CI on: pull_request jobs: contractspec: runs-on: ubuntu-latest permissions: contents: read packages: read steps: - uses: actions/checkout@v6 - uses: lssm-tech/contractspec/packages/apps/action-validation@main with: github-packages-token: ${{ secrets.CONTRACTSPEC_PACKAGES_TOKEN }} ``` For affected private GitHub Packages dependencies, `github-packages-token` must be a GitHub token that can read the ContractSpec packages granted to the consuming repository, bot, or GitHub App. ## Inputs - `checks` (default: `all`) — Checks to run (comma-separated: structure,integrity,deps,doctor,handlers,tests) or "all" - `skip` — Checks to skip (comma-separated) - `pattern` — Glob pattern for spec discovery - `fail-on-warnings` (default: `false`) — Fail the action on warnings (not just errors) - `check-handlers` (default: `false`) — Include handler implementation checks - `check-tests` (default: `false`) — Include test coverage checks - `upload-sarif` (default: `true`) — Upload SARIF results to GitHub Code Scanning - `working-directory` (default: `.`) — Working directory for running checks - `bun-version` (default: `latest`) — Bun version to use - `mode` (default: `validate`) — Action mode: "validate" (run checks) or "impact" (detect breaking changes) - `baseline` — Git ref to compare against for impact detection (default: base branch from PR context) - `pr-comment` (default: `true`) — Post impact results as PR comment - `github-token` (default: `${{ github.token }}`) — GitHub token for PR comments and check runs - `github-packages-token` — Optional token used to configure private GitHub Packages auth before dependency installs ## Outputs - `success` — Whether all checks passed - `errors` — Number of errors found - `warnings` — Number of warnings found - `sarif-file` — Path to SARIF output file (if uploaded) - `json-file` — Path to JSON output file - `impact-status` — Impact status: "no-impact" | "non-breaking" | "breaking" - `breaking-count` — Number of breaking changes detected - `non-breaking-count` — Number of non-breaking changes detected ## Key Files - `action.yml` — GitHub Action definition (composite action) - `README.md` — Usage documentation - `package.json` — Package metadata (private, not published to npm) ## Local Commands - `bun run test` — bun test ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Stability - PublishConfig not supported by bun ## Notes - All input/output changes must be reflected in both `action.yml` and `README.md`. - The action is versioned with tags on the repository — breaking input changes require a major version bump. - Test locally using `act` or by referencing the local action: `uses: ./packages/apps/action-validation`. --- ## @lssm-tech/action.version Description: GitHub Action for ContractSpec version management Path: packages/apps/action-version URL: /llms/action.version # @lssm-tech/action.version Website: https://contractspec.io **GitHub Action for automated ContractSpec version management in CI.** ## What It Does - Standalone action with no workspace dependencies - Configured entirely via `action.yml`; no TypeScript source ## Usage ```yaml name: ContractSpec Version Manager on: pull_request jobs: contractspec: runs-on: ubuntu-latest permissions: contents: write packages: read pull-requests: write steps: - uses: actions/checkout@v6 - uses: lssm-tech/contractspec/packages/apps/action-version@main with: github-packages-token: ${{ secrets.CONTRACTSPEC_PACKAGES_TOKEN }} ``` For affected private GitHub Packages dependencies, `github-packages-token` must be a GitHub token that can read the ContractSpec packages granted to the consuming repository, bot, or GitHub App. ## Inputs - `mode` (default: `analyze`) — Action mode: analyze (check only) or bump (apply changes) - `auto-bump` (default: `false`) — Whether to automatically applying bumps based on impact analysis - `commit-message` (default: `chore(release): bump spec versions [skip ci]`) — Commit message for version bumps - `create-pr` (default: `false`) — Create a Pull Request instead of pushing directly - `pr-title` (default: `chore(release): version packages`) — Title for the Pull Request - `pr-branch` (default: `release/next-versions`) — Branch name for the Pull Request - `github-token` (default: `${{ github.token }}`) — GitHub Token for creating PRs - `github-packages-token` — Optional token used to configure private GitHub Packages auth before dependency installs ## Outputs - `has-changes` — Whether changes were detected/applied - `specs-bumped` — Number of specs bumped ## Key Files - `action.yml` — GitHub Action definition (entry point) - `tests/action-version.test.ts` — standalone host test (`bun run test`): runs the `action.yml` steps locally with recording `bun`/`bunx`/`git`/`gh` stubs; requires `jq` ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - PublishConfig not supported by bun - Move automation into actions ## Notes - Do not change `action.yml` inputs/outputs without updating downstream workflow consumers - This is a standalone action — avoid adding workspace dependencies unless necessary --- ## @lssm-tech/app.agent-host Description: (none) Path: packages/apps/agent-host URL: /llms/app.agent-host # LSSM OS Agent Host `@lssm-tech/app.agent-host` is the single deployable host for governed agent applications. Its first production vertical is Release Steward, but the host is shared by the wider CommunicationOS and CompanyOS omnichannel program. Run `bun run test` for the complete package suite. It runs test files sequentially in fresh Bun processes so native/WASM and HTTP state cannot leak between suites. Test helpers use `.test-support.ts` names and are imported by actual test files. The Release Steward replay qualification intentionally takes over 200 seconds; its declared 270-second timeout remains in force. The host claims strict Durable Queue V2 envelopes, passes each exact claim to an injected Runtime Node V3 service, and acknowledges transport only from the service's durable operation receipt. Queue fences never authorize effects. Indeterminate work remains unacknowledged and is reconciled from SQL before a retry. Shutdown stops new claims and drains bounded in-flight work. The application lifecycle is `install_disabled -> configured -> qualified -> active`, with `paused`, `revoked`, and `uninstalled` safety states. Readiness requires active lifecycle, a recent queue cycle, and exact qualified component bindings for Runtime Node, queue, topology state, durable agent state, task graph, CommunicationOS gateway, and organizational policy. `startAgentHostApplicationV1` is the deployable composition boundary: it starts the governed consumer, serves liveness/readiness, forwards cancellation, and drains bounded in-flight work. ### Production entrypoint and readiness matrix `src/server.ts` (what `build` and `start` target) calls `startAgentHostServerV1`, which parses explicit `AGENT_HOST_*` keys, loads the qualified deployment document and, only when every binding is present, composes the PostgreSQL T1 host (`composeAgentHostT1ServerV1`): verified queue/topology profiles, the installation lifecycle, Runtime Node V3 with the Postgres dispatch authority, a verify-only Connect authority whose policy is the standing mandate, pinned component qualifications and registered effect providers. Otherwise it serves `/healthz` (live) and a `/readyz` 503 whose body names each blocking capability; a bootstrap artifact is never usable. | Key | Meaning | | --- | --- | | `AGENT_HOST_PORT` (`PORT`) | Listen port, default 3004 | | `AGENT_HOST_RUNTIME_DATABASE_URL` | Runtime role (secret; never logged) | | `AGENT_HOST_AUTHORITY_DATABASE_URL` | Distinct dispatch-authority role (secret) | | `AGENT_HOST_DATABASE_SSL_MODE` | `verify-full` (default) or `disable` | | `AGENT_HOST_DATABASE_POOL_MAX` | 1-32, default 4 | | `AGENT_HOST_DEPLOYMENT_FILE` | `lssm.agent-host.deployment.v1` JSON: lifecycle scope, queue/topology profiles, queue binding, backpressure, component bindings, qualification pins, provider bindings, `deploymentDigest` | | `AGENT_HOST_CONSUMER_INSTANCE_ID` | Stable consumer id (random per process when unset) | | `AGENT_HOST_INTERVAL_MS` / `_TIMEOUT_MS` / `_SHUTDOWN_DRAIN_MS` | Bounded timings | | `AGENT_HOST_CONNECT_ISSUER_REF` / `_KEY_REF` / `_PUBLIC_KEY` | Connect issuer identity and raw Ed25519 public key (base64); the host never holds a signing key | | `AGENT_HOST_DELIVERY_WORKLOAD_TOKEN_SHA256` | SHA-256 hex of the CommunicationOS worker bearer token (delivery effects) | | `AGENT_HOST_PROTOCOL_WORKLOAD_TOKEN_SHA256` | SHA-256 hex of the protocol-admission workload bearer token | | `AGENT_HOST_EFFECT_WAIT_MS` | Bounded wait for a request-driven effect receipt, default 20000 | Connect evidence (`createPostgresConnectAuthorityStoreV1`) and standing mandates (`createPostgresAgentStandingMandateStoreV1`) are read from `@lssm-tech/integration.lssm-os-state-postgres` through the runtime role; apply its `LSSM_OS_POSTGRES_CONNECT_AUTHORITY_MIGRATION_V1` and `LSSM_OS_POSTGRES_AGENT_STANDING_MANDATE_MIGRATION_V1` first. Windowed mandate grants reserve their slot atomically per exact Connect request digest. ### Request-driven duties (single effect path) - `POST /v1/communication/runtime-node/delivery-effects` (`communication.runtime-node.delivery-effect.v1`, bearer workload token, required `Idempotency-Key` equal to the outbox record key) admits one delivery through the Connect-side `effectAdmission` binding and the durable queue, then answers a `CommunicationDeliveryEffectResult` from the Runtime Node operation and provider receipt. Not admitted → retryable `rejected`; admitted but unobservable → `indeterminate` with the work-order digest. - `POST /v1/agent-host/protocol-runs` (`lssm.agent-host.protocol-run-admission.v1`) admits or exactly resumes a protocol run for the installed application. Application, compiler and model route are host-bound (`protocolRuns` binding); artifacts persist in the canonical Postgres protocol artifact store. - `createAgentHostCodingAgentControlPortV1` implements the S08 `CodingAgentControlPortV1` over the same admission path; anything unproven throws `AgentHostCodingControlUncertainError` and is never re-sent. Each duty has its own optional readiness row (`delivery_effects`, `coding_control`, `protocol_runs`, `bounded_agent_runs`) and never blocks worker readiness. ### Bounded agent runs `createAgentHostBoundedAgentRunnerV1` composes the `@lssm-tech/lib.ai-agent` bounded-epoch runner for a `ContractSpecAgent` (any target with its `generate`), so a run is bounded by a host-owned epoch policy (per-epoch token, wall-time and tool-call budget, finite renewals, a no-progress stop and `maxResumes`) and not only by the agent's `maxSteps`. Each `generate` call is capped at the remaining tool-call budget, receives the epoch abort signal and runs as one write-ahead journaled effect (`agent-host:generate::`): a restarted host replays recorded calls without sending them again, and the open epoch's token and tool-call spend continues from its persisted value. A call that fails, is cancelled or reaches the wall-time budget after its journal entry is written, or that a crash interrupts, stops the run as `effect_indeterminate`; it is never sent again. That holds when the host restarts after the epoch's wall time has run out: the call's journal entry admitted its step, so the restarted epoch reaches the entry without a budget check. The run result's `stopDetail` names the call and a redacted failure class (the abort reason or the error's class name, never its message). `generate` takes no token cap, so tokens are checked between calls: one call can overrun the epoch token budget. Runs are keyed by tenant, workspace and `runRef`. The runner refuses at composition a policy the epoch contract rejects and an `approval_required` policy without a renewal approver. In the server, the optional `boundedAgentRuns` binding supplies the agent id, policy and approver; the duty stores runs in the canonical PostgreSQL agent checkpoint table of the runtime role (apply `migratePostgresAgentDurableStore` from `@lssm-tech/integration.agent-durable-store/postgres/migrations` first) and exposes the runner as `duties.boundedAgentRuns`. Its row is `disabled` until bound, and `invalid` for a binding that throws or a refused policy. ### Connect-side effect admission With `AGENT_HOST_CONNECT_DATABASE_URL` (the `lssm_os_connect` role), `AGENT_HOST_CONNECT_SIGNING_KEY_FILE` (mounted PKCS#8 Ed25519 key, never an inline value) and deployment `effectProfiles`, the host composes the issuing Connect authority (`admitConnectEffectV1` from `@lssm-tech/lib.contractspec-connect`): the standing-mandate policy decides, Connect signs the Runtime V3 lifecycle, the operation and its envelope are admitted co-atomically (`admitPostgresOperationAndQueue`), the qualification authority records the orders and the operation is queued after `verifyAdmission`. Admission is idempotent per request (time-anchored replay); a different request for the same idempotency key is denied. Standing mandates must carry `ownerSignature` over `mandateDigest`, verified against an active human key registered to the owner (`createPostgresPrincipalKeyStoreV1`); a delegate key never authenticates. Mandate exceptions are lifted only by a Connect operation-approval receipt (`createAgentHostMandateApprovalsV1`): human approver other than the delegate, single-use nonce, re-verified (not re-consumed) for the same request. When the deployment declares `routes.operationStatus: "required"` (RT-009), the `operation_status` row becomes required and stays missing until an `operationStatus` authorization binding is supplied. Readiness rows (`configuration`, `runtime_database`, `authority_database`, `deployment`, `durable_queue`, `application_lifecycle`, `runtime_node`, `effect_providers`, `connect_verifier`, `standing_mandate`, `component_qualification`, `worker_cycle`) fail closed individually; `operation_status` is optional and disabled until an authorization port is bound. Connect authority stores, the standing-mandate store and the CommunicationOS outbox dependencies are injected through `AgentHostServerBindingsV1` by their owners; until bound they stay `missing`. `SIGTERM`/`SIGINT` stop claims, drain, stop HTTP and close both pools. A restart resumes from SQL: unacknowledged claims are redelivered after lease expiry and Runtime Node replays durable receipts instead of repeating effects. ### Standing mandate to typed permits `lssm.agent-host.standing-mandate.v1` records the owner, delegate actor, installation scope, granted action classes (sender accounts, target prefixes, permit lifetime, optional rate window), exception rules and contract-required human-decision classes. `createAgentHostStandingMandatePolicyV1` is the Connect policy: on issuance and again at dispatch it resolves the current revision into a typed expiring permit, `deny`, or `require_review`. Revocation, expiry, a changed sender/target, an exhausted window or an unresolved exception stops the action; a review is lifted only by an approval bound to the exact Connect request digest. Issuers encode actions with `encodeAgentHostMandateConnectTargetV1` so sender and target are part of the signed request. The same application can expose authenticated durable operation status at `/v1/lssm-os/operations/{tenant}/{workspace}/{environment}/{operation}` by injecting `operationStatus`. Authorization is bounded and exact-scope before the PostgreSQL/SQLite operation adapter is read; denied identities receive a non-disclosing 404. Successful responses return the canonical Runtime Node REST projection unchanged, including HTTP 202 for every nonterminal state and the exact request, receipt, and projection digests. Responses are private and `no-store`; malformed, substituted, timed-out, or unavailable dependencies fail closed without returning bearer material. Application shells that need only this boundary may import `@lssm-tech/app.agent-host/operation-status` without loading queue, provider, or state-adapter compositions. The integrated F3 proof drives that REST handler through the canonical SDK, CLI, MCP, and React UI projections and requires one identical projection digest on every surface. The PostgreSQL application-installation lifecycle is tenant/workspace/ environment/product scoped and revision-CAS guarded. Apply `AGENT_HOST_POSTGRES_LIFECYCLE_MIGRATION_V1` through an owner connection, provision the initial disabled installation through the owner-only helper, and give the runtime only SELECT plus the guarded transition function. Raw runtime INSERT/UPDATE/DELETE stays revoked. The state machine and its validators are owned by `@lssm-tech/lib.agent-protocol-spec/protocol/application-lifecycle`, and the adapter and migration by `@lssm-tech/integration.lssm-os-state-postgres/agent-application-lifecycle` (and `-migration`); the host root re-exports them under the existing names. Release Steward uses one frozen application profile through T1, T2, and T3. T2 requires a separately qualified distributed-cache binding and T3 a separately qualified event-stream binding; both retain the same SQL durable queue and Runtime Node authority components. Its first channels are web and in-app, its default is single-agent, and merge/release authority is hard-disabled until branch protection is independently qualified. `createAgentHostWakeAcceleratedQueueV1` is the app-local T2/T3 composition seam. It retains PostgreSQL as the complete Durable Queue V2 and claimed-envelope authority while routing admission, claim, acknowledgement, and reconciliation through a qualified event-stream wake accelerator. Capability, renewal, redrive, health, and envelope reads remain directly SQL-backed. A T2 host must also inject an actual distributed-cache port matching its qualified component; a component label alone is rejected. The Release Steward T2 walking skeleton uses the real Redis integration with an independently qualified cache and Streams binding, then makes Redis unavailable during claim and acknowledgement. SQL still completes and acknowledges exactly one effect, and a stale wake hint cannot create a second effect after Redis recovers. This is credential-free fallback evidence, not live Redis/Valkey failover or performance qualification. T3 additionally requires an injected event-stream port whose exact component, capability, adapter, server, client, topology, and generation bindings match the qualified topology. The Release Steward T3 walking skeleton uses the real SQS wake integration over the same PostgreSQL queue. It admits co-atomically in SQL, publishes one opaque SQS hint, makes SQS unavailable during claim and acknowledgement, and still completes exactly one authorized effect through SQL. After SQS recovers, the stale broker hint observes an empty SQL queue and cannot repeat the effect. This is credential-free fallback evidence; AWS/Scaleway live failover, visibility-expiry, scale, cost, and performance qualification remain blocked. The same Release Steward T3 path is qualified with the real RabbitMQ wake adapter and an independently bound quorum-queue capability profile. Publisher confirms only accelerate a co-atomically admitted SQL operation; broker loss during claim and acknowledgement falls back to SQL, and the recovered stale delivery cannot repeat the durable Runtime Node effect. This remains a credential-free simulation. Live RabbitMQ quorum failover, publisher-confirm ambiguity, consumer death, prefetch/backpressure, DLQ redrive, scale, cost, and performance qualification remain blocked. GCP Pub/Sub and Cloud Tasks use the same Release Steward T3 proof with separate, exactly qualified transport profiles. Both publish only after durable SQL operation and outbox admission. Transport failure during claim and acknowledgement cannot prevent SQL completion or repeat the provider effect; after recovery, a stale Pub/Sub delivery or Cloud Tasks callback remains a non-authoritative hint and observes an empty SQL queue. This is credential-free simulation evidence only. Live GCP redelivery, acknowledgement deadline, callback authentication, regional failover, scaling, cost, and performance qualification remain blocked. MQTT remains an ingress/fan-out protocol rather than an Agent Host work queue. The CommunicationOS credential-free walking skeleton authenticates and normalizes one MQTT 5 publication, derives a source-bound outbox identity, and admits it into the real PostgreSQL Durable Queue V2 before Agent Host can claim it. The existing CommunicationOS Runtime Node path then produces one governed audit, one reply event, one durable effect, and one queue acknowledgement; duplicate MQTT publication before or after completion replays the SQL admission and cannot repeat the effect. This is simulated product evidence only. Live broker ACL, mTLS/token, QoS/session reconnect, retained-message, shared- subscription, broker-failover, scale, cost, and performance evidence remains blocked. `qualifyReleaseStewardApplicationV1` is the host-owned proof boundary for the first vertical. It requires an active durable installation and runs the real filesystem-authored Release Steward application through bounded injected execution. The v0 gate records 100 production-shaped, credential-free runs, including approval, exactly-once replay, checkpoint/resume, dead-letter, and local-harness evidence. The report remains `candidate`, keeps merge and release authority disabled, and explicitly requires separate live qualification. Release Steward now opts into Protocol V1 compilation. A signer is an injected port and never exposes its private key to Agentpacks or Agent Host. Agent Host verifies the canonical application signature with an Ed25519 first-party trust root, binds its publisher/key/policy and artifact digests, then advances the durable installation through `install_disabled -> configured -> qualified -> active` with revision CAS. Replayed activation is idempotent only for the exact configuration and qualification. The credential-free keypair used by tests is ephemeral and is not production trust evidence. `./t1` provides the PostgreSQL infrastructure factory. It creates the real Durable Queue V2, topology-state, and V3 operation adapters and only reports verified after their owner-provisioned queue and topology profiles match the exact active binding. It does not provision profiles, mint authority, or bridge the legacy V2 worker. The T1 Runtime Node bridge reloads the exact claimed envelope, durable operation, and signed standard or cleanup V3 order; keeps the queue fence distinct from the Runtime Node authority fence; and delegates at most one effect to an injected V3 execution service. It creates a queue acknowledgement only after rereading the exact terminal operation receipt. Terminal retries replay that receipt without repeating the effect, while missing, substituted, timed-out, or indeterminate results stay unacked. Production activation still requires static composition of the concrete V3 execution service and a durable application lifecycle adapter. `createAgentHostCommunicationOsT1RuntimeV1` is the production composition seam for CommunicationOS provider execution. It accepts a qualified provider binding plus injected durable payload, delivery, and execution-custody ports, then returns only the governed Runtime Node port. The concrete provider is not exposed, so a worker or product cannot call it as ambient send authority. `admitAgentHostContextV1` is the fail-closed AI context boundary. It accepts only the exact qualified `context_compiler` binding for the active topology, returns a typed block reason when required context is unavailable, and keeps retrieved or channel content non-instructional even when it contains prompt-like text. The baseline effect worker remains backward compatible and cannot use context admission to expand Runtime Node authority. `admitAgentHostProtocolRunV1` composes that exact context boundary with the durable `AgentProtocolRuntimeV1`. Admission requires qualified, topology-matched `context_compiler`, `protocol_runtime`, `agent_durable_store`, and baseline Agent Host bindings. It also re-materializes the exact signed first-party application through an injected qualification authority on every admission and resume. The manifest, permission summary, policy bindings, installation revision, lifecycle digests, release SHA, application/prompt/model/tool/policy/ context/evaluator versions, and sandbox digest must all match before context is compiled or durable state is returned. Revoked, paused, stale, unsigned, non-first-party, substituted, or tool-widened applications fail closed. Admission also stores an immutable run-scoped application binding, preventing a same-version requalification or policy change from silently altering a resumed run. It independently validates and persists the exact model routing V2 capability profile, invocation profile, route, qualification, evaluation decision, selection, and optional canary artifacts before context compilation, after an exact Connect route decision and connection verification. The selection must use the installed application's model policy; `live_verified` routes require an exact production-canary binding. Resume (`resumeAgentHostProtocolRunV1`) takes the same V2 route plus authority and connection ports, re-verifies Connect authority and route expiry at resume time, never recreates missing model artifacts, and requires a replan when the persisted selection changes. Model routing V1 admission, V1 checkpoint fallback, and the V1 resolver are retired; a V1 route supplied to admission is rejected. A run persisted under model routing V1 is upcast deterministically on resume. V1 records carry no model author, serving identity, invocation profile, evaluation decision, dataset, qualification expiry, or Connect decision, so the upcast never invents them: `classifyAgentHostPersistedModelRoutingV1` verifies the persisted run state and every bound V1 profile, route, qualification, and selection (digest-bound, schema-strict, via the contracts-spec `planAgentModelRoutingV2Migration` plan), and `upcastAgentHostModelRoutingV1ToV2` accepts only a requalified V2 route for the same run, plan, selection policy, model id/version, route version, and region. The full V2 admission (Connect authority, connection verification, expiry, budget) re-runs and persists the V2 artifacts before the run state is rebound to the V2 selection with `model_routing.v1_upcast.` evidence; a second resume sees a V2 run. Unknown, malformed, or tampered V1 state, a terminal, in-flight, reconciling, or fallback-active V1 run, a resume expectation that does not bind the run, and a non-corresponding route block with `agent_host.model_route_upcast_rejected` (`model_routing.upcast_rejected:`, `AgentHostModelRoutingUpcastError`) before any V2 artifact is written; a denied or failed V2 admission blocks with `agent_host.model_route_untrusted` and leaves the run on V1. Re-admitting an existing V1 run blocks with `model_routing.v1_resume_required:`; resume performs the upcast. Checkpoint fallback (`admitAgentHostModelFallbackV2`) re-materializes the active signed application, verifies the admitted run binding, and permits only an equivalent eligible route. It never falls back from an indeterminate provider outcome, and exact retry returns the same durable decision without another transition. The Host-owned resolver reloads that persisted selection/fallback before every model execution, canonical-verifies the active V2 candidate, rechecks the run budget, and requires an exact Connect decision before requesting a lease. It also loads the current `IntegrationConnection`, hashes only an adapter-allowlisted secret-free projection, and rejects version, configuration, deployment, gateway, adapter, policy, or connection substitution. Route/profile/invocation/current qualification/evaluation/current canary artifacts and exact route cost are reconstructed directly from the Host artifact store. A changed qualification or canary head invalidates the selection binding before authority or lease resolution; callers do not provide candidate artifacts to the production resolver. Qualification and canary lifecycle writes use artifact-head CAS and retain historical revisions. A model reselection is accepted only after the active route has a persisted evidence-backed rolled-back canary. Agent Host verifies the replacement baseline and its Connect/connection bindings before the Protocol runtime atomically activates the new plan, validation, and selection and clears stale fallback state. Admission persists the immutable compiled context manifest and idempotently resumes an exact already-admitted run instead of duplicating its plan. `respondToAgentHostProtocolHelpV1` accepts a waiting-run response only through an exact qualified organizational-policy authority port. That port must verify the responder and evidence against the pending request. Conversation text and model output are never treated as approval or authority. The governed automation runtime materializes only an exact automation definition listed by the active signed application manifest and bound to its current qualification digest. Injected authority and scheduler ports control materialization, pause/resume/revoke/expiry, claims, and background follow-ups. State uses revision CAS; occurrence and run identities are deterministic; active claims survive lease loss as `resume_required`; receipt-first completion recovers after process interruption without inventing another run. An indeterminate result keeps its claim in `reconciliation_required` and cannot create a follow-up. Agent Host persists coordination artifacts but never sends the follow-up or performs the scheduled run's external effects. `createAgentHostV3ExecutionServiceV1` is that frozen execution composition (owned by `@lssm-tech/lib.lssm-os-runtime/runtime-node/v3-execution-service` as `createRuntimeNodeV3ExecutionServiceV1`; `./t1` re-exports it). It projects the signed V3 one-step authority into the provider lifecycle, independently persists the exact provider receipt, and completes the durable operation before the queue can acknowledge. A running retry without durable provider evidence never repeats the effect; it enters `indeterminate` custody. When an exact provider receipt supplies sanitized diagnostic evidence for that ambiguity, custody persists those refs alongside its deterministic recovery ref without inventing an external delivery reference. Those diagnostics support reconciliation and operator help but never authorize retry, fallback, or a terminal outcome. The provider-receipt adapter remains an injected persistence boundary so T0 and T1 state packages can preserve their own atomic transaction semantics. The GitHub T1 walking skeleton composes the actual GitHub provider lifecycle, PostgreSQL qualification authority, V3 operation and provider-receipt stores, and Agent Host execution service. Its credential-free PGlite qualification proves one draft effect across 100 concurrent host calls plus exact restart replay. It is production-shaped candidate evidence, not live GitHub evidence; credentialed canary create, observe, compensate, teardown, and billing proofs remain required before live activation. The Vercel T1 walking skeleton reuses that same PostgreSQL authority and Agent Host execution boundary with the actual Vercel Runtime Node provider. Its credential-free structural project command proves one effect across 100 concurrent host calls and exact terminal replay after reconstructing the host and provider composition. The Vercel qualification row remains blocked until credentialed create, observe, compensate, teardown, billing, and 24-hour observation evidence is attached. The Railway T1 walking skeleton exercises the provider API ownership mode with an exact service-update command through the same PostgreSQL authority and Agent Host execution boundary. One of 100 concurrent calls performs the effect, and a reconstructed host/provider composition replays the terminal receipt without another mutation. Railway remains blocked until credentialed lifecycle, teardown, billing, and 24-hour observation evidence is attached. The Supabase T1 walking skeleton routes an exact private storage-bucket command through the management-driver side of the actual Supabase Runtime Node provider. The PostgreSQL authority permits one effect across 100 concurrent Agent Host calls, and reconstructed composition replays the durable terminal receipt. Supabase remains blocked until credentialed lifecycle, teardown, billing, and 24-hour observation evidence is attached. The Neon T1 walking skeleton binds an opaque project, branch, parent branch, role profile, and region into a branch-create command. The actual Neon Runtime Node provider performs one effect across 100 Agent Host races and replays its durable receipt after reconstruction. Neon remains blocked until credentialed branch lifecycle, teardown, billing, and 24-hour observation evidence exists. The Resend T1 walking skeleton binds only opaque message, recipient, sender-profile, template, and encrypted-content references into the actual Resend Runtime Node provider. The PostgreSQL authority permits one send across 100 Agent Host races, and reconstructed composition replays the durable receipt without another effect. No credential or email body enters the order. Resend remains blocked until credentialed delivery, observation, billing, and 24-hour evidence is attached. The Release Steward T1 walking skeleton additionally crosses the complete product-shaped path: co-atomic accepted operation and Durable Queue V2 admission, real Agent Host claim and V3 execution, one structural GitHub draft effect, durable provider and operation receipts, exact queue acknowledgement, then 100 consecutive post-effect acknowledgement interruptions across fresh host/runtime/provider composition. Every five failed claims follows the declared attempt ceiling into DLQ and uses a digest-bound redrive receipt before continuing. The final delivery acknowledges the original terminal operation with exactly one provider effect. This remains `credential_free_simulation` evidence and does not promote any provider, product, or channel row to live qualification. The paired real-PostgreSQL completion-boundary command additionally SIGKILLs 100 worker processes after terminal operation/receipt verification but before queue acknowledgement. Fresh processes reclaim every expired lease and commit 100 exact acknowledgements while the durable effect table remains exactly 100. This is local-live completion-boundary evidence; the remaining boundaries are tracked below and independent production-host audit remains blocked. The T1 outbox-boundary command separately SIGKILLs 100 workers immediately after co-atomic operation, outbox, and queue admission. A fresh worker exact- replays every request, and the final database inventory must contain exactly 100 operations, 100 outbox rows, and 100 messages with no provider effect. The authority command separately SIGKILLs 100 workers after atomic lifecycle issuance; the same public issuance call exact-replays in fresh processes without charging budget or inserting again. The dispatch command kills 100 workers after the running-operation and normal-reservation CAS; fresh workers recognize the exact durable authority tuple without redispatching. The effect-boundary command kills 100 workers after one durable simulated provider mutation but before any receipt. Fresh workers reconcile the existing effect into one terminal operation receipt without reinsertion. The receipt- boundary command kills after immutable provider receipt append and recovers that exact receipt into terminal completion. Both finish with 100 effects and zero duplicates. Cleanup then kills 100 workers after permit-bound teardown effects and recovers signed absence completion. Settlement kills 100 workers after evidence commit and exact-replays the same public settlement call. All eight local PostgreSQL crash boundaries pass; independent production-host audit remains required. The CommunicationOS in-app T1 walking skeleton uses the same authority path without making Agent Host a channel sender. CommunicationOS owns the approved delivery command, exact context resolution, `approveAndSend` reconciliation, event, and audit. Its public `./agent-host` adapter binds that command to a Runtime Node provider lifecycle receipt, while `./agent-host-admission` creates the strict Queue V2 handoff consumed by Agent Host. The credential-free proof covers PostgreSQL admission, V3 execution, the real CommunicationOS approved-send orchestrator, governed audit persistence, one reply event, durable receipts, failed first ack, restart/redelivery, and exactly one in-app delivery. Product and channel rows remain blocked until credentialed provider and full omnichannel qualification exists. The ContractSpec T1 walking skeleton runs the real workspace Connect service for a safe governed contract edit, persists its context, plan, and permit verdict, binds their exact digests into the accepted operation, queue envelope, outbox, signed V3 GitHub draft order, and provider evidence, then crosses the same Agent Host restart/replay boundary without a second effect. This advances the ContractSpec product journey with credential-free CLI-service evidence; The integrated operation proof now covers API, MCP, SDK, CLI, and React UI projection parity. Credentialed GitHub and live product qualification remain release blockers. The Managed CompanyOS T1 walking skeleton composes its real deterministic workspace, fail-closed policy decisions, replay, executable proof, and evidence receipt with an actual ContractSpec Connect permit. Those exact digests bind a draft-only GitHub V3 order before co-atomic PostgreSQL admission, Agent Host execution, durable receipts, failed acknowledgement, restart, and exact replay. Managed CompanyOS remains the policy/control-plane owner; Connect and Runtime Node remain effect authority. This is credential-free simulated product evidence, not a live provider or production qualification claim. The Pactena T1 walking skeleton binds its standalone founder-suite meeting projection to a real Connect permit. The AI projection may edit but cannot approve, publish, or dispatch; the human projection retains those actions. Their exact digest enters a draft-only V3 order, PostgreSQL admission, Agent Host execution, durable receipts, failed acknowledgement, restart, and replay. This is simulated product evidence only; complete Pactena omnichannel and live provider qualification remain blocked. The HCircle T1 walking skeleton executes the real subject-bound personal community contract for a private, non-discoverable profile draft. A human-required decision receipt, exact idempotent replay, and real Connect permit bind the draft-only V3 order, PostgreSQL admission, Agent Host execution, failed acknowledgement, restart, and durable replay. This remains credential-free simulated evidence; HCircle live provider and complete omnichannel qualification remain blocked. Provider adoption qualification also verifies that GitHub, Docker, Vercel, Railway, Supabase, Neon, and Resend expose and advertise the canonical `./runtime-node` production boundary in workspace, published, and ContractSpec catalog metadata. Offline discoverability does not satisfy credentialed provider lifecycle or 24-hour observation gates; every provider row remains blocked until those external proofs exist. The Docker T1 walking skeleton now binds a Docker-specific V3 work order and payload to the production Runtime Node adapter, persists authority and receipts in the PostgreSQL state boundary, races 100 host executions, and replays after a fresh host/provider composition without a second Docker effect. The driver is a credential-free structural simulation; the Docker provider row therefore remains blocked for isolated live lifecycle and 24-hour observation evidence. `./t0` provides the embedded single-node infrastructure factory. It composes the real SQLite-backed Durable Queue V2, topology-state, and V3 operation adapters, validates the exact T0 topology and queue qualification, and proves that admitted work survives a process restart. Qualification-order reads and provider-receipt persistence remain explicit injected authority boundaries; the factory neither substitutes in-memory authority nor claims that the current SQLite state package can issue signed V3 orders. T0 activation stays closed until those durable boundaries and the application lifecycle are statically composed. `qualification:generate` materializes the one-time LSSM OS v0 requirements genesis at `generated/qualification/lssm-os/v0//requirements.json`. The inventory covers retained v3 authority, Agent Host, Release Steward, T0-T5, each mandatory database/cache/broker/replica transition and rollback path, cache, brokers, providers, products, channels, topology, scale, chaos, disaster recovery, and canary proof. Evidence must be tracked and is SHA-256 bound into the deterministic ledger. Required rows cannot be omitted or promoted to `live_verified` without provider-live, canary, and authority evidence. Local tests therefore never inflate the production denominator. Genesis is accepted only on the commit that introduces the generator. The repository CLI intentionally has no continuation mode until a trusted lineage verifier is statically composed. Integrations may use the public builder for continuation only by injecting independent lineage and requalification verifiers that authenticate the prior ledger as an exact ancestor artifact and retain that verifier identity in the new ledger. Any changed scope, topology, adapter/client/server version, policy requirement, authority binding, product contract, rollback rule, dependency, blocker, or evidence digest is emitted as `requalification_required` with `freshness: invalidated`. The generator reads evidence from the selected Git commit object and refuses a dirty worktree, so working-copy bytes cannot masquerade as evidence for `HEAD`. Invalidation is sticky across repeated generations; it cannot be cleared by presenting the invalidated ledger again. A separately governed, validated requalification transition is required before such a row may become fresh. ## Memory import HTTP boundary The application factory accepts optional `memoryImports` dependencies. When present and the lifecycle is active, `POST /v1/agents/memory-imports` accepts a bearer-authenticated JSON request and dispatches `agent.memory.import.submit@1.0.0` through the supplied canonical registry. Use `createMemoryImportOperationRegistry` with real Runtime Node verification, restricted artifact readers and the durable submission adapters. The authenticator must return server-owned identity and permissions; body fields never establish the actor. Disabled/unconfigured hosts return 503. Bodies are capped at 64 KiB; authentication, body reading and execution are bounded. Responses are private/no-store and expose only submission status, proposal digest and operation reference. A timed-out dispatch is indeterminate, not failed or successful. This boundary does not mint work orders or promote memory. Production authentication/authority configuration and console route wiring remain required. Memory import transports can use `createAgentMemoryImportAuthenticator` with a trusted deployment origin serving AuthOS and CompanyOS authority. It verifies the bearer session, explicit current fleet-review permission, tenant binding, active organization/workspace, response freshness and authority revisions, then rechecks the session. The HTTP handler refreshes authority after reading input; workspace changes or revoked permission stop dispatch. No role-derived grant or deployment permission is produced. Production still requires configured runtime authority and durable ports plus live session qualification. `createAgentHostMemoryImports` composes AuthOS/CompanyOS authentication, the canonical command registry and the V3 memory-import verifier. Pass its result as `startAgentHostApplicationV1({ ..., memoryImports })`. The composition requires explicit runtime order/payload/operation readers, Connect verification, restricted artifact readers, content/owner policy verification and an artifact store. It cannot accept a replacement command registry or a shortcut operation verifier. The application checks fresh lifecycle state and current readiness before import authentication and dispatch. Paused, unavailable, unready or shutting-down hosts reject new imports. Shutdown does not grant authority to finish an uncertain external effect; Runtime Node reconciliation and durable state still own recovery. The database composition proof exercises this application path with synthetic AuthOS/CompanyOS responses and an injected Connect signature-verification fixture, including permission revocation, runtime denial, pause, shutdown and database reopen/replay. Production ports, credentials and live qualification remain required. ## Internal supervised provider processes `createSupervisedProvider` can adapt a statically configured, trusted POSIX child entrypoint to the existing provider lifecycle port. Compose it in the exact provider router consumed by `createAgentHostV3ExecutionServiceV1`; V3 dispatch and SQL receipt persistence remain authoritative. The child receives one bounded execution JSON document on stdin and must emit one canonical receipt on stdout. An independent receipt verifier must accept that receipt before it can return. The executable and working directory must be absolute, environment is explicit with production mode, and no shell or ambient credentials are inherited. Timeout, cancellation, excessive output, nonzero exit, or an unconfirmed process group exit yields an error for the existing V3 indeterminate-custody path. A partial stdout receipt never establishes success. Local tests exercise real child processes plus synthetic provider receipts; they do not qualify live Builder inference, a production child entrypoint, or host-crash recovery. Windows needs a qualified Job Object/container implementation and is currently rejected. This is supervision of trusted host code, not containment for hostile code, escaped process groups, or arbitrary external effects. The adapter is internal and is not activated by the default host binary. ### Static Builder child composition The canonical `@lssm-tech/app.agent-host/t1` surface exports `createAgentHostBuilderChild`, `serveSupervisedProviderChild` and `createSupervisedProvider`. The child factory composes the real Git patch adapter with the governed Builder patch service and existing Runtime Node provider. Deployment configuration must supply exact provider binding, repository/checkout/ artifact roots, qualified generation providers, Connect packet authority, QA, clock, approved payload reader, active-claim coordinator and durable receipt writer/verifier. None has a permissive default. The app does not accept this configuration from a submitted intent or choose a model from ambient login state. A deployment-owned entrypoint statically imports its configuration and calls `await serveSupervisedProviderChild(createAgentHostBuilderChild(configuration))`. The supervising host configures that exact executable and entrypoint, routes it through V3 authority, and independently verifies its returned receipt. There is no dynamic plugin/configuration-module path in the submitted JSON protocol. The composition integration test produces a real Git candidate, verifies retained artifacts and exact receipt replay. Authority signatures, claim coordination, model output and receipt persistence in this test are fixtures. Provider credentials, independent QA and live deployment qualification remain activation blockers. Same-host process custody is described below. The default binary is unchanged and does not claim to generate applications yet. After a termination request the supervisor observes closure for at most two more seconds. Unconfirmed processes retain their host handles until actual close; operator inspection through `unresolvedSupervisedProcesses` never authorizes a retry. Escaped descendants with inherited pipes are covered by a real subprocess test. Deadline expiry is never treated as proof that an executor stopped. ### Builder V3 PostgreSQL receipts `createAgentHostBuilderPostgresChild` accepts the admitted operation's exact scope/order reference and a restricted runtime PostgreSQL pool. It composes the existing issued-order reader and V3 provider receipt store, then supplies them to the Builder child. Operators no longer need a V2 receipt/claim-store adapter. `createBuilderV3ReceiptWriter` is the lower-level composition for qualified V3 ports. Neither function issues orders, authorizes dispatch, runs migrations or provides an active-claim coordinator. Each read/write reloads the issued standard order and binds all execution fields to its canonical V3 execution. SQL rejects receipt writes before dispatch. A receipt returns only after exact persisted readback; replay requires the same candidate and evidence. The existing Agent Host V3 service owns terminal operation completion and skips provider execution when its durable receipt already exists. A file-backed embedded PostgreSQL test now closes and reopens the database, creates fresh writer/host instances, and verifies receipt/terminal replay with one generation. It also rejects pre-dispatch writes, cross-workspace execution and altered replay results. Generation, signature-verification and connection-role metadata remain explicit fixtures; live PostgreSQL role isolation and production execution fencing still require qualification. No default host activation or live inference is implied. ### Local/personal Builder process custody `createAgentHostBuilderLocalPostgresChild` supplies the same-host coordinator as well as concrete V3 SQL receipt persistence. Configure a stable custody directory, the admitted node identity and a bounded maximum duration. Run this provider in the supervised child process with a supervisor timeout no greater than that maximum. Generation still requires configured Connect packet authority, a qualified model provider and independent QA. The coordinator verifies the issued order and current running SQL claim before reserving an operation and again around its callback. Its filesystem reservation is keyed by tenant/workspace/environment/operation, so a new attempt cannot erase an unresolved previous executor. Only one actual process can reserve that local operation. Roots and ancestors must be owned/trusted, cannot traverse symlinks, and must remain disjoint from repository and checkout roots. Reservation and outcome markers plus their directory entries are flushed durably. A throw, lost acknowledgement or dead owner leaves custody in place. Expiry or a missing PID never releases it. After restart the existing V3 service can replay a verified SQL receipt without dispatching the provider again; absent such evidence, operator reconciliation is required. Never delete custody to force a retry. This is local POSIX process exclusion, not distributed/cloud fencing or automatic recovery of arbitrary external effects. Windows and cross-host coordination remain unqualified. Tests race two real processes, kill an owner after durable reservation, and reject fresh-process/expired-custody reuse. The SQL/host proof now loses acknowledgement after a real receipt append, retains unknown custody, closes/reopens the database, and completes by receipt replay with exactly one generation. Policy signatures, model output and SQL connection-role metadata in that proof remain fixtures. ### Private provider failure diagnostics Supervised process configuration accepts an optional diagnostic port. Host-owned compositions can use `createPrivateProviderDiagnostics` with a stable run reference and a private directory. Failed process stdout/stderr share the configured byte budget; known environment secrets and recognizable bearer/key tokens are redacted. Files are created exclusively with mode 0600 under a checked trusted directory, flushed and read back before returning an opaque diagnostic reference. Arguments, environment maps and credential files are not copied into diagnostic records. Failure objects expose only the reason, numeric exit/signal when observed, whether stream closure was confirmed, the diagnostic reference and availability status. Raw child output stays in the private artifact. An exited parent with an unclosed inherited pipe remains explicitly unconfirmed even if its exit code was zero. Diagnostic persistence is observed for at most five seconds; unavailable or uncertain logging never converts a failed/unknown execution into success. Existing V3 custody and reconciliation remain authoritative. Diagnostic artifacts need host-authorized access and operator retention/cleanup; they are not public release evidence. ### Local Builder with SQLite `createAgentHostBuilderLocalSqliteChild` on `./t0` composes the existing Builder child with concrete SQLite issued-order reads, V3 provider receipt persistence, operation state and same-host custody. Configure one migrated SQLite driver, the admitted operation's exact order reference, trusted clock, protected custody location, qualified generation provider, Connect packet authority and QA. The owner runs `migrateSingleNodeState`, `migrateSqliteQualificationAuthority` and `migrateSqliteV3ProviderReceipts` first. `SqliteQualificationIssuance` persists the canonical signed lifecycle with mandatory Connect verification, and `SqliteQualificationDispatch` must authorize the queued operation before the child can reserve custody or write receipts. Existing T0 queue/topology infrastructure accepts the same `SqliteQualificationOrderReader` and `SqliteV3ProviderReceiptPortV1`. The child supplies no permissive verification or model defaults and requires no PostgreSQL service. The file-backed local proof executes one custody callback, persists synthetic Builder evidence, closes/reopens SQLite and replays the exact receipt. It does not qualify live generation. The SQLite qualification evidence adapter separately supports evidence-backed settlement and release of an unused cleanup reservation; those methods require canonical signed evidence and retain conservative budget accounting. `createSqliteQualificationAuthorityV2` now composes cleanup dispatch, signed absence completion and two-principal custody transfer as well. Run the explicit `migrateSqliteQualificationCleanup` upgrade and configure mandatory Connect, observation, evidence and custody verifiers before using these methods. The child composition grants no authority; live provider effects and deployment trust qualification remain separate from these local state-port proofs. `createBuilderClaimedQueuePayloadReader` is available from `./t0`. Construct it for the exact issued order, current queue claim and qualified queue binding, then supply its `loadApprovedInput` to `createAgentHostBuilderLocalSqliteChild`. Every read reloads the claimed envelope and verifies transport binding, claim, order and content digests. It neither grants dispatch authority nor substitutes for the child's durable operation/custody checks. Do not cache a returned payload across claims or use a caller-supplied order reference. ## Disposable bounded-epoch PostgreSQL qualification target contract `bounded-epoch-postgres-kill-qualification.test-support.ts` reads only the dedicated `AGENT_HOST_QUALIFY_POSTGRES_URL`; an absent value retains the explicit skip. A generic application `DATABASE_URL` never selects this qualification. Before creating any pool, connecting, creating a database or terminating a backend, the qualifier validates both its explicit admin target and its derived data target through the owner-private test guard. Admission requires `postgres:` or `postgresql:`, an explicit port from 1025 through 65535, a simple explicit role name and numeric IPv4 loopback `127.0.0.1`, or `localhost` canonicalized to that numeric host before the connector sees it. IPv6 is explicitly refused: the installed connector's handling of bracketed URI hosts is not qualified by these proofs. Raw whitespace/control characters, malformed percent-encoded credentials, every query option and fragments are refused. This includes effective-target redirects such as `host`, `hostaddr`, `dbname`, `user` and `service`; no URL or credential is included in the static refusal diagnostic. Admin admission is an explicit purpose limited to `/postgres`. Data admission never accepts that admin database: it requires the exact generated `agent_host_epoch_kill__` name, with a valid PostgreSQL identifier length. The qualifier creates that child itself; migration, runtime work, backend termination and drop remain bound to that same child. The guard admits this narrow target convention; it does not prove who owns a server or turn a shared local server into a disposable one. The caller must supply an owned disposable server, and actual qualification records its ownership and cleanup. The guard and constructor-spy cases are private `.test-support.ts` / `.test.ts` qualification sources, with no package export or production runtime change. Positive target admission is not a kill/reconnect pass: only actual execution through the campaign's sole verifier can provide that evidence. --- ## @lssm-tech/app.alpic-mcp Description: MCP server exposing ALPIC application lifecycle and platform integration operations. Path: packages/apps/alpic-mcp URL: /llms/app.alpic-mcp # @lssm-tech/app.alpic-mcp Website: https://contractspec.io **MCP (Model Context Protocol) server for Alpic. Exposes ContractSpec documentation and tooling to AI agents via the MCP standard.** ## What It Does - Uses `@lssm-tech/bundle.alpic` for Alpic business logic. - Uses `@lssm-tech/lib.logger` for structured logging. - Built with tsdown; runs as a Node.js server. - Related ContractSpec packages include `@lssm-tech/bundle.alpic`, `@lssm-tech/lib.logger`, `@lssm-tech/tool.tsdown`, `@lssm-tech/tool.typescript`. ## Running Locally From `packages/apps/alpic-mcp`: - `bun run dev` - `bun run start` - `bun run build` ## Usage ```bash bun run dev ``` ## Architecture - Uses `@lssm-tech/bundle.alpic` for Alpic business logic. - Uses `@lssm-tech/lib.logger` for structured logging. - Built with tsdown; runs as a Node.js server. - `src/index.ts` is the root public barrel and package entrypoint. - `src/server.ts` is the main server bootstrap entrypoint. ## Public Entry Points - Export `.` resolves through `./dist/index.mjs`. - Export `./server` resolves through `./dist/server.mjs`. - Export `./*` resolves through `./*`. ## Local Commands - `bun run dev` — tsdown --watch - `bun run start` — node dist/server.js - `bun run build` — tsdown && mkdir -p dist && cp -R assets dist/assets - `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 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 ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - MCP protocol compliance is critical — do not break tool/resource schemas. - Keep server startup fast; defer heavy initialization. --- ## @lssm-tech/app.api-application-monolith Description: (none) Path: packages/apps/api-application-monolith URL: /llms/app.api-application-monolith # Managed CompanyOS API Application Monolith ## Migration execution contract The app owns migration execution through `src/db/migration-contract.ts` and the existing transaction/query ports. Each migration's SQL effects and its original version, source and raw digest ledger row must commit in one driver transaction. A failure before commit must leave neither effects nor row. A committed replay must preserve the row and its `applied_at` timestamp. Frozen SQL is the identity. An app-local lexical execution view may remove only supported simple outer `BEGIN;` / `COMMIT;` tokens, preserving interior bytes; unsupported, interior, unpaired or ambiguous transaction controls fail before any database write. This does not change SQL policy, accepted historical digests or OPA activation admission. It prevents future interrupted-install orphans and does not infer ledger ownership from an already orphaned schema. Such targets remain failed and need separate operator-authorized recovery. ## OPA production completion `GET/POST /api/v2/opa/automation-settings` exposes current-session policy ancestry and revision-checked updates. Apply additive migration 0073 before deployment. The CompanyOS editor explicitly reports background execution as inactive while delegation and effect-time worker binding remain unqualified. Saved planner placements can be reviewed and added through the existing focus-create lifecycle; the server rechecks saved identity, Work revision, and fresh availability. Personal Planner generation now loads canonical Work and fresh calendar state, persists a proposal atomically with its command, and returns proposed placements and unscheduled reasons. Generation does not apply calendar changes. Active organization/workspace authority is checked again before committing. Meeting generation requires an explicit Vercel AI Gateway binding, pinned model, EU provider inference and separately approved global Gateway transit (see [Meeting AI through Vercel Gateway](#meeting-ai-through-vercel-gateway)). Missing configuration leaves generation unavailable; existing artifacts remain readable. The approval reference is an operator configuration binding, not a substitute for processing review or model evaluation. An explicit saved meeting policy must also enable AI suggestions or editing; missing or disabled policy prevents model invocation. See `docs/evidence/opa/production-completion-2026-09-04.md` for open release gates. ## Durable CompanyOS onboarding preferences `PATCH /api/companyos/onboarding-preferences` implements the versioned `companyos.onboardingPreferences.complete@1.0.0` command. It accepts only a bounded experience-preference patch, expected tenant-scoped revision, and idempotency key. User and tenant authority always come from the verified session. Migration `0071` stores one document per user and tenant; exact replay, conflicting replay, concurrent revision fencing, cross-user isolation, and cross-tenant isolation are covered by the PGlite repository proof. The existing authenticated shell-preference query returns the validated persisted document so a subsequent page load hydrates the same experience. ## OPA meeting provider intake `createCompanyOpaMeetingIntake` composes the provider-neutral intake binding with the CompanyOS OPA operation registry, so automatic recorder matches pass through the same session-derived authority and governed `opa.recording.source_bind` handler as interactive requests. The host factory accepts the real Google or Outlook calendar adapter and Granola or Fireflies recorder adapter without embedding credentials. Migration `0063` installs the owner-scoped occurrence and immutable review tables; `0065` adds recurring definitions and token-fenced execution leases. When callers do not inject narrower ports, the production composition uses this SQL store for current recorder-binding revisions and mandatory review requests. The deployable worker remains fail-closed until its allowlisted composition supplies selected calendar OAuth/Graph credentials, recorder credentials, and protected configuration resolution. No provider or fixture is selected implicitly. ## SupportOS to OPA destination authority `POST /internal/opa/support/destinations/resolve` is the only server-to-server bridge that turns a SupportOS opaque profile or booking destination reference into a public CompanyOS URL. It verifies a short-lived AuthOS grant for the `companyos-opa-support` audience and exact tenant, workspace, case, handoff, and destination binding. The database query independently scopes the stable OPA `profile_ref` or `link_ref`, requires a published current profile/link revision, and never returns provider or calendar data. Configure `COMPANYOS_OPA_SUPPORT_AUTHOS_GRANT_VERIFY_URL` and `COMPANYOS_OPA_SUPPORT_AUTHOS_WORKLOAD_TOKEN`; `APP_WEB_BASE_URL` remains the canonical public origin. ## CompanyOS Briefings 2.0 Calendar intelligence is recipient-owned. The scheduler reads only selected Google calendars attached to the authenticated user's non-shareable personal context; workspace booking resources are never briefing sources. Missing personal OAuth, selections, or authority fails closed as `setup_required` with no provider read or delivery. The ledger stores digests, state, composition metadata, and authorized evidence refs only—never notes, graph content, or email bodies. Outbound email has exactly one recipient: the user's verified CompanyOS delivery address. Authenticated preview requests select either `morning-recap` or `meeting-preparation` and cannot select a recipient; the server runs only the current user's bounded personal calendar and freshly authorized graph pipeline without persisting event content or rendered bodies. Migration `0068` deterministically replaces any historical raw or missing briefing provider message identifier with a one-way `provider-message:sha256:*` reference before installing its provider-evidence constraint. This keeps forward replay compatible with legacy successful deliveries without retaining provider identifiers in the governed ledger. Scheduled rollout is server-derived and cannot be selected by the browser. It becomes `live` only after personal calendar setup is `ready` and at least one delivery cadence is enabled; disabling both cadences or losing setup readiness atomically returns it to `off`. Migration `0043` binds every source to the same user's active personal OAuth connection with a composite foreign key and generated owner reference. Production promotion uses the non-automatic, approval-gated `db/cutovers/companyos-briefings-v2.sql` transaction after the canary, backup, and zero-legacy-read replay; automatic migration must not remove V1 storage before those gates pass. Run `bun run companyos:briefings:postgres:test` against a disposable PostgreSQL URL for the owner, RLS, occurrence, and cutover proof. ## Company Intelligence governed learning persistence S9 persists the governed-learning lifecycle through the existing migration `0022` canonical records, refs, receipts, and events plus the `0023` transactional outbox. The transaction-scoped repository takes a lifecycle advisory lock, verifies the expected sequence/head, validates a packet-closed history, and delegates canonical append/idempotency. There is no dedicated learning table, index, provider call, export, or live canary. Migration `0027` belongs to S10 API replay and budget state; governed-learning history remains on the canonical `0022`/`0023` authority. S10 exposes the four authenticated governed-learning routes through this repository and fails closed when `LSSM_STUDIO_DATABASE_URL` is absent. FORCE RLS remains tenant-scoped; run `bun run test:company-intelligence:governed-learning-persistence` and the local PostgreSQL proof before changing this boundary. ## Company Intelligence Brain persistence Migration `0026` adds one append-only FORCE-RLS object-version table for the CompanyOS-owned Brain entry, review, edition, gap, remediation, and compiled artifact families. The repository reuses canonical Company Intelligence receipts/events, rejects static/demo fixture sources in production, binds every query to tenant and workspace scope, keeps valid and recorded time distinct, and applies capability/field redaction before projection. Run `bun run test:company-intelligence:brain`; both managed PostgreSQL 15 proof scripts execute the same corpus under `NOSUPERUSER NOBYPASSRLS`. ## Company Intelligence durable graph and identity Migration `0025` adds FORCE-RLS query projections and append-only identity candidates, reviewed decisions, aliases and merge/split lineage over the canonical `0022` record/event authority. Canonical content fingerprints bind replay to the complete request. The repository rejects conflicting replay, cross-tenant decisions and label-only auto-linking, and exposes deadline- and edge-bounded traversal that authorizes every recursive branch. Run `bun run test:company-intelligence:graph-repository` for the exact package corpus. `bun run companyos:db:prove-existing-postgres` (or the disposable PostgreSQL proof) executes its S6 integration test against PostgreSQL 15 under a constrained `NOSUPERUSER NOBYPASSRLS` runtime role. ## Company Intelligence tenant persistence Migrations `0022` and `0023` provide the additive app-owned PostgreSQL/Drizzle authority for the canonical G002 Company Intelligence contracts: bitemporal records and normalized references, append-only receipts/events, controlled tombstone purging, and durable job/outbox/DLQ/backfill state. Every table uses FORCE RLS; runtime qualification authenticates as a `NOSUPERUSER NOBYPASSRLS` role and proves cross-tenant read/write denial. Run `bun run companyos:db:prove-disposable-postgres` for the isolated Docker or native-cluster proof. When a PostgreSQL 15 server is already running locally, `bun run companyos:db:prove-existing-postgres` creates two unique loopback test databases, runs the same S2 migration/recovery/repository/RLS checks, and drops both databases. See [`docs/company-intelligence-persistence-runbook.md`](./docs/company-intelligence-persistence-runbook.md) for resumable backfill, corruption checks, forward repair, and purge controls. Use [`docs/company-intelligence-operations-runbook.md`](./docs/company-intelligence-operations-runbook.md) for readiness, safe metrics and budgets, correlation troubleshooting, kill switch recovery, and the executable S12 qualification commands. ## Company Intelligence continuous ingestion S4 reuses the same `0022`/`0023` authority without adding tables. Upload, webhook, polling, and connector deliveries enter one idempotent durable job path for initial/incremental sync, backfill, resync, cancel, deletion, ACL, and identity changes. Claims use bounded leases, heartbeats, optimistic checkpoints, deterministic retry/backoff, quotas, cancellation, DLQ evidence, and resumable cursors. Duplicate delivery keys create one job and replayed record commits create zero additional effects. The provider-neutral registry binds direct ingress, Drive, Gmail, Slack, Teams, GitHub, Linear, Jira, Notion, and meeting transcripts to their existing integration/package owners. CI uses caller-supplied canonical deterministic contract fakes; it never substitutes fixtures when credentials are missing. Required credentials resolve outside job payloads through opaque provider session handles. Missing credentials produce `not_run` plus `missing_credentials`, a durable redacted receipt/DLQ entry, and zero provider calls. Source deletion and ACL revocation cancel queued work and append immutable superseding tombstones through the current canonical record closure (source, source version, asset, part, fragment, evidence, and current dependent records). No S5-S9 graph, Brain, retrieval, or public API behavior is implied. Run `bun run test:company-intelligence:ingestion` for deterministic connector contracts and `bun run companyos:db:prove-disposable-postgres` for the complete lease/checkpoint/propagation/RLS qualification. ## Company Intelligence structured extraction S5 adds strict model-output candidate schemas and a pure trusted runtime that alone resolves authorized pre-existing evidence IDs and exact locators into canonical records. Invalid output, invented or cross-tenant evidence, locator drift, instruction-like content, policy override attempts, and model-declared approval produce stable typed rejections with zero canonical effects. Confidence below `0.75` and high/critical risk require a separately supplied trusted review decision. Redacted deterministic receipts record model, prompt, schema/runtime versions, cost, evidence, dispositions, and correction lineage without raw source/provider content. Migration `0024` adds only a nullable JSONB details column to the existing generic receipt table; the existing canonical record repository remains authoritative. The disposable PostgreSQL proof covers first commit, exact replay, immutable correction history, and tenant denial. The v2 profile backend is mounted at `/api/v2/opa/profile/*` for session/RBAC-scoped administration and `/api/v2/public/profiles/:handle` for the redacted latest-published projection. Mutations require trusted origin and a session-bound CSRF token; admin responses are always `no-store`. The deployed composition lazily binds the transactional SQL profile repository to `LSSM_STUDIO_DATABASE_URL` and fails closed when it is absent. The in-memory profile store is available only through explicit test/demo injection. The public response and admin redaction boundaries omit private topology and provider references. Draft restoration accepts newly created hybrid events but rejects newly invented owned-live events until authoritative provisioning exists. Cache and publish/revoke invalidation remain server-owned. OPA v1 booking contracts are unsupported; promotion remains blocked until G004b binds and verifies the exact v2 runtime and API handlers. G004b Phase B is implemented locally. Canonical migration `0037` remains absent from default migration discovery and is not production-promotable without a fresh, exact-target opaque activation minted from an independently trusted Ed25519 reset authorization. That authorization digest-binds the `0036` ledger head and exact `0037` digest to ordered external snapshot, schema, restore, runtime build/test, ContractSpec Connect decision/replay, actor, and observed database proof. Application revalidates the target and time window immediately before any migration work and spends the activation once. No external evidence bundle is checked in, so this package does not claim a canary or production activation. ## Managed Google Meet booking persistence Migration `0028` adds protected primary and staged-replacement conference state to the canonical tenant/RLS-scoped booking intent. Published owned-live event types carry their provider-neutral conference mode into both public booking entrypoints. The provider-effect worker confirms a Meet booking only after a verified `https://meet.google.com` link is encrypted in the same fenced transition; pending, failed, and ambiguous creation stays recoverable by exact known ID. Cancellation clears the link, while rescheduling promotes only the ready encrypted replacement after definitive old-event cancellation. The canonical `opa.profile.public_list@2.0.0` REST identity is `GET /api/v2/public/profiles`. The Elysia host exposes that route plus `GET /api/v2/public/profiles/readiness`; handler contract tests freeze those v2 gateway mappings. Real API monolith for tenant-scoped Managed CompanyOS commands and queries. ## Company Intelligence authenticated API The Elysia host mounts the contract-derived v1 surface at `/api/companyos/company-intelligence/v1/*`. Every operation requires a tenant-bound user session or service principal, returns private no-store responses with API and correlation headers, and enforces bounded bodies, pagination, timeout, budget, and idempotency semantics. Migration `0027` persists tenant-scoped replay results and minute request budgets with integrity constraints and FORCE RLS, so new handler instances preserve both controls. Production has no fixture fallback. `GET /api/companyos/company-intelligence/v1/surface?surface=` resolves the authenticated overview, sources, Brain, graph, assistant, learning, or operations descriptor before browser data reads. The handler accepts exactly one logical `surface` query parameter and rejects tenant or role input. It returns canonical route, truthful route state, safe-read posture, action availability, and dependency blocks derived from the authenticated actor and server composition; missing PostgreSQL composition is reported as degraded rather than replaced with demo data. Connections, jobs, uploads, evidence, reviews, graph traversal, Brain reads, replay, health, and the four governed-learning mutations bind canonical PostgreSQL repositories or tables. Structured extraction and grounded answers delegate authorization-aware retrieval to explicitly bound production services without preloading tenant-wide records. Evidence and replay reads, reviewed decisions, graph traversal, and Brain projections use built-in PostgreSQL ACL/workspace authority adapters. Health is `degraded` until the external extraction and grounding services are bound; those two operations alone fail closed with `503 dependency_unavailable` when absent. Run `bun run test:company-intelligence:api` for parity, auth, isolation, limits, durable idempotency/budgets, degraded behavior, cancellation, and log safety. The disposable PostgreSQL 15 proof covers restart replay, tenant-key isolation, budget continuity, and constrained `NOSUPERUSER NOBYPASSRLS` denial. ## Company Intelligence operational safety S12 operational controls reuse the canonical append-only PostgreSQL receipt and event authority for dependency health, kill-switch changes, and pre-dispatch audit decisions. Missing switch state fails closed. Ingestion and connector dispatch recheck the durable `ingestion` and `connector_dispatch` switches before every provider call; blocked jobs return to retry without consuming an attempt. Run `bun run company-intelligence:failure-injection` from the repository root to prove database, vector, model, queue, and connector degradation, all six audited switches, recovery within twice the outage duration, safe correlated telemetry, and disposable PostgreSQL cleanup. ADR-008 reference qualification is fail-closed and never shortens the required 60-minute load plus 8-hour soak. Run `bun run company-intelligence:reference-qualification` to validate the exact 10-tenant corpus manifest, pull and verify PostgreSQL 16, Qdrant 1.15.0, the locked Qdrant 1.18.0 adapter, and Bun 1.4.0 runner, then launch both phases as one durable background process. Before load begins, a pinned Bun runner applies the tracked database migrations and fails closed unless `managed_companyos_ci_records` and `managed_companyos_ci_jobs` both resolve in PostgreSQL and the digest-backed migration ledger matches versions `0022` and `0023`. The command records leader-owned environment, schema-preflight, container, image-digest, PID, and log handoff evidence. Docker allocations below 8 CPUs or 16 GiB fail with a concrete `blocked` packet and launch no qualification; such a packet is not S12-A3 completion. ## Google Calendar booking edge The Elysia host owns protected OAuth start/callback/disconnect routes under `/api/companyos/integrations/google-calendar/*` and the authenticated `/api/cron/google-calendar-maintenance` polling/reconciliation route. Runtime configuration is server-only and uses `MANAGED_COMPANYOS_GOOGLE_CALENDAR_*` `CLIENT_ID`, `CLIENT_SECRET`, and exact `REDIRECT_URI`; tenant/account/calendar topology is enumerated from durable `opa_calendar_connections`. OAuth tokens and their granted scopes/expiry bind to the ciphertext-only OPA vault. Callback and disconnect persist tenant/account-scoped connection state; disconnect disables the local connection before remote token revocation. Exact-scope drift records `reauthorization_required` before best-effort revocation of rejected grants. The maintenance cron isolates each tenant, refreshes only near expiry, proves paginated CalendarList owner/busy topology, polls durable free/busy snapshots, and durably schedules daily known-ID reconciliation without broad event listing. Every request-time free/busy read, freshness refresh, booking event creation, Google Meet creation, cancellation, reschedule, and reconciliation resolves an explicit `(tenant, workspace, scheduling resource, write calendar)` binding. The booking saga keeps the tenant-scoped write-calendar reference as its stable identity; immediately before every Google call, the trusted adapter resolves it to the current provider calendar identifier. The provider identifier is never accepted from or returned to the anonymous booking browser. One connected Google account may serve multiple workspaces only when each workspace has its own persisted scheduling preference joined to that resource and connection. Missing, foreign, contradictory, or ambiguous bindings fail before snapshot, OAuth vault, protected booking, or Google provider access. Personal mode uses the same contract with its personal workspace authority. Connection-wide maintenance can probe and refresh a connected account, but it does not grant request authority to any workspace. Migration `0033_google_workspace_availability_snapshots.sql` partitions opaque snapshots by tenant, workspace, and scheduling resource while retaining legacy maintenance rows in an explicit empty-workspace partition. Malformed timestamps or busy intervals fail closed. The production integration keeps booking availability free-busy based and uses the separately consented read-only event scope only for bounded daily intelligence. `events.list` is capped at 40 events per user/run. Raw event titles, descriptions, attendees, locations, bodies, and email content are never persisted; only delivery state and content digests are durable. The Google and Microsoft readers keep attendee addresses beside the display labels (`CalendarIntelligenceMeeting.attendees`, contract 2.7.0) under `COMPANYOS_CALENDAR_ATTENDEE_ADDRESS_POLICY`. Shared pre-meeting briefs use them to propose recipients, so named attendees are no longer missed; the owner still reviews every recipient. They are stripped from the briefing model input and redacted from log lines. The only stored copy is a shared-brief draft's recipient list, which the owner reviews. ## Live profiles, booking surfaces, and daily intelligence Migration `0042` adds evidence-only calendar-intelligence preferences and delivery attempts, canonical owner scopes for the existing OPA profile/calendar tables, and the public published-profile lookup boundary. The `core-workspaces` (and `all`) bootstrap profile reconciles the live LSSM and CompanyOS organizations. Hirly and NDconsulting were decommissioned in production on 2026-10-20 ([evidence](../../../docs/evidence/authos/decommission-hirly-ndconsulting-2026-10-20.md)); no live profile recreates them. Collaborators join through the invitation flow and are never seeded as admins. After every target workspace has a connected Google Calendar topology, run `bun run companyos:booking-surfaces:activate`. It publishes shared links for LSSM and CompanyOS plus Théo's personal link (`/u/theo`). The former Hirly surfaces (`/u/hirly`, `/u/hirly-talent-team-booking`) are unpublished. Each surface uses Europe/Paris weekday availability, Google Meet, bounded advance/notice policy, and the workspace-owned scheduling resource. Activation advances the canonical link to the published profile revision and revokes active links from superseded revisions, so a replay cannot expose a dead booking URL. It also reconciles the exact first-party `https://www.companyos.run` embed origin on all three canonical links so the hosted loader and React canary work immediately. Every additional embedding origin remains an explicit owner-managed allowlist entry. Canonical owner/admin authority must include the complete owner capability set (`COMPANYOS_OWNER_CAPABILITIES`, which contains the Meeting Intelligence set) at the organization, workspace-default, and user-workspace layers. Bootstrap provisions that set for new personal and organization contexts. Existing LSSM and CompanyOS grants converge additively with `bun run companyos:opa:reconcile-meeting-authority`: run it first with `COMPANYOS_OPA_MEETING_AUTHORITY_RECONCILE=dry-run` (writes nothing, prints the missing capabilities per layer), then with `=1` to apply. The owner set is a floor: separately reviewed extras such as `builder.*` are preserved, and the `companyos:db:verify:live` bootstrap prerequisite checks containment rather than exact equality. Team grants only receive the Meeting Intelligence set. The owner set includes `opa.plan_run.manage`, which background planning reproves on both the company workspace and the owner's personal context, so the command also reconciles the canonical owner's personal context. Members get the same self-scoped capability through the `frontline_staff` template (also the joined-member default; OWNER-DECISIONS-2026-10-19); existing member grants receive it on re-grant or through the joined-template authority repair. Planning counts sessions already added from earlier plans (active planner-sourced focus blocks) as scheduled time, so a re-plan never proposes them again or reports them as moved. The command targets only the canonical owner on the live organizations and increments each changed authority revision so existing sessions fail closed until refreshed. Prefer it over re-running `companyos:bootstrap-admin` on a live target: bootstrap rewrites grants to the exact set (dropping reviewed extras) and re-enables calendar-intelligence preferences. Owners can revise an active link's embed allowlist through `POST /api/v2/opa/links/:linkRef/embed-origins`. The command requires the server-derived opaque `scopeRef`, same-origin CSRF authority, and the current link revision. It replaces the complete list with unique exact HTTPS origins; passing an empty list returns the link to hosted-only mode without changing its public token. Protected profile execution uses the exported v3 profile operation version and requires a server-authorized opaque `scopeRef`. Booking approval is available only through the canonical scoped `POST /api/v2/opa/bookings/:bookingRef/approval` operation. The former `/api/companyos/booking-approvals/:bookingRef/decide` host alias is removed because it could not satisfy the v3 owner-scope authority contract. Production credential recovery requires the exact rotation confirmation and an unused permission-restricted path below `/tmp` via `OPA_ADMIN_PASSWORD_DELIVERY_FILE`. The rotation command writes the generated password only to that mode-`0600` file and never prints it or stores it in the repository. The `/api/cron/calendar-intelligence` route runs every five minutes. It sends a Europe/Paris morning recap once per local day and a preparation email in the five-minute window one hour before each meeting. Model composition is temporarily paused at the host: existing Mistral environment values cannot enable it. The localized deterministic-v2 fallback keeps delivery available without persisting source calendar content. Preview delivery failures return the stable `briefing_delivery_unavailable` 503 projection; provider response bodies and credentials are never returned to the browser. The protected admin topology endpoints list every paginated provider `CalendarList` option, then re-enumerate before atomically materializing the selected owned-write/readable-busy topology and Europe/Paris working hours, buffers, notice, horizon, and approval mode. Tenant identity comes only from the authenticated session; identifiers absent from the current provider response are rejected. Booking lifecycle recovery uses the exact active original or replacement slot and the persisted saga-owned provider identity. App-owned provider-effect and notification outbox rows are atomically leased with tenant/owner fencing before relay. Notifications use the durable SQS queue when `MANAGED_COMPANYOS_BOOKING_QUEUE_URL` and the protected delivery service are configured. Serverless deployments without that pair drain the same Postgres outbox directly: recipient material is decrypted only after a token-fenced delivery claim, Resend receives the durable dedupe key as its native idempotency key, and the email management grant stays in the URL fragment until the hosted page exchanges it for HttpOnly cookies. Provider calls are mocked in repository tests; production qualification still requires a reversible live delivery canary. ## Smart-meeting preparation The authenticated `GET|POST /api/companyos/opa-os/manual-loop` surface composes the existing authorized OPA manual loop for Managed CompanyOS. Session authority owns tenant, workspace, organization, actor, and role scope. The request body contains meeting intent only and strict parsing rejects browser-supplied authority or provider identifiers. Preparation authorizes before Google work, selects calendar preferences by the session-derived tenant and active workspace, refreshes free/busy through the production calendar bridge, and labels availability as fresh, cached, or unavailable. Readiness distinguishes normal setup states from an explicit runtime outage. It then atomically persists the plan, agenda, booking proposal, immutable command audit, and `opa.plan.proposed` outbox signal. Exact idempotent replay returns the original redacted receipt; conflicting reuse returns `409`. The response remains `pending_approval` with external effects blocked. No calendar event or Google Meet link is created by this endpoint. Migration `0031_smart_meeting_workspace_calendar.sql` preserves legacy tenant-only preferences but requires an authorized workspace binding before they can participate in smart-meeting readiness. The separate authenticated `/api/companyos/smart-meetings` lifecycle exposes tenant/workspace-scoped list and status reads plus receipt-scoped approval, cancel, and reschedule mutations. Enterprise admins and founder approvers may mutate the lifecycle; operations managers may prepare and monitor but do not receive external-action approval authority. Approval re-enumerates the active workspace topology, refreshes the selected slot, and links the proposal exactly once to the canonical booking saga. The existing fenced provider-effect worker then owns Google Calendar and optional Google Meet creation; browser and route handlers never call Google directly. Cancellation and rescheduling reuse the same durable leases, deterministic provider identity, reconciliation, and outbox path. Apply `0032_smart_meeting_booking_lifecycle.sql` before enabling this lifecycle. It adds nullable forward linkage from the smart-meeting proposal to the canonical booking intent, preserving all existing proposals and enforcing tenant-scoped uniqueness for new links. Operator qualification is documented in [`docs/runbooks/opa-smart-meeting.md`](../../../docs/runbooks/opa-smart-meeting.md). ## Resend purpose ownership and signed status ingress Auth mail uses `AUTH_EMAIL_FROM` as `CompanyOS Security `; booking mail uses `RESEND_BOOKING_FROM` as `CompanyOS `. Both share an explicit, validated `RESEND_REPLY_TO`, and all three addresses are parsed once before a provider call. Auth callbacks may send directly through the auth-owned provider. Booking code attaches its owned sender only at the protected delivery service and durable outbox claim/dedupe/retry/reconciliation path; it must not call the auth sender. `POST /webhooks/resend/events` reads the raw request body and verifies `svix-id`, `svix-timestamp`, and `svix-signature` with `RESEND_WEBHOOK_SECRET` before parsing. Duplicate `svix-id` deliveries return a replayed status and do not re-apply the status projection. Production replay and status authority lives in the caller-owned PostgreSQL tables created by migration `0014`; a unique `event_id` plus a transactional monotonic upsert keeps restart and concurrent-instance delivery safe. Stored rows and API results bind only deterministic `provider-message:sha256:*` references, status, and timestamps—never raw provider message ids, signed payloads, or webhook secrets. Distinct, older events remain recorded but cannot regress the current message status. In-memory storage is test-injected only. This ingress is observational: the booking outbox and protected delivery receipt remain the durable delivery authority. Repository verification never registers a webhook or calls the live Resend API. Calendar-intelligence email selected through CommunicationOS is admitted to the canonical journal and domain-command outbox before dispatch. The ledger records `queued` separately from provider acceptance and delivery. The shared worker resolves only the opaque `env://COMMUNICATION_OS_CONNECTION_COMPANYOS_CALENDAR_RESEND` credential reference, forwards one stable provider idempotency key, and exposes `reconciliation_pending` if provider acceptance cannot be durably completed. Migration `0069_calendar_intelligence_queued_delivery.sql` is required before enabling `COMPANYOS_CALENDAR_OMNICHANNEL_ENABLED=1`. > **api-monolith-elysia-convergence:** this app is now verified as a single **Elysia host** (`src/app.ts` + `api/index.js` `@vercel/node` entry). Former Next.js App Router handlers have been removed from `src/app/api`; route tests exercise `app.handle(Request)` directly. The `vercel.json` deploy flip and external webhook re-registration remain human-gated, but source ownership, tests, and local builds are Elysia-owned. Build the host with `bun run build:elysia`. Most proof handlers remain deterministic until their production adapters are explicitly approved. The Managed CompanyOS v2 design-partner routes are an exception: production uses the app-owned Postgres repository and fails closed when its database, migration, tenant kill switch, or evidence relay health is unavailable. Provider strategy remains app-layer and secret-reference-only; bundle/libs/modules remain provider-neutral. This implementation supports persisted multi-organization authority for the stable canonical slugs. Only `lssm` and `companyos` are live; `ndconsulting` and `hirly` were decommissioned on 2026-10-20 ([evidence](../../../docs/evidence/authos/decommission-hirly-ndconsulting-2026-10-20.md)). A verified Better Auth `activeOrganizationId` is an identity-plane key; an enabled one-to-one binding selects the physical tenant used by FORCE RLS. Production activation still requires the rollout, evidence, and ownership gates in [`docs/runbooks/managed-companyos.md`](../../../docs/runbooks/managed-companyos.md). The former private-pilot configuration remains migration history and rollback input only; it is not forward authorization. `GET /api/companyos/workspaces` is a private authority projection. Every success, deny, and degraded response sets `Cache-Control: private, no-store`; trusted-origin credentialed CORS never makes the response share-cacheable. The route lazily creates one app-owned Postgres authority repository/pool, reuses it for the Elysia host lifecycle, and closes it on host shutdown. It never creates or tears down a pool per request. ## Personal, company, team, and workspace authority Migration `0055_companyos_shell_preferences.sql` adds one user-scoped, optimistically versioned shell-preference row and a nullable session preview persona. `GET/PATCH /api/companyos/shell-preferences` synchronizes context placement across devices. `GET/POST /api/companyos/persona-preview` authorizes Enterprise Admin by default, stores presentation preview only in the current session, and returns a safe current route or persona home. Context changes and session expiry clear preview; the real session role remains authoritative. Migration 0160 adds a tenant-keyed `opa_home_modes` map to the same row: `GET/POST /api/companyos/opa-os/home-mode` (`companyos.opaHomeMode.*`, `workspace.read`) reads or sets the OPA OS landing view for the session's own organization (at most 50 organizations remembered); the web app keeps its per-tenant cookie only as a cache for when the API is unavailable. The additive context family lets an authenticated user operate without a company and switch among one or many companies, teams, and workspaces: - `POST /api/companyos/personal-context/ensure`; - `POST /api/companyos/personal-context/disable`; - `GET /api/companyos/contexts`; - `POST /api/companyos/contexts/set-active`. Migration `0029_personal_context_authority.sql` adds the system-owned, non-shareable personal-context manifest, session authority version, one-use nonce digests, and idempotency receipts. Database triggers reject a second member, invitation, or team in a personal organization. Personal ensure creates the existing tenant/binding/grant/workspace topology idempotently; disable revokes binding, grant, public intake, OAuth tokens, and matching active session scope without deleting evidence. Migration `0030_team_context_authority.sql` adds canonical direct-user workspace, team, and team-workspace grants plus workspace authority versions. Existing enabled organization/workspace authority is materialized as explicit direct grants during migration; new workspaces require an explicit grant. The set-active transaction locks the session, consumes the signed five-minute token once, revalidates organization, team, grant, workspace, and projection versions, then updates active organization/team/workspace and emits exactly one `context.activeChanged` event. Request middleware freshly resolves the selected tuple and intersects organization, team, and workspace capabilities; revoked or stale nested authority fails closed before a protected handler runs. Only explicitly granted workspaces are listed or accepted at commit time. Opaque `contextRef`, `teamRef`, and `workspaceRef` values cross the public boundary. They are locators, not credentials. Physical tenant identifiers remain server-derived and are never accepted by these routes. Repository-local PGlite proves ensure replay, anti-share enforcement, one-use CAS, stale-token denial, team grant selection, and revocation denial. A real PostgreSQL migration/RLS qualification and live deployment remain separate rollout gates. ## Vercel-only Managed CompanyOS production topology Managed CompanyOS production is cost-capped to the Vercel-hosted web and API monoliths. The API monolith absorbs required background duties through request-time HTTP snapshots and Vercel Cron handlers; it must not require the standalone Bun worker or any browser-held realtime connection for production readiness. The legacy `builds` entry in `vercel.json` makes Vercel ignore the dashboard Build Command. The repository root `postinstall` therefore dispatches on the Vercel project id and runs this package's `build:elysia` script during install, before `@vercel/node` traces `api/index.js`. That build must bundle `src/app.ts` to both `dist/index.js` and `api/dist/index.js`. The Vercel adapter deliberately loads the generated module through an opaque runtime path and `vercel.json` explicitly includes only `api/dist/index.js`; this prevents Node File Trace from re-analyzing the 70+ MB pre-bundled file or packaging the second local-runtime copy. Implemented route families include retained design-partner-named compatibility adapters. Those adapters preserve NDconsulting history and remain scoped to `tenant_ndconsulting_special_ops` / `workspace_ndconsulting_special_ops`; their names do not make pilot identifiers an authorization source. | Purpose | Route | | --- | --- | | Graph/status snapshot | `GET /api/companyos/vercel/snapshot` | | Replay/evidence snapshot | `GET /api/companyos/vercel/replay-evidence` | | Supervision-equivalent snapshot | `GET /api/companyos/vercel/supervision` | | Manual integration sync trigger | `POST /api/companyos/integrations/sync-trigger` | | Scheduled snapshot trigger | `GET /api/cron/companyos-snapshot` | | Profile cache invalidation dispatch | `GET /api/cron/profile-cache-invalidation` | | Design-partner evidence relay | `GET /api/cron/companyos-design-partner-evidence-relay` | `/api/cron/companyos-snapshot` is service-principal gated with the same `control-plane.core` authorization path as other Vercel crons. User-facing reads remain tenant-session scoped and cross-tenant requests fail closed. Public profile reads, including 404 responses, use `Cache-Control: no-store` until a web cache invalidation provider is configured. Publish/revoke signals are durably leased, retried, and emitted by the authenticated profile cache cron. ## Runtime surface - `src/app.ts` — authoritative Elysia host composition for `/api/auth/*`, `/api/companyos/*`, `/api/companyos/builder/*`, webhooks, crons, schemas, control-plane, billing, and waitlist routes. - `api/index.js` — Vercel Node adapter from `(req, res)` to Web `Request` to `app.handle(request)`. - `src/handlers/auth-handler.ts` — better-auth catch-all with readiness gates, observability, and credentialed CORS. - `src/handlers/companyos/companyos-status-handler.ts` — tenant-scoped Managed CompanyOS read routes (`health`, `database`, `evidence`, `providers`, `integrations`, `replay`, `workflow`, `workspace`, `surface`, `health/degraded`) plus Vercel-only snapshot routes (`vercel/snapshot`, `vercel/replay-evidence`, `vercel/supervision`) and the manual integration sync trigger. - `src/handlers/companyos/companyos-command-handler.ts` — verified-session command routes (`integrations/setup`, `workflow/approve`). - `src/handlers/companyos-auth-*.ts` — invitation, lockout, passkey, sign-out, test-login, and sibling-session revoke routes. - `src/handlers/companyos/*special-ops*.ts` — Special Ops and AI Ops Sprint scoped route families. - `src/handlers/companyos/design-partner-readiness-handler.ts` — design-partner Special Ops v2 routes for persisted readiness, expert attestation, and founder approval; production derives authority from the verified session and commits through one tenant-scoped Postgres transaction. - `src/handlers/builder/builder-public-handler.ts` — public Builder REST surface at `/api/companyos/builder/*`, distinct from agent/workflow. - `src/handlers/webhooks/*` — signed provider ingress (GitHub, Slack, Telegram, WhatsApp Meta/Twilio, Resend, OPA recorders and notetaker bots). Every edge logs through `src/observability/webhook-log.ts`, a binding over the hashing structured logger: records carry the webhook, the route template (never a route token), a correlation id (a well-formed `x-correlation-id`, `x-request-id` or `x-vercel-id`, else a generated `whk_` id) and the W3C `traceparent`/`trace_id` from a valid `traceparent` header. Fields are allowlisted: the tenant is hashed, an id that is not a plain token is digested, and an error keeps only its name, code and a message digest, so raw payloads, headers, secrets and provider error text are never logged. - `src/index.ts` — pure command/query functions shared by Elysia handlers and unit tests. ## Design-partner readiness API routes The design-partner readiness routes are the API monolith's sole authenticated runtime authority for the bounded private-pilot slice. When activated, production reads packet versions from Postgres; mutations atomically commit the human decision, durable receipt, audit event, evidence outbox intent, and replay event. The response cannot claim tenant activation or broader production readiness and returns HTTP 503 when database, migration, relay, DLQ, or scheduled-snapshot health is degraded. Migration `0011_design_partner_runtime_authority.sql` adds the server-owned tenant `enabled` kill switch and excludes disabled tenants from scheduled relay enumeration. The fictive NDconsulting projection remains available only on explicit test/demo surfaces (`MANAGED_COMPANYOS_DESIGN_PARTNER_RUNTIME=fixture` outside production, or the jointly enabled test-login + test-session-header harness). Production never falls back to this fixture or process-memory receipts. Canonical fixture IDs: | Field | Value | | --- | --- | | Tenant ID | `tenant_ndconsulting_design_partner_demo` | | Workspace ID | `workspace_ndconsulting_desliance_demo` | | Scenario ID | `scenario_atlantique_industrie_mission_retournement` | | Scenario title | `Atlantique Industrie — mission retournement` | Routes: | Method | Path | Role gate | | --- | --- | --- | | `GET` | `/api/companyos/special-ops/design-partner-readiness` | Read roles: founder, operations, expert, auditor, AI, frontline, enterprise admin; all remain tenant/workspace/feature scoped. | | `POST` | `/api/companyos/special-ops/design-partner-readiness/decision-packets/:packetId/attest` | `expert_reviewer` only; requires packet version, statement, and idempotency key; returns the durable receipt. | | `POST` | `/api/companyos/special-ops/design-partner-readiness/decision-packets/:packetId/founder-approval` | `founder_approver` only; requires an accepted expert attestation on the exact version; `enterprise_admin` is denied as a founder substitute. | Denied by contract: missing session, cross-tenant access, missing feature entitlement, wrong workspace, unknown packet id, auditor mutation, AI mutation, frontline mutation, operations attestation/approval, expert founder approval, founder expert attestation, enterprise-admin founder approval, and every provider/customer/legal/financial dispatch path. ## Special Ops database-first cutover Use [`docs/runbooks/special-ops-monolith-production.md`](../../../docs/runbooks/special-ops-monolith-production.md) for the NDconsulting/Special Ops seed, tenant/workspace isolation, capability graph, AI Ops Sprint, and all-in-one work-graph promotion gates. The DB repository lane is implemented; live customer-data promotion remains blocked until its migration, RLS, backup, closed ND manifest, canary, and rollback evidence is approved. ## Production prerequisites The following items must be resolved before this app is promoted to production with real-tenant data. The design-partner v2 persistence and Vercel relay lane is implemented; unrelated deterministic proof lanes retain their own deferrals. | Prerequisite | Status | Detail | |---|---|---| | **JWT/session middleware for tenant identity** | ✅ **IMPLEMENTED** | All routes now derive `requestTenantId` from a verified HMAC-HS256 session token (`x-managed-companyos-session` header) via `src/middleware/session.ts`. Invalid or tampered tokens return 401. Set `MANAGED_COMPANYOS_SESSION_SECRET` to a strong secret before admitting real-tenant data. | | **Persistent storage adapter** | ✅ **IMPLEMENTED FOR MANAGED COMPANYOS TABLES** | App-owned Drizzle/local lifecycle paths use canonical `managed_companyos_*` tables for tenant, session, invitation, passkey, lockout, audit, replay/evidence, capability, and mutation-ledger state. External production DB access remains URL-gated; live credentials are not committed. | | **Production queue** | Approval-gated | Background job logic is in-process. A durable queue must be approved and wired before live workloads. | | **Provider strategy** | ✅ **IMPLEMENTED APP-LAYER REFERENCE CATALOG** | `src/production/providers.ts` exposes an executable provider-neutral catalog and dispatch adapter for managed-reference and BYOK-reference modes. The wider provider family matrix remains a readiness/runbook contract until each family has app/provider-layer smoke evidence. Dispatch accepts env-backed redacted reference aliases only and fails closed before the harness when refs are missing, raw-looking, or not redacted. | Do not activate organization authority until all prerequisites above and every decision in `docs/runbooks/managed-companyos.md` has explicit approval artifacts and implementation sign-off. The archived private-pilot material is ND migration history, not the forward execution checklist. ## Organization authority migration history Historical migration `0012_better_auth_schema.sql` remains immutable and creates missing Better Auth tables. Forward-only migration `0016_better_auth_partial_schema_evolution.sql` evolves empty partial schemas and fails transactionally when existing rows or column types cannot satisfy the canonical schema. The migration ledger records each version only after its full schema validation commits. The profile-aware bootstrap preserves existing credentials, requires `BOOTSTRAP_ADMIN_PASSWORD` only when `tboutron@lssm.co` does not yet exist, and requires an explicit live profile instead of tenant/workspace selectors. The stable manifests own those values. Better Auth organization IDs are never assumed to equal physical tenant IDs. ### Organization authority HTTP lifecycle The API binds the public CompanyOS authority operations to real routes: - `GET /api/companyos/organizations`; - `POST /api/companyos/organizations/set-active`; - `GET /api/companyos/auth/authority`; - `GET /api/companyos/workspaces`. Browser requests require the exact configured web Origin, ambient credentials, and explicit admitted `OPTIONS` preflights. Absent Origin is accepted only for server transport. Every success, deny, conflict, and degraded authority projection is `Cache-Control: private, no-store`. Set-active preserves every distinct provider `Set-Cookie` value through the Elysia handler and Node response adapter, including cookies whose `Expires` attribute contains a comma. The post-write canonical authority read bypasses provider and HTTP caches. Membership rejection returns `403`, stale or mismatched canonical authority returns `409`, and malformed or unavailable stores return retryable `503`. A session without an active organization may list only its current memberships and select one, but it receives zero workspace authority until canonical revalidation succeeds. The host shares one lazy authority repository/pool across requests and closes it during shutdown. Migration `0020_organization_active_audit.sql` installs a constrained security-definer PostgreSQL trigger that records `organization.activeChanged` in the same transaction as a real active-organization transition. Re-selecting the current organization emits nothing; invalid authority and audit insertion failure roll back the transition, and provider-owned clearing emits no tenant event. Use the disposable PostgreSQL commands in [`docs/runbooks/real-organizations-rollout.md`](../../../docs/runbooks/real-organizations-rollout.md) to prove migration, transition, no-op, and rollback behavior. Repository-local proof does not claim that a live production database was migrated or cut over. ## Local commands ```bash bun run --cwd packages/apps/api-application-monolith dev bun run --cwd packages/apps/api-application-monolith test bun run --cwd packages/apps/api-application-monolith typecheck bun run --cwd packages/apps/api-application-monolith lint:check bun run --cwd packages/apps/api-application-monolith build bun run --cwd packages/apps/api-application-monolith companyos:db:migrate:test bun run --cwd packages/apps/api-application-monolith companyos:db:seed:test bun run --cwd packages/apps/api-application-monolith companyos:db:verify:test bun run --cwd packages/apps/api-application-monolith companyos:db:prove-rls:test bun run --cwd packages/apps/api-application-monolith companyos:db:prove-disposable-postgres # Live/shared DB path: approval-gated, non-destructive, URL-redacting. bun run --cwd packages/apps/api-application-monolith companyos:db:migrate:live bun run --cwd packages/apps/api-application-monolith companyos:db:seed:live bun run --cwd packages/apps/api-application-monolith companyos:db:verify:live ``` `typecheck` runs two projects: `typecheck:build` (`tsconfig.build.json`, the `src/` sources that `prebuild` also gates) and `typecheck:scripts` (`tsconfig.scripts.json`, every `scripts/**/*.ts` operator script and its tests). The Postgres bootstrap recovery suite (`scripts/bootstrap-admin-postgres.test.ts`) runs only when `MANAGED_COMPANYOS_TEST_DATABASE_URL` points at a disposable local database. ## Managed Builder public REST surface The Elysia host exposes Builder operations at `/api/companyos/builder/*` as a tenant-scoped Builder surface distinct from agent/workflow. The public handler uses AuthOS/control-plane service-principal authorization, rejects raw-looking provider or webhook credentials, and reuses the Builder runtime resources that select DB-backed storage by default (or `BUILDER_RUNTIME_STORAGE=memory` for tests). Key route families include sessions, sources, intents, spec packs, plan compile/tasks, provider preflight, executions, webhooks, readiness, previews, releases, replay, evidence, analytics, and improvements. Provider/webhook activation stays fail-closed unless callers pass approved typed refs such as `provider_ref:*` and `webhook_ref:*`; raw `sk-*`, `whsec_*`, GitHub, Slack, or long secret-looking values return 422. ## Auth, DB lifecycle, and RLS closure The API monolith owns the executable Managed CompanyOS auth/database/RLS slice: - Session authority is request-derived from the `managed_companyos_session` cookie or the test-only `x-managed-companyos-session` header; invalid, missing, revoked, expired, or tenant-mismatched sessions fail closed. - Auth lifecycle state is exposed through API-local invitation, passkey, lockout, sign-out, and governed session-revoke routes. Invitation administration supports list, send, token-rotating resend, and terminal revoke; invitation and passkey routes return refs only, while raw passwords, public keys, provider tokens, and secret-manager URIs are rejected or kept out of responses. The seeded `/api/companyos/auth/test-login` helper is disabled outside test mode unless `MANAGED_COMPANYOS_ENABLE_TEST_LOGIN=1` is set. - The app Drizzle schema, migrations, local lifecycle, seed manifest, and mutation repository use canonical `managed_companyos_*` table names, including `managed_companyos_invitations`, `managed_companyos_passkeys`, `managed_companyos_passkey_challenges`, `managed_companyos_auth_lockouts`, and `managed_companyos_mutation_ledger`. - Drizzle schema code is the canonical source for feasible owned tenant RLS metadata. `src/db/schema.ts` attaches `pgPolicy` tenant-isolation policies to tenant-scoped Drizzle tables, while `src/db/rls-policy-inventory.ts` records executable SQL parity expectations, the explicit-`WITH CHECK` tenant policies, schema-only classifications and runtime descriptor fallback, and re-exports `src/db/rls-policy-inventory-exceptions.ts` (the 0066 topology evidence split, platform exceptions and the current Drizzle 0.x version gate: `pgPolicy` only; no `pgTable.withRLS`). Migration 0179 makes every inventory tenant policy compare `nullif(current_setting('app.tenant_id', true), '')`; 0183 validates its non-empty `CHECK` constraints. - Checked-in SQL migrations remain the executable artifacts. Before changing policy names, roles, `USING`, `WITH CHECK`, `ENABLE`, or `FORCE` semantics, run the ContractSpec Connect gate and the static parity tests; treat any table/policy/role SQL drift as compatibility-impacting unless explicitly classified in the plan/evidence bundle. - Local/test DB lifecycle commands require `MANAGED_COMPANYOS_TEST_DATABASE_URL` or `LSSM_STUDIO_TEST_DATABASE_URL` and refuse production-like targets. Reset removes every personal-context, team-grant, user-workspace-grant, personal-calendar, and briefing table before replay, so repeated reset/seed/bootstrap runs do not retain authority state. Auth lifecycle repository fallback to memory is test-only unless `MANAGED_COMPANYOS_ENABLE_MEMORY_AUTH_REPOSITORY=1` is explicitly set. When `AUTH_PROVIDER_MODE=better-auth`, the catch-all better-auth route also fails closed unless one of `MANAGED_COMPANYOS_AUTH_DATABASE_URL`, `MANAGED_COMPANYOS_TEST_DATABASE_URL`, `LSSM_STUDIO_TEST_DATABASE_URL`, or `LSSM_STUDIO_DATABASE_URL` is configured, preventing accidental in-memory auth fallback in production mode. - Live/shared DB lifecycle commands are separate: `companyos:db:migrate:live`, `companyos:db:seed:live`, and `companyos:db:verify:live`. They read `LSSM_STUDIO_DATABASE_URL` (or `MANAGED_COMPANYOS_LIVE_DATABASE_URL`), emit only a redacted target fingerprint, require approval evidence for all commands, require backup/checkpoint evidence for migrate/seed, and expose no reset/drop/truncate-all live action. Seed and verify accept no forward tenant/workspace selector: one invocation reconciles the selected contract-owned profile (`all`/`core-workspaces`: the live `lssm` and `companyos` organizations) in deterministic order. Each organization is atomic across its declared families, committed organizations remain resumable after a later failure, and replay succeeds only when receipt, expected counts, and the live semantic digest agree. Optional hybrid booking is configured only through the fixed LSSM or CompanyOS URL/evidence pairs documented in `deploy/env/api.env.example`. Supplying only half a pair, a non-HTTPS/non-Calendly URL, or either legacy singular selector fails before the seed opens its manifest-wide runner. Receipts and command output expose only configured organization slugs and URL digest evidence; they never emit the raw booking URL. - `companyos:db:prove-rls:test` verifies forced RLS metadata and SQL tenant-denial behavior when a permitted local/test DB URL exists. The proof provisions `managed_companyos_rls_proof_app`, queries `pg_roles`, and fails unless that role is `rolsuper=false` and `rolbypassrls=false`; tenant-denial assertions never run on a superuser or BYPASSRLS role. If no permitted URL is present, report the live proof as not run rather than passed. ### AuthOS identity provider & identity-rbac authority When `AUTH_PROVIDER_MODE=better-auth`, the API serves a real AuthOS identity provider through the `@lssm-tech/integration.authos-better-auth` bridge (`src/auth/better-auth-setup.ts`). The runtime-backed login surface is email+password, email OTP, email magic link, and built-in social login for Google, Microsoft, LinkedIn, TikTok, Facebook, and GitHub. Verified aliases resolve to the same Better Auth user and shared password while OTP, magic-link, and recovery delivery uses the address entered. Public self-signup remains disabled by default; promotion requires every external evidence reference plus production Turnstile configuration. `GET /api/companyos/auth/login-methods` exposes only enabled method IDs, labels, and link requirements—never credentials. The reviewed central LSSM identity profile is an isolated host deployment, not a wider CompanyOS cookie mode. With `LSSM_IDP_ENABLED=1`, both auth and web origins must be exactly `https://id.lssm.co`, the cookie is host-only, and the OAuth 2.1/OIDC provider exposes standards-compatible discovery aliases. Product applications receive pairwise subjects and continue to own tenant, membership, role, and data authority locally. LSSM OS is a separate relying party projected through this API. Reviewed activation registers only `lssm-os-web`, the exact `app_lssm_os` scope, PKCE, and `https://os.lssm.tech/auth/callback/lssm`. The browser session remains an API-local `SameSite=None; Secure` cookie for `api.companyos.run`; it is not an ecosystem cookie. `os.lssm.tech` and `console.lssm.tech` enter the credentialed CORS allowlist only while that reviewed client is fully configured. The product-access path is a separate fail-closed authority. Public intake is scoped to one registered application; opening the private status link proves email possession and moves the request to review. Approval issues a 256-bit, single-use invitation whose plaintext exists only in email. Acceptance at `id.lssm.co/auth/accept-invite` provisions or reuses the central identity and atomically records the active coarse entitlement plus redacted provisioning receipts. The OAuth provider requests exactly one product scope and redirects to `/auth/access` unless that identity has an active, non-expired entitlement. Migration `0058_authos_product_access.sql` owns the durable event, invitation, entitlement, and receipt tables; replay is additive and tested with PGlite. - **Single-session authority.** Every credential path and enabled plugin funnels through `finalizeAuthenticatedSession` (`src/auth/active-org-hook.ts`). A preselected organization is preserved only after current membership validation. Otherwise, new-session selection uses the sole deterministic fallback `organization.created_at ASC, organization.id ASC`; no membership leaves the organization unset and downstream access fails closed. - **Fresh organization authority.** `activeOrganizationId` is an identity-plane key, not a physical tenant ID. Each protected request rechecks the current Better Auth session and membership, resolves an enabled organization-to-tenant binding plus canonical `managed_companyos_organization_grants` row, and derives the RLS tenant only from that verified binding. Global `user.role` and `managed_companyos_operators.role` remain compatibility/reporting projections and never authorize CompanyOS domain actions. - **Commit-time switch protection.** Resource transactions retain the expected session, organization, binding, and grant versions. Immediately before commit they lock and recheck the authoritative Better Auth session row and re-prove membership/binding/grant authority. A concurrent organization switch or authority change rolls the transaction back; callers must begin a fresh request rather than retrying under a newly selected organization. - **Fail-closed plugin config.** A capability marked `runtime-backed` in the spec without a real runtime-wired better-auth plugin throws at setup (`assertEnabledPluginRuntimeWiring` in `src/auth/plugin-config-guard.ts`) instead of silently no-opping. - **Provider tokens at rest.** Better Auth seals provider OAuth access and refresh tokens (`account.encryptOAuthTokens` plus a seal-on-refresh hook); legacy plaintext stays readable until it is rewritten, ID tokens are stored as received, and the deploy prerequisites, dual read and rollback rules live in `src/auth/oauth-token-encryption.ts`. - **Canonical grants feed identity-rbac.** The organization grant's validated role maps to the exact, least-privilege identity-rbac permission set in `src/middleware/companyos-role-permissions.ts`. `src/middleware/companyos-subject.ts` wraps `createSubjectProvider` (`@lssm-tech/lib.authos-runtime`) into the governance `Subject`, and `src/middleware/authorization.ts` attaches the resolved permission set to user actors. Control-plane/builder capability gating remains a separate axis; organization membership alone never grants domain, approval, billing, provider, or machine-only authority. - **401 vs 503 (retryable RBAC distinction).** No session → **401**. A *valid* session whose identity-rbac resolution fails (store transiently unavailable / unmapped role) → **503** with an `auth.rbac.unavailable` signal (hashed tenant, no PII/tokens), NEVER the 401 reserved for "no session". ### Profile-aware bootstrap `MANAGED_COMPANYOS_SEED_PROFILE=core-workspaces bun run companyos:bootstrap-admin` reconciles the live LSSM and CompanyOS organizations for one canonical account; `all` selects the same live set. Live commands require an explicit profile and refuse the deprecated reference-only `legacy-reference` profile because it includes NDconsulting, decommissioned with Hirly on 2026-10-20 ([evidence](../../../docs/evidence/authos/decommission-hirly-ndconsulting-2026-10-20.md)). The retired `lssm-hirly` profile is refused by every bootstrap and seed path, local included, and no `collaborators:hirly` phase runs; the company spec keeps the id exported only as a deprecation window until its next major. - The bootstrap takes a session-scoped PostgreSQL advisory lock. Better Auth identity operations and tenant-scoped authority transactions are separate, idempotent saga phases; migration `0019` records each completed phase durably instead of claiming cross-connection atomicity. - Existing users never require or update a password. `BOOTSTRAP_ADMIN_PASSWORD` is read only when the configured admin account is absent; secrets and the admin email are not emitted in receipts or logs. - When Better Auth creates the absent user's primary email row first, bootstrap verifies that same-user row in place and preserves its opaque provider ID. A normalized email already owned by another user remains a hard conflict. - The canonical user has primary `tboutron@lssm.co`, verified alias `theo@tryhirly.com`, and one private personal space. LSSM and CompanyOS bind the primary owner email; Hirly, which bound the alias, was decommissioned on 2026-10-20. - Every selected organization has a distinct physical tenant/workspace binding with only OPA and CommunicationOS enabled by default. - Replays are idempotent for the same profile and manifest revision. Email, personal-space, membership-email, and module phases have durable receipts. Migration `0039` adds one-time, attempt-bounded alias verification challenges; `0040` adds owner-controlled join policies, verified-domain claims, and transactional access-request decisions; `0041` adds retryable personal-context provisioning state. Session creation never fails solely because private-space provisioning is temporarily unavailable: the user remains authenticated and can inspect `GET /api/companyos/personal-context/provisioning-status` before a bounded retry. Better Auth database lookups canonicalize verified aliases for OAuth callbacks without rewriting provider-account identity, so a verified secondary email links to the existing user instead of creating a duplicate. Authenticated profile, smart-meeting, booking-repair, approval, and Google Calendar routes verify the active workspace's OPA entitlement before touching OPA storage or provider runtimes. A disabled module is therefore hidden by the web shell and denied independently at the API boundary. Deferred AuthOS capabilities (honest, contract-only with reasons — never marked runtime-backed): - `passkey` (WebAuthn): better-auth 1.6.15 ships no passkey plugin; requires `@simplewebauthn` + cross-package dep wiring — deferred to its own wave. (The app-local `managed_companyos_passkeys` ref routes above are a separate deterministic proof-path, not the better-auth WebAuthn plugin.) - `sso` / `saml` and `scim`: modeled as `external:*` bridge declarations (`runtimeWired: false`); ADR follow-ups pending real `@better-auth/sso` / `@better-auth/scim` wiring. - `audit`: Better Auth has no audit plugin; the API-owned `/api/companyos/auth/audit` projection reads the tenant RLS ledger, returns redacted classified events with signed pagination, and exposes a bounded administrator/auditor CSV export. - `connect-lssm-account-link`: the LSSM IdP (`oidc-provider`) is gated on `enableLssmIdp` + a security-review ref, neither configured in v1. Live DB operation checklist: 1. Record the ContractSpec Connect gate/evidence for the migration/RLS decision. 2. Put the live DB URL only in `LSSM_STUDIO_DATABASE_URL` or `MANAGED_COMPANYOS_LIVE_DATABASE_URL`; command output redacts URL user/password and records only a target fingerprint. 3. Provide `MANAGED_COMPANYOS_LIVE_DB_APPROVAL_EVIDENCE_PATH` (or an opaque approval ref) for migrate/seed/verify. 4. Provide `MANAGED_COMPANYOS_LIVE_DB_BACKUP_EVIDENCE_PATH` (or an opaque backup/checkpoint ref) before migrate/seed. 5. Set `MANAGED_COMPANYOS_SEED_PROFILE`, run `companyos:bootstrap-admin`, and require the complete selected authority manifest before business seeding. 6. Run `companyos:db:seed:live` once for the selected contract-owned profile; do not supply tenant/workspace selectors. 7. Run `companyos:db:verify:live` and require exact family receipts, counts, semantic digests, tenant isolation, and redacted evidence. 8. Run only `companyos:db:migrate:live`, `companyos:db:seed:live`, and `companyos:db:verify:live`; there is no live reset/drop/truncate-all command. 9. Run static parity first: `bun test --cwd packages/apps/api-application-monolith src/db/schema.test.ts src/db/rls-policy-inventory.test.ts src/db/rls-proof.test.ts`. 10. Run DB-gated migrate/seed/verify/prove commands only when the URL is permitted. 11. Report skipped or blocked DB proof as **not run**, never as passed. The exact-head disposable PostgreSQL 15 proof creates two uniquely named loopback-only databases, compares empty migration with a production-through-0017 forward replay, bootstraps the canonical organizations, forces and resumes a family failure, replays twice, verifies all families, and runs a cross-tenant SELECT/INSERT/UPDATE matrix as a real `NOSUPERUSER NOBYPASSRLS` role. It stops the cluster, removes its temporary data, and proves the port is closed. ## Integration Points ### REST API Integration External systems integrate with Managed CompanyOS via REST routes: ```bash # Workspace projection (workflow state, integrations, replay packets) curl -H "x-managed-companyos-session: " \ https://api.host/api/companyos/workspace # Evidence verification (audit proof) curl -H "x-managed-companyos-session: " \ https://api.host/api/companyos/evidence?correlationId=corr_xyz # Health check curl https://api.host/api/companyos/health # Degraded health (returns 503 if API or scheduled snapshot duties are unhealthy) curl https://api.host/api/companyos/health/degraded # Request-time Vercel snapshot readiness curl -H "x-managed-companyos-session: " \ https://api.host/api/companyos/vercel/snapshot # Replay/evidence snapshot curl -H "x-managed-companyos-session: " \ https://api.host/api/companyos/vercel/replay-evidence # Supervision-equivalent snapshot curl -H "x-managed-companyos-session: " \ https://api.host/api/companyos/vercel/supervision ``` All tenant-scoped queries derive `tenantId` from the verified session token. Cross-tenant access is rejected with 403. ### MCP (Model Context Protocol) Integration For AI agents and CLI tools, use the planned `@lssm-tech/app.managed-companyos-mcp` server (see `.omx/audits/mcos-mcp-design-20260515.md` for design). MCP tools expose the same operations as the REST API but with additional: - Tool context factory for tenant/actor/policy decisions - Resource URIs for replay packets, evidence receipts, and health snapshots - Prompts for copilot-style operator guidance ### Manual refresh / snapshot integration Web production should request snapshots from the API monolith and let users refresh or navigate to obtain a fresh request-time snapshot. Do not add WebSocket, SSE, EventSource, interval polling, or automatic polling as a replacement in the Vercel-only topology. The standalone Bun realtime runtime remains documented in the worker package for non-production proofs and future VPS mode only; it is not a managed CompanyOS production dependency while this cost-capped Vercel topology is active. Central governed-recovery bindings reuse the shared fail-closed HTTPS port from `@lssm-tech/lib.data-exchange-server`. Each product binding has one exact HTTPS origin and distinct server-only bearer; duplicate application bindings are rejected rather than overwritten. Revocation and rights requests omit worker lease metadata, ambient credentials, and redirects, and accept only bounded schema-valid product evidence. ## Managed CompanyOS environment Copy `deploy/env/api.env.example` into the deployment secret-manager-backed environment group and apply the canonical environment contract in `docs/runbooks/managed-companyos.md`. Keep raw provider credentials out of committed files and evidence; concrete providers remain approval-gated. For the managed monolith Vercel rollout, the supplied API DB URL belongs only in `LSSM_STUDIO_DATABASE_URL` and `MANAGED_COMPANYOS_AUTH_DATABASE_URL`. Do not copy it into the web app. `MANAGED_COMPANYOS_WAITLIST_DATABASE_URL` is optional and requires a separate low-privilege waitlist writer URL; leave it absent/empty otherwise. Using the same supplied API DB URL across production/preview/development and both API DB variables is an intentional blast radius only when all envs + migration were explicitly selected; split runtime, auth, migrator, and waitlist credentials later. | Variable | Purpose | | --- | --- | | `MANAGED_COMPANYOS_STATE_FILE` | Local/VPS preview only. Do not configure on Vercel; production state uses PostgreSQL. | | `CRON_SECRET` | Bearer secret used by Vercel Cron service-principal authorization. Required for scheduled snapshot, waitlist purge, channel dispatch, and connect-review sweep crons. | | `MANAGED_COMPANYOS_SESSION_SECRET` | **Required in production.** HMAC-HS256 signing secret for `x-managed-companyos-session` tokens. Must be a strong random value (≥32 bytes). Never commit to source control. | | `MANAGED_COMPANYOS_CONTEXT_AUTH_SECRET` | **Required for profile editing in production.** Distinct server-only HMAC key (≥32 bytes) that verifies web profile-context assertions. | | `MANAGED_COMPANYOS_DEFAULT_TENANT_ID` | Local/CI fixture fallback only. Leave empty in production; browser, query, and body tenant identifiers never authorize access. | | `MANAGED_COMPANYOS_ORG_AUTHORITY_CUTOVER` | Production authority selector. `1` requires verified organization membership, binding, grant, and organization-owned workspace scope. | | `MANAGED_COMPANYOS_PILOT_TENANT_ID` / `MANAGED_COMPANYOS_PILOT_WORKSPACE_ID` / `MANAGED_COMPANYOS_PILOT_SCENARIO_ID` | Exact legacy ND admission inputs during shadow/pre-cutover and for a rehearsed rollback build that requires cutover `0`; excluded from auth readiness and never forward authority. | | `MANAGED_COMPANYOS_REMOTE_CONFIG_URL` | **Required.** Signed tenant remote-config manifest URL for feature flags, runtime endpoints, and kill switches. Use `https://…` in deployment or `managed-companyos://fixture/` in deterministic tests. | | `MANAGED_COMPANYOS_REMOTE_CONFIG_SIGNING_KEY_REF` | **Required.** Redacted key reference for remote-config manifest verification. Never commit raw signing material. | | `MANAGED_COMPANYOS_PROVIDER_APPROVAL_REQUIRED` | Must remain `true` until explicit provider approval exists. | | `LSSM_STUDIO_DATABASE_URL` | Shared managed CompanyOS PostgreSQL database used by the API and profile SEO. SEO assumes transaction-local NOINHERIT reader/builder roles; it does not require additional database URLs. | | `MANAGED_COMPANYOS_AUTH_DATABASE_URL` | Auth DB URL. May intentionally match `LSSM_STUDIO_DATABASE_URL` only for the approved all-env migrate rollout; prefer split credentials later. | | `LSSM_IDP_ENABLED` | Set to `1` only in the reviewed `id.lssm.co` deployment; omit elsewhere. | | `LSSM_IDP_SECURITY_REVIEW_REF` | Opaque approved security-review evidence reference required by the central identity profile. | | `LSSM_IDP_PAIRWISE_SECRET` | Secret-manager value of at least 32 characters used to derive pairwise relying-party subjects; never expose it to clients or logs. | | `LSSM_IDP_VALID_AUDIENCES` | Comma-separated exact HTTPS relying-party audience origins. Wildcards and an empty audience set fail closed. | | `LSSM_IDP_RP_RECONCILE_TOKEN` | Temporary 32+ character operator bearer for `POST /internal/authos/relying-parties/reconcile`. Configure only during a controlled client create/rotation ceremony, then remove and redeploy. | | `{HCIRCLE,PACTENA}_LSSM_RP_ENABLED` / `{HCIRCLE,PACTENA}_LSSM_RP_SECURITY_REVIEW_REF` / `{HCIRCLE,PACTENA}_LSSM_RP_CLIENT_SECRET` | Central IdP reconciliation inputs for the matching catalog client. Applications registered after the legacy four (for example `tafio-web`, D-222) use the derived central-only names `LSSM_IDP__RP_{ENABLED,SECURITY_REVIEW_REF,CLIENT_SECRET}` (`` is the registry segment, for example `LSSM_IDP_TAFIO_RP_*`) and reconcile only an `active`, production-enabled catalog row whose review reference equals the env value. The catalog placeholder `REVIEW-REF-REQUIRED` is refused as a review reference for every product. Secrets are read only from the identity host environment and never accepted in the request. Remove the central client secret after the database reconciliation receipt is verified; the product API retains its matching runtime secret. | | `LSSM_IDP_LSSM_OS_RP_*` / `LSSM_OS_RP_*` | The `LSSM_IDP_` names are temporary central reconciliation bindings for the dedicated LSSM OS client; the unprefixed names belong only to the product runtime. Legacy central use of the unprefixed names remains compatible, but new ceremonies must use the explicit prefix so central readiness cannot confuse registration with product activation. | | `LSSM_GOVERNED_DATA_DATABASE_URL` | Central identity only: least-privilege forced-RLS runtime connection for governed projection grants, leased deliveries, rights jobs, revocation events, and acknowledgements. Run additive migrations separately; never supply a migrator/admin URL. The recovery console requires a fresh central `admin` session with verified MFA. | | `LSSM_GOVERNED_{HCIRCLE,PACTENA,COMPANYOS,LSSM_OS}_CATALOG_TOKEN` | Central identity only: distinct 32+ character product-service bearer for immutable projection and localized sharing-offer publication. Never reuse recovery, provisioning, or cron credentials. | | `LSSM_GOVERNED_ORGANIZATION_SUBJECT_SECRET` | Central identity only: server-only 32+ character key for keyed HMAC organization subject references. Rotating it changes every derived `org_` subject. Organization grant issuance needs it and refuses without it. Operators grant the identity service role SELECT and INSERT only on `governed_data.organization_grant_bindings`. | | `LSSM_GOVERNED_ORGANIZATION_SUBJECT_BINDINGS_ORIGIN` / `LSSM_GOVERNED_ORGANIZATION_SUBJECT_BINDINGS_READ_TOKEN` | Central identity only: safe HTTPS origin of the OSINT host and its distinct 32+ character read bearer (the OSINT host's `OSINT_GOVERNED_SUBJECT_BINDINGS_READ_TOKEN`) for trusted organization subject bindings. Without both, organization issuance answers `organization_issuance_unavailable:subjects`. | | `LSSM_GOVERNED_ORGANIZATION_SUBJECT_BINDING_REFS_ORIGIN` / `LSSM_GOVERNED_ORGANIZATION_SUBJECT_BINDING_REFS_WRITE_TOKEN` | Central identity only (D-160, EXCHANGE-01m): HTTPS origin of the OSINT host (http only on loopback) and its distinct 32+ character write bearer (the OSINT host's `OSINT_GOVERNED_SUBJECT_BINDING_REFS_WRITE_TOKEN`). After organization issuance commits, and again on replay, identity hands the keyed `org_` subjectRef back to `POST /internal/osint/governed-subject-binding-refs`; best effort, and without both nothing is sent. | | `LSSM_GOVERNED__CATALOG_TOKEN` / `LSSM_GOVERNED__SOURCE_RIGHTS_TOKEN` | Central identity only: names derived from the AuthOS registry for every `active` `app_` registration (`` is `` upper-cased, non-alphanumerics as `_`); the HCIRCLE, PACTENA, COMPANYOS and LSSM_OS names derive byte-identically. Draft, unknown, unprefixed or colliding ids derive no name. | | `LSSM_GOVERNED_{HCIRCLE,PACTENA,COMPANYOS,LSSM_OS,PERSONAL_OS}_RECOVERY_ORIGIN` | Central identity worker: exact HTTPS origin for a qualified product recovery ingress. Omit unqualified products. | | `LSSM_GOVERNED_{HCIRCLE,PACTENA,COMPANYOS,LSSM_OS,PERSONAL_OS}_RECOVERY_TOKEN` | Central identity worker: distinct 32+ character server-only bearer for the matching product. Never expose to web clients or reuse `CRON_SECRET`. | | `COMPANYOS_GOVERNED_DATA_DATABASE_URL` / `LSSM_OS_GOVERNED_DATA_DATABASE_URL` | Matching product API only: separate product-local forced-RLS encrypted-copy database. Never use the central grant database or a migrator connection at runtime. | | `COMPANYOS_GOVERNED_RECOVERY_TOKEN` / `LSSM_OS_GOVERNED_RECOVERY_TOKEN` | Matching product API only: distinct 32+ character recovery bearer. Database plus recovery bearer may be configured without enabling new materialization. | | `COMPANYOS_GOVERNED_DATA_REGION` / `LSSM_OS_GOVERNED_DATA_REGION` | Exact receiving-product residency region. Must be configured together with the matching materialization binding registry or startup fails closed. | | `COMPANYOS_GOVERNED_MATERIALIZATION_BINDINGS` / `LSSM_OS_GOVERNED_MATERIALIZATION_BINDINGS` | Secret-manager JSON array of exact `sourceApplicationId` and distinct 32+ character `bearerToken` pairs. Enables only `POST /internal/governed-data/materializations/:sourceApplicationId`; unknown/duplicate sources fail closed. Never use one ecosystem-wide token. | | `COMPANYOS_GOVERNED_DATA_AUTO_MIGRATE` / `LSSM_OS_GOVERNED_DATA_AUTO_MIGRATE` | Controlled activation only. Runtime defaults to no migration; apply additive schema with an approved migration owner first. | | `COMPANYOS_GOVERNED_DATA_SSL_MODE` / `LSSM_OS_GOVERNED_DATA_SSL_MODE` | `require` by default; `allow` or `prefer` only for a qualified local target. | | `LSSM_OS_RP_ENABLED` | Set to `1` only in the reviewed, dedicated `api.os.lssm.tech` deployment; it cannot share the CompanyOS RP deployment. | | `LSSM_OS_RP_SECURITY_REVIEW_REF` | Opaque approved security-review evidence required before the LSSM OS client or origins are exposed. | | `LSSM_OS_RP_CLIENT_SECRET` | Secret-manager value of at least 32 characters for `lssm-os-web`; never expose it as `NEXT_PUBLIC_*`. | | `LSSM_OS_MEMBERSHIP_PROVISION_TOKEN` | Dedicated 32+ character server-only token for idempotent central AuthOS → LSSM OS local membership provisioning. | | `LSSM_OS_MEMBERSHIP_PROVISION_URL` / `LSSM_OS_MEMBERSHIP_PROVISION_TOKEN` | Exact HTTPS LSSM OS receiver and matching central caller token. The receiver URL is `/internal/authos/product-memberships`; no query, fragment, or embedded credentials are accepted. | | `HCIRCLE_MEMBERSHIP_PROVISION_URL` / `HCIRCLE_MEMBERSHIP_PROVISION_TOKEN` | Exact HTTPS hCircle receiver and its independent 32+ character central caller token. | | `PACTENA_MEMBERSHIP_PROVISION_URL` / `PACTENA_MEMBERSHIP_PROVISION_TOKEN` | Exact HTTPS Pactena receiver and its independent 32+ character central caller token. | | `MANAGED_COMPANYOS_WAITLIST_DATABASE_URL` | Optional public waitlist writer URL. Must be separate and low-privilege; omit unless that credential exists. | | `MANAGED_COMPANYOS_BOOKING_GRANT_PEPPER` | **Required for the Postgres-backed booking provider-effect host.** Distinct server-only random pepper (≥32 bytes). | | `MANAGED_COMPANYOS_GOOGLE_CALENDAR_CLIENT_ID` / `MANAGED_COMPANYOS_GOOGLE_CALENDAR_CLIENT_SECRET` / `MANAGED_COMPANYOS_GOOGLE_CALENDAR_REDIRECT_URI` | Dedicated Google Workspace Calendar OAuth application. The exact HTTPS redirect is `/api/companyos/integrations/google-calendar/oauth/callback`; localhost is allowed only for local development. | | `MANAGED_COMPANYOS_BOOKING_QUEUE_URL` / `MANAGED_COMPANYOS_BOOKING_DELIVERY_SERVICE_URL` / `MANAGED_COMPANYOS_BOOKING_DELIVERY_SERVICE_TOKEN` | Optional external booking notification queue/service pair. Configure all three together; when the queue URL is omitted the calendar-maintenance cron uses the Postgres-durable direct relay. | | `OPA_PROFILE_SEO_MAX_PAGES` | Builder publication page gate, capped at 49,998. | | `OPA_PROFILE_SEO_MAX_BUILD_DURATION_MS` | Maximum authenticated repeatable-read build duration before rollback. | | `OPA_PROFILE_SEO_MAX_TOTAL_BYTES` | Maximum aggregate canonical page bytes before rollback. | | `OPA_PROFILE_SEO_MAX_PAGE_BYTES` | Maximum canonical bytes per page; must remain below 50 MiB. | | `POSTHOG_API_KEY` | Optional server-side PostHog key. The emitter is noop when unset. | | `POSTHOG_HOST` | PostHog server-side capture host. Use EU Cloud ingest `https://eu.i.posthog.com`. | | `MANAGED_COMPANYOS_MANAGED_REFERENCE_CREDENTIAL_REF` | Platform-managed reference-provider credential alias for the executable provider-neutral catalog. The value must be a redacted reference label/alias, not a raw key, webhook URL, bearer token, or secret-manager URI. | | `MANAGED_COMPANYOS_BYOK_REFERENCE_CREDENTIAL_REF` | Tenant-owned BYOK reference-provider credential alias for the executable provider-neutral catalog. The app stores and returns only redacted metadata. | | `MANAGED_COMPANYOS_MANAGED__CREDENTIAL_REF` / `MANAGED_COMPANYOS_BYOK__CREDENTIAL_REF` | Future provider-family env names for approved app/provider-layer adapters. Keep values in the deployment secret manager and pass only redacted aliases/metadata through API responses, logs, tests, and evidence. | ### Provider strategy matrix The executable app-layer provider catalog currently includes: - `managed-reference` → `reference-managed-channel`, configured by `MANAGED_COMPANYOS_MANAGED_REFERENCE_CREDENTIAL_REF`. - `byok-reference` → `reference-byok-channel`, configured by `MANAGED_COMPANYOS_BYOK_REFERENCE_CREDENTIAL_REF`. Both entries expose redacted metadata only (`********`) and dispatch through an injected/provider-neutral harness. Missing env refs, raw-looking values (`sk-*`, `xox*`, bearer tokens, URLs/URIs, or oversized values), unknown provider ids, and unconfigured catalog entries fail closed before dispatch. The broader provider family matrix is documented in `docs/runbooks/managed-companyos.md` and `specs/companyos-managed-readiness.md` as catalog/readiness intent, not blanket live-dispatch approval. Concrete SDK imports/defaults remain confined to app/integration/provider layers; lower bundles/libs/modules must stay provider-neutral. ### Forms platform CompanyOS mounts management at `/companyos/forms`, public forms at `/f/{opaqueToken}`, and the API at `/api/forms/v1`. Configure `MANAGED_COMPANYOS_FORMS_DATA_PROTECTION_SECRET`, milestone flags, and optional verification, AI, and distributed-defense `MANAGED_COMPANYOS_FORMS_*` ports. Migrations `0048_forms_platform.sql` and `0050_forms_scope_hardening.sql` own the product-local schema and its tenant/workspace/owner plus row-bound public RLS upgrade; creator scope is always derived from the resolved API session. ### Governed meeting workspace Migration `0053` installs the OPA meeting-workspace forced-RLS tables. The additive `0061` access-grant, `0063` provider-intake, and `0065` recurring intake-job migrations preserve the same five-axis owner scope. The Elysia host mounts all nineteen exact catalog operations below `/api/v2/opa` using the verified CompanyOS organization/workspace session, module entitlement, persisted capability grants, app-origin check, and CSRF session reference. Production initialization requires `LSSM_STUDIO_DATABASE_URL` plus the versioned `OPA_BYOK_KEY_VERSION` and `OPA_BYOK_MASTER_KEY_` secret; missing storage or encryption configuration fails closed. The provider-neutral transcript intake adapter is intentionally not an anonymous HTTP ingress. Its host caller must derive owner scope, active consent receipts, and recorder bindings from verified server state; normalized content remains unpublished until a credentialed provider integration earns its own transport and live qualification evidence. ### OPA capture intake Migration 0075 adds owner-scoped consent receipts after encrypted staging 0074. The seven declared capture routes are mounted under `/api/v2/opa`. Set `OPA_CAPTURE_ENABLED=1`, `OPA_CAPTURE_STORAGE_REGION=eu`, and the existing `OPA_BYOK_KEY_VERSION=v1` / `OPA_BYOK_MASTER_KEY_v1` secret to enable audio intake. Effective workspace grants must include `opa.recording.read`, `opa.recording.control`, and `opa.recording.consent_self`; existing grants are not implicitly elevated. The meeting must already exist in the canonical workspace. Configuration exposes the effective policy digest and consent notice version. Grant consent explicitly before creating a microphone/import session; submit sequential digest-bound base64 chunks of at most 1 MiB. Finish checks the announced chunk/byte totals and returns processing, never a fabricated transcript. Native bearer requests are freshly verified without a cookie fallback. Browser writes require the configured web origin and the current session CSRF token. Processing availability is derived from the approved worker configuration and dispatcher credentials. Bot/system-audio/video intake remains unavailable in this host. Worker deployment, device capture, cleanup and the full release evidence must be qualified before rollout. Revocation, cancellation and deletion remain available when intake is switched off, subject to current membership and legal holds. ### Scheduling effect authority Apply additive migration 0076 before deploying the scheduling receipt producer. Human calendar intents persist a policy-bound authorization receipt. Immediate execution and cron retries reprove current session/membership/workspace, policy, Work placement, calendar write target and lease before provider credential lookup. Policy changes invalidate queued approvals. Legacy pending commands require a fresh owner intent; historical applied effects are retained unchanged. `OPA_SCHEDULING_EFFECTS_DISABLED=1` stops every scheduling provider mutation. Automation policy `disabled` stops new placement/movement while allowing an otherwise-authorized owner cancellation. These are human-approved continuations; delegated autopilot is not promoted by this change. Migration 0077 adds encrypted, owner-scoped transcript revision persistence after 0076. It preserves existing artifacts and recordings. CompanyOS AI drafting rejects transcript creation: use recorded/imported evidence through the transcription core. The processing dispatcher and private transcript read route are mounted behind explicit configuration. Transcript review and the remaining release gates are still unqualified. ### Durable capture processing Migration 0078 queues finalized captures and adds bounded worker admission plus restricted dispatcher discovery. Configure a login whose current role is exactly `companyos_capture_dispatcher` in `MANAGED_COMPANYOS_CAPTURE_PROCESSING_DATABASE_URL`. The role may call the due-scope function but cannot read media or transcripts. The worker itself reads and writes captures on the restricted runtime login `companyos_capture_runtime` (migration 0181) in `MANAGED_COMPANYOS_CAPTURE_RUNTIME_DATABASE_URL`, never on `LSSM_STUDIO_DATABASE_URL`; the bot crons use `companyos_bot_runtime` (`MANAGED_COMPANYOS_BOT_RUNTIME_DATABASE_URL`) and recorder sync `companyos_recorder_runtime` (`MANAGED_COMPANYOS_RECORDER_RUNTIME_DATABASE_URL`). Each cron refuses any other `current_user`, a superuser, BYPASSRLS or an `opa_migrator` member (`CAPTURE_/BOT_/RECORDER_RUNTIME_ROLE_INVALID`). Automatic capture processing is currently paused: the configured binding returns null until Gateway EU transcription and speaker labels are qualified. Existing Mistral credentials or capture flags cannot reactivate the default provider. The cron at `/api/cron/opa-capture-processing` requires the exact `CRON_SECRET` (minimum 32 characters) and executes every minute with a 300-second budget. The worker checks current recording-scope membership and consent independently of the active browser workspace. Transcript persistence and completion share one commit. Cancellation/deletion invalidates queued work and releases capacity. The existing transcript GET route exposes private segments and provenance; it does not approve a transcript or enable participant sharing. Review, participant consent integration and the broader production gates remain incomplete. Transcription model choice (`opa.transcription.settings.get|save`, migration 0161) is stored per user and per workspace (workspace default for workspace administrators) at `/api/companyos/opa/transcription/settings`; the cron worker resolves each capture owner's choice, and only EU-qualified catalog ids are ever forwarded. While the catalog is empty the settings report `no_eu_model`. Deleting a capture with `deleteDerivedOutcomes: true` also erases, in the same transaction, the unpublished and unshared drafts, outcomes and context derived from its transcripts (aggregate plus the append-only projections through the 0162 owner-bounded definer function `opa_erase_derived_meeting_records`), cancels their outcome jobs, keeps published or shared notes and writes an `opa.capture.derived_outcomes_deleted` audit event with counts only. ### Transcript review Migration 0079 enables encrypted source-bound review history. POST the existing transcript review route with its 3.0.0 input: exact transcriptRef, artifactDigest, expectedRevision and expectedReviewRevision. A missing review has revision zero. The route requires current private read and review permissions and native bearer or browser origin/CSRF authority. Source changes never inherit an old approval. Reviewed replacement text is a separate encrypted copy; original timed segments remain unchanged and are omitted from the reviewed-copy projection. Parent deletion erases replacement content. The UI's canReview flag is presentation, not execution authority. Review alone does not send or commit any outcome. ### Private reviewed meeting outcomes The existing meeting-workspace routes accept `x-opa-owner-view: private` to derive individual ownership from the verified user within the selected workspace. Omitting the header preserves context ownership; arbitrary owner selectors are rejected. Use the same private view for outcome analysis and subsequent artifact reads. The web BFF forwards this selector after its existing authentication and mutation-origin checks. CompanyOS outcome analysis loads the persisted approved transcript review, verifies exact source and review bindings, and checks current `intelligence.generate` policy before generation and commit. Rejected, changed, unauthorized or workspace-widened sources fail closed. The adapter uses the caller transaction and does not publish private capture text. Model calls run outside aggregate transactions. Finalization reloads current state and rechecks authority and the reviewed source before saving. Durable outcome jobs are available behind explicit configuration; downstream effects and live quality qualification remain open. ### Reviewed outcome drafts in CompanyOS The approved transcript panel can generate and read private meeting drafts through existing OPA operations. Generation controls use server-derived `canGenerateOutcomes`; authority and automation policy are rechecked server-side. Draft generation creates no messages or Work tasks. French, English and Spanish copy distinguishes loading, generation, retry, denied access and empty history. Artifact list 2.2.0 accepts optional `reviewRef`, selecting the current review before source reproof so stale historical drafts do not block current results. Transcript get 2.2.0 adds the generation capability projection. The client pins private ownership and an exact review-derived retry key, including across reloads. Interactive generation has a bounded 180-second request deadline; the web proxy allows a 300-second function budget. Persisted background jobs, signed-native presentation and full browser/accessibility qualification remain incomplete. ### Correcting and reviewing outcome drafts Artifact review 3.0.0 accepts optional `editedContentMarkdown` when approving. The request still binds the displayed artifact revision and original content digest; the receipt approves the corrected digest. Human edit metadata records the prior digest, actor and timestamp. Empty edits, edits combined with rejection/CRDT snapshots, and independent edits during open collaborative sessions are rejected. A retry key cannot approve a different payload. The private draft cards expose edit, approve and needs-changes controls using server-derived `canReviewOutcomes`. Uncertain review responses retain the current draft for retry; access denial removes it. Approval does not send messages, publish links or create Work tasks. Actual edited-review PostgreSQL qualification, complete collaborative editing and downstream actions remain open. ### Durable outcome processing Analyze 3.1.0 accepts `executionMode: background` on its existing route. Repeating the exact request observes the same persisted job; processing responses carry `processingJobRef`, while completion returns the saved outcome. The private draft client selects background mode when the server advertises it and can stop polling without cancelling accepted work. Terminal failures remain failures. Apply additive migration 0080, configure a dedicated `companyos_outcome_dispatcher` login, and enable `OPA_OUTCOME_JOBS_ENABLED=1` only with approved pinned `OPA_MEETING_AI_*` EU processing. The every-minute `/api/cron/opa-outcome-processing` route requires `CRON_SECRET`. Runtime credentials must not be superuser, BYPASSRLS or a member of `opa_migrator`. The queue admits four global jobs and one per owner, bounds pending owner jobs at 25, retries at most five times and uses six-minute fenced leases. Current membership, module entitlement, intelligence policy, source consent/review and model binding are rechecked before generation and commit. ### Meeting follow-up effects cron `/api/cron/opa-meeting-effects` (every minute, `CRON_SECRET`) hosts the meeting effect worker cycle in process, so approved follow-ups deliver without a separate worker host. Apply additive migration 0172 and give `companyos_meeting_effect_dispatcher` a login in `MANAGED_COMPANYOS_MEETING_EFFECTS_DATABASE_URL`; that role can only call `companyos_meeting_effect_due_scopes`, which returns owner scopes, never effect refs or content. Claims, authority reproof, rollout, approval and artifact-digest checks, the Postgres dispatch fence, delivery and settlement run as the RLS-bound runtime role (`LSSM_STUDIO_DATABASE_URL`, never superuser, BYPASSRLS or `opa_migrator`) on a pool opened per invocation. Switches: `OPA_MEETING_EFFECTS_CRON_ENABLED=1` and `OPA_MEETING_FOLLOWUP_DELIVERY_ENABLED=1`; `OPA_MEETING_FOLLOWUP_TARGETS` and a strict `companyos` entry in `OPA_MEETING_EFFECT_ROLLOUTS_JSON` are required. Off or unprovisioned answers 200 with `stoppedBy` and variable names only. Each invocation handles at most 10 owner scopes, 3 leases per scope and a 60 s budget; the log line `opa_meeting_effects_cycle` carries counts and failure codes only. Run exactly one effect host per database: this cron or `@lssm-tech/app.meeting-effect-worker`. The `verified_email` target routes the reserved recipient `owner:self` to an owner-only recap: the approved follow-up or summary goes to the approving owner's primary verified account address (individual owner scopes only) through the CompanyOS Briefings Resend mailbox, keyed by the effect for provider deduplication. It is off unless `OPA_MEETING_FOLLOWUP_OWNER_RECAP_ENABLED=1` and `RESEND_API_KEY` are set. Attendee refs on `verified_email` and every `communicationos_thread` effect go through CommunicationOS, composed per delivery inside the owner transaction: - **Authority.** The server-side `createCommunicationOsAuthorityIssuerV1` issues the Runtime V3 order only for the one send that delivery describes, after the delivery service has re-proved the plan approval, the approver and their dispatch capability. The approval port recomputes that request itself (bound scope, `production` environment, effect, channel, effect-bound idempotency key, and the approved context digest over the room in `threadRef`, the address the approved recipient ref resolves to, the re-proved artifact content and the bound principal); the room is the adapter's per-delivery room, bound through that digest. The order's authorization digest commits to the approval evidence. Thread refs use `communicationOsRoomThreadRefV1` (`communication-room:`), unlike the calendar briefing path, which still sends the raw room id. `OPA_MEETING_FOLLOWUP_COMMUNICATION_AUTHORITY_JSON` carries the operator deployment (Runtime Node, provider binding, queue profile, TTL); unset or invalid keeps both targets `adapter_unavailable`, and an invalid value logs `OPA_MEETING_FOLLOWUP_COMMUNICATION_AUTHORITY_INVALID` (code only). - **Durable record.** The admission is deferred to the caller: an email's operation, order, runtime outbox and envelope refs go into its CommunicationOS outbox row, a thread post's into its message event metadata. An explicit authority denial or queue refusal dead-letters the effect; an unavailable approval, a packet mismatch or an outage retries. - **Binding.** Only an individual CompanyOS owner scope approved by that owner binds, to the owner's enabled personal CommunicationOS context as `user:`. Team and workspace scopes stay `adapter_unavailable`. - **Recipients.** A `participant::` ref resolves only when its owner-salted subject matches exactly one attendee address of that meeting, read live from the owner's calendar (OPA stores no address) once per delivery and bounded to 10 s (a timeout answers 503 and retries). Named attendees resolve once the meeting event reader keeps provider addresses; until then only e-mail-shaped attendee labels do. - **Store and connections.** The journal and outbox use the effect host's own pool (the `companyos_opa_runtime` login in the cron), never a pool on `LSSM_STUDIO_DATABASE_URL`. A delivery holds its owner transaction while it reads attendees and writes CommunicationOS, so it needs at least two more connections of that pool. No migration grants the cron login membership in `communication_os_app` yet (without it delivery fails and retries); an operator migration must add it. The login must also hold `execute` on `managed_companyos_resolve_personal_context(text)` (0173) and `select` on the attendee read's tables (`managed_companyos_personal_briefing_preferences`, `managed_companyos_personal_contexts`, the personal calendar sources, selections and workspace mappings, `managed_companyos_user_workspace_grants`, `managed_companyos_workspaces`, `opa_calendar_connections`, `managed_auth_email_addresses` through 0182). Google calendar reads use the Google calendar runtime's own pool. The email is queued in the CommunicationOS outbox; the CommunicationOS worker and Agent Host send it with the `env://COMMUNICATION_OS_CONNECTION_OPA_MEETING_FOLLOWUP_RESEND` credential, before its order expires (deployment `ttlSeconds`, at most 900 s). The effect already counts as delivered, so an expired order must be re-admitted on the CommunicationOS side, not by an OPA retry. Outcome persistence and completion share a transaction; model calls are outside SQL. Queue rows contain references and authorization evidence, not transcript text or credentials. Model cost may repeat after a crash before commit. Terminal-job self-service repair, queue retention/deletion propagation, live model/provider qualification and production rollout remain open. No production activation is implied by the local tests. ### Work commit authority for OPA follow-through Managed Work mutations now resolve canonical identity, read projections, persist the event/idempotency/outbox, and reprove authority within one outer transaction. The existing verified operator binding is preserved. Current organization, session, workspace and applicable team grants are locked before the effect and checked again before commit. A final denial rolls back all Work writes. The HTTP mutation route uses the shared verified-bearer resolver, rejects cookie fallback when authorization is present, and requires exact origin/CSRF for browser requests. Bodies are bounded to 1,100,000 bytes. Read-only and suggest-only labels cannot authorize mutation; approval-required and reserved actions remain unavailable until their approval verifier is composed. Errors are content-free and not cached. This is the commit foundation; approved OPA action projection and CommunicationOS delivery still require their explicit adapters. ### Canonical Work hierarchy and legacy parity Apply additive migration 0081 after 0080 before enabling new Work identity allocation. New operators reuse canonical tenant/organization/workspace IDs for the same verified legacy scope, and a principal retains its canonical ID across workspaces within a tenant. The database enforces this during mixed-version rollout; new allocation is serialized per legacy tenant. Existing bindings are read without taking the allocation lock. Existing rows and Work events remain intact. A coherent legacy mapping is adopted for new operators; conflicting parent or principal mappings block new allocation with `WORK_IDENTITY_RECONCILIATION_REQUIRED`. Use `inspectWorkIdentityParity` inside an authorized transaction with the physical tenant GUC set to inventory conflicts. It reports scope categories and counts without rewriting data. Do not pick an arbitrary legacy ID or rewrite immutable Work events to clear the error. A reviewed reconciliation and parity/restore proof are required before enabling shared projection for a conflicted tenant. The preparation function rejects foreign scope or unavailable trigger enforcement. Personal-context provisioning uses distinct physical tenants/workspaces, which remain isolated. This change is locally verified on PostgreSQL 15; production migration and existing-data reconciliation remain separate release gates. ### Evidence-bound action proposals Meeting prompt 2.0.0 requires structured `actions` for action-plan generation. Each proposal carries a title, optional description, explicit/uncertain classification and exact quotations tied to supplied citation references. Missing action output or unsupported quotes fails generation. Model output cannot supply owners or deadlines. Quote membership proves traceability, not semantic correctness. Action-plan artifacts retain `actionProposals`, and their content digest covers prose and structured actions together. Artifact review 3.1.0 requires `acknowledgeActions` for a nonempty task list. Reviewers may edit titles/details while preserving verifiable source evidence. The private draft cards display proposed tasks, uncertainty and source quotes with an explicit approve-draft-and-tasks label. Prose-only or collaborative edits clear stale structured actions; edited structured input is revalidated against the current approved transcript. This creates reviewed proposals, not Work commitments. Assignment, due dates, canonical Work projection, downstream delivery, deletion propagation and the live precision/recall benchmark remain open. Prompt-version changes invalidate incompatible queued generation bindings; never relabel old processing as using the new prompt. ### Approved action to canonical Work `opa.task.project` 3.0.0 projects one approved structured action through the existing task route. The request binds artifact revision/digest, approval receipt, action reference and selected workspace. It requires explicit workspace disclosure acknowledgment and confirmation for an uncertain proposal. The UI exposes this action only for approved task lists and server-derived projection permission. Only the reviewed title and details are transferred; raw/private transcript text and source quotes are not copied into Work. Assignees and deadlines remain unset. Current `outcome.commit` policy, transcript review/consent and Work workspace write authority are rechecked. Work event/idempotency/outbox and the OPA projection receipt commit in one transaction. Repeated projection returns the existing Work object; a receipt represents committed task creation, not task completion or realtime projection convergence. New owner capability manifests include `opa.task.project`; existing grants require an authorized update and are not silently widened. Legacy input-only projection clients must update to 3.0.0. CommunicationOS delivery, assignment/due-date controls, real-authority deployment qualification and full release gates remain open. ### Native meeting mutation authority OPA meeting workspace routes use bearer-only session verification whenever Authorization is present. Cookies and test-session headers are stripped before bearer verification; invalid tokens cannot borrow browser authority. Verified bearer POST requests need no fabricated Origin or CSRF. Browser POST requests retain exact origin and current session CSRF checks. Entitlements and current domain authority remain mandatory. Only GET/POST are accepted, and mutation bodies are streaming-bounded to 1,100,000 bytes even without Content-Length. The CommunicationOS native-session exchange uses the same isolated bearer resolver. Route tests do not qualify signed native clients, MFA/deep links, capture permissions or app-store acceptance. Migration 0082 adds immutable owner-scoped legacy-to-canonical meeting bindings. The default-off legacy diagnostic probe now uses persisted mappings with current CompanyOS authority reproof; missing mappings cannot initialize synthetic workspaces. This integration only reads mappings. A verified backfill and current workflow parity evidence are required before any legacy route cutover; no production data is reset or automatically rebound. ### Private meeting preparation context CompanyOS graph context now requires a verified individual, an exact five-axis `meetingContextOwnerScope`, the selected `meetingRef`, explicit bounded `meetingContext` text, and declared `meetingContextClaimKind` and `meetingContextSensitivity`. Inferences require confidence; estimates also require calculation/expiry timestamps. Generic titles/summaries and unscoped legacy projections are omitted. Append new validated graph projections through the existing Company Intelligence repository; do not rewrite append-only rows to infer missing bindings. Reads run in a physical-tenant transaction. Every citation must resolve to current, non-superseded evidence and a fragment in the authorized workspace or principal ownership, with a current explicit principal ACL. Revocation tombstones invalidate their superseded sources. Graph payload audience flags and consent strings cannot authorize sharing: this source returns private context only. Generation compares every claim and source revision with a fresh authorized read before model invocation and before accepting the result. Historical artifact erasure and verified participant-sharing sources remain separate release requirements. Private OPA route families now support exact trusted-origin credentialed browser CORS, using the existing AuthOS trusted-origin configuration. Preflight accepts only the declared methods/headers, including `x-opa-owner-view` and `x-csrf-token`; endpoint authentication and mutation checks remain mandatory. Public booking/embed transport is independent. Background preparation without a verified principal/source workspace remains unavailable; a database-ready worker alone is not source or workflow qualification. ### Durable private meeting creation `GET /api/v2/opa/meeting-creation-context` returns the current private owner-scope digest and remaining meeting capacity. `POST /api/v2/opa/private-meetings` accepts `request.expectedOwnerScopeDigest` and a stable `request.idempotencyKey`. Both operations require current `opa.meeting_work_session.manage` authority. The digest is a workspace-change guard, not an authorization token. Creation atomically saves the encrypted workspace aggregate, lookup projection and replay receipt, with current authority checks before and after writes. It creates no calendar event, booking, recording or consent. Exact replays remain valid at the 10,000-meeting per-owner bound. Native bearer requests use the existing MFA-safe mutation resolver; cookie mutations retain origin and CSRF checks. Capture lookup accepts either the current user's persisted private meeting or the selected authorized shared meeting and restores private scope afterward. These two CompanyOS routes are additive to the unchanged nineteen-operation generic meeting service group. They use existing workspace persistence; no new migration or data reset is required. Existing read-only workspace materialization remains non-persistent and now carries a valid policy digest. ### Preparation transaction boundaries CompanyOS preparation model calls now run outside workspace database transactions. Initial and final phases check current authority, explicit AI policy and context; source validation reuses the caller transaction and restores the OPA owner GUCs after the CI read. Finalization reloads the aggregate, preserves unrelated writes and commits drafts plus replay state atomically. Cached requests remain authorized and cannot change the requested artifact sequence. Reviewed outcome generation uses its own draft generator inside the existing transcript-review and job-authority orchestration. It no longer requires unrelated graph-context projections. Source/member revocation and cancellation continue to fence outcome finalization. Model calls in these tests were controlled ports; live model quality and full load qualification remain open. CompanyOS preparation generation now requires additive migration `0083` before deploying this runtime. `SqlPreparationAdmissionStore` admits one active model request per complete owner scope, using six-minute database-clock leases and at most five attempts per request. Immutable digests bind the request key to its exact input, context and policy; conflicting reuse fails. Concurrent requests receive the existing `IDEMPOTENCY_IN_PROGRESS` error and may retry the same key. Expired workers cannot commit artifacts or release a replacement worker's lease. Admission completion and artifact persistence share one transaction. Cached artifacts still require fresh authority and source checks. Crashes may repeat model cost after lease expiry; this does not establish global model quotas, background preparation qualification or live-provider acceptance. `GET /api/companyos/work/objects/:objectId` reads a canonical UUIDv7 Work object under current server-derived workspace authority. The request accepts no scope parameters. Existing coherent canonical workspace mappings are read without allocation; conflicting mappings fail closed. The API uses the scoped, event-head-aware Work store and reproves read authority before returning. Responses are private/no-store, and absent, foreign or archived objects return not found. Native task-detail presentation is separate qualification work. POST `/api/companyos/work/objects/:objectId/status` accepts only a canonical object ID, expected revision, status category and idempotency key. Current writable authority and actor/scope are derived server-side inside the transaction. The existing Work service commits status changes and three outbox destinations atomically. Completion uses server time; reopening clears completion time. Identical retries resolve the stored event before current-state validation. Native controls and live end-to-end qualification remain open. Work task detail now exposes canonical status choices when the authenticated read projection supplies `canUpdateStatus`. Missing permission is read-only. Native updates bind the displayed revision and reuse the same request key for an uncertain retry of the same status. Verified event identity, next revision, status and original workspace scope are required before reloading the task. Session invalidation and blur abort the client request without claiming to undo a possible server commit. Signed-device completion/reopening acceptance remains open. `createCompanyBotWebhookIntake` composes host-selected owner/deployment/secret resolution, bounded raw UTF-8 signature verification and atomic bound-bot settlement. It returns acceptance only after settlement commits and preserves replay acknowledgments. No public route is mounted by this helper: a durable route registry and domain lifecycle/outbox apply handler are mandatory before enabling bot callbacks. Payload tenant fields cannot select authority. Bot webhook raw-body intake enforces a ten-second total read deadline in addition to the one-megabyte bound. Aborted, oversized and stalled streams are cancelled without awaiting their cancellation callback. Fatal UTF-8 decoding still preserves exact valid signed text across chunk boundaries. Timeout never acknowledges callback acceptance. Bot reconciliation uses additive migration 0084 and a coalescing owner-scoped request row. Verified callback intake defaults to enqueueing reconciliation in its receipt transaction, rather than applying delayed provider state. Workers claim three-minute leases, one active per owner, with five failed attempts and a retry delay. New notifications during a lease remain queued after completion; expired/replaced workers cannot settle. More notifications cannot revive an exhausted job. The provider-fetch worker, repair UI and deployment dispatcher still require integration; do not activate callback routes before migration and host wiring. Confirmed bot bindings may retain the existing capture authorization context inside their encrypted payload. CompanyOS `guardCompanyBotCapture` requires this context, the bot capture enable flag, current background membership/policy digests, the exact active bot capture, unexpired retention, consent and current meeting access. It reuses the existing background authority resolver rather than browser session state. Legacy bindings without context remain readable identity evidence but cannot execute background bot work. Concrete dispatcher/provider wiring and cleanup authority remain separate integration requirements. `createCompanyBotProviderRead` supplies the reconciliation worker's concrete Attendee read adapter. It resolves configuration by the encrypted binding's deployment reference and checks lease, immutable bot identity and CompanyOS capture authority before secrets and again immediately before HTTP dispatch. Cancellation is forwarded and provider I/O remains outside SQL. Hosts must supply the deployment registry and queue/binding stores; no production dispatcher is enabled by importing the factory. CompanyOS deployment resolution now permits existing-bot reads only for active or draining configurations. It captures the encrypted registry revision, lazily resolves the owner-scoped API secret, and rechecks configuration before secret access and again before HTTP dispatch. Disabling or rotating configuration invalidates pending reads. `SqlBotDeploymentStore.readInTransaction` reuses the effect-authority transaction without acquiring another connection. Administrative UI, concrete secret-store binding, bot starts, global scheduling and live provider qualification remain open. Private meeting creation uses `createCompanyPrivateMeetingAuthority` for the existing individual owner scope, capability checks and transaction-bound membership reproof. Capture authority delegates the same checks and retains its additional consent/policy/source enforcement. The web private-meeting entry requires creation-context, creation, authorized workspace and artifact-list reads to be deployed together; creation alone does not provide recording or editable meeting notes. ## Private meeting notes CompanyOS exposes one private human-authored notes draft per meeting through additive `opa.meeting_artifact.get_note` and `opa.meeting_artifact.save_note` operations at `GET/POST /api/v2/opa/smart-meetings/:meetingRef/notes`. Existing meeting-work-session management permission authorizes this personal authoring surface; recording, transcript generation and model credentials are not prerequisites. Saves use `expectedRevision` (zero for creation), at most 100000 characters and a stable idempotency key. Notes remain `live_notes/private_user/draft`, persisted in the existing encrypted aggregate. Empty content clears the draft. Revision conflicts preserve the local draft and show the latest saved notes before an explicit choice to continue. Saving notes creates no Work task and sends no message. The Work-to-OPA planning loader must assemble each task’s dependencies from the latest relationship state across all aggregates in the exact tenant/organization/workspace scope. Both outgoing `blocked_by` and incoming `blocks` edges are prerequisites under the existing Work projection contract. Filtering which tasks can be placed must not erase dependency edges from other Work aggregates. This is a loader correctness invariant; it does not activate the background outbox reoptimizer. Work planning now uses `loadSnapshot(scope)` to obtain placement candidates and `completedWork` references from one scoped event replay. Completed prerequisites remain valid even without estimates or selection for personal placement. `loadWork(scope)` remains compatible for older callers. Reopening removes completion truth; no estimated duration is fabricated. Interactive proposal digests include completion revisions. OPA direct workspace authority binds four contiguous SQL parameters; team authority binds five. An unused null parameter in the direct-grant query previously caused PostgreSQL 42P18 and made private meeting readiness unavailable. Current membership, workspace scope, grants and revocation checks remain mandatory. The regression executes the exact workspace query through the production PostgreSQL driver. `WorkProposalPersistence` is a preparatory proposals-only publisher for future Work-outbox reoptimization. It uses existing personal plan ownership and canonical Work plan envelopes, requires transaction-local full-owner/lease/current-policy guards both before effects and before commit, and leaves placement/calendar tables untouched. Its guard bindings and dispatcher activation are still unimplemented; constructing the seam is not proof of active background planning. Private meeting failure diagnostics record only the operation, processing stage, an allowlisted error class and a five-character SQLSTATE. Error messages, SQL text/parameters, note content and credentials are excluded. Disabled OPA workspace modules return the declared FORBIDDEN response rather than being disguised as service unavailability. Capture processing must resolve meeting access using the same private-first rule as interactive capture: check the captured individual’s private meeting, then the currently authorized workspace/team meeting. Background company context must not make a private meeting disappear. Every fallback restores the complete capture owner scope and retains authority, consent, policy and lease checks. ### Explicit regional processing endpoints New AI/outcome configuration requires the exact Gateway origin with geography `other`, explicit `eu` provider inference and separate global-transit approval. The configured model/provider allowlist, no-training and retention restrictions remain mandatory. The host rechecks the binding before transport and accepts only matching EU response evidence. Capture transcription has no active default provider while EU speaker-labelled Gateway processing remains unqualified. Historical endpoint-bound artifacts remain readable, including explicit Mistral EU/EFTA test fixtures. They do not activate a live provider, and no historical record or queued approval is rewritten. Storage placement and provider inference/transit are independent qualification requirements. The CompanyOS calendar-intelligence host omits direct-Mistral credentials and model selection, even when the old environment variables remain present. It composes localized deterministic-v2 recaps/briefs and records deterministic fallback status. Calendar reads, booking maintenance and delivery authority are unchanged. Gateway is not wired into this calendar path yet; see `docs/runbooks/companyos-briefings-v2.md`. ## Meeting AI through Vercel Gateway New production meeting generation uses `OPA_MEETING_AI_PROVIDER=vercel-ai-gateway` with `OPA_MEETING_AI_ENABLED=1`, a pinned `OPA_MEETING_AI_MODEL`, exact `OPA_MEETING_AI_ENDPOINT_ORIGIN=https://ai-gateway.vercel.sh`, `OPA_MEETING_AI_REGION=eu`, `OPA_MEETING_AI_PROCESSING_APPROVAL_REF`, `OPA_MEETING_AI_GATEWAY_TRANSIT_APPROVAL_REF`, and one approved non-Mistral `OPA_MEETING_AI_GATEWAY_PROVIDER`. Credentials come from `AI_GATEWAY_API_KEY` or existing `VERCEL_OIDC_TOKEN`; no Mistral key/default fallback is read. Outcome jobs additionally require their existing enable switch. References must correspond to actual approved processing/transit decisions before activation. Gateway transit is recorded as geography `other`, separately from EU inference. Exact binding checks run immediately before transport and after generation. Returned routing metadata must prove the served provider appears among the approved EU attempts; request flags alone are insufficient. Existing private/shared context filtering and cited outcome validation remain enforced. Automatic capture transcription is temporarily unavailable: `eu_transcription_not_qualified` and `speaker_labels_not_supported`. Its binding returns typed null and its default worker rejects with `CAPTURE_PROCESSING_UNAVAILABLE`; legacy Mistral credentials/flags cannot reactivate it. Existing records and controlled test ports remain intact. Qualify actual Gateway speaker-labelled EU transcription before changing this boundary. CompanyOS uses one processing-readiness predicate for the capture configuration view and new-session admission. New captures check readiness before insertion and before commit. Exact authorized create retries bypass new-session admission; existing media can still be uploaded and recovered under current consent, policy and source controls. An unavailable processor does not silently collect new recordings. Gateway EU response evidence accepts both zone and specific endpoint scopes only when geoRegion is explicitly eu. A more specific EU endpoint is not a global fallback. Missing/global/non-EU evidence remains rejected; requested routing flags alone never prove the served geography. This does not grant private Gateway transit approval. Work proposal publication v2 carries the exact outbox delivery attempt. Its default SQL lease guard locks the current leased Work record and checks destination, full event, owner, attempt and expiry using database time. It restores the prior tenant context on success or failure. Owner mapping and effective policy guards remain mandatory; the dispatcher is not activated by this binding. Existing valid replay does not write calendar placements or effects. The shared OPA background authority resolver now supports planning.propose with the exact opa.plan_run.manage capability, alongside existing capture and intelligence actions. It uses current locked organization/workspace/team grants and module entitlement, independently of browser-session lifetime. It returns the resolved policy mode and digests; callers must separately enforce manual/approval/delegation semantics. The capture-named export remains a compatibility alias. No planner dispatcher is enabled by this extraction. `loadWorkProposalOwner` resolves existing selected-workspace and personal-owner authority, locks the canonical Work mapping for the production user identity, and produces a combined authority digest plus both policy modes. It allocates no identities and grants no execution authority. All six SQL owner-context settings are restored, or rolled back with an aborted transaction. Work source/input revision proof and the policy-aware dispatcher still require composition. Workspace revision fencing hashes every canonical Work aggregate head, including unplaced, completed and archived work. Work commits take a shared workspace advisory lock; proposal publication takes its exclusive counterpart and checks the complete digest before persistence. The interactive planner and internal background proposal publisher use this fence. Upgrade all Work writers before qualifying it; older writers that omit the shared lock are not covered. Calendar freshness and policy/approval checks remain independent. Google free/busy snapshots now carry normalized query provenance. Cache reuse requires the same calendars, time window and timezone, and rejects future or unbound observations. CompanyOS preparation requires covered planning time plus a matching refresh snapshot digest, evaluated at current server time after refresh. Additive migration 0085 adds query_binding; apply it before deploying the new store/read paths. Historical rows remain readable without earning freshness, and older refreshes cannot overwrite newer observations. Calendar identifiers stay in the tenant-scoped server store. Interactive Work proposals now retain opaque calendar snapshot/configuration evidence and reprove it in the publishing transaction before writes and again before return. Reproof locks current configuration and snapshot rows, rejects changed/disconnected/expired evidence, and restores the caller tenant setting. A workspace advisory lock also fences newly inserted preferences; both Google topology and event-preference writers participate. Upgrade these writers together before qualification. Provider calls remain outside this lock; no calendar effect is applied. Planner topology selection distinguishes full scheduling preferences from event-calendar binding rows in the shared table. A newer binding without working hours cannot hide the workspace scheduling policy. A real PostgreSQL contention test verifies the actual event-preference writer waits for same-workspace publication while another workspace proceeds. Production rollout and broader load qualification remain separate. `createWorkSuggestionPolicyGuard` fills the existing proposal policy-guard port for explicit suggestion workers. It resolves current owner/policy before inputs and again after input and lease reproof, then uses the shared automation gate. The required reproveInputs callback must validate current calendar-then-Work revision evidence and return the actual input digest inside the same transaction. Other modes require their own verified command/approval/delegation composition; this helper does not enable a worker. Planner input now includes all active focus occupancy owned by the personal user, with buffer margins. Other-workspace titles/timezones are reduced to Busy/UTC before leaving SQL; another user's rows are excluded. A semantic focus digest ignores provider sync metadata and is checked under the existing focus-intent lock before calendar and Work publication locks. No new migration or lock-key protocol is introduced. `generatePersonalWorkProposal` also returns its exact inputSnapshot for trusted internal workers; it is not added to HTTP responses. `createWorkSuggestionInputRevalidator` clones that input and proposal with owner, Work, focus and calendar evidence. It checks publication identity before SQL, then runs the concrete focus/calendar/Work checks in order, verifies current projected and completed Work revisions, and recomputes the private captured input digest. Use only trusted loader/optimizer output, not a client-supplied capture. Planner reoptimization migration 0086 introduces one private owner/workspace queue entry for coalesced Work, calendar, focus, policy and recovery wakeups. Exact expiring claims fence atomic publication; resource guards precede queue row locks. Exhausted jobs require explicit current-authority reproof and a matching failed revision to repair. The adapter and local tests do not activate trigger fanout, a dispatcher, or production migrations. Queue-origin planner publication uses the existing WorkProposalPersistence with native job/ref revision identity and explicit queue guards. createQueueSuggestionInputRevalidator shares the trusted focus/calendar/Work input proof without requiring a fabricated Work event. These internal adapters do not activate a worker. Planner cron /api/cron/planning-suggestions is scheduled every ten minutes for service principals and is a no-op until OPA_REOPTIMIZATION_ENABLED=1 (the global kill switch; OPA_PLANNING_SUGGESTIONS_ENABLED is no longer read). Activation requires migrations 0086, 0087 and 0130, the normal LSSM_STUDIO_DATABASE_URL, and a distinct MANAGED_COMPANYOS_PLANNING_DISPATCH_DATABASE_URL authenticated exactly as companyos_planning_dispatcher (function execution only; provision its password through the secret manager). Each run first drains due wakeups reserved with FOR UPDATE SKIP LOCKED (batch 20), then re-plans one cursor page of owners whose last run is older than two hours, within a 120 s budget and a 45 s per-owner timeout. Work mutations, task status changes and focus block changes enqueue savepoint-isolated, debounced (30 s) wakeups in their own transaction. Background planning is admitted when "Plan work" is "Suggestions only" or higher and paused by "Manual only"/"Disabled"; preconditions such as a stale calendar defer without consuming attempts, failures back off exponentially and dead-letter after five attempts until PlanningReoptimizationJobs.repair. A refreshed proposal is published only when it differs from the current plan and carries content-free diff provenance (opa.plan.refreshed); placements are never applied in the background. Notetaker bots (W5): `opa.bot_capture.*` routes under `/api/v2/opa/bot-captures/**` and `/api/v2/opa/bot-capture-settings` let a member send an Attendee notetaker bot to one Google Meet/Teams meeting after explicit recording consent and a confirmed participant notice (both recorded with the capture consent receipt in the append-only `opa_bot_capture_events` audit). Migration 0165 adds `opa_bot_captures` (encrypted meeting link, route digest, lease/attempt/dead-letter work queue), workspace settings and per-meeting switches. `/api/cron/opa-bot-dispatch` (start, observe, leave, import, provider cleanup, retention erasure) and `/api/cron/opa-bot-reconciliation` (webhook/observe wakeups over 0084) run every minute through `MANAGED_COMPANYOS_BOT_DISPATCH_DATABASE_URL` (exact `companyos_bot_dispatcher`). Callbacks arrive at `/api/webhooks/opa-bots/:routeToken` (route bound to one capture, signature verified). Global `OPA_BOTS_ENABLED=1`, workspace and meeting switches are rechecked before every provider call; switching off defers (global) or stops/leaves (workspace, meeting, lapsed consent). Recordings import into encrypted EU capture storage and finish into the EU transcription pipeline; without an EU speech model the EU-confirmed provider transcript (`OPA_BOTS_PROVIDER_TRANSCRIPT_REGION=eu`) or the recording alone is kept. Production stays off: see `docs/evidence/opa/opa-bots-production-readiness-2026-10-19.md`. Work planning enrollment: the planner and the background re-planner address an owner only through a Work identity binding (`managed_companyos_work_identity_bindings`, one per tenant, organization, workspace and user). `ensureWorkPlanningEnrollment` creates it after rechecking membership, organization authority and an enabled direct or team grant on an active, non-personal workspace, serialized per tenant, idempotent, with one `opa.work_planning.enabled` audit event. It runs on company workspace selection (best effort), on first plan generation, and from `POST /api/v2/opa/work-planning/enable` (`GET /api/v2/opa/work-planning` reports the state and never allocates). Existing users are enrolled with `bun run companyos:opa:backfill-work-planning` (`COMPANYOS_WORK_PLANNING_BACKFILL=dry-run`, then `=1`; output is per-organization counts only; re-runs report bindings as existing). Recovery counts an owner whose grants no longer allow background planning as paused rather than failed. Planner inputs optionally carry unscheduledWork for owner-selected pending items requiring an estimate. They retain Work revisions, appear as estimate_required, and never receive invented durations or placements. Existing callers default to an empty list. Task split preferences use the existing scheduling proxy and opa.work_split_preference.get/save operations. Owner identity is server-derived; saves use revision CAS plus an idempotency receipt and enqueue replanning atomically. Apply migrations 0088/0089 and verify runtime grants before deploying this workflow. Absent/null preference remains unsplit, and saving never changes the Work estimate or applies calendar effects. Production acceptance remains pending. ## Builder delivery authoring isolation Every delivery route requires an authenticated tenant. The draft workspace uses a SHA-256 tenant namespace under `WORKSPACE_ROOT/.contractspec/builder-delivery-tenants/`. Body and query fields cannot select another tenant. Actor/operator references come from the authenticated principal; caller role descriptions confer no permissions. Missing-loop preflight returns 404. Shared legacy drafts are never read as a fallback: review ownership before explicitly adopting them into a tenant workspace. This filesystem composition remains single-writer authoring storage, not the production multi-tenant state service. The authenticated CompanyOS session-authority response includes `permissionRefs` from the canonical server role-permission resolver after fresh organization authority is established. Clients must not infer permissions from `grantRole` themselves. Fleet read/manage keys are granted to the existing full-permission enterprise-admin role; narrower roles and runtime deployment authority are unchanged. Public Builder requests require an authenticated tenant. Supplied tenant IDs must match that identity; missing tenant authority and mismatches fail before runtime execution. This boundary does not activate production deployment. Authorized Builder request execution binds the authenticated tenant and principal to the existing RLS pool context. That context is scoped to the async request and does not persist into later requests. Member authoring uses fresh `contextAuthority.effectiveCapabilities`, not role names or machine capability inheritance. The route contract is `src/handlers/builder/builder-member-policy.ts`: creation needs `builder.chat.web` and `builder.fusion.resolve`; intent/read needs `builder.chat.web`; blueprint, plan, preview and readiness need their exact fusion/compile/generate/harness grants. Configure these through the existing organization/team/workspace authority store; no grants are installed automatically. Auditor and AI-operator mutations remain denied. Mutations require the exact `APP_WEB_BASE_URL` origin and the current session CSRF token. All member reads/writes check tenant, owner and original organization/team/ workspace scope. Legacy unbound workspaces need explicit adoption before member use. Creation IDs are derived from the member, scope and request ID; the original request ID can recover a lost response in the same context. Creation replay reads existing state instead of regenerating it. Member payloads cannot choose owners, providers, channels or authority. Execution/release endpoints remain outside this admission. Vercel source uploads exclude TypeScript and JavaScript test entrypoints through root `.vercelignore`. In particular, `api/index.test.js` remains part of local QA and must not appear as a deployed serverless function alongside `api/index.js`. ## Preview authentication `COMPANYOS_AUTH_PROFILE=preview-v1` selects the additive preview topology. Set `COMPANYOS_PREVIEW_WEB_ORIGIN` and `COMPANYOS_PREVIEW_API_ORIGIN` to exact HTTPS origins outside the production cookie domains. In the API, `BETTER_AUTH_BASE_URL` and `APP_WEB_BASE_URL` both equal the preview **web** origin because browser auth uses its same-origin proxy. Configure `AUTH_PROVIDER_MODE=better-auth`, a dedicated `COMPANYOS_PREVIEW_AUTH_SECRET` (at least 32 characters), and `COMPANYOS_PREVIEW_DATABASE_URL`. `LSSM_STUDIO_DATABASE_URL` must match that database; optional auth/channel database references must also match. Unset `BETTER_AUTH_SECRET`, `BETTER_AUTH_COOKIE_DOMAIN` and production federation flags. Production Vercel deployments cannot select this profile. Cookies use the `companyos-preview` prefix, no parent domain, and the preview web origin for passkeys. Provision and verify dedicated data and credentials before enabling this profile. Matching configuration strings are not evidence of actual provider isolation. Database migrations, synthetic accounts, callback behavior, session revocation, tenant checks and deployed browser sign-in still require qualification. Better Auth account identity requires `issuer` plus `account_id`. Apply tracked migration `0090` before deploying the updated Drizzle account schema. It preserves password hashes and normalizes password-bearing `credential` rows to `local:credential` plus `user_id`; ambiguous duplicates abort atomically. It does not guess OAuth issuers. Existing external accounts with a null issuer require provider-specific reconciliation and login qualification before production promotion. Newly created accounts receive the issuer from Better Auth itself. ## Standalone container hosting After `build:elysia`, `start:elysia` runs `server.mjs`, binds HTTP on `PORT` (default 3000), and handles SIGTERM/SIGINT through the app lifecycle with a bounded shutdown deadline. The Vercel adapter still imports the same application bundle. Build the package Dockerfile from the repository root. Its pinned Node/Bun build stages produce a non-root Bun runtime containing only the built API, packaged Loro runtime and standalone entrypoint. Use the root route as a process-start probe; database, identity and application-journey readiness require separate checks. In preview mode, login discovery omits email-delivery methods when Resend is not configured; password login remains available for provisioned synthetic accounts. The standalone Bun launcher emits fixed startup phases: loading, loaded and listening. Import failure and a 90-second import deadline fail startup without logging credentials or exception payloads. These markers diagnose startup; only the listening application answers health checks. ## Builder company context `builder.companyContext.resolve` and POST `/api/companyos/builder/context/resolve` accept an owned Builder workspace and a question up to 4096 UTF-8 bytes. The shared member surface invokes this query through the authenticated web BFF. Missing configuration returns 503; query failures are never retried as saved mutations. The host binds the persisted Builder workspace to its verified actor and selected company context. Current Company Intelligence Brain authorization and field projection select approved, fresh, visible entries. Contradictory sources refuse retrieval. Canonical source/version/asset/part/fragment/evidence records are checked for tenant, ACL, validity, deletion and supersession, then re-read after storage IO. Point reads filter object identity before pagination. Verified citations retain source, redaction and replay references even when the question paraphrases them. Knowledge supplies context; existing release and execution permissions still apply. ### Shared server startup Both standalone Bun and serverless requests use `getBuilderRuntimeResources`. Its first initialization reads the optional server-only `BUILDER_GROUNDING_CONFIGURATION` JSON through the versioned `BuilderGroundingStartupManifestSchema`. Unconfigured, malformed, expired or missing-secret profiles leave authoring available and grounding unavailable. `getBuilderGroundingStartupState` reports a static configuration state without secret details. A configured state is not a live qualification result. The manifest names explicit models, independent contexts, allowed tenant/workspace pairs, a request limit per minute, review/retrieval/code references and approved source objects/excerpts. It uses the existing AI provider factory and `SecretProviderManager` with environment-backed references: - `env://BUILDER_GROUNDING_MODEL_SECRET` may serve both model roles. - `env://BUILDER_GROUNDING_DRAFTER_SECRET` and `env://BUILDER_GROUNDING_VERIFIER_SECRET` allow separate accounts. - `env://BUILDER_GROUNDING_STORAGE_SECRET` contains the existing S3 connection fields: accessKeyId, secretAccessKey, HTTPS endpoint, region, bucketName and urlStyle. Keep credentials in deployment secrets, outside the manifest. OpenAI, Anthropic, Mistral and Gemini use explicit model IDs through the canonical factory. The same vendor/account can serve both roles when model identity and independence domain differ. Separate role clients receive independent prompts and contexts. Models get no tools, automatic retries are disabled, and canonical claim/citation verification remains mandatory. Each source approval binds an opaque storage reference to an exact S3 bucket/key, byte cap, SHA-256 and optional object version. Each reviewed excerpt additionally binds its evidence ID, content SHA-256 and redaction decision. Only matching canonical text/plain line excerpts enter a model. Asset reads are bounded to 1 MiB and excerpts to 16 KiB. PDF/media extraction requires another qualified profile. Storage cancellation bounds waits and requests stream teardown; it does not independently establish that remote IO stopped. The profile scope intersects existing Brain authority. It does not grant an operations manager administrative content access. Eligible model requests consume the existing tenant/principal Company Intelligence request quota first; unavailable quota persistence fails closed. The runtime needs source/Brain SELECT permission and the existing `managed_companyos_ci_api_budgets` SELECT/INSERT/UPDATE path under FORCE RLS. Source provisioning remains an operator-owned canonical repository operation. Request quotas do not replace monetary reservation/reconciliation. Configuration and clients are reused across warm requests. Deploy/restart after changing a manifest or environment-backed secret. Trusted tests or explicit host compositions can still use `configureBuilderRuntimeGrounding` before the first initialization; rebinding an active singleton is refused. ### Qualification status Actual Railway S3 and constrained PostgreSQL qualification verified six canonical records and the exact 176-byte synthetic source, including replay with zero new effects and cross-tenant denial. The complete SQL-to-answer composition is tested with mock model/storage ports. Live model connections, cancellation, redaction, spend reservation and full member journeys require separate qualification before production acceptance. No member Brain grant or model call is implied by the source-read proof. ### Critical production schema build gate The Vercel production build first runs `scripts/critical-schema-preflight.ts`. It requires `account.issuer` (text) on the resolved authentication database and `opa_google_availability_snapshots.query_binding` and `managed_companyos_personal_briefing_deliveries.generation_provenance` (jsonb) on the runtime database. The probe uses a read-only PostgreSQL session, metadata inspection and zero-row SELECTs, with five-second connection, ten-second statement and five-second close bounds. Missing configuration, incompatible columns or unavailable read access fail the build; previews explicitly skip without qualification. Credentials and SQL error details are never printed. The gate never migrates or reads customer rows. Use the existing authorized migration workflow to repair prerequisites. This proves only these columns and read access, not account reconciliation, all migrations, booking journeys or full readiness. The snapshot column is derived from current source requirements, not a confirmed diagnosis of the particular column behind the observed production SQLSTATE 42703. This app-owned deployment contract is not an operation spec; no CLI operation-validation success is claimed. Planner rollout preflight v1.1 rejects missing or duplicate required catalog entries and checks physical topology_version, workspace_id and query_binding columns, including migration 0091 prerequisites. Failures remain content-free. It is read-only: it does not apply migrations, repair schema, or prove provider execution and full workflow readiness. ### Calendar briefing model provenance Apply migration 0092 before deploying the briefing store: finish writes nullable generation_provenance JSONB even for deterministic drafts. Legacy receipts remain unqualified with null provenance. CompanyOS keeps direct Mistral disabled. Gateway generation additionally requires the private-processing admission adapter described in "AI-written, cited briefings (OPA)" above; without it the labelled template is sent. Accepted generation requires supplied citation validation, explicit served EU/provider evidence, stop completion, text-only output and post-generation admission recheck. Prompt size is bounded to 80000 serialized characters. Neither environment configuration nor a briefing delivery toggle grants private-processing authority. No live activation is established by this slice. ### AI-written, cited briefings (OPA) Morning recaps, meeting preparation, preview e-mails and private drafts share one generator (`src/calendar/opa-ai-briefing-*`). A briefing is written through the Vercel AI Gateway only when the private-processing admission adapter admits the owner. Otherwise the deterministic template is sent and labelled ("Standard template — "). Admission requires, in order: 1. `OPA_AI_BRIEFINGS_ENABLED=1`; 2. the approval references `OPA_AI_BRIEFINGS_PROCESSING_APPROVAL_REF` and `OPA_AI_BRIEFINGS_GATEWAY_TRANSIT_APPROVAL_REF`, and a Gateway credential resolved per request by `@lssm-tech/lib.ai-providers/vercel-gateway-auth`: `AI_GATEWAY_API_KEY`, else on Vercel the invocation's `x-vercel-oidc-token` header (pinned to `VERCEL_PROJECT_ID` when exposed), else `VERCEL_OIDC_TOKEN`. Cron, preview, settings and draft routes pass their request, so scheduled runs on Vercel Functions authenticate too; 3. the owner's explicit opt-in (Settings → Personal briefings → AI briefings). It is stored in the owner-only consent record and bound to a digest of the processing policy (catalog, EU routing, zero retention, no training, sent fields, approvals). A policy change makes the consent stale and asks the owner again; 4. an organization automation policy that does not disable `intelligence.generate`, plus the `opa.meeting_outcome.analyze` capability; 5. a model from the shared catalog `@lssm-tech/lib.provider-spec/gateway-model-catalog`. Model precedence: owner override → workspace default → `OPA_AI_DEFAULT_MODEL` → catalog default. Organization owners and admins with the enterprise-admin grant set the workspace default (migration `0125`, `opa_ai_briefing_workspace_models`). Before `0125` is applied the workspace default reads as empty and cannot be changed; everything else works. Only event titles, times, attendee display names and agendas are sent. E-mail fallbacks for attendees are reduced to their local part, and links, e-mail addresses and phone numbers are removed from agendas. Company knowledge is added only when the owner selects it. Every claim must cite a supplied source: unknown citations are removed, uncited claims are dropped, and output without a cited summary falls back to the template. Admission is re-proved before and after each call, and the served route must prove EU inference. AI briefings record provenance 1.1.0 in `generation_provenance`: model, prompt version, sources digest, generation time, model source and citation count. Settings changes append `companyos.calendar_intelligence.ai_briefings.settings_changed` to `managed_companyos_audit_events`. Endpoints: `GET|POST /api/companyos/opa/briefings/ai-settings` (owner) and `GET|POST /api/companyos/opa/briefings/ai-settings/workspace` (administrators). `GET /api/companyos/health/degraded` reports the secret-free `opaAiBriefings` status (`enabled`, `disabled_flag`, `missing_approval`, `no_gateway_auth`); it never degrades overall health. ### Meeting context sources (OPA preparation and AI briefings) `src/organization-planning/meeting-context/` binds one aggregate knowledge source, `knowledge:companyos-meeting-context`, into meeting preparation (next to the Work Graph source) and into AI briefings. On every load it re-reads the owner's source choices (stored with the AI processing consent; revoked consent enables nothing) and runs each enabled adapter inside a `MeetingContextSourceBudget` (items, bytes, time, and source TTL). Cacheable sources retain their snapshot TTL (15 minutes by default); PersonalOS results are never cached, so every preparation/reproof read revalidates current consent, expiry, revocation and retention. A failing or slow adapter adds nothing and logs `opa_meeting_context.source_collected` with a stable code; no provider id, e-mail address or message body is logged. | Owner kind | Adapter | Store / grant | | --- | --- | --- | | `tasks` | open Work tasks, personal workspace | Work event log, `workspace.read` | | `communication-history` | meeting threads + recent messages | CommunicationOS journal, owner personal scope | | `participants` | attendees × HubSpot contacts | live calendar read + `opa_oauth_tokens` `hubspot` | | `drive`, `notion`, `slack` | title search, metadata only | `opa_oauth_tokens` `google-drive`, `notion`, `slack` | | (preparation only, consent-gated) | PersonalOS context | PersonalOS consumer bridge; current `companyos_meeting_context` consent | The PersonalOS bridge stays fail-closed until `OPA_PERSONALOS_BRIDGE_URL` and `OPA_PERSONALOS_BRIDGE_TOKEN` are configured. AI briefing reads do not bind it. Disabling its result cache changes no other source TTL or item, byte or timeout budget, and does not create a sharing grant. `OPA_MEETING_CONTEXT_SOURCES` (comma list: `communication-history`, `participants`, `drive`, `notion`, `slack`, `hubspot`) decides which kinds the deployment offers; unset offers none, so deploying changes nothing. Grants use `accountRef = individual:` in the physical tenant. Token refresh uses `GOOGLE_DRIVE_OAUTH_CLIENT_ID/SECRET` (Drive's own Google client; refused when it equals the calendar client, because Google revocation drops every scope a user granted one client) and `HUBSPOT_OAUTH_CLIENT_ID/SECRET`. #### Meeting context connections (OAuth connect flows) `meeting-context/oauth-connect-routes.ts` implements `OPA_MEETING_CONTEXT_CONNECTIONS_CONTRACT` (organization-planning spec) for the owner's personal grants. The routes are composed into the personal-briefings plugin, so the web BFF reaches them under `/api/companyos/opa-os/briefings/meeting-context/*`: | Route | Gate | Answer | | --- | --- | --- | | `GET …/meeting-context/connections` | session + personal context | per provider: `connectable` (listed in `OPA_MEETING_CONTEXT_CONNECT_SOURCES` and an OAuth client set), `offered` (listed in `OPA_MEETING_CONTEXT_SOURCES`), `state` | | `POST …/meeting-context/{provider}/connect` | trusted web origin | `{ authorizationUrl }` (https consent page) | | `GET …/meeting-context/{provider}/callback` | the same session | always 303 to `/companyos/opa-os/settings?meetingContext=connected\|failed&provider=…[&reason=…]`; an ended session is `reason=session_required` | | `POST …/meeting-context/{provider}/disconnect` | trusted web origin | `{ provider, state: 'not_connected' }` | Providers and consent scopes: `google-drive` (`drive.metadata.readonly`, PKCE, offline access; client `GOOGLE_DRIVE_OAUTH_CLIENT_ID/SECRET`, never the calendar one), `notion` (owner=user; `NOTION_OAUTH_CLIENT_ID/SECRET`), `slack` (user scope `search:read`, token rotation off; `SLACK_OAUTH_CLIENT_ID/SECRET`) and `hubspot` (`oauth crm.objects.contacts.read`; `HUBSPOT_OAUTH_CLIENT_ID/SECRET`). The provider redirect URI is the API callback, `${BETTER_AUTH_BASE_URL}/api/companyos/opa/briefings/meeting-context//callback` (default origin `https://api.companyos.run`), and must be registered with each provider app. A provider shows "Connect" only once the operator lists it in `OPA_MEETING_CONTEXT_CONNECT_SOURCES` (`drive`, `notion`, `slack`, `hubspot`) after registering that redirect URI and scopes, so a client already set for refresh never sends owners to an unprepared consent page. The OAuth state is sealed with the BYOK cipher under the owner's personal tenant key and names the provider, user, a session digest, the PKCE verifier and a ten-minute expiry. The single live attempt per owner and provider is recorded in `opa_oauth_tokens` (provider `meeting-context-oauth-state:`) and consumed under a row lock before the code exchange, so a replayed, parallel or superseded callback fails without a provider call. The row holds only the nonce digest; one inert row per owner and provider remains until the personal context is deleted. A grant missing the source's required scope, or one the vault fails to store, is revoked and not stored. Grants are stored under the reader key above. Disconnect asks the provider to revoke (Google, Slack, HubSpot; Notion has no revocation endpoint, so the owner removes the integration in Notion), then overwrites the row with an inert token: `opa_app` has no DELETE policy on `opa_oauth_tokens`, so the delete only succeeds for a role that may delete. Connecting never enables a source. List a kind in `OPA_MEETING_CONTEXT_SOURCES` only after its connect flow passed an end-to-end canary on the deployment. The PGlite suites (`*.pglite.test.ts` in `meeting-context/`) run against a disposable local PostgreSQL instead when `OPA_MEETING_CONTEXT_TEST_DATABASE_URL` names a local server (each file creates and drops its own database). Vercel delegates API production builds to `scripts/vercel-build.ts`, keeping the configured command below the platform limit. The orchestrator runs the critical-schema gate before crypto utilities, LSSM OS contracts and API compilation, and stops on the first failure. Runtime schema diagnostics distinguish absent columns from incompatible types, inspect role attributes and the planning migration ledger, and optionally compare the expected Supabase project/database. Only status and coarse classifications are returned; the script does not print connection details, read customer rows, migrate or grant authority. ## Builder candidate routes `POST /api/companyos/builder/plans/{prepare,approve,execute,status}` uses the existing member/session/CSRF admission and Builder capabilities. Prepare/status require `builder.plan.compile`; approve/execute require `builder.plan.execute`. The server resolves identity and workspace scope, strips caller authority, and forwards only reviewed plan reference and request identity to the runtime. Returned available actions are intersected with current actor capabilities. Configure the concrete `BuilderCandidateService` through trusted runtime composition; no default approval, order issuance or successful execution exists. Private briefing consent and non-delivering draft previews require migrations 0093/0094. Explicit consent binds model and source scope; signed one-use human-command receipts bind current policy and inputs. Failed generation does not silently rerun under the same command. Concurrent revocation can wait behind active shared locks, and new-table retention/deletion integration remains incomplete; these routes are not production-qualified. Microsoft identity and isolated OAuth storage require 0095/0096, with legacy Microsoft state/credential reconciliation before cutover. Local/test reset now removes private draft command receipts, processing consents and Microsoft identity/OAuth state before personal context rows. This prevents stale authority surviving a test reset; it does not implement production erasure or retention, which remain separate outstanding workflows. The new Microsoft-only vault uses encryption domain v2, binding tenant, workspace, user, provider purpose and account reference. Ciphertext copied between accounts or OAuth/PKCE purposes fails authentication. It does not accept the earlier unactivated owner-only domain; any pilot rows written with that draft implementation require controlled reauthorization rather than silent decryption fallback. This does not change the shared Google vault. Microsoft vault envelope v3 supersedes the local v2 draft and additionally authenticates scopes/expiry. Reads reject metadata mismatches; no old envelope is silently accepted. No production vault migration or Microsoft activation is claimed. Private briefing handlers use the existing streaming bounded JSON reader: draft input is capped at 4096 bytes and processing consent at 64000 bytes. Oversized bodies return 413 after authentication/origin checks and before service execution; malformed/non-object JSON returns 422. ## Local Builder installation From this package, enroll a private local owner once: ```sh bun scripts/install-local-builder-owner.ts /absolute/local/auth http://127.0.0.1:43119 local-tenant local-workspace 'Local Builder' bun scripts/serve-local-builder.ts /absolute/local/auth /absolute/local/authoring ``` Enrollment writes a private owner profile and prints only its path. Do not expose or commit that file. The launch command binds the configured loopback origin and exposes no public signup or organization administration. Pair through `POST /local/auth/pair` with the configured Origin and the local pairing credential as Bearer authentication; the result sets an HttpOnly session cookie. Subsequent Builder mutations require that cookie, the exact Origin and `x-csrf-token` equal to the session ID returned by `GET /local/auth/session`. The shipped launch command enables durable authoring only. It does not configure candidate execution. Programmatic `createLocalBuilderApplication` may receive a qualified candidate service composed by `createBuilderCandidateLocalHost`; all project, topology, worker, policy, signing and recovery evidence must be supplied explicitly. Grant removal is reread for every session check; new grants cannot broaden an already-running local authority. Sign-out revokes the current session. Close drains in-flight work before database shutdown. An unconfirmed drain retains storage ownership for reconciliation. This local API increment does not claim a complete console UI, live generated candidate, hosted preview or release workflow. `verifyEncryptedBackup` authenticates the complete encrypted backup stream, validates manifest sizes/hash and computes a plaintext digest without returning or writing plaintext. It retains restoreVerified:false: cryptographic integrity is not a PostgreSQL restore rehearsal, independent key custody or PITR qualification. Submit an outcome to the running local authoring API without manually copying cookies or session IDs: ```sh bun scripts/local-builder-intent.ts /absolute/local/auth 'Create an accessible project checklist' ``` The command reads the private local profile, pairs through AuthOS, submits the intent with session/CSRF binding, and signs out its temporary session. Output contains only the workspace identity and acceptance status. It does not execute a candidate, call a model, or ship a release. ### Personal Microsoft calendar OAuth Personal connection contracts expose POST `/api/v2/opa/personal-calendar/microsoft/authorize` and GET `/api/v2/opa/personal-calendar/microsoft/callback`. Ownership comes from the authenticated personal context. PKCE state and encrypted credentials use the Microsoft-only owner-scoped storage; callbacks pin verified Microsoft identity. These operations do not yet provide calendar discovery or qualify booking/planning integration. Production activation requires configured Microsoft credentials/callback, migrations and least-privilege grants, followed by real account acceptance. GET `/api/v2/opa/personal-calendar/microsoft/calendars` enumerates the current personal connection through the verified account runtime. Its response is bounded and excludes raw provider identifiers and credentials. Calendar selection and planner activation remain separate steps. **Graph scopes (least privilege).** The app requests exactly `offline_access` (refresh), `User.Read` (`GET /me` id pinned before credentials persist) and `Calendars.Read` (calendar list and `calendarView` reads). CompanyOS writes nothing to Microsoft calendars (focus blocks and bookings go to Google only), so `Calendars.ReadWrite` is no longer requested; grants consented earlier with it stay valid. The Entra app registration only needs these delegated permissions; a future Microsoft write effect needs a reviewed scope change and owner re-consent. **Reauthorization.** A refresh refused by the Microsoft identity platform (`invalid_grant` — expired/revoked refresh token, revoked consent —, `interaction_required`/`consent_required`/`login_required`, or any other 400/401 except `invalid_client`/`unauthorized_client`) moves the personal `opa_calendar_connections` row from `connected` to `reauthorization_required` and enqueues one `opa.calendar.reauthorization_required` outbox alert (`providerKind: microsoft`), in a fresh transaction after the failed read rolled back. The maintenance cron relays it as one en/fr/es email to the owner, linking `/companyos/opa-os/settings`. Discovery, selection save and briefing reads then answer `409 CALENDAR_REAUTHORIZATION_REQUIRED` without calling Microsoft until the owner reconnects; a successful OAuth callback restores `connected`. 429/5xx/`temporarily_unavailable`/timeouts are transient (`503 MICROSOFT_CALENDAR_UNAVAILABLE`, `Retry-After` when Microsoft sent one) and never change state; `invalid_client` is logged as `microsoft_calendar_connection.client_rejected` (operator fault). GET `/api/v2/opa/personal-calendar/microsoft/health` returns `{ reauthorizationRequired, checkedAt }` from stored state only; the web shell uses it for the reconnect banner on every OPA page. Recorded-shape fixtures for these responses live in `packages/integrations/provider-calendar/test/fixtures/microsoft/`. ### Published profile handle reservations Apply migration `0097` before deploying profile draft-renaming changes. It permits separate live and draft reservations while retaining global handle uniqueness. Backfill aborts on conflicting historical claims; operators must reconcile those claims without stealing another profile’s handle. Publication releases the previous reservation in the same transaction as its public-pointer update. ### Native scheduling authorization Personal scheduling mutations accept verified native bearer sessions without an Origin header. Invalid bearer credentials never borrow a browser cookie session. Cookie-authenticated browser requests retain exact-origin validation. Domain session, membership and policy checks remain required; transport authentication alone grants no scheduling effect. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. --- ## @lssm-tech/app.api-founder-suite-monolith Description: (none) Path: packages/apps/api-founder-suite-monolith URL: /llms/app.api-founder-suite-monolith # Tendframe Founder Intelligence API Standalone Elysia host for Tendframe Founder, Executive, and Talent Intelligence. Tendframe is the public name of the existing founder product. Stable `PACTENA_*` keys, `app_pactena`, `pactena-web`, database schemas, scopes and HTTP headers remain unchanged. Explicit `BETTER_AUTH_BASE_URL`, `APP_WEB_BASE_URL` and `MARKETING_WEB_BASE_URL` settings override the new Tendframe defaults so a legacy-origin deployment can remain active until the new origins are qualified. Before switching origins, deploy/reconcile the AuthOS catalog's additional `https://app.tendframe.me/auth/callback/lssm` registration on the identity authority. The legacy exact callback remains registered. The API selects its callback from the configured app origin and rejects unregistered origins; existing invite-only, security-review, client-secret and CORS gates are retained. Peer issuer defaults remain `https://api.pactena.run` until their owners migrate the corresponding registrations. The default email display name is Tendframe, while the existing verified `notifications.pactena.run` sender address is retained. The PostgreSQL and independent AuthOS layers are live; optional email and AI capabilities remain truthfully blocked until their provider credentials exist. ## Environment Server-only variables: - `PACTENA_DATABASE_URL` - `PACTENA_DATABASE_RUNTIME_ROLE` pins the exact non-owner login expected by startup and readiness. The role must own no tables and must not create roles, databases, or schema objects, replicate, or bypass RLS. Runtime readiness verifies public schema structure and grants but leaves the forced-RLS SEO seed inspection to the explicit migration-owner verification lane. - `PACTENA_WAITLIST_DATABASE_URL` (low-privilege waitlist writer) - `DATABASE_URL` is never accepted. The waitlist credential must resolve to the same protocol/host/port/database identity as `PACTENA_DATABASE_URL`. - `BETTER_AUTH_SECRET` - `BETTER_AUTH_BASE_URL` (defaults to `https://api.tendframe.me`) - `APP_WEB_BASE_URL` (defaults to `https://app.tendframe.me`) - `MARKETING_WEB_BASE_URL` (defaults to `https://tendframe.me`) - `PACTENA_LSSM_RP_ENABLED`, `PACTENA_LSSM_RP_SECURITY_REVIEW_REF`, and `PACTENA_LSSM_RP_CLIENT_SECRET` for the reviewed central LSSM OIDC relying party. Enablement without review evidence or a 32+ character secret fails startup closed. - `PACTENA_MEMBERSHIP_PROVISION_TOKEN` is the 32+ character, server-only token used by central AuthOS to idempotently create an `app_pactena` membership. Product routes require that local membership even when a Better Auth session exists. - `PACTENA_GOVERNED_DATA_DATABASE_URL` selects the separate product-local encrypted projection-copy store. `PACTENA_GOVERNED_RECOVERY_TOKEN` is its distinct 32+ character central-worker bearer; `PACTENA_GOVERNED_DATA_AUTO_MIGRATE=true` and `PACTENA_GOVERNED_DATA_SSL_MODE=require|allow|prefer` control explicit schema activation and transport. Do not enable the central Tendframe recovery origin until every governed projection copy uses this canonical store. Export stays unavailable until a Tendframe source exporter is bound. - `PACTENA_GOVERNED_DATA_REGION` and the secret-manager JSON value `PACTENA_GOVERNED_MATERIALIZATION_BINDINGS` jointly enable encrypted-copy admission at `/internal/governed-data/materializations/:sourceApplicationId`. Each array record has exact keys `sourceApplicationId` and `bearerToken`, and each source-to-Tendframe pair uses a distinct 32+ character bearer. Omit both to keep materialization unavailable while recovery remains active. Partial topology, unknown sources, purpose/field/region/expiry/retention/key drift, and plaintext fail closed before persistence. Production also requires the receiver key service and retention cleanup to be qualified. - `PACTENA_VAULT_ENCRYPTION_KEY` - `PACTENA_WAITLIST_TOKEN_SECRET` - `CRON_SECRET` - `OPENAI_API_KEY` and optional `PACTENA_OPENAI_MODEL` (`gpt-5.6-luna`) - `MISTRAL_API_KEY` and optional `PACTENA_MISTRAL_MODEL` (`mistral-small-2603`) - `RESEND_API_KEY` and `AUTH_EMAIL_FROM` - `PACTENA_FORMS_MILESTONES` (`forms.v0` by default, or `all`) - `PACTENA_FORMS_VERIFICATION_ENDPOINT`, bearer token, and channel list - `PACTENA_FORMS_AI_ENDPOINT`, bearer token, provider ID, and self-hosted flag - `PACTENA_FORMS_DEFENSE_ENDPOINT`, bearer token, and identifier secret for distributed fail-closed abuse control - `COMPANY_OS_METRICS_API_ORIGIN`, `COMPANY_OS_METRICS_PACTENA_ISSUER`, and `COMPANY_OS_METRICS_PACTENA_SHARED_SECRET` for short-lived, scope-bound CompanyOS metric session exchange The `/api/v1/company-metrics` peer proxy has an explicit operation allowlist, requires the Tendframe application origin and an idempotency key for mutations, and derives company scope from fresh session authority. Founder-private scope is not representable by this proxy. No provider key or database URL has a fixture fallback in production. ## Conversations, notifications and calendar The CommunicationOS BFF under `/api/v1/communication-os/*` exchanges the session for a scoped CommunicationOS bearer and forwards an explicit operation allowlist. It includes the canonical contract send `POST /api/v1/communication-os/communication/message/send/v3.0.0` used by the shared client: the app origin, a matching `idempotency-key` header and body `idempotencyKey`, and the session-derived workspace and space are required, so a retry replays the original message and a founder-private room never accepts a company-scoped send. Reconnect uses `POST .../v2/auth/realtime-ticket` and cursor replay through `GET .../v2/events`. `GET` and `POST /api/v1/notification-preferences` are the Tendframe preference center over `@lssm-tech/lib.notification/product-channels`: in-app is always on and updates are revision-checked. An update sends `expectedRevision`, `globalEnabled`, `enabledChannels` and `consentedChannels`; the BFF mints each consent ref from the session (person, channel and new revision), so email is enabled only with that explicit consent and a client never supplies consent evidence. Responses list `consentedChannels`, never the refs. A stale revision answers `409 idempotency_conflict`, the conflict code of the Tendframe error vocabulary. `POST /api/v1/calendar/intake` imports upcoming founder-private calendar meetings the founder has not declined as digest-only OPA meeting workspaces through the shared intake materializer, and answers only its counts. Both mutations require the app origin and `x-csrf-token` equal to the session id, like the meeting workspace, and cap the body (8 KB for preferences, 1 KB for intake, which takes none); the CommunicationOS send reads at most 64 KB even for chunked uploads. Both answer `503 dependency_unavailable` until a preference store and CommunicationOS admission host, or a calendar connection host and intake materializer, are bound; nothing is bound in the deployed host today. Public signup remains disabled. Direct magic links resolve existing invited emails only. When the reviewed LSSM relying party is enabled, the local Tendframe identity may be projected from a centrally authenticated email only after the central `app_pactena` entitlement gate succeeds; the exact product scope is requested and no ecosystem cookie is shared with Tendframe. Central activation also unregisters Tendframe's local magic-link plugin and email callback. Disabling the RP restores that existing-email path as the explicit rollback authority; the two authorities are never enabled together. Forms management is exposed at `/forms`, public forms at `/f/{opaqueToken}`, and the API at `/api/forms/v1`. Migrations `0003_forms_platform.sql` and `0004_forms_scope_hardening.sql` are the Tendframe-owned immutable Forms schema and row-bound public-access upgrade. ## Database lifecycle Database changes never run during startup or request handling. Operators use the explicit `database:plan`, `database:bootstrap:fresh`, `database:adopt-0001`, `database:migrate`, `database:verify`, `database:snapshot:verify`, `database:reset:nonlive`, and `database:prove:postgres` scripts. Mutating lanes require an evidence reference; the non-live reset additionally requires a typed allowlisted fingerprint, a fresh encrypted snapshot receipt, provider effects disabled, and approved same-task Connect decision plus passed replay artifacts. Migration `0001` remains immutable at `sha256:216989309872df7873bb983ec37439c68c93bb8e0165035b93eadb4e6f86daff`. Tendframe-owned migration `0002` creates the fresh-only 31-table OPA v2 schema, pins all 28 owner tables to `product_ref='pactena'`, and records both versions in `pactena_owned_migration_ledger`. Adoption verifies the exact `0001` catalog before recording provenance. Full reset/adoption execution remains blocked until external database, snapshot, and Connect authority exists. Migration `0005` installs the forced-RLS governed meeting workspace tables; `0007` adds digest-only public access grants and `0008` adds owner-scoped calendar occurrence mappings plus immutable recorder-review evidence. `0009` adds recurring intake definitions and expiring, token-fenced execution leases. The Elysia host mounts the nineteen exact `/api/v2/opa/meeting-*` and `/api/v2/opa/smart-meetings/*` operations with Better Auth session-derived organization scope. Mutations require the Tendframe app origin and the current session id as CSRF evidence. Meeting content is recovered from an encrypted, optimistically versioned owner aggregate; approval, artifact, dispatch, CRDT, share, recorder, and outbox evidence remains on the dedicated SQL surfaces. The current fresh schema contains exactly 84 public tables: 18 immutable Tendframe baseline tables, 52 OPA tables, 12 Forms tables, `pactena_product_memberships`, and `pactena_owned_migration_ledger`. Forms verification is pinned to the 12 tables created by immutable migrations `0003`/`0004`; newer shared Forms features require an explicit Tendframe migration. It deliberately preserves unrelated tables. Reset authorization, snapshot proof, and Connect replay remain pending; this inventory does not authorize execution. The read-only readiness probe reports bounded verification phases (`ledger`, `tables`, `inventory`, `rls`, `grants`, `products`, or `seed`) and a safe SQLSTATE. It never logs SQL, credentials, connection details, or provider error messages. Privilege repairs must use the explicit same-database `PACTENA_DATABASE_MIGRATION_URL`; never grant ledger access to `PUBLIC`. --- ## @lssm-tech/app.api-library Description: (none) Path: packages/apps/api-library URL: /llms/app.api-library # @lssm-tech/app.api-library **Library API server for ContractSpec documentation and templates. Thin HTTP layer over `bundle.library`.** > Hosted MCP endpoints were previously removed (zero hosted MCP compute; MCP ships locally via `contractspec mcp`). As of the api-monolith-elysia-convergence, the **builder, channel/control-plane, dispatch, schema, and in-process scheduler hosting has been converged into `@lssm-tech/app.api-application-monolith`** (the managed CompanyOS Elysia host). This server now serves ONLY: > > - `/mdx/*` markdown (the deliberate survivor, backed by `bundle.marketing`), and > - the provider webhook ingress (Slack/Telegram/GitHub/WhatsApp), kept LIVE in parallel until the provider webhook URLs are repointed to the monolith host (human-gated). The webhook routes are stripped in a follow-up after repoint is confirmed. > > The Vercel project (`contractspec-library-api`) is retained for markdown + the gated webhook survivor. ## What It Does - Markdown + webhook survivor — a thin HTTP layer; business logic lives in `bundle.library` / `bundle.marketing`. - `src/handlers/` retains: `markdown-handler`, the 4 webhook handlers, and the channel/builder runtime resources the webhooks ingest through. - Control-plane / channel dispatch / builder / schema endpoints are no longer served here — see `@lssm-tech/app.api-application-monolith`. - Related ContractSpec packages include `@lssm-tech/bundle.library`, `@lssm-tech/bundle.marketing`, `@lssm-tech/bundle.workspace`, `@lssm-tech/integration.provider-messaging`, `@lssm-tech/integration.runtime`, `@lssm-tech/lib.contracts-spec`, ... - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `packages/apps/api-library`: - `bun run dev` - `bun run start` - `bun run build` ## Usage ```bash bun run dev ``` ## Architecture - This app is a thin HTTP layer — all business logic lives in `bundle.library`. - Elysia server exposing GraphQL, webhooks, control-plane, and channel handlers (no MCP endpoints). - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - This package is a deployable application rather than a library with published subpath exports. ## Local Commands - `bun run dev` — bun run --watch src/index.ts - `bun run start` — bun run ./dist/index.js - `bun run build` — bun run build:types && bun run build:bundle - `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 clean` — rm -rf dist api/dist - `bun run build:bundle` — bun build --target node --packages bundle --outfile dist/index.js src/index.ts && mkdir -p api/dist && cp dist/index.js api/dist/index.js - `bun run build:types` — tsc -p ./tsconfig.json --noEmit - `bun run postinstall` — if [ "$VERCEL" = "1" ]; then bun run build:bundle; fi ## Recent Updates - Removed the hosted MCP endpoints (docs/cli/internal/contracts); MCP now ships locally via `contractspec mcp`. - Replace eslint+prettier by biomejs to optimize speed. - Resolve lint, build, and type errors across nine packages. - Expose contract management via CLI and MCP. - Stabilize lint gate and runtime contract typing. - Add ai-native messaging channel runtime. - Inline server into index.ts and add Vercel configs. ## Notes - Keep this app thin — no business logic here; delegate to `bundle.library`. - MCP is no longer hosted here; agents/editors must use the local `contractspec mcp` stdio servers. The reusable MCP builders still live in `bundle.library` (`createDocsMcpHandler` remains used by `app.web-landing`). - API route changes require coordinating with `app.web-landing` and any external clients. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. ### Railway prebuilt lane The [bounded prebuilt helper](../../../deploy/vercel-prebuilt/README.md) builds this app on an explicitly bound Railway executor, audits its standalone Bun function and Node-compatible markdown adapter, and permits only digest-bound Vercel prebuilt delivery. Preview qualification is recorded separately; production promotion and other apps are outside this first lane. --- ## @lssm-tech/app.cli-contractspec Description: CLI tool for creating, building, and validating contract specifications Path: packages/apps/cli-contractspec URL: /llms/app.cli-contractspec # @lssm-tech/app.cli-contractspec Website: https://contractspec.io **Slim CLI host for authoring, materializing, and validating ContractSpec targets.** The optional AI, Builder and examples contribution exports include generated declarations under `dist/types/optional-contributions`. `build:all` emits these from their explicitly typed sources with isolated declaration generation; the ordinary `build` still runs the complete CLI typecheck before bundling. Published type exports therefore resolve without shipping the source tree. ## What It Does - **Core commands** (`src/commands/`) - Authoring, validation, workspace, release, registry, OpenAPI, Connect, CI, doctor, and maintenance surfaces. - **Command packs** - Optional command families discovered from direct consumer dependencies carrying `contractspec.commandPack` metadata. - **Prompts** (`src/commands/create/wizards/`) - Interactive UI using `@inquirer/prompts`. - **CLI setup** (`src/index.ts`, `src/cli.ts`) - Commander.js configuration. - **Types** (`src/types.ts`) - CLI-specific types. - **Services** (`@lssm-tech/bundle.workspace/services/`) - Core use-cases. - `create.ts` - Authored target creation logic. - `build.ts` - Runtime/package materialization from authored targets. - `openapi.ts` - OpenAPI export. ## Delivery onboarding and orchestration Initialize incrementally without selecting a CI or cloud provider: ```bash contractspec init --preset delivery-local contractspec init --preset delivery-hybrid contractspec init --preset delivery-managed ``` The public orchestration commands retain the specialist Connect, Builder, and Harness commands underneath them: ```bash contractspec delivery plan --input delivery-material.json contractspec delivery profile --input project-profile-material.json --output project-profile.json --json contractspec delivery autonomy --policies autonomy-policies.json --context authenticated-scope.json --json contractspec delivery status contractspec delivery verify --plan .contractspec/delivery/plan.json contractspec delivery replay --digest sha256:... contractspec quality plan --input quality-material.json contractspec quality run --plan quality-plan.json --registry quality-registry.ts --config runner.json contractspec quality verify --plan quality-plan.json --receipt quality-receipt.json ``` The local ledger is content-addressed and tamper-evident for replay, but it is not production authority. Managed promotion still requires durable Connect read-back and an exact promotion permit. ## Running Locally From `packages/apps/cli-contractspec`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage ```bash bun run dev ``` ## Optional command packs The default install intentionally excludes specialist command families. Install only the packs a workspace uses: ```bash bun add @lssm-tech/integration.cli-contractspec-design bun add @lssm-tech/integration.cli-contractspec-ai bun add @lssm-tech/integration.cli-contractspec-builder bun add @lssm-tech/integration.cli-contractspec-examples ``` The host discovers packs only from the consuming workspace's direct dependencies. Loading is deterministic by package name, duplicate command names and pack load failures stop startup before argument parsing, and `.contractsrc` can explicitly include or exclude packages (exclusion wins): ```jsonc { "commandPacks": { "include": ["@lssm-tech/integration.cli-contractspec-design"], "exclude": [] } } ``` Use `createCoreProgram()` when an embedding needs the synchronous, pack-free program. `createProgram()` performs discovery and is asynchronous: ```ts import { createCoreProgram, createProgram, } from "@lssm-tech/app.cli-contractspec"; const coreProgram = createCoreProgram(); const program = await createProgram({ consumerRoot: process.cwd() }); ``` Calling an optional command without its pack prints the corresponding install hint. See `docs/migrations/cli-command-packs-v7.md` for the major-version migration. ## Local Connect review authority ### Durable host-hook authority Contracts-spec host hooks deny by default unless the repository host injects a trusted `HookAuthorityPort`. Environment-selected modules are never loaded as authority. Production hosts construct the port with `createSingleNodeHookAuthorityPort` from `@lssm-tech/integration.lssm-os-state-sqlite`, a migrated driver, the real Connect signature verifier, and a live binding resolver. Hook payloads carry the signed V1 request as `authorityRequest`; session start also carries a caller-generated `sessionCapability` through the dedicated one-use input. Only its signed SHA-256 commitment and opaque session reference reach durable state, receipts, and output. Local patch-verdict JSON is never treated as signature or live-binding authority. ### Host hook run modes With `--host claudecode|codex|cursor` and no durable authority wired, a hook evaluates Connect policy first (deny and rewrite always block), then lets the agent host's `permission_mode` decide whether the operator is asked: | Host mode | Run mode | Governed actions | | --- | --- | --- | | `bypassPermissions`, `dontAsk` | `autonomous` | never asked; destructive commands and immutable paths are denied with a reason | | `auto`, `acceptEdits` | `assisted` | asked only for high-criticality actions (protected paths, governance roots, review commands, `git push`/`merge`) or review verdicts | | `default` | `supervised` | asked | | `plan` | `readonly` | denied | Shell policy covers every command a line runs: `cd && git push --force`, `git -C push -f`, `git push origin +ref`, `bash -c "..."` and `pwsh -Command "..."` are denied like the plain force push, in every run mode. The generated Claude Code hooks govern both the `Bash` and `PowerShell` tools. An operator can grant a bounded mode for the current worktree, including `full` (never asks; only policy denies block): ```bash contractspec connect mode show contractspec connect mode set autonomous --for 8h --scope packages/domains --reason "overnight refactor" contractspec connect mode clear ``` `.contractsrc.json` `connect.runModes` sets `default` (hosts that report no mode), `hostModes`, `maxLevel`, and extra `highCriticalityPaths`; `connect.durableAuthorityRequired: true` caps every run mode at `supervised`. Agent tool calls cannot raise their own autonomy: edits to hook settings or the grant file and executed `connect mode set|clear` are asked in supervised and assisted modes and denied in autonomous and full. Every decision taken without asking is appended to `.contractspec/connect/run-mode-decisions.ndjson`. Durable local review uses PostgreSQL and does not require a separate database or a control-plane API token. Configure `CHANNEL_RUNTIME_DATABASE_URL`, `DATABASE_URL`, or reuse the managed CompanyOS `LSSM_STUDIO_DATABASE_URL`, then inspect readiness and decisions: ```bash contractspec connect doctor --json contractspec connect review get --json contractspec connect review status --json contractspec connect review approve --stdin --json contractspec connect review reject --stdin --json ``` After tracked migrations reach `006a`, migration owners must run the conflict-aware `connect review provision-authority` dry run and then apply with exact role, issuer actor, authorization fingerprint, reviewer email/fingerprint, authority-ref, and proof-ref confirmations. The command stores public metadata only, verifies the explicit role equals the authenticated `session_user`/`current_user`, and accepts no private key. This direct, fully confirmed command is the deliberately narrow out-of-band bootstrap for the first reviewer; applying it through shell composition is denied, and later authority changes remain subject to Connect review. Migration owners can then idempotently enroll a human reviewer from a pending decision with `connect review enroll`, then create the exact short-lived signing packet with `connect review challenge`. Enrollment accepts only an Ed25519 public key (`--public-key` or `--stdin`) plus provenance/audit metadata; scope and capability always come from the stored decision, and private key material is rejected. Approve/reject stdin must be a fresh human-signed challenge packet. Capability claims, TTY confirmation, packet actor fields, fixture keys, and agent-authored signatures do not establish authority. See `docs/runbooks/connect-local-review.md` for role setup and verification. ## Recommended OSS Onboarding ```bash contractspec init --preset connect contractspec validate ``` Example-backed onboarding is provided by `@lssm-tech/integration.cli-contractspec-examples`. ## Discover capabilities ("can it help?") Ask whether ContractSpec already provides a capability — or whether your repo already has one — before building it yourself. Fully offline, no model required. ```bash contractspec can-help "render a data table from a contract" contractspec ask "capture an invoice from a customer" --scope workspace contractspec can-help "replace FastAPI" --runtime node --stability stable --json ``` Returns a `have-it` / `can-help` / `gap` verdict over a two-tier corpus (the shipped ContractSpec + ecosystem adoption catalog plus a local overlay of your own surfaces), with the canonical surface to adopt and a confidence score. `--scope` accepts `all` (default), `workspace`, `installed`, `contractspec`, or `ecosystem`; `local` remains a compatibility alias for `workspace`. Results include installed state, target version, install command, canonical imports, documentation, alternatives, score reasons, and catalog provenance. The same query is exposed to agents as the offline MCP tool `contractspec.can_help` (served by `contractspec mcp`). ### Enforce reuse (Connect ladder) ```bash # Graduated verdict: permit(0) / rewrite(10) / require_review(20) / deny(30) contractspec connect leverage --intent "build a multi-agent AI chat surface" # Opt-in hard-deny at high confidence; bypass with a recorded override contractspec connect leverage --intent "..." --deny --override "need a bespoke variant" --actor you ``` `deny` is opt-in and high-confidence only; an `--override` justification is persisted to `.contractspec/connect/leverage-overrides.json` as audit evidence. ### Leverage-gap report & catalog freshness (CI) ```bash contractspec can-help report # where this repo reinvented existing capabilities contractspec can-help catalog sync --json # refresh the complete V2 local mirror contractspec can-help catalog status --json # source/hash/freshness/degraded state contractspec can-help catalog search "Pydantic" --json contractspec can-help catalog get "@lssm-tech/lib.schema" --json contractspec can-help catalog --snapshot capability-catalog.json contractspec can-help catalog --check capability-catalog.json # exit 1 if stale (CI gate) ``` `contractspec connect adoption sync --json` and `can-help catalog sync` select the newest hash-valid registry, installed, local-mirror, or CLI-embedded V2 catalog. In a workspace that contains `@lssm-tech/lib.contractspec-catalog`, that package's own `catalog.json` is an installed candidate ranked above the local mirror, reported with the `catalog.workspace-package` diagnostic. Offline fallback is explicit in the returned diagnostics; the written `.contractspec/adoption/catalog.json` always contains the complete selected document rather than only local release artifacts. ## Repository lifecycle ```bash contractspec update --json # read-only V2 compatibility plan contractspec update --check --json # CI: non-zero for updates, blockers, or stale artifacts contractspec update --apply --wave framework.expo-57 contractspec update --apply --wave peer-normalization contractspec update --wave compatible.patch-minor --json # deprecated read-only aggregate contractspec update --apply --wave compatible.ai contractspec update --apply --wave compatible.tooling contractspec update --apply --wave breaking.better-auth # explicit migration review contractspec update --apply --wave major.frontend contractspec doctor --format json # read-only health and provenance contractspec doctor --fix # sequential safe waves, then fresh checks contractspec spec update # canonical spec editing command ``` Update selects the highest version compatible with framework constraints, runtime engines, package peers, singleton requirements, configured pins, and the currently adopted stable or prerelease channel. V2 JSON includes the selected channel, constraint provenance, registry provenance, risk, blocked reasons, and deterministic waves. `@lssm-tech/*` metadata comes from public npmjs package records; local workspace versions prevent publisher-repository downgrades. Applying requires one explicit wave. Compatible patch/minor updates are split into deterministic `compatible.` transactions; the legacy `compatible.patch-minor` selector remains read-only. Semver-zero minor jumps, `0.0.x` changes, and version transitions with catalog migration metadata are reported as high-risk `breaking.` waves. Doctor only auto-applies framework, peer-normalization, and compatible waves. Expo apps use Expo SDK API compatibility data and fall back offline to the installed `expo/bundledNativeModules.json`. Shared React and React Native stay singletons, while mobile TypeScript is isolated in `catalog:native`. Existing broad peer ranges remain unchanged; incompatible peers are widened without narrowing already published compatibility. File, Git, workspace, and unsupported alias ranges stay unchanged with diagnostics. Receipts and rollback snapshots live under `.contractspec/update/transactions/`. The legacy `upgrade` command forwards to this lifecycle for compatibility and also requires `--wave` when applying. When installation or verification fails, rollback restores owned files and then reconciles the install tree from the restored lockfile; a failed frozen reinstall is reported as a failed rollback rather than a successful one. Selected waves verify the packages whose manifests changed, plus migration and Doctor checks. Repository-wide typecheck, lint, and tests remain final release gates rather than being repeated twice for every ecosystem wave. ## Core Authoring/Build Model - `create` authors both runtime specs and package-oriented targets such as `module-bundle`, `builder-spec`, and `provider-spec`. - `build` materializes one authored target into runtime artifacts or package scaffolds. - `generate` runs workspace-wide generation for docs and derived artifacts. - `validate` checks authored targets, package scaffolds, and optional runtime implementations. - `contractspec create visual-scenario` scaffolds a provider-neutral `.visual-scenario.ts` contract with safe synthetic capture defaults. - `contractspec build --target storybook [visual-scenario-file]` generates the configured Storybook catalog; add `--check` in CI to fail on generated drift. - Example-backed onboarding is an optional command-pack responsibility rather than part of the default CLI closure. ## LSSM OS durable operation status The CLI and default MCP server reuse the canonical LSSM OS operation client. They do not define their own status, receipt, or error mappings. ```bash export LSSM_OS_AUTHORIZATION='Bearer ' export LSSM_OS_AGENT_HOST_ORIGIN='https://agent-host.example.com' contractspec lssm-os operation status operation-123 \ --origin "$LSSM_OS_AGENT_HOST_ORIGIN" \ --tenant-id tenant --workspace-id workspace --environment-id production ``` The command writes the canonical CLI projection as JSON and exits `5` while the durable operation is nonterminal, `0` after success, and `1` for terminal failure or a closed canonical error. The MCP tool `contractspec.lssm_os.operation_status` uses the configured origin and returns the exact canonical MCP structured content. Authorization is read only from `LSSM_OS_AUTHORIZATION`; it is never accepted as a command argument, MCP input, or returned evidence. The package qualification suite also dereferences one real Agent Host HTTP 202 response through the SDK, this CLI exit-5 path, MCP structured content, and the canonical React hook. All five surfaces must retain the same operation and projection digests; this is credential-free simulated parity, not live product or provider qualification. ## Model Context Protocol (MCP) servers The CLI ships two local, offline-first MCP servers over stdio. They replace the previously hosted `api.contractspec.io` MCP endpoints (docs/cli/internal/contracts), which have been **removed** — point your editor/agent at the local commands below. ```bash # Knowledge + author tools (default). Offline, zero setup, no network. contractspec mcp # Runtime projection of THIS repo's own contracts (opt-in, fail-closed). contractspec mcp --runtime # Operate against a different working directory: contractspec mcp --cwd /path/to/project ``` - **`contractspec mcp` (knowledge + author tools)** — fully offline. Exposes docs search/get/resolve-route/contract-reference/facets, CLI usage/suggest, the internal endpoint catalog, examples browsing, and author tools over the consumer's `cwd`: `contracts.list/get/validate/build/update/delete` plus the new **`contracts.create`** spec scaffold. The knowledge corpus is generated at build time from the docblock manifest + docs registry + example metadata (plus a small curated getting-started/patterns overlay) and bundled into the published package, so it works with **no network and no setup**. - **`contractspec mcp --runtime` (runtime projection)** — opt-in. Discovers and loads the consumer's own `OperationSpecRegistry` and projects it as MCP tools. It is **fail-closed**: - Projects **only handler-backed operations** (spec-only ops are never surfaced). - **Read-only queries are allowed; every write/command is DENIED by default** (destructive and `admin` operations included). Permit specific writes by name via `.contractsrc.json`. - On no registry / zero bound ops / load failure it prints a clear error to stderr, exits non-zero, and registers nothing. ### Security notes - **Author server has no policy gate (scope to trusted workspaces).** `contractspec mcp` (the default knowledge + author server) exposes write tools — `contracts.create`, `contracts.update`, `contracts.delete`, and `contracts.build` — that create, modify, delete, and generate spec files in the working directory. There is no per-tool policy check on this server, so only run it against a workspace you trust the connected agent to modify (and prefer `--cwd` to scope it explicitly). - **`--runtime` handlers run as `actor: 'anonymous'`.** Every operation projected by the runtime server is executed with an anonymous actor context. Consumers MUST NOT treat `anonymous` as an elevated or privileged identity inside their handlers; gate any sensitive behavior on explicit policy, not on the absence of an actor. ### `.contractsrc.json` `mcp.runtime` keys (runtime server) ```jsonc { "mcp": { "runtime": { // Path to a module exporting an OperationSpecRegistry (named `registry`/ // `operations`/`ops`, or default). Overrides convention-based discovery. "registry": "dist/registry.js", // Operation keys allowed to be projected as writable tools (opt-in). "allowWrites": ["project.create"] } } } ``` When `mcp.runtime.registry` is omitted, the server resolves candidate registry modules from the contractsrc `operations` layout (and common defaults like `operations/`, `src/operations/`). **v1 limitation:** the `mcp.runtime` block is read directly (not yet part of the typed `contractsrc.schema.json`), so editor schema autocomplete is not available for these keys. ### Editor wiring (`mcp.json` / settings) ```json "contractspec": { "command": "npx", "args": ["-y", "@lssm-tech/app.cli-contractspec", "mcp"], "env": {} }, "contractspec-runtime": { "command": "npx", "args": ["-y", "@lssm-tech/app.cli-contractspec", "mcp", "--runtime"], "env": {} } ``` > Migration from the removed hosted MCP: replace the old `api.contractspec.io` MCP entries in > your `mcp.json` (or `.claude`/`.cursor`/`.zed` config) with the two stdio entries above. Zed > entries also need `"type": "stdio"`. All MCP logging goes to **stderr**; stdout is the JSON-RPC channel. ## Help and command discovery `contractspec --help` is the canonical public command index. It groups root commands by category and includes implemented public command families such as `intelligence`, `connect`, `release`, and `changelog`. Subcommand help uses the same grouped renderer, so `contractspec intelligence --help` and `contractspec connect --help` preserve clean descriptions and category headings instead of falling back to an unstructured command list. ## Release capsule guardrails Prefer guided release authoring over raw YAML edits: ```bash contractspec release prepare --baseline main contractspec release edit contractspec release fix --write contractspec release check --strict --baseline main ``` `contractspec connect hook release-capsule after-file-edit --stdin` validates `.changeset/*.release.yaml` and paired `.changeset/*.md` edits without mutating files. When malformed YAML is recoverable, `contractspec release fix --write` rewrites the canonical `.release.yaml` and preserves unsupported fields in `.changeset/.release.quarantine.yaml`; scalar values of the string-list fields (`deprecations`, `affectedRuntimes`, `affectedFrameworks`, `knownGaps`) are quarantined there too. The default dry run previews the plan and exits non-zero while a repair would change capsule content or quarantine something; capsules that differ from the canonical layout only in YAML formatting are listed as `formatting-only` and do not fail the preview (`--write` normalizes them). `contractspec release check` also reports advisory `validation-entries` warnings, which never fail the check: validation commands that read as labels, outcomes, placeholders or prose, commands that cite `packages/` or `examples/` paths missing from the workspace, and evidence that quotes a run of a command not listed in `validation.commands`. ## Generative Core Preview Commands Generative Core commands are thin CLI wrappers over workspace/bundle services. They expose graph and regeneration evidence without bypassing Connect review gates: - `contractspec graph inspect --json` reads authored contracts and workspace evidence and reports schema-versioned counts, diagnostics, and artifact paths. - `contractspec graph export --json` writes only canonical graph artifacts under `generated/contractspec/graphs/**` after deterministic artifact metadata is available. - `contractspec drift check --json` classifies contract, code, generated artifact, docs, tests, and downstream-consumer drift for advisory CI before strict gates. - `contractspec generate plan --dry-run --json` produces planned writes and provenance hashes without mutating files. - `contractspec generate apply --json` and future repair apply flows require `contractspec connect verify` to allow or review the protected/generated write. ## Shell Completion Install the package so the `contractspec` executable is available on your `PATH`, then choose one of the supported shells: ```bash contractspec completion script bash contractspec completion script zsh contractspec completion script fish ``` For managed installation, write the completion file and optionally patch the shell profile: ```bash contractspec completion install bash contractspec completion install zsh --write-profile contractspec completion install fish ``` `completion install` always writes the generated completion script to a managed user config path. By default it does not edit startup files in non-interactive sessions. Use `--write-profile` to append an idempotent `source` block automatically. ## Initialization Presets `contractspec init` is now preset-driven. The shared setup layer owns the flow, and the CLI just forwards the preset and renders the resulting next steps. ```bash # Generic ContractSpec workspace setup contractspec init --preset core # Enable ContractSpec Connect defaults and local artifacts contractspec init --preset connect # Prepare Builder for a managed runtime contractspec init --preset builder-managed # Prepare Builder for a local runtime contractspec init --preset builder-local # Prepare Builder for a hybrid runtime contractspec init --preset builder-hybrid ``` In non-interactive mode, setup remains config-first: it writes `.contractsrc.json`, editor wiring, and tailored follow-up commands, but it does not call live Builder bootstrap APIs for you. `contractspec builder` remains control-plane-backed for managed, local, and hybrid runtime flows. The CLI resolves the Builder API base URL from `CONTRACTSPEC_API_BASE_URL`, then `.contractsrc.json` `builder.api.baseUrl`, then `https://api.contractspec.io`, and reads auth from the configured control-plane token environment variable. Builder execution aliases are additive shorthands over canonical execution-lane artifacts: ```bash contractspec builder ralphone "Finish this change" --json contractspec builder ultrawork "Parallelize this rollout" --json contractspec builder ulw "Parallelize this rollout" --json contractspec builder background --dry-run --json contractspec builder tools doctor --json contractspec builder tools diagnostics --json ``` `ralphone` starts the `complete.persistent` lane, while `ultrawork` and `ulw` start the `team.coordinated` lane. Persisted lane artifacts keep those canonical lane keys; aliases are only command-entry metadata. ### Builder specs-pack dry-runs and Connect-gated apply Use `contractspec builder pack` when product intent lives in an external zip or folder and must be inspected before any repository mutation. Import, analyze, and plan emit structured JSON; `implement` remains dry-run only, while `apply` requires an explicit Connect decision and returns a fail-closed task ledger until approved Connect, replay, verifier, and test evidence are present. ```bash contractspec builder pack import specs/autonomous-company-specs --json contractspec builder pack analyze specs/autonomous-company-specs --json contractspec builder pack plan specs/autonomous-company-specs --dry-run --json contractspec builder pack implement specs/autonomous-company-specs --dry-run --json contractspec builder pack apply specs/autonomous-company-specs --connect-decision connect:decision:1 --json ``` The pack report keeps external product intent separate from repository implementation reality, preserves source refs for README/AGENTS/prompts/examples/fixtures, surfaces ambiguity/readiness blockers, and recommends whole-pack versus layer-by-layer follow-up planning. The apply ledger records Contract Steward tasks before handwritten work, reviewed write scopes, required artifact kinds, and verifier blockers. Use `$ralplan` for reviewable implementation planning, `$ralph` for one-owner completion, and `$team` only when the Builder plan marks layers or package scopes safe to parallelize. ### Translation diagnostics Use `contractspec i18n check` to run the reusable ContractSpec static translation diagnostics from the CLI. The command scans `packages/**/src/i18n/catalogs` by default, compares `en/fr/es`, and reports missing catalogs, missing or extra keys, blank values, ICU syntax failures, and placeholder parity issues. ```bash contractspec i18n check contractspec i18n check --format json contractspec i18n check packages/platform/agents/ai-agent --base-locale en --locales en fr es ``` JSON output is the stable automation surface and contains `{ ok, summary, issues }`. Optional `.contractsrc.json` `i18n` settings provide workspace defaults; command flags override config values. ### Builder tmux Sessions Use `contractspec builder tmux` for full interactive Builder terminal work: REPLs, debuggers, TUIs, long-running dev servers, and local agent sessions that need a durable terminal instead of a one-shot command. ```bash contractspec builder tmux doctor contractspec builder tmux start --session builder-debug -- node --inspect contractspec builder tmux attach --session builder-debug contractspec builder tmux send --session builder-debug -- npm test contractspec builder tmux capture --session builder-debug --lines 120 contractspec builder tmux stop --session builder-debug ``` Sessions default to `contractspec-builder`, use argv-based tmux calls, fail on existing sessions unless `--reuse` is set, and support JSON output for automation. ### Builder agent lanes and diagnostics Builder agent-lane commands keep persisted lane identity canonical even when operators use shorthand aliases: | Operator surface | Persisted lane key | Metadata | | --- | --- | --- | | `contractspec builder ultrawork` / `contractspec builder ulw` | `team.coordinated` | `sourceAlias: "ultrawork"` or `sourceAlias: "ulw"` | | `contractspec builder ralphone` | `complete.persistent` | `sourceAlias: "ralphone"` | | `contractspec builder background` | `team.coordinated` | background-agent lease, scope, status, cancel, and attach evidence | | `contractspec builder tools doctor` / `contractspec builder tools diagnostics` | diagnostics surface only | tool capability, adapter readiness, and degraded-state evidence | Aliases are compatibility metadata, not new lane keys. Downstream state, release notes, workbench summaries, and replay artifacts should continue to branch on the canonical lane key and may display `sourceAlias` for human traceability. ## Architecture - **Commands** (`src/commands/`) - Thin wrappers that call bundle services. - **Prompts** (`src/commands/create/wizards/`) - Interactive UI using `@inquirer/prompts`. - **CLI setup** (`src/index.ts`, `src/cli.ts`) - Commander.js configuration. - **Types** (`src/types.ts`) - CLI-specific types. - **Services** (`@lssm-tech/bundle.workspace/services/`) - Core use-cases. - `create.ts` - Authored target creation logic. - `build.ts` - Runtime/package materialization from authored targets. - `openapi.ts` - OpenAPI export. - `registry.ts` - Registry client. - `examples.ts` - Examples management. ## Public Entry Points - Export `./run` resolves through `bun`, `node`, `default`. ## Local Commands Managed CompanyOS historical approval databases may materialize a migration-007 decision while the database stores the exact legacy text value `"1"`; only that value or integer `1` is normalized at the database read boundary. Enroll and activate the human reviewer, resolve the signed approval, and replay before applying `007_approval_canonicalization_v1_integer`. The migration command dry-runs by default; apply requires the exact migration ID through `--confirm-migration`, uses only `CHANNEL_RUNTIME_DATABASE_URL`, and ledger-replays as `existing`. The tracked `001`-`006a` chain preserves every historical ledger ID while adding the nonce table, issuer fields, and nonce RLS required by reviewer runtime queries. Authority provisioning is a separate dry-run-first command so reusable migrations contain no operator-specific trust record. Managed CompanyOS Connect review uses `contractspec connect review materialize --request ` before `connect review enroll`. Materialization accepts no caller scope or capability and only creates pending review authority. It is dry-run-first; apply requires `--apply`, the exact packet/source-diff confirmations, and `CHANNEL_RUNTIME_DATABASE_URL` (never the generic `DATABASE_URL` fallback). See `docs/runbooks/connect-local-review.md`. - `bun run dev` — bun build ./src/cli.ts --outfile ./dist/cli.js --target node --watch - `bun run build` — bun run prebuild && bun run build:types && bun run build:all - `bun run test` — isolated CLI black-box checks, then `bun test` - `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` — rimraf dist - `bun run build:bun` — bun scripts/build-runtime-bundle.mjs bun (self-contained Bun bundle) - `bun run build:node` — bun scripts/build-runtime-bundle.mjs node (self-contained Node bundle) - `bun run build:all` — bun run build:bun && bun run build:node - `bun run build:types` — tsgo --noEmit - `bun run dev:bun` — bun build ./src/cli.ts --outfile ./dist/cli.bun.js --target bun --watch - `bun run test:watch` — bun test --watch ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add table capabilities. - Stability. - Vnext ai-native. - Add latest models and align defaults. - Resolve lint and build errors in workspace bundle and integrations lib. ## Notes - Works alongside `@lssm-tech/bundle.workspace`, `@lssm-tech/lib.ai-agent`, `@lssm-tech/lib.ai-providers`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, ... - `contractspec apply` has been retired; use `contractspec generate` for write-generation flows. ## Contract Intelligence The CLI includes a dry-run-first `contractspec intelligence` workflow for analyzing the current repository, exporting a portable bundle, importing it into another target, reconciling reality, and producing a selective import plan. `analyze` defaults to repo-derived evidence; pass `--fixture ` only for deterministic examples and regression fixtures. `adopt --apply` is intentionally blocked until ContractSpec Connect review and replay evidence exist. See `docs/contract-intelligence.md`. `contractspec list --json`, `contractspec integrity --json`, and `contractspec integrity --format mermaid` are machine-output surfaces: stdout is reserved for the requested JSON or diagram, while human diagnostics belong in text mode or stderr. Discovery reports only authored contract/spec evidence and skips prompt/template implementation files that merely contain strings such as `key:`. `contractspec portfolio index|centralize|propagate|radar` creates advisory portfolio envelopes over bundle refs without mutating shared cores or vertical projects. See `docs/portfolio-centralization.md`. ## i18n diagnostics Run static translation catalog diagnostics from a workspace or catalog directory: ```bash contractspec i18n check [path] --locales en fr es --format json ``` The command reports reusable ContractSpec diagnostics for missing catalogs/keys, extra keys, blank values, malformed message shapes, invalid ICU syntax, and placeholder parity. JSON output is stable for CI and exits `1` for diagnostic failures or `2` for fatal config/import errors. ## Restricted agent Markdown archives These subcommands belong to the optional AI command contribution that provides `agent`; they are not registered by the base CLI alone. Configure that command pack before use. `contractspec agent migration archive --input selected.json --output archive.json` validates explicitly selected Markdown content and writes a new owner-readable archive. The input contains `id`, agent `scope`, `sourceRuntime` (`hermes` or `openclaw`), `sourceVersion`, `sourceRootRef`, `createdAt`, and `files` entries with `path` and `content`. No home-directory scan or instruction execution occurs. `contractspec agent migration inspect --input archive.json` verifies hashes and prints only counts and archive identity. Archive files contain private data; retain them in restricted storage. These commands do not submit proposals, promote memory, install skills, reconnect credentials, or activate schedules/channels. The package-local Turbo configuration lists the CLI's public workspace build and typecheck dependencies explicitly. Its private Agent Host development dependency is used only by the source-level durable-operation parity test; compiling the host's deployable server is not a prerequisite for the CLI. The parity test and development dependency remain in place. When changing CLI workspace dependencies, update both task lists and run `bun test scripts/delivery/cli-build-dependencies.test.mjs` from the repository root; this check also rejects unexpected private dependencies. ## Published CLI artifact verification `bun run verify:pack` builds the actual CLI and verifies its canonical local publication projection without publishing. It requires every conditional root, bin, optional contribution and declaration target, plus exactly the emitted JavaScript dependency closure. Unreferenced chunks, source/test/map/cache files and unsafe archive members are rejected. Executable CLI targets retain the Node shebang; declaration files and imported contributions do not require a shebang. The installed Node/Bun consumer keeps runtime authority and network policy gates. --- ## @lssm-tech/app.cli-database Description: Command-line database tooling for ContractSpec-managed schemas and operations. Path: packages/apps/cli-database URL: /llms/app.cli-database # @lssm-tech/app.cli-database Website: https://contractspec.io **CLI tool for contract-source-first Drizzle/PostgreSQL database management: generate, migrate, seed, and schema operations.** ## What It Does - Uses `@lssm-tech/lib.schema` for schema definitions. - Generates Drizzle/PostgreSQL artifacts from portable ContractSpec database entities. - Commands dispatched via minimist argument parsing. - Related ContractSpec packages include `@lssm-tech/lib.schema`, `@lssm-tech/tool.tsdown`, `@lssm-tech/tool.typescript`. ## Running Locally From `packages/apps/cli-database`: - `bun run dev` - `bun run build` ## Usage ```bash npx database --help # or bunx database --help ``` ## Architecture - Uses `@lssm-tech/lib.schema` for schema definitions. - Generates Drizzle/PostgreSQL artifacts from portable ContractSpec database entities. - Commands dispatched via minimist argument parsing. - `src/cli.ts` is the CLI entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Binary `database` points to `dist/cli.js`. - Export `.` resolves through `./dist/index.mjs`. - Export `./cli` resolves through `./dist/cli.mjs`. - Export `./commands/check` resolves through `./dist/commands/check.mjs`. - Export `./commands/generate` resolves through `./dist/commands/generate.mjs`. - Export `./commands/import` resolves through `./dist/commands/import.mjs`. - Export `./commands/migrate` resolves through `./dist/commands/migrate.mjs`. - Export `./commands/schema-compose` resolves through `./dist/commands/schema-compose.mjs`. - Export `./commands/schema-generate` resolves through `./dist/commands/schema-generate.mjs`. - Export `./commands/seed` resolves through `./dist/commands/seed.mjs`. - Export `./lib/config` resolves through `./dist/lib/config.mjs`. - The package publishes 12 total export subpaths; keep docs aligned with `package.json`. ## Database Workflow Boundary Prisma support is retired for supported workflows. Broad root workflows such as `lint:fix`, `typecheck`, and release checks must not run Prisma implicitly; use the explicit Drizzle/PostgreSQL `packages/apps/cli-database` commands below when a database schema workflow is required. ## Local Commands - `bun run dev` — bun run build --watch - `bun run build` — tsdown - `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 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 test` — standalone host test: spawns `src/cli.ts` in a throwaway project (schema generate/compose, check, Drizzle config, dry-run and refused migrations, status, seed) with no database - `bun run dbs:generate` — database generate --dry-run - `bun run dbs:migrate` — database migrate:dev --dry-run - `bun run dbs:deploy` — database migrate:deploy --dry-run - `bun run dbs:status` — database migrate:status - `bun run dbs:seed` — database seed ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Do not change CLI argument signatures without updating docs and CI scripts. - Drizzle/PostgreSQL artifact generation is contract-source-first — test migrations carefully. --- ## @lssm-tech/app.cli-databases Description: Multi-database command-line workflows for ContractSpec workspaces. Path: packages/apps/cli-databases URL: /llms/app.cli-databases # @lssm-tech/app.cli-databases Website: https://contractspec.io **CLI orchestrator for multi-database workflows. Coordinates operations across multiple database profiles defined in a project.** ## What It Does - Lightweight CLI with no workspace bundle dependencies. - Uses minimist for argument parsing, execa for subprocess execution. - Delegates per-database work to `cli-database`. - Related ContractSpec packages include `@lssm-tech/tool.tsdown`, `@lssm-tech/tool.typescript`. ## Running Locally From `packages/apps/cli-databases`: - `bun run dev` - `bun run build` ## Usage ```bash npx databases --help # or bunx databases --help ``` ## Architecture - Lightweight CLI with no workspace bundle dependencies. - Uses minimist for argument parsing, execa for subprocess execution. - Delegates per-database work to `cli-database`. - `src/cli.ts` is the CLI entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Binary `databases` points to `dist/cli.js`. - Export `.` resolves through `./dist/index.mjs`. - Export `./cli` resolves through `./dist/cli.mjs`. - Export `./profile` resolves through `./dist/profile.mjs`. - Export `./*` resolves through `./*`. ## Local Commands - `bun run dev` — bun run build --watch - `bun run build` — tsdown - `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 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 test` — standalone host test: spawns `src/cli.ts` against a fixture profile with recording `prisma`/`database` stubs on PATH (fan-out, fail-fast, profile and usage errors) ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Keep this as a thin orchestrator — business logic belongs in `cli-database`. - Do not change CLI argument signatures without updating docs and CI scripts. --- ## @lssm-tech/app.communicationos-api Description: (none) Path: packages/apps/communicationos-api URL: /llms/app.communicationos-api # CommunicationOS API `/v2/accounts` and `/v2/contacts` expose public-safe exact-scope projections. Their projections rebuild from the durable journal after API restart and remain empty for foreign tenant, workspace, or space scopes. `/v2/identity-reviews/:reviewId/decision` is manager-only and permits one audited merge or rejection transition. Stateless Elysia entrypoint for `api.hcircle.app`. The public health endpoint is `/v2/health`; protected routes require an injected AuthOS verifier and explicit tenant, workspace, and space scope. The default composition fails closed until production authentication and ticket issuance ports are wired. Authenticated `GET /v2/spaces` and `GET /v2/rooms` return deterministic projections for exactly the supplied scope. Cross-space discovery belongs to an authorized scope catalog and is not inferred from journal access. The canonical ContractSpec transport is available under `/communication/*`. Version 3 space, room, account, and contact reads derive their complete scope from the verified bearer session. Version 3 room creation accepts only a name, room kind, and idempotency key; client-supplied tenant or principal fields never become authority. Invalid intent returns problem details without appending to the journal. Canonical governed-work v2 list, create, and transition operations use the same boundary, enforce manager roles for managed kinds, and translate missing or invalid lifecycle state into explicit problem responses. ## Meetings: one concept, two owners A meeting has exactly one identity, owned by OPA. CommunicationOS owns the conversation around it. | Concern | Owner | Contracts | | --- | --- | --- | | Scheduling, approval, booking, conference link | OPA (CompanyOS API) | `opa.smart_meeting.*` | | Private preparation, notes, transcripts, reviewed outcomes, shares | OPA meeting workspace (CompanyOS API for CompanyOS, this API for hCircle) | `opa.meeting_workspace.*` | | Conversation room, shared agenda, conversation participants, shared notes | CommunicationOS meeting thread | `communication.meeting_thread.{list,link,revise}@1.0.0` | | Follow-ups | CommunicationOS governed work (`kind: action`, bound to the meeting room) | `communication.governed_work.*` | `GET|POST /v2/meeting-threads` and `POST /v2/meeting-threads/:threadId/revise` persist meeting threads in the scope journal. Linking is idempotent per `(meetingSource, meetingRef)` and creates the meeting room on first link; revisions require the current `expectedRevision` (stale writes answer `409` with the latest thread). Scope and principal always come from the verified session; client authority fields are rejected. A meeting thread never grants OPA authority: link-outs open the OPA workspace, which re-authorizes. Shared notes are room-visible conversation notes, distinct from private OPA notes. In CompanyOS the web BFF gates `list` by `communication-os.rooms.read` and `link`/`revise` by `communication-os.reply.send`. ## OPA Meeting Intelligence host (hCircle) The shared `opa.meeting_workspace.*` contract routes are mounted under `/api/v2/opa/*` for hCircle personal scopes. CompanyOS workspaces use the OPA meeting workspace of the CompanyOS API instead; workspace (community) scopes stay denied here until a live community membership resolver is bound. `HCIRCLE_MEETING_RUNTIME_ENABLED` stays off by default. When it is `true`, the startup verdict validates, before any connection opens: | Variable | Requirement | | --- | --- | | `HCIRCLE_GOVERNED_DATA_DATABASE_URL` | `postgres://` URL connecting as `opa_app` (RLS enforced) | | `HCIRCLE_GOVERNED_RECOVERY_TOKEN` | at least 32 characters; required by governed-data recovery whenever `HCIRCLE_GOVERNED_DATA_DATABASE_URL` is set (startup refuses otherwise) | | `HCIRCLE_GOVERNED_DATA_MIGRATION_URL` | `postgres://` URL connecting as `opa_migrator`; must differ from the runtime URL | | `DATABASE_URL` | existing direct-auth database (product membership authority) | | `HCIRCLE_MEETING_BYOK_MASTER_KEY` | at least 32 characters, dedicated | | `OPA_MEETING_ACCESS_GRANT_PEPPER` | at least 32 characters, different from the BYOK key | | `HCIRCLE_GOVERNED_DATA_SSL_MODE` | optional: `require` (default), `prefer`, or `allow` | | `COMMUNICATION_OS_API_ORIGIN` | optional exact origin; `https` (plain `http` only on loopback) | `/v2/health` reports `meetingHost`: `enabled`, `disabled_flag`, or `misconfigured`, and `release.sha` (`COMMUNICATION_OS_BUILD_SHA`, else `VERCEL_GIT_COMMIT_SHA`). A misconfigured host no longer aborts API startup: the rest of CommunicationOS stays up and every meeting route answers `503 meeting_host_misconfigured`. A disabled host leaves the routes unmounted. The schema ledger `hcircle_meeting_schema_ledger` applies, under one advisory lock and digest check, `0039` (meeting workspace + access grants, the deployed batch), `0040` (meeting intake occurrences and immutable review storage), and `0041` (recurring intake definitions and fenced execution leases). Before any DDL it requires the `opa_app` and `opa_migrator` roles; afterwards it proves that all 21 runtime tables exist with forced row-level security. Missing roles, a tampered digest, or an incomplete schema report `misconfigured`. PGlite tests cover first apply, replay, digest tampering, lost forced RLS, and owner-scope isolation for the application role. Each request requires the existing short-lived CommunicationOS bearer plus its exact tenant, workspace, and space headers. The host hashes that verified scope into an hCircle owner scope, re-verifies the bearer before governed mutations, reloads current direct-auth product membership from `DATABASE_URL`, and never accepts owner authority from a request body. Preparation reads the authenticated scope's CommunicationOS history through the same tenant-scoped journal runtime. PersonalOS context remains fail-closed until an active, non-expired consent projection is supplied through its projection port; private projection fields are never included in shared briefs. Production qualification: after deploying the exact commit with the variables above, run `bun run --cwd packages/apps/communicationos-api canary:meeting-host -- --origin https://api.hcircle.app --sha <40-hex commit> --out `. It passes only when health reports the exact SHA and `meetingHost: enabled`, meeting routes are mounted and fail closed without a bearer (`403`), and the public share route fails closed with `no-store`. Attach the evidence file to the release capsule. Authorized owners, administrators, auditors, and operators can inspect the same append-only scope through `GET /v2/audit`. Its response follows the stable `audit.scoped.query@1.0.0` record shape while replacing event payloads with an empty object. `GET /v2/replay?traceId=...` follows `audit.trace.get@1.0.0` and returns a deterministic, effect-free trace. Neither route exposes message bodies, provider payloads, credential references, or another scope. `GET|POST /v2/governed-work` and `POST /v2/governed-work/:workId/transition` persist the governed lifecycle used by identity review, drafts, actions, handoffs, escalations, triage, summaries, agents, consent, retention, and policy. Scope and principal authority always come from the verified session; managed identity/privacy/policy decisions are restricted to manager roles and every mutation requires an idempotency key. The public contract keys are `communication.governed_work.list@1.0.0`, `communication.governed_work.create@1.0.0`, and `communication.governed_work.transition@1.0.0`. Approved agent, consent, retention, and policy authority can be revoked; approved operational work can be resolved; blocked work can recover only through an explicit resolution. Provider callbacks use opaque HMAC-bound endpoint tokens under `/v2/webhooks/:network/:endpointToken`. Production composition additionally requires `DATABASE_URL`, a dedicated `COMMUNICATION_OS_WEBHOOK_TOKEN_SECRET` (at least 32 bytes), an exact `COMMUNICATION_OS_API_ORIGIN`, and explicit `COMMUNICATION_OS_CREDENTIAL_REF_PREFIXES`. Slack, Telegram, and official Meta WhatsApp and Microsoft Teams bot callbacks are authenticated before canonical journal ingestion; unsupported or incompletely configured providers return an unavailable result instead of ingesting unverified content. Teams bot callbacks require both the opaque connection endpoint token and a fully verified Microsoft Bot Connector JWT. Verified activities durably update an evidence-bound conversation reference; signed installation removals revoke it. Delegated Graph OAuth and installed-bot credentials remain non-confusable profiles. Email channel endpoints accept Google-first Gmail OAuth, explicitly selected Microsoft Mail OAuth, and MailerSend server-managed connections. OAuth state pins `providerKey: "google" | "microsoft"` so both email providers can coexist. A MailerSend credential resolves server-side to `{ network: "email", provider: "mailersend", apiKey, signingSecret, fromEmail, fromName? }`. Authenticated `inbound.message` callbacks enter the canonical email adapter and journal; delivery and test callbacks are authenticated and recorded without creating duplicate room messages. Raw API keys, signing secrets, and provider message identifiers are never returned to clients. Microsoft Mail uses delegated `Mail.Read` and `Mail.Send`. Graph validation tokens are echoed only after the opaque connection endpoint resolves, callback batches require the exact subscription/client-state binding, and their content is reduced to a durable sync invalidation. Missed lifecycle callbacks request a delta reconciliation pass; they never enter agent context as instructions. Provider onboarding uses authenticated `POST /v2/oauth/:network/start` and the public provider callback `GET /v2/oauth/:network/callback`. Scope, principal, placement, provider proof material, expiry, an issuer-derived return origin, and a relative return path are AES-GCM encrypted into opaque state; Postgres stores only a SHA-256 replay fingerprint and consumes it atomically. Exchanged tokens go directly to either GCP Secret Manager or the portable AES-GCM Postgres credential vault, and only an opaque credential reference reaches the canonical connection. ## Message attachments Authenticated clients upload supported PDF, image, CSV, or text files through `POST /v2/attachments`, then reference at most five opaque attachment IDs when sending a message. The API verifies the declared size and SHA-256 digest, persists content inside the selected scope, and serves downloads only through the authenticated `/v2/attachments/:attachmentId` route. Public message projections never expose storage locations or provider credentials. Managed OAuth configuration requires `DATABASE_URL`, `COMMUNICATION_OS_OAUTH_STATE_SECRET` (at least 32 bytes), exact `COMMUNICATION_OS_API_ORIGIN`/`COMMUNICATION_OS_WEB_ORIGIN`, one credential vault (`COMMUNICATION_OS_SECRET_GCP_PROJECT_ID` or the at-least-32-byte `COMMUNICATION_OS_CREDENTIAL_MASTER_SECRET`), and at least one provider pair: `COMMUNICATION_OS_GMAIL_CLIENT_ID` plus `COMMUNICATION_OS_GMAIL_CLIENT_SECRET`, `COMMUNICATION_OS_SLACK_CLIENT_ID` plus `COMMUNICATION_OS_SLACK_CLIENT_SECRET` and, for authenticated Slack webhooks, `COMMUNICATION_OS_SLACK_SIGNING_SECRET`, or `COMMUNICATION_OS_META_CLIENT_ID` plus `COMMUNICATION_OS_META_CLIENT_SECRET` and the Meta Login for Business `COMMUNICATION_OS_META_CONFIGURATION_ID`, or `COMMUNICATION_OS_MICROSOFT_CLIENT_ID` plus `COMMUNICATION_OS_MICROSOFT_CLIENT_SECRET`. Microsoft Teams uses delegated authorization-code PKCE with `User.Read` and `ChannelMessage.Send`; app-only Graph tokens are not ordinary channel-send authority. Slack PKCE must be enabled in its app settings; Meta uses its confidential-client Business configuration and state. Embedded hosts are configured with `COMMUNICATION_OS_OAUTH_HOST_ORIGINS`, a JSON object mapping each trusted host-exchange issuer (the `COMMUNICATION_OS_COMPANYOS_ISSUER` value, carried as the signed `hostIssuer` claim of the exchanged session) to its exact HTTPS UI origin, for example `{"https://companyos.hcircle.app":"https://www.companyos.run"}`. The shared access-token issuer `https://api.hcircle.app` is never a key. Direct sessions, sessions minted before the claim existed, and unknown, malformed, wildcard, or path-bearing origins fall back to `COMMUNICATION_OS_WEB_ORIGIN`. Direct-auth email uses `RESEND_API_KEY` as the primary provider. Any Resend transport error or non-success response falls back to MailerSend when `MAILERSEND_API_KEY` and `MAILERSEND_FROM_EMAIL` are present; optional sender labels use `MAILERSEND_FROM_NAME`. Both providers share `COMMUNICATION_OS_AUTH_EMAIL_FROM` as the requested sender address. If neither provider is configured, or both fail, authentication fails closed and no login ticket is issued. Direct hCircle identity is invite-only. `COMMUNICATION_OS_AUTH_SECRET`, `COMMUNICATION_OS_ACCESS_TOKEN_SECRET`, `COMMUNICATION_OS_API_ORIGIN`, and `COMMUNICATION_OS_CHAT_ORIGIN` bind the local application session. Magic-link and email-code plugins cannot create identities. The central LSSM relying party remains disabled unless `HCIRCLE_LSSM_RP_ENABLED=1`, `HCIRCLE_LSSM_RP_SECURITY_REVIEW_REF`, and an at-least-32-character `HCIRCLE_LSSM_RP_CLIENT_SECRET` are all present. It uses the fixed `hcircle-chat` client registration, PKCE, issuer validation, and the exact `https://chat.hcircle.app/auth/callback/lssm` redirect. The central provider will not mint the code without an active `app_hcircle` entitlement; only then may the hCircle Better Auth host create its local account projection. Local magic-link signup stays disabled. When the reviewed central RP is active, the API does not register the local magic-link plugin or delivery callback at all; disabling the RP restores the existing-email local path only as a rollback authority. The resulting personal scope remains product-local. These settings do not replace room, role, consent, or data authority checks. `HCIRCLE_MEMBERSHIP_PROVISION_TOKEN` is the 32+ character, server-only token used by central AuthOS to create an idempotent local `app_hcircle` membership. The direct session exchanger issues no CommunicationOS token until that local membership is active; the local role, not a central claim, remains the product role authority. `HCIRCLE_BOOTSTRAP_OWNER_EMAILS` is an optional comma-separated recovery seed for canonical owners whose central entitlement predates local membership provisioning. Reconciliation runs only after a valid local Better Auth session, a verified exact email match, and a linked LSSM pairwise account. It is idempotent, server-derived, and does not bypass any later room or data scope. Governed cross-product copies use a separate product-local PostgreSQL boundary: `HCIRCLE_GOVERNED_DATA_DATABASE_URL`, a distinct 32+ character `HCIRCLE_GOVERNED_RECOVERY_TOKEN`, optional `HCIRCLE_GOVERNED_DATA_AUTO_MIGRATE=true`, and `HCIRCLE_GOVERNED_DATA_SSL_MODE=require|allow|prefer`. The internal `/internal/governed-data/revocations` and `/internal/governed-data/rights` ingresses fail closed when this boundary is absent. Do not configure the central recovery origin until every hCircle governed projection copy uses this canonical encrypted store; exports remain unavailable until an authoritative hCircle exporter is bound. Encrypted-copy admission is independent and defaults off. Configure both `HCIRCLE_GOVERNED_DATA_REGION` and the secret-manager value `HCIRCLE_GOVERNED_MATERIALIZATION_BINDINGS` to enable `POST /internal/governed-data/materializations/:sourceApplicationId`. The bindings value is a JSON array of exact `{"sourceApplicationId":"app_…","bearerToken":"<32+ chars>"}` records with one distinct bearer per source-to-hCircle pair. Partial topology, unknown sources, reused source ids, stale purpose/field/region/expiry/retention/key authority, and plaintext fail closed before persistence. Recovery-only configuration remains supported; do not bind production materialization until the receiver key service and retention cleanup are qualified. ## AI thread assistance (Vercel AI Gateway) `POST /v2/threads/:roomId/summary` (`comms.thread.summarize`) and `POST /v2/threads/:roomId/draft` (`comms.reply.draft`) call models only through the Vercel AI Gateway. They use the shared adapter `createVercelGatewayModel` (`@lssm-tech/lib.ai-providers/vercel-gateway`). No direct provider key is read: `MISTRAL_API_KEY`, `ANTHROPIC_API_KEY`, `COMMOS_LLM_PROVIDER`, `COMMOS_LLM_MODEL` and `COMMOS_LLM_BASE_URL` are ignored. Environment: | Variable | Required | Meaning | | --- | --- | --- | | `COMMUNICATION_OS_AI_ASSIST_ENABLED` | yes | Must be `true`. Thread content never reaches a model without it. | | Gateway credential | one of them | `AI_GATEWAY_API_KEY` is used first. Otherwise, on Vercel (`VERCEL=1`), the per-invocation OIDC token from the `x-vercel-oidc-token` request header is used and labelled `oidc`. If `VERCEL_PROJECT_ID` is exposed, the token must belong to this project. A `VERCEL_OIDC_TOKEN` env value is the last fallback. | | `COMMUNICATION_OS_AI_DEFAULT_MODEL` | no | Default Gateway model id. Ignored unless it is in the catalog. | The flag and the credential are read on every request, so nothing is cached at startup. If either is missing, authorized calls answer `503 ai_unavailable`. Public `GET /v2/health` reports `data.aiAssist` as `enabled`, `disabled_flag` or `no_gateway_auth`, with no secrets, so you can check production without user credentials. Tokens are passed per call and never logged. **Switching models.** The allowlist is `COMMUNICATION_OS_AI_MODEL_CATALOG` (`@lssm-tech/lib.communication-spec/contracts/ai-model-catalog`). It lists Anthropic Claude Haiku/Sonnet/Opus 5.5, OpenAI GPT-6 Luna and GPT-6.1 Sol, and Google Gemini 3.8 Flash and Gemini 4 Argon. Each request uses the first match in this order: 1. The request body `model`. It must be in the allowlist, and only `ai.use` roles may send it. Otherwise the call fails with `422 ai_model_not_allowed` or `403 ai_model_override_denied`. 2. The workspace setting. 3. `COMMUNICATION_OS_AI_DEFAULT_MODEL`. 4. The catalog default, `anthropic/claude-haiku-5.5`. The workspace setting lives at `GET|POST /v2/ai/model-settings` (`communication.ai.model-settings.get|set`). Owner, admin, enterprise_admin and founder_approver roles can change it. Each change is appended to the journal as `communication.ai.model-setting.changed`, with the actor and the previous model. To add a model, add a catalog entry (contract first) and release. No environment change is needed. Summaries return `modelName` (the Gateway id) and `modelSource`. AI drafts record `modelName`, `modelSource`, `modelGateway` and `inferenceRegion` in the governed-work details. The existing governance still applies: drafts are never sent automatically, authors are pseudonymized, at most 40 messages are sent, there are at most five pending drafts per principal and thread, and provider failures answer `503 ai_provider_unavailable`. **Inbox triage.** `POST /v2/threads/:roomId/triage` (`comms.thread.triage`) and `POST /v2/threads/triage` (`comms.thread.triage.batch`, body `{ "threadIds": [...] }`, 1 to 25 unique ids) return advisory labels. Each label has a category (request, question, complaint, sales, support, scheduling, fyi, spam_suspect), an urgency (low, normal, high), `needsReply` and a one-line `reason`. - Only `ai.use` roles may call them. They use the same flag, Gateway credential and model order as summaries. - The model must return the strict structured label. Anything else is a provider failure, and no label is stored. - A fresh label is appended to the journal as `communication.ai.thread-triaged`, with its model, prompt version and revision (the latest covered message id). The next call reuses it until a new message arrives. - Fresh classifications are limited to 100 per principal and workspace every 10 minutes, counted per process. Cache hits do not count. - Reasons are stripped of emails and phone numbers. - In a batch, each thread reports `fresh`, `cached`, `skipped` (with `thread_not_found`, `insufficient_messages` or `rate_limited`) or `failed`. One thread failing never fails the whole batch. - Labels never send, assign or change a thread. **Data residency.** Every Gateway call asks for EU-zone inference (`inferenceRegion: { scope: 'zone', geoRegion: 'eu' }`), zero data retention and no prompt training. Calls are limited (`only`) to the catalog's inference providers: Bedrock for Anthropic, OpenAI for OpenAI, Vertex for Google. On 2026-10-15 each of these advertised an EU region for its catalog models. This constrains provider inference only. The Gateway itself routes and processes requests globally, so EU-only transit is not guaranteed and needs its own approval. Requested routing is also not proof of where a request was served: use `readVercelGatewayRoutingMetadata` for per-call evidence. Mistral models are not offered. The Gateway lists no EU inference region for them, and the shared adapter refuses Mistral inference. ## Forms Forms uses the same bearer principal and tenant/workspace scope as messaging. Configure `COMMUNICATION_OS_FORMS_DATA_PROTECTION_SECRET` and `COMMUNICATION_OS_FORMS_MILESTONES`; optional verification, AI, and distributed defense adapters use the matching `COMMUNICATION_OS_FORMS_*` endpoint, bearer, channel/provider, and identifier-secret variables. The API is `/api/forms/v1`; public hosts expose `/f/{opaqueToken}`. Fresh databases receive the hardened schema directly; existing Forms databases are upgraded additively by `0002_forms_scope_hardening.sql` semantics during readiness initialization. ## Support private notes Service-only `POST /api/communications/v1/support/cases/{caseRef}/internal-notes` creates encrypted private-note content. The matching evidence URL verifies the exact case, note, and evidence reference without returning content. Both routes derive tenant, workspace, actor, audience, and capability from a short-lived AuthOS grant; caller scope headers are ignored. Configure `COMMUNICATION_OS_SUPPORT_NOTE_PROTECTION_SECRET`, the separately rotated `COMMUNICATION_OS_SUPPORT_NOTE_IDENTIFIER_SECRET`, `COMMUNICATION_OS_SUPPORT_NOTE_KEY_VERSION`, `COMMUNICATION_OS_AUTHOS_GRANT_VERIFY_URL`, and `COMMUNICATION_OS_AUTHOS_WORKLOAD_TOKEN`. The routes remain unavailable if any required authority or protection adapter is absent. The database migrator records immutable, digest-bound `0001_communication_os_baseline` and `0002_communication_support_internal_notes`, followed by the pinned `0003_communication_os_rls` receipt before enabling these routes; changed historical source or receipt digests fail closed. ### Authorized send retries Message retries recheck current membership and connection authority before returning accepted content. Reuse of a request key with a different principal, room, content, subject, reply target, metadata, encryption envelope or attachment list is denied. Object metadata key order does not change semantic identity. Missing or partial attachment resolution fails before acceptance. The journal/outbox transaction validates a replayed message before enqueueing delivery, and insert-returned journal events preserve their tenant scope. Queued acceptance remains distinct from provider delivery. Source-bound OPA follow-up delivery, full concurrent authority fencing and production qualification remain open. ### Provider queue acceptance An external connection send requires `appendForDelivery`; journal-only persistence cannot claim provider queue acceptance. The event/outbox transaction validates the accepted message identity, connection and exact persisted delivery scope, command, policy and payload. Conflicting outbox keys roll back instead of silently dropping delivery. Provider delivery keys use `delivery:`; retries cannot substitute another key. Atomic journal replay uses the accepted message ID rather than the discarded candidate ID. Internal room journal acceptance remains available without a provider adapter. Queued does not imply sent or delivered. Legacy malformed delivery inputs fail closed and require explicit repair; broader cross-scope key migration and OPA follow-up delivery remain separate qualification work. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. --- ## @lssm-tech/app.communicationos-desktop Description: Tauri 2 desktop shell for CommunicationOS. Path: packages/apps/communicationos-desktop URL: /llms/app.communicationos-desktop # `@lssm-tech/app.communicationos-desktop` Message search uses the authenticated canonical space projection and shares the same typed API boundary as web and mobile. It is not limited to the active room. Thin Tauri 2 and React/Vite shell for CommunicationOS. It consumes the shared application kit, declares Stronghold/OS keychain credentials and Tauri SQLite projections, and supports device, managed-cloud, or self-hosted connectors. Stronghold stores both the native AuthOS session and provider credentials. The shell exchanges that session for a short-lived CommunicationOS grant and renders only live spaces and room counts returned for the server-derived scope. The signed-out and expired-session surfaces include direct email/password and TOTP recovery. CompanyOS validates the Stronghold bearer and performs the server-only hCircle host assertion; the webview never receives the shared secret or proposes tenant/workspace/space authority. Transient send failures enter the Tauri SQLite outbox, retain their original idempotency keys, and replay on reconnect or a five-second recovery interval. The shell keeps the queued count visible until the server confirms delivery. Queued payloads use the v2 AES-256-GCM envelope with a random key held only in Stronghold and AAD bound to tenant, workspace, space, principal, room, and idempotency key. Every list, count, delivery, retry, quarantine, and discard statement repeats that full owner scope. SQLite secure-delete is enabled and v1 or legacy plaintext rows are purged instead of replayed. Corrupt v2 ciphertext is retained as payload-opaque quarantine evidence until the user discards and recomposes it. The active authorized room is refreshed from realtime invalidations, online recovery, and a 15-second safety poll through one per-session queue. Outbox replay completes before the next timeline read, so confirmed messages do not disappear between recovery frames and overlapping triggers cannot race. Durable monotonic sequence numbers preserve enqueue order even when multiple messages share the same timestamp. Replay treats an API `401` as terminal session expiry: it never increments the retry schedule, propagates to the session boundary, removes credentials, and closes live work before the signed-out recovery surface commits. Every conversation refresh and send-result commit is fenced to the current native session, route, and room; a late response from a previous deep link cannot replace the active conversation. A send-side `401` invalidates live work before Stronghold session removal completes and renders explicit sign-in recovery instead of an attachment error. The composer validates and hashes up to five supported files locally, uploads them through the scoped API, replays opaque attachment IDs after transient send failures, and downloads without exposing storage locations. Room and thread details retain separate canonical hashes. Thread routes resolve to a room only through server-returned channel bindings and keep an explicit thread-context marker above the shared attachment-aware composer. The client never accepts a tenant, workspace, space, or room membership as authority. The desktop navigation mounts shared Forms management at `/communications/forms` and resolves every API call from the in-memory scoped grant rather than persisting access tokens in the webview. Run `bun dev`, `bun test`, `bun run build`, or `bun tauri dev` from this package. The Vite 8 production profile keeps the default 500 kB warning budget and isolates React into a stable vendor chunk instead of hiding oversized bundles. `bun --bun run tauri build --debug --no-bundle` is the bounded native-window compilation gate when the host has the Rust/Tauri toolchain. Forcing Bun keeps the Tauri CLI on the host's native architecture; signed distributable acceptance remains platform- and certificate-specific. --- ## @lssm-tech/app.communicationos-discord-worker Description: (none) Path: packages/apps/communicationos-discord-worker URL: /llms/app.communicationos-discord-worker # CommunicationOS Discord worker Thin Node.js 24 composition for the observe-only Discord integration. Deploy the same binary once with `DISCORD_TRUST_ZONE=staff` and a staff bot token, and once with `DISCORD_TRUST_ZONE=managed-community` and a separate bot token. Required environment variables: - `DISCORD_BOT_TOKEN` - `DISCORD_TENANT_ID`, `DISCORD_WORKSPACE_ID` - `DISCORD_TRUST_ZONE` (`staff` or `managed-community`) - `DISCORD_GUILD_PROFILES_JSON`, a non-empty array of objects containing `guildId`, `sourceId`, `spaceId`, `connectionId`, `specialtyKeys`, `allowedChannelIds`, and `excludedChannelIds` - `DISCORD_DATABASE_URL` - `DISCORD_ENCRYPTION_KEY_BASE64` (32-byte AES key encoded as base64) - `DISCORD_PSEUDONYM_KEY` (separate keyed-HMAC secret for analysis identities) Optional policy variables are `DISCORD_ALLOWED_CHANNEL_IDS`, `DISCORD_EXCLUDED_CHANNEL_IDS`, `DISCORD_BACKFILL_DAYS`, and `DISCORD_AUDIT_RECONCILIATION_DAYS`. `DISCORD_OBSERVATION_SINK_MODULE` can override the built-in encrypted PostgreSQL sink with a module exporting `createDiscordObservationSink`; there is no lossy fallback. Each trust-zone deployment must use a distinct encryption key and key reference. The database remains mandatory with an external sink because the active `community_source` and `discord_guild_installation` rows are refreshed before every live or backfilled raw write. Revoked, unhealthy, mismatched, or newly excluded guild/channel observations fail closed before payload encryption. The legacy `DISCORD_ALLOWED_GUILD_IDS`, `DISCORD_SOURCE_ID`, `DISCORD_SPACE_ID`, `DISCORD_CONNECTION_ID`, `DISCORD_SPECIALTY_KEYS`, and channel policy variables remain supported only when exactly one guild ID is configured. Multi-guild deployments fail closed without complete JSON profiles. `DISCORD_STAFF_ROLE_IDS`, `DISCORD_MODERATOR_ROLE_IDS`, and `DISCORD_SPECIALTY_KEYS` configure governed analysis. The worker exposes `GET /health` on `DISCORD_HEALTH_PORT` (default `8083`); degraded and offline coverage, including startup, returns HTTP 503. `GET /live` reports process liveness without claiming Gateway readiness. Railway's `PORT` is used when `DISCORD_HEALTH_PORT` is not set. ## Managed hosting `DISCORD_WORKER_HOSTING=lssm_managed` selects the managed-ecosystem composition (`src/managed-composition.ts`). It builds the same runtime, but refuses to compose (`discord_managed_binding_incomplete`, naming the keys only) unless the managed binding is complete: no `DISCORD_OBSERVATION_SINK_MODULE` (managed hosting always uses the built-in encrypted PostgreSQL sink), `DISCORD_DATABASE_URL`, `DISCORD_ENCRYPTION_KEY_BASE64`, an explicit `DISCORD_ENCRYPTION_KEY_REF` for this trust zone (the `discord-raw-aes-key` default is refused) and `DISCORD_PSEUDONYM_KEY`. Any other value keeps self-hosted behaviour. --- ## @lssm-tech/app.communicationos-mcp Description: MCP server exposing CommunicationOS contracts as AI-callable tools via the Model Context Protocol. Path: packages/apps/communicationos-mcp URL: /llms/app.communicationos-mcp # CommunicationOS MCP Governed Model Context Protocol surface for CommunicationOS. It exposes tenant-scoped thread reads, drafting, summarization, extraction, provider health, inbound-route inspection, and the canonical Forms operation registry. Forms tools inherit their contract auth and PII annotations. Direct `communication.reply.send` is intentionally excluded: outbound delivery remains subject to room membership, current authority, and the approval/send orchestrator. ## MailerSend diagnostics `createMailerSendMcpProviderDependencies` binds the read-only `integrations.email.provider.health` and `integrations.email.inbound-routes.list` tools. The host injects a tenant-and-connection-scoped resolver returning MailerSend credentials and a domain id. Secrets never appear in MCP tool inputs or outputs. Both tools take `tenantId` as input, but they only run for the verified subject (`src/provider-scope.ts`). The input tenant must equal the subject's `tenantId`, and the subject must hold the `admin` role, because the contracts declare `policy.auth: 'admin'` and the MCP gate itself only checks for an authenticated actor. Anything else is `FORBIDDEN` (403) before the connection resolver is called, so a token for one tenant can never load another tenant's MailerSend connection. ## Subject and trust boundary The stdio entrypoint (`startCommunicationOsMcpServer`) verifies one CommunicationOS access token at startup with `createCommunicationAccessTokenVerifier` from `@lssm-tech/integration.communication-os-host-auth`, then builds the server. It reads only these variables: | Variable | Purpose | | --- | --- | | `COMMOS_MCP_ACCESS_TOKEN` | Access token minted by communicationos-api (issuer `https://api.hcircle.app`, audience `communication-os-api`). | | `COMMOS_MCP_TENANT_ID`, `COMMOS_MCP_WORKSPACE_ID`, `COMMOS_MCP_SPACE_ID` | The scope the token must carry exactly. | | `COMMUNICATION_OS_ACCESS_TOKEN_SECRET` | The shared HS256 signing secret (at least 32 bytes). | A verified, in-scope token becomes the subject of every tool call: `{ actor: 'user', userId: , tenantId, workspaceId, roles }`, with the token's space as the `policyContext.spaceId` fact. Handlers and policies therefore see the verified workspace and space, not only the tenant. The principal and the token's `exp` are cached; from `exp` onward, and whenever a variable is missing or the secret, signature, issuer, audience, scope or expiry does not verify, every call is anonymous and the MCP auth gate rejects it. The startup log line reports `subject: authenticated | unconfigured | rejected` and never the token. Restart the gateway with a fresh token to renew it. **Trust boundary.** Verifying the token needs the shared HS256 secret, which can also mint tokens. Run this gateway only server-side, next to communicationos-api and inside its secret boundary, never on a client or developer machine. Distributing it to clients would need a contract-first token introspection route instead of the shared secret. The import-time `server` export and `buildCommunicationOsMcpServer()` without a resolver stay anonymous. `startCommunicationOsMcpServer` builds and connects its own gateway after verification, so the exported `server` is not the connected instance. The default server binds no provider resolver, so production hosts must also inject a vault-backed connection resolver before the provider tools can execute; the subject guard above still applies. ## Managed CompanyOS composition When the managed CompanyOS ecosystem launches the gateway it sets `COMMOS_MCP_HOST_ASSERTION` instead of an access token, and the entrypoint uses `composeManagedCommunicationOsMcpGateway` (`src/managed-composition.ts`). The assertion is a short-lived CompanyOS host assertion for exactly the configured `COMMOS_MCP_TENANT_ID`, `COMMOS_MCP_WORKSPACE_ID` and `COMMOS_MCP_SPACE_ID`. The gateway exchanges it with the CommunicationOS host-session exchanger that communicationos-api uses, then verifies the issued token through the standalone subject resolver and builds the same governed gateway. It reads only these extra variables: | Variable | Purpose | | --- | --- | | `COMMOS_MCP_HOST_ASSERTION` | CompanyOS host assertion (audience `https://api.hcircle.app/v2/auth/host-exchange`). | | `COMMUNICATION_OS_COMPANYOS_ISSUER`, `COMMUNICATION_OS_COMPANYOS_SHARED_SECRET` | The only accepted assertion issuer and its HS256 secret (at least 32 bytes). | | `COMMUNICATION_OS_HOST_MEMBERSHIPS` | JSON array of explicit `{ issuer, subject, tenantId, workspaceId, spaceId }` tuples, as in communicationos-api. | An assertion from another issuer, secret or scope, a subject without an exact membership tuple, or a missing or malformed membership policy leaves the gateway anonymous (`subject: rejected | unconfigured`), so every tool call fails closed. The startup log line reports `hosting: managed`. **Session lifetime.** The exchanger issues the access token with its default 5-minute lifetime, and the assertion itself expires after 60 seconds. The managed session therefore lasts 5 minutes from launch; from then on every tool call is anonymous and fails closed. There is no refresh path: the CompanyOS host must relaunch the gateway with a fresh assertion. **Trust model.** This is not an independent authorization boundary in the way the communicationos-api exchange is. The process holds the CompanyOS assertion secret as well as the access-token secret, and the membership policy comes from the same launch environment as the assertion. Only `COMMOS_MCP_HOST_ASSERTION` and the `COMMOS_MCP_*_ID` scope may be per-launch input. `COMMUNICATION_OS_HOST_MEMBERSHIPS`, `COMMUNICATION_OS_COMPANYOS_ISSUER` and both secrets must come from operator-controlled deployment configuration, never from per-launch host input. The assertion carries communicationos-api's host-exchange audience, so treat the launch environment as secret: a leaked assertion can be replayed at communicationos-api until it expires (60 seconds). The standalone trust boundary above still applies: run the gateway only server-side, inside the CommunicationOS secret boundary. --- ## @lssm-tech/app.communicationos-mobile Description: Expo Router iOS and Android shell for CommunicationOS. Path: packages/apps/communicationos-mobile URL: /llms/app.communicationos-mobile # `@lssm-tech/app.communicationos-mobile` Message search uses the authenticated canonical space projection and shares the same typed API boundary as web and desktop. It is not limited to the active room. Thin Expo Router shell for CommunicationOS on iOS and Android. It consumes the shared application kit, declares SecureStore for credentials and SQLite for offline projections, and permits device, managed-cloud, or self-hosted connector placement. Auth sessions and provider credentials are stored through a scoped, device-only SecureStore vault. Calm Signal renders only spaces supplied by the authenticated session; signed-out and no-access states never invent personal or company spaces. Native AuthOS bearer sessions are exchanged for short-lived, scope-derived CommunicationOS grants before live spaces, rooms, or messages are loaded. Signed-out users receive a native email/password and TOTP surface in English, French, or Spanish. The bearer and MFA authority remain in device-only SecureStore, and CompanyOS performs the server-secret hCircle host exchange so no tenant, workspace, or space is accepted from the device. The additive `useMobileCommunicationWorkspace` hook exposes reload, authorized room selection, idempotent send, pending state, and recoverable action feedback; the state-only `useMobileCommunicationSession` hook remains compatible. Transient send failures are persisted in the encrypted, workspace-scoped SQLite outbox. The active session retries them every five seconds with their original idempotency keys and exposes an accessible queued-message status until confirmed. Each queued payload is additionally sealed with expo-crypto AES-256-GCM in the shared `v2` outbox envelope, under a per-database key held only in device-only SecureStore (separate from the SQLCipher key), with tenant, workspace, space, principal, room and idempotency key as additional data. Tampered, re-scoped or still-plaintext rows are quarantined on replay and never sent; a key that cannot load fails replay closed and leaves rows pending. When the database opens, pending sealed rows whose key was lost are quarantined as `seal_key_lost` before a new key is created, and plaintext v2 rows written by an earlier build are sealed in one transaction because they already carry the full owner scope; nothing is dropped. The native composer uses the platform document picker for up to five supported files, hashes and uploads them inside the active scope, replays only opaque IDs, and opens authenticated downloads through the system share sheet. Canonical room and thread URLs render a dedicated conversation detail instead of falling back to the generic Inbox. The screen names the requested opaque room or thread, resolves thread bindings only from the authenticated workspace, and mounts messages and the composer only after the resolved room is authorized. Late route responses are fenced, 401 detail loads clear the device credential, and sends retain the active room, attachment IDs, outbox, and idempotency rules. One shared workspace generation fences selection, send, recovery, and replay. Selection merges only its conversation slice into the latest workspace, while a per-session single-flight queue serializes send and replay outbox mutations. Failed upload, authentication, and network attempts keep the native draft and selected files until a send is confirmed or durably queued. Forms management is available at `/communications/forms` using the current short-lived grant. Native public forms use `/f/{opaqueToken}` and the shared localized renderer; answers and bearer tokens are never placed in URLs. Support case snooze and archive controls are available only when both `support.authority` and `support.case-lifecycle` are present in the explicit `EXPO_PUBLIC_SUPPORT_OS_FLAGS` list. The SupportOS API independently enforces the tenant/workspace rollout gate. Native retries preserve the operation key and the original snooze deadline; archive confirmation does not claim erasure. Support case keyword search and saved-view apply, save, and archive are available only when `support.authority` and `support.search-views` are both present in that same explicit list. Results stay on the redacted SupportOS projection, saved-view mutations retain their retry identity, and late initial-list responses cannot replace a newer search result. Saved filters not editable on mobile remain apply/archive-only instead of being silently rewritten. Ordinary case claim and self-release are available with `support.authority`; the native surface never exposes administrator assignment or governed steal. Live count-only collision labels and heartbeats additionally require `support.case-presence`, so presence remains disabled unless both that flag and authority are enabled. Outcome-ambiguous assignment retries preserve their key, and a completion for a previously selected case cannot rewrite the current case detail revision. Merge, split, and link review is also authority-gated. Mobile refreshes and fences both case revisions through the shared relation orchestrator, presents a separate inline confirmation, retains retry identities after ambiguous outcomes, and reconciles only redacted case projections. Relation/evidence authority and CommunicationOS content references are never rendered. Private-note composition requires the full authority, internal-note, composer, and reconciliation flag conjunction. The body is sent only through the governed compose operation to CommunicationOS-owned encrypted storage; the SupportOS mobile list renders body-free evidence. An ambiguous retry freezes the original body, case revision, and operation key together until completion or an explicit edit. The Expo bundle imports only the Calm Signal font weights rendered by the shell: IBM Plex Sans 400/500/600, IBM Plex Mono 500, and Newsreader 600. Run `bun dev`, `bun android`, `bun ios`, `bun test`, or `bun run typecheck` here. --- ## @lssm-tech/app.communicationos-realtime Description: Long-running CommunicationOS realtime gateway for realtime.hcircle.app. Path: packages/apps/communicationos-realtime URL: /llms/app.communicationos-realtime # CommunicationOS realtime gateway Long-running Bun WebSocket gateway for `realtime.hcircle.app`. It accepts only configured origins and a valid, single-use `/v2/events` ticket. Cursor catch-up is supplied through an event-source port so replay remains backed by the canonical journal rather than process memory. --- ## @lssm-tech/app.communicationos-web Description: Next.js and PWA shell for the CommunicationOS application kit. Path: packages/apps/communicationos-web URL: /llms/app.communicationos-web # `@lssm-tech/app.communicationos-web` The authenticated `/communications/meetings` surface is hCircle's calm, connection-first projection of the shared OPA meeting workspace. Preparation is optional and non-blocking; productivity scoring and clinical inference are not available, sensitive inference is ephemeral, and sharing remains consent-led. An opaque `meetingRef` selected by the route loads live contract-validated OPA state through the current hCircle access grant; route state never grants access. The Search workspace calls the canonical `communication.message.search@2.0.0` projection. Queries stay within the authenticated tenant, workspace, and space; the browser does not search provider APIs or infer authority from route state. Thin Next.js App Router and installable PWA shell for CommunicationOS. It consumes `@lssm-tech/bundle.communication-os`, uses managed-cloud or self-hosted connectors, and declares encrypted IndexedDB as its projection store. Credentials never belong in browser storage. For focused source feedback, run `bun run check:edit -- --package @lssm-tech/app.communicationos-web --test packages/apps/communicationos-web/src/app/CommunicationSignIn.test.tsx`. The reviewed fixture profile also accepts the inbox and route-copy test files; lint and source typechecking remain required. This is focused feedback, not affected-consumer or release acceptance. `bun run dev:focus -- --package @lssm-tech/app.communicationos-web` selects the local signed-out UI fixture on `http://127.0.0.1:43120`. It mirrors this app into an ignored, disposable directory without dotenv or generated output, links existing workspace dependencies, and runs the existing Next development server. The loopback API fixture on port 43121 returns no authenticated session and denies sign-in and consequential mutations. It never sends invitations or messages. App edits are mirrored using filesystem events with a bounded 500 ms app-only reconciliation fallback; shared workspace source remains directly linked. Stop the command to close its server, fixture and source watcher. Cold-route and Fast Refresh qualification is recorded under `docs/refactoring/lssm-ecosystem/evidence/w1-ui-feedback`; the presence of this profile alone does not establish that the UI latency budgets have passed. The qualified browser binding uses the existing CommunicationOS locale, capability and personalization providers and Calm Signal shell through their four module subpaths. The module's package-level browser metadata is a union of supported surfaces; it does not make its root or server exports browser-safe. Failed central sign-in responses are shown through the existing localized alert, and pending/error state is part of the local interaction qualification. Signed-out users receive an invite-only hCircle entry surface. When `NEXT_PUBLIC_HCIRCLE_LSSM_RP_ENABLED=1`, it offers only central LSSM OIDC; the local invited-email magic-link control is removed from the rendered tree. The web-owned callback strictly forwards the bounded authorization response to the hCircle API; the browser route never exchanges tokens or accepts an arbitrary destination. Disabling the central RP restores the existing-email magic-link path as an explicit rollback authority, so both authorities are never active in one deployment. Authenticated users receive an explicit product-local sign-out in the Calm Signal shell. It clears only the current hCircle session projection, active-room selection, and scoped queued-message outbox; the central Passport and other products retain their independent sessions. The protected production replay is opt-in through `HCIRCLE_LSSM_PRODUCTION_CANARY_AUTHORIZED=1`, exact `E2E_PRODUCTION_BASE_URL=https://chat.hcircle.app`, and secret-manager-provided canary credentials. `bun run test:production-oidc-canary` proves central sign-in, optional consent, hCircle session exchange, product sign-out, denied replay, and Passport sign-out with Playwright traces and screenshots disabled. The public host boundary is explicit: `www.hcircle.app` serves the Human Topography product site, localized EN/FR/ES feature/persona/solution pages, waitlist and status experiences, and deterministic sitemap/robots/LLMS files; `chat.hcircle.app` owns the Chat one-pager and authenticated application. The apex redirects to `www`, private app routes are excluded from discovery, and unknown hosts fail with 421. All acquisition surfaces use the shared design system; the authenticated CommunicationOS route registry remains unchanged. A hosting-recovery canary may set `HCIRCLE_PREVIEW_SURFACE=marketing`. Only the exact injected `RAILWAY_PUBLIC_DOMAIN` then rewrites to the public acquisition surface; a provider suffix or another generated domain is not trusted. The canary does not activate CommunicationOS auth, API, realtime, or waitlist delivery. The PWA registers a same-origin service worker for the offline shell and hashed static assets only. Navigations fall back to the Calm Signal `/offline` route; `/api/*`, `/v2/*`, messages, credentials, and authenticated responses are never placed in the service-worker cache. Security headers bind browser connections to the configured CommunicationOS API and realtime origins. The Calm Signal Spaces and Rooms routes consume live typed projections. They show isolation and encryption posture, list canonical rooms, and keep the explicit active-room choice for the current browser session. The catch-all route validates all 23 canonical CommunicationOS paths through the shared route registry. Room and thread detail URLs retain their opaque target; unknown paths return the Next.js not-found boundary, disabled extensions render an explicit recovery state, and neither case silently opens another room. Traversal-shaped, separator-bearing, malformed, control-character, and oversized opaque targets are rejected by the same shared resolver before the conversation surface receives an identifier. The production canary proves HTTP resolution for all 23 canonical paths. Its 10-route anonymous public-web cohort additionally exercises 320, 390, 768, 1280, and 1440 CSS pixels in light and dark mode with reduced motion. Every representative route receives route-level Axe scanning in both themes; phone widths reject sub-44px visible controls, and keyboard focus, navigation containment, active-route state when navigation links are present, console errors, and document overflow are checked explicitly. This evidence is scoped to standalone web and does not promote PWA, Expo, or Tauri qualification. Inbox is a dedicated route-specific overview rather than an alias for the active room. It shows the authorized room count, a compact recent-message ledger for the active room, canonical links to every other authorized room, and an explicit room-setup recovery state when the scope is empty. The room composer accepts up to five PDF, image, CSV, or text attachments (5 MB each). It verifies and uploads files before sending, preserves opaque attachment IDs during offline message replay, and downloads through the authenticated API; no provider or storage URL enters the browser projection. At phone widths, the message field and explicit Attach/Send actions reflow into full-width rows with 44px-or-larger targets. Accounts without an authorized space receive a recovery-oriented empty state instead of a blank content region. The governed-work routes are no longer event-only placeholders. Each route can create a persisted work item and presents the allowed approve, reject, or resolve decision. Realtime and periodic refreshes reconcile the journal-backed state, while the API remains the authority for manager-only decisions. The Connections route presents one-click official OAuth cards for Gmail, Slack, and WhatsApp Business with explicit managed/self-hosted placement. Telegram's opaque vault-reference workflow remains behind an operator-only disclosure; public users are never asked to paste provider tokens or secret references. Run `bun dev`, `bun test`, `bun run typecheck`, or `bun run build` from this package. ### Better Auth 1.7 callback forwarding The existing public LSSM callback alias forwards only its bounded authorization response to the fixed API owner's `/auth/callback/` endpoint, replacing the removed `/auth/oauth2/callback/` path. Existing issuer and parameter checks remain in force. API token exchange, provider registrations, cookies and account-identity migration still require live qualification before cutover. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. --- ## @lssm-tech/app.communicationos-worker Description: (none) Path: packages/apps/communicationos-worker URL: /llms/app.communicationos-worker # CommunicationOS worker Provider effects remain behind canonical Runtime Node approval and its execution fence. The worker claims and settles durable outbox records; it does not manufacture approval. The journal resolver requires current sender membership and applicable agent grants. Deleted messages and revoked memberships cannot resolve provider context. Dispatch snapshots context before adapter/health calls and resolves again immediately before sending; changed recipients, content, credentials or routing metadata are rejected without provider.send. Ownership: the subscription lifecycle coordinator and connection sync coordinator belong to `@lssm-tech/lib.communication-runtime` (`./ecosystem-subscription-coordinator`, `./ecosystem-connection-sync`). This host binds them to the Runtime Node subscription authority, the secret-backed adapter resolver and `CommunicationDeliveryError`, and schedules them through the sync and subscription workers. ## Capability readiness Read (synchronization), draft and send readiness are reported separately in `/health` (`capabilities`). Started without `DATABASE_URL`, the worker stays up, opens no connection, starts no loop and answers `/health` with 503 `configuration_required` / `database_not_configured`, listing `DATABASE_URL` under `missing` for every capability. Sync-only installations (`COMMUNICATION_OS_WORKER_ENABLE_SYNC=true`, delivery disabled) ingest with state `partial` while sends report their blocker. Sync and delivery run on independent loops. Sends require `COMMUNICATION_OS_WORKER_ENABLE_DELIVERY=true`, a credential-reference policy and an actual Runtime Node delivery port: `COMMUNICATION_OS_RUNTIME_NODE_DELIVERY_URL` (HTTPS, or loopback HTTP) plus `COMMUNICATION_OS_RUNTIME_NODE_WORKLOAD_TOKEN` (`COMMUNICATION_OS_RUNTIME_NODE_TIMEOUT_MS`, default 15000). Without them every claimed record is rejected with `runtime_node_authority_not_configured`. The port posts `{ schema: "communication.runtime-node.delivery-effect.v1", outboxRecord }` with an `Idempotency-Key`; a timeout, lost response, malformed success or 5xx is held in reconciliation custody and never resent. Gmail connections synchronize through durable, account-bound history sync: a bounded backfill (`COMMUNICATION_OS_GMAIL_BACKFILL_QUERY`, e.g. `after:2019/01/01`), history catch-up from the pre-scan baseline, and incremental history afterwards. The cursor is journaled only after a page's records commit. Credentials may record `grantedScopes`; a credential without a send scope refuses sends while read-only sync continues. Every Gmail read is bound to the connection's authorized address: a credential that authenticates another mailbox is `connection_scope_mismatch` and the connection becomes `revoked`; a transient provider failure is `offline` and is retried on the next poll. A message that fails on its own (non-retryable typed error or normalization failure) is recorded as a `message_held` sync invalidation and keeps coverage `partial`. Founder connections are created by the CommunicationOS Gmail OAuth flow; see `docs/operations/founder-ops-v2/gmail-connect.md`. ## Schema and outbox recovery The worker never migrates in production. Run `bun run migrate` (explicit step, same `DATABASE_URL`) before rolling out workers; at start the worker only verifies the migration ledger and reports `schema_version_mismatch` on every capability when its migrations are missing or differ. `COMMUNICATION_OS_WORKER_MIGRATE_ON_START=true` is a development/test convenience and is ignored when `NODE_ENV=production`. A re-claimed expired outbox lease is held in reconciliation custody (`lease_expired_outcome_unknown`) instead of being redispatched, once the store marks it (`reclaimedExpiredLease`). A database that cannot be reached or refuses the login is reported as `database_unreachable` (reason `connection`, `authentication`, `tls_handshake`, `tls_not_offered` — `sslmode=require` against a server that offers no TLS, diagnosed with one SSLRequest — or `query_failed`, never the URL or message), distinct from `schema_version_mismatch`, whose body lists `migrations.expected`, `found` and `missing` ids. `/health` is always `Cache-Control: no-store`. The schema is checked once at start: restart the worker after the database becomes reachable or is migrated; a persistent 503 on `/health` lets the orchestrator's health check restart it. ## Evidence ingestion With `COMMUNICATION_OS_EVIDENCE_ENABLED=true` and a complete binding (`COMMUNICATION_OS_EVIDENCE_TENANT_ID`, `_ORIGINALS_BUCKET`, `_COLLECTION`, `_QDRANT_URL`, optional `_QDRANT_API_KEY` and `_NAMESPACE`, `_EMBEDDING_API_KEY`, `_EMBEDDING_MODEL`, `_REDACTION_DECISION_REF`, plus a durable evidence ledger supplied by the host), Gmail sync hands every attachment original to knowledge custody (one original per digest, one provenance per account) and ingests each thread with account-bound ids; provider deletions withdraw the thread. Anything missing reports `evidence_ingestion` as `evidence_binding_not_configured` with the missing names, and sync continues without evidence. This host does not compose a durable ledger yet, so the row stays blocked on `durable_evidence_ledger`. Run `bun run typecheck`, `bun run build`, and the delivery-dispatcher/journal-delivery-context/Slack/Teams pipeline tests. These synthetic tests do not qualify deployed providers, OPA follow-up source authority or production rollout. ## Managed hosting `COMMUNICATION_OS_WORKER_HOSTING=lssm_managed` selects the managed-ecosystem composition (`src/managed-composition.ts`). It starts the same configured worker composition, but only when the managed binding is complete: `DATABASE_URL` with `COMMUNICATION_OS_DATABASE_SSL_MODE` left at `require` (TLS required; the certificate is not verified in this mode), no `COMMUNICATION_OS_WORKER_MIGRATE_ON_START`, a stable `COMMUNICATION_OS_WORKER_ID` lease owner, and, when delivery is enabled, an HTTPS Runtime Node delivery URL (loopback HTTP is refused) with its workload token. When delivery or sync is enabled, every `COMMUNICATION_OS_CREDENTIAL_REF_PREFIXES` entry must stay inside the encrypted database vault (`communication-vault://…`, the `managed_cloud` placement) with `COMMUNICATION_OS_CREDENTIAL_MASTER_SECRET` set. Support reconciliation additionally needs HTTPS `SUPPORT_OS_API_ORIGIN` and `COMMUNICATION_OS_AUTHOS_DOWNSTREAM_EXCHANGE_URL` plus the AuthOS workload token. Otherwise the worker opens no connection and answers `/health` with 503 `configuration_required` / `managed_binding_incomplete`, listing the keys to fix (never their values) and the same capability matrix as an unconfigured worker, every capability blocked. Any other value keeps self-hosted behaviour. --- ## @lssm-tech/app.contractspec-ci-controller Description: Burst-aware GitHub delivery dispatcher and JIT runner authority for ContractSpec CI. Path: packages/apps/contractspec-ci-controller URL: /llms/app.contractspec-ci-controller # ContractSpec CI controller This private LSSM application coalesces GitHub delivery events, reserves the LSSM CI budget, and issues one repository-scoped JIT configuration per Railway runner. It is an execution adapter for the provider-neutral delivery protocol; it is not policy or promotion authority. The default is `CI_CONTROLLER_ENABLED=false`. In that state the service exposes `GET /healthz` and an unavailable `GET /readyz`; every mutation endpoint returns `503 controller_disabled`, and GitHub App, webhook, economic-evidence, and runner credentials are not required. This mode exists for infrastructure and health qualification before authority is installed. Active mode requires `CI_CONTROLLER_ENABLED=true` plus the complete repository-only GitHub App and controller credentials. Startup fails closed if any active credential is absent. Never substitute a personal or production-wide token. Budget defaults are `$30` target and `$45` circuit breaker. Override them with `CI_MONTHLY_TARGET_USD` and `CI_CIRCUIT_BREAKER_USD`; the target must remain strictly below the breaker. The controller listens on IPv6 and IPv4 using the assigned `PORT`. Its runner label is a single validated `CI_RUNNER_LABEL`, defaulting to `railway-linux`. The active readiness response means configuration is loaded, not that a runner pool or end-to-end delivery is qualified. Dispatch intent is persisted before contacting GitHub. An unconfirmed dispatch retains its budget reservation and blocks that branch across restarts. New attempts receive a durable UUID before dispatch, included with the source SHA in the workflow run name. On restart the controller scans complete bounded GitHub run pages and accepts only a unique matching workflow from its own App in the configured repository. A newer queued head survives acknowledgement of the older attempt. No match, incomplete pagination, identity conflict, or duplicate matches retain the reservation and block retries. Legacy attempts without a UUID still require operator reconciliation. Never erase the queue to retry. Queue and budget transitions sync the file and directory before acknowledgement. They support one controller writer on durable storage, not multiple active writers. `/healthz` reports blocked dispatch count. GitHub calls have bounded deadlines. `CI_DELIVERY_WORKFLOW_REF` selects the trusted workflow branch (default `release`); deploy the matching workflow correlation changes before enabling the controller. This recovery covers GitHub dispatch acknowledgement, not the runner-service pool. Only matching-repository branch pushes and open, non-draft, same-repository PR updates enter the queue. Labels and fork metadata do not grant trusted-runner access. Workflow dispatch uses Actions permission with source read-only access. Budget inputs reject negative/non-finite amounts, historical billing periods, and unexplained decreases. Ordinary positive-cost admission closes at the configured circuit breaker. Provider reservations, actual usage reconciliation, independent watchdog operation and progressive production cutover remain separately qualified platform work. ## Run-scoped disposable pool (operator mode) The `src/pool` engine persists intent before create/start/delete, reserves cost by stable job identity and verifies resource absence before closing a lease. Unknown creates are recovered by exact generated identity; no observed resource means no retry. Unknown starts are observed rather than reissuing JIT credentials. Use a dedicated local state directory and an operator-reviewed configuration: ```json { "repository": "owner/repo", "runId": 123, "runAttempt": 1, "workflowSha": "<40-character approved workflow commit>", "sourceSha": "<40-character approved source commit>", "actorLogin": "ci-app[bot]", "workspaceId": "", "projectId": "", "environmentId": "", "repositoryRoot": "/absolute/repository", "stateDirectory": "/absolute/private/run-state", "githubAppId": "", "githubInstallationId": "", "githubPrivateKeyPath": "/secure/github-app.pem", "maximumConcurrent": 2, "maximumRunUsd": 2, "estimatedJobUsd": 0.25, "maximumLifetimeMs": 1200000 } ``` Manual Dev CI defaults its `ephemeral_pool` input to enabled. Other workflows must explicitly enable that input when supported. This selects run/job-bound Railway workers; it does not start the operator automatically. Then run `bun run pool:run /absolute/config.json` and, as a separate process, `bun run pool:watchdog /absolute/config.json`. The watchdog can also run once with `--once`. The operator host needs authenticated `gh` and `railway` CLIs and Bun. The main writer holds an OS-backed SQLite lock; restart cannot change the pinned operator scope. Runner build files come from the approved Git object, not a mutable checkout. A separate expiry watchdog records its own cleanup receipts without writing the main ledger. It remains independent of the Railway workers. Every job uses a run/attempt/job-specific label, with no shared Railway label on its worker. Labels are only routing: an administrator-installed pre-job guard compares GitHub's assigned identity with the launch manifest. Mismatch terminates the runner process group and blocks, preventing even subsequent `always()` steps. GitHub may download action packages during setup before this hook; this profile is for explicitly reviewed source, not qualification of hostile-code isolation. The initial profile uses 2 vCPU and 8 GB, one JIT job, no restart, no data volume, no public domain and no controller bootstrap credential in the worker. The operator caps reservations per run and checks observed project usage against the LSSM CI circuit breaker. Holds remain until provider cost reconciliation; deleting a worker does not prove its cost was zero. This is a local operator capability, not active-active managed scheduling. The shared pool authority port remains mandatory; managed installation must wire current Connect/Runtime Node authority and shared atomic budget/state adapters. The HTTP controller's automatic admission stays separately qualified and disabled until the complete pool cutover requirements pass. General reviewed dispatches can supply `workflowPath` and `jobBindings` in the operator config. Exact source/workflow identity, App actor, repository, run, attempt and job labels remain mandatory. The pinned scope includes the job map; a restart cannot change it. General PR/matrix admission remains a separate qualification. The single-host scheduler defaults to a 60-second observed quiet window before admission. `quietWindowMs` accepts 0–600000 milliseconds. Candidate changes reset persisted quiet time; no worker or cost reservation is created while coalescing. A disappearing candidate or a backward clock resets the window. Previously admitted work resumes immediately with its original reservation and authority. This local coalescing behavior still requires live push qualification before activating automatic routing. ## Build workload measurements Dev CI requests a Turbo run summary and projects only source identity, run/attempt, workload profile, elapsed time, task counts, cache-hit counts and the ten slowest tasks. Raw command lines, filesystem locations, environment values and global cache inputs are never published by this projection. Malformed or mismatched summaries fail explicitly. Measurements appear in job output and the GitHub step summary; they are diagnostic evidence, not release or execution authority. Operator shutdown first requests normal cancellation, then waits up to 90 seconds for terminal status and log availability. Force cancellation requires a fresh verified run/attempt snapshot after that grace period. Final receipts distinguish worker cleanup from log availability. Transient CLI observation failures retry within the original run lifetime; they do not imply the run is terminal. Manual full-repository Dev CI qualification has a 120-minute build ceiling. Its operator must be configured with an appropriate bounded lifetime (at most two hours); ordinary CI retains its existing timeout. This cold-baseline allowance does not satisfy the affected-change latency target or alter configured budgets. The first operator admission persists an immutable run deadline before any runner context or allocation. Restart reuses that deadline; missing/corrupt lifetime state after work began fails closed. Legacy interrupted runs must be drained with their original operator before adopting the new lifetime record. Late workers cannot receive a fresh full lifetime: their retirement is capped by the run deadline plus a two-minute cleanup reserve. The watchdog remains active through that retirement bound and its cleanup grace, including after an operator crash. Operator configuration parsing rejects unsupported event/actor types, absent or invalid workflow paths, mismatched source/workflow commits, and empty, duplicate or malformed job maps before returning an executable configuration. This closes a comma-expression regression that discarded the initial policy predicates. Independent GitHub run/job verification remains required before allocation. `inspectReviewedPullRequestRun` is a read-only PR identity boundary. It binds an explicit reviewed repository, actor, PR number, workflow, head, base and synthetic merge commit against two independent run/PR observations. Forks, closed PRs, `pull_request_target`, substituted associations and changed attempts fail closed. The result explicitly has `executionAuthorized: false`; allocation requires an explicit operator configuration with matching `pullRequest` identity and a reviewed `runnerContextSha`. The operator revalidates current PR metadata on each snapshot. The runner guard checks the exact PR merge ref, GITHUB_SHA and workflow SHA. The local scheduler accepts `discovery.kind: pull_request` with a reviewed PR number, head branch, base branch, actor and job map. Each candidate is pinned to current GitHub head/base/merge identities and rechecked before return. It uses the existing quiet window, persistent reservation and exact-run resume. Push discovery remains the default when `kind` is omitted. A PR lane requires a reviewed `operator.runnerContextSha` before scheduler startup. When the PR changes, admission fails closed and the operator retires the old run. The retirement reader verifies immutable run/attempt/repository/actor/PR association without demanding that the PR remain open at its old head. Only shutdown and terminal receipt readback use that reader; allocation continues to require fresh PR state. Live scheduler/guard qualification remains necessary before cutover. Operator `resourceProfile` selects a versioned host-owned capacity contract: `standard-v1` (default, 2 vCPU / 8 GB), `light-v1` (1 vCPU / 2 GB), or `build-v1` (4 vCPU / 16 GB). The selected ID and capacity are recorded in profile evidence and bound into restart scope. Workflow labels cannot select capacity. Set a reviewed run reservation and lifetime appropriate to the chosen profile; resource support alone is not cost or workload qualification. Existing operators without the field preserve their original standard capacity. The reviewed PR canary also runs durable worker concurrency/restart tests, Builder readiness, coding receipt parsing and sandbox CLI recovery checks. It builds crypto-utils and lssm-os-spec prerequisites after the pinned install. Sandbox checks in this lane are subprocess/CLI fixtures, not live Docker containment evidence. The exact self-hosted job label and PR selector remain. ## Targeted Next build resource qualification `build-v2` retains the `build-v1` allocation of 4 vCPU / 16 GB. It additionally binds `CONTRACTSPEC_BUILD_CPU_BUDGET=4` to the operator resource profile. The runner validates this exact version/value pair and forwards only the two non-secret profile variables through its empty job environment. Existing v1 profiles and their persisted scope material remain unchanged; labels or workflow inputs cannot select a larger allocation. Use `.github/workflows/web-landing-build-qualification.yml` after integrating the reviewed commit into `release`. It is manual-only, has no GitHub-hosted fallback, and binds job name `Web landing build qualification` to key `next-build`. Start with the existing reviewed CI project/environment, `resourceProfile: build-v2`, `maximumConcurrent: 1`, and an explicitly reserved run budget plus independent watchdog. Bind `sourceSha` and `workflowSha` to the exact same release commit, `workflowPath` to this file, the actual run/attempt, and a fresh state directory. Keep the existing maximum lifetime at or below two hours; do not reset a failed run's deadline or reuse its scope to try a different profile. The workflow first measures the dependency-only Turbo build closure, then runs the complete web-landing package build (including its type gate) in a separate measurement phase. The dependency selector was verified to exclude web-landing itself. The app build is not skipped through a Turbo cache hit. Route counts belong to the exact source; do not freeze the old failed run's 1678 routes when the current release has changed. Reports bind actual Git HEAD, source SHA, run and attempt. They retain configured capacity, host-visible CPU count, actual cgroup quota/memory limit, CPU use and throttling, OOM-kill deltas, sampled phase memory and kernel lifetime peak. The lifetime peak includes earlier phases; sampled current memory can miss short spikes. Qualification requires exact CPU quota and an exact 16 GB or 16 GiB byte interpretation, which is reported explicitly. Larger, unbounded, missing or changed allocations cannot qualify the 4/16 profile. Failed commands, startup failures and OOMs retain failing measurement records without logging arguments or environment values. Download `web-landing-resources--` or read the corresponding bounded JSON log records. Compare the Next phase with the prerequisite phase and Railway usage before/after the scoped run. Reconcile actual costs and verify both runner inventories are clean through the operator/watchdog receipt. This is one workload sample, not full Dev CI, progressive cutover or operational acceptance. Do not increase memory until measured peak/limit evidence justifies a different reviewed profile. For the bounded correction to repository-wide cache invalidation, see [root workspace cache scope](../../../../docs/delivery/root-workspace-cache-scope.md). Next workload qualification requires an initially absent `.next` output directory and newly produced BUILD_ID, prerender and route manifests. Their hashes are recorded alongside source/run-bound resource observations. A zero exit code from Bun help or another no-op cannot qualify the Next phase. Existing outputs fail preflight rather than being silently deleted or reused. `recoverBuildMeasurements` recovers the exact measurement JSON records from operator-fetched job logs when artifact transport fails. Callers must verify the repository/run/job provenance separately. Recovery checks source/run/attempt, requires every requested workload, rejects conflicting duplicate records and hashes the retained bytes. It always reports `qualificationAccepted: false`; recovery cannot turn historical allocation-only or no-op evidence into success. Run the recovery command with an operator-fetched log from the verified job: ```sh bun src/recover-build-measurements-cli.ts /absolute/job.log /absolute/new-receipt.json SOURCE_SHA RUN_ID ATTEMPT web-landing-dependencies-v1 web-landing-next-v1 ``` The output is exclusive-create with private file permissions; an existing receipt is never overwritten. Only record count and log hash are printed. Review recovered records against workload artifacts and independent provider observations before accepting qualification. For a fresh GitHub read, `bun src/pool/recover-measurements.ts OPERATOR_CONFIG JOB_KEY /absolute/new-receipt.json WORKLOAD...` first revalidates the configured repository/run/attempt/workflow/source and selects one matching terminal job. It then downloads that job's logs through the bounded CLI transport and writes private, exclusive-create recovery evidence. This runs after shutdown and never holds cleanup open. A failed provider read leaves recovery unverified; use an already-retained, independently identified log only through the explicit file recovery command. ## Trusted push to Delivery bridge The existing single-host scheduler now accepts an opt-in `delivery` configuration that coalesces a trusted branch push, durably correlates an App-owned Delivery dispatch, and starts the existing job-bound operator/watchdog pair. The HTTP controller remains disabled; no provider deployment is implied. Run `schedule.ts CONFIG.json --check` before explicit `--watch` qualification with a one-run budget. See [the exact qualification procedure](../../../../docs/delivery/trusted-push-railway.md) for the config, runtime test coverage, receipts and ambiguity/recovery rules. --- ## @lssm-tech/app.job-application-api Description: (none) Path: packages/apps/job-application-api URL: /llms/app.job-application-api # Job application API Isolated authenticated REST/OpenAPI/SSE/WebSocket host for candidate-private job applications. Set `JOB_APPLICATION_API_ENABLED=true` and provide an allowlisted `JOB_APPLICATION_API_COMPOSITION_MODULE` to activate operations. Inbound Resend receiving is disabled unless `JOB_APPLICATION_RESEND_WEBHOOK_MODULE` names an allowlisted `@lssm-tech/integration.job-application-webhook-*` module. The `POST /api/job-application/v1/webhooks/resend` route preserves the raw body, forwards the exact Svix headers, rejects bodies over 1 MB, and exposes no email content or verification secrets in its response. The managed Resend module participates in API readiness and graceful shutdown. Use `@lssm-tech/integration.job-application-webhook-resend-managed` with its dedicated least-privilege database role and allowlisted encrypted-object/scanner dependency module. Missing scanner, storage, database, or Resend configuration keeps readiness failed closed. --- ## @lssm-tech/app.job-application-cli Description: (none) Path: packages/apps/job-application-cli URL: /llms/app.job-application-cli (No README.md) --- ## @lssm-tech/app.job-application-console Description: (none) Path: packages/apps/job-application-console URL: /llms/app.job-application-console # `@lssm-tech/app.job-application-console` Deployable candidate/operator host for the privacy-isolated job-application bounded context. The app proxies authenticated same-origin requests to the generated job-application API and projects only redacted bundle view models. Set `JOB_APPLICATION_API_URL` to the private API origin. Browser sessions and authorization remain owned by the upstream identity provider; no credential or candidate answer is stored by this host. The command center provides a URL-backed application list and detail selection, keyboard-accessible lifecycle/evidence/account/inbox/form tabs, explicit degraded and authority states, and exact-resource confirmations for every server-authorized high-risk action. Query parameters contain only opaque application and presentation-tab identifiers. The host never writes candidate values, bearer tokens, action authority, inbox content, or secrets to local or session storage. Validation: ```sh bun run test bun run typecheck bun run lint:check bun run build bun run test:e2e ``` --- ## @lssm-tech/app.job-application-mcp Description: (none) Path: packages/apps/job-application-mcp URL: /llms/app.job-application-mcp (No README.md) --- ## @lssm-tech/app.job-application-worker Description: (none) Path: packages/apps/job-application-worker URL: /llms/app.job-application-worker # Job application worker Continuous, abortable, fenced worker host for isolated account, inbox, browser, application, reconciliation, export, and deletion jobs. The managed composition claims from one exact deployment queue. Each work item carries its immutable candidate scope and initiating actor envelope; the worker reauthorizes the command and executes it under that candidate scope. Leases, heartbeats, completion, retry, and dead-letter transitions require the current fencing token. An isolated deployment may set `JOB_APPLICATION_EFFECTS_MODULE` to an allowlisted `@lssm-tech/integration.job-application-effects-*` package. The module must expose complete submit, reconciliation, and account effect ports, plus optional readiness and shutdown hooks. Partial or untrusted modules fail before claims begin; omitting the module preserves the killed-effect default. The managed effects package handles an authorized, durable `job-application.account.verify` claim by reserving exactly one pending inbox challenge and a fenced link/OTP sub-effect. It reads the sanitized message only through the candidate-scoped encrypted-object dependency, settles successful work, releases retryable failures, and moves unsafe or ambiguous challenges to takeover. External effects remain disabled unless both the worker control and the allowlisted effects module are explicitly enabled. Application deletion enqueues opaque external destinations before database references are scrubbed. When the global kill switch is off and `JOB_APPLICATION_EXTERNAL_EFFECTS_ENABLED=true`, the managed host starts a separate deletion service using `JOB_APPLICATION_DELETION_WORKER_ID` (falling back to `JOB_APPLICATION_WORKER_ID`). Tasks are ordered by the fifteen-minute deadline, heartbeat independently, and settle only through the exact candidate, owner, fence, and live lease. A lost lease never acknowledges an external effect; destination ports must be idempotent for safe crash replay. `JOB_APPLICATION_PROFILE_FACT_INVALIDATION_ENABLED` (default `false`, parsed like `JOB_APPLICATION_PACKET_BINDING_ENABLED`) starts a separate profile fact invalidation service; when it is off the consumer is neither composed nor started. Each tick discovers, in deployment worker mode, the candidates with a `job-application.profile.fact.no-longer-confirmed` outbox entry after their durable cursor (store migration 0018), composes one consumer per exact candidate scope with the worker client and polls until an empty batch. The cursor is persisted after every batch and after a failure, so a restart resumes from it and a replay is idempotent. A failing event stops only its candidate at the last recorded sequence and is reported by typed code. The service writes no external effect and is not gated by the global kill switch. ### Native effects bootstrap (candidate) The existing allowlisted effects module may export a composition or a `ManagedJobApplicationEffectsFactoryV1`. The latter receives the worker's native SQL client, fresh authority, workload token and live control reader at bootstrap. Its readiness runs before work is claimed. The provider owns the selected engine binding; the app has no private engine dependency. Missing provider/host authority keeps the existing disabled/unbound behavior. --- ## @lssm-tech/app.lssm-board Description: Private LSSM Board host for the founder-intelligence Board semantics, behind Vercel team protection and an app-level deny-by-default admission port (D-103, D-105). Path: packages/apps/lssm-board URL: /llms/app.lssm-board # @lssm-tech/app.lssm-board Private LSSM Board host for `board.lssm.co` (WEB-01, D-103, D-105, D-117). Board semantics are owned by the founder-intelligence spec, runtime and module; this app only hosts them and supplies the LSSM brand composition. ## Admission (D-105) Vercel `team-all-deployments` protection plus an app-level deny-by-default port (`src/admission`). Only the exact value `LSSM_BOARD_ADMISSION=vercel-team` admits. Unset, empty, `authos` (there is no AuthOS binding), `true`, `1`, case or whitespace variants and any unknown value refuse. `src/proxy.ts` applies the port to every path (pages, `/intake/**`, `/_next/static/**`, the favicon) and answers a refusal with a minimal `403 Forbidden` that keeps the private headers; the page re-checks admission with `forbidden()`. Local fixture checks never prove the Vercel protection; anonymous denial on a deployment needs its own authorized evidence. Every response is `private, no-store`, `noindex, nofollow, noarchive`, `DENY` framing (`frame-ancestors 'none'`), `no-referrer`, `nosniff` and `camera=(), microphone=(), geolocation=()`. ## Data source (server only) - Default: the synthetic founder-intelligence fixture with the LSSM profile applied. The UI labels the active source. - `LSSM_BOARD_DATA_SOURCE=private`: the file-backed `BoardPrivateStore` reads `LSSM_BOARD_PRIVATE_DATA_PATH`, which must be absolute and resolve outside the repository and the app, and `loadVerifiedPrivateDataset` checks it against `LSSM_BOARD_PRIVATE_SHA256` and `LSSM_BOARD_PRIVATE_BYTES`. The custody file is JSON: a `BoardWorkspaceData` whose handoff answers use the donor `SourceAnswer` shape, plus `boardProfileWorkspace` (the dataset-coupled profile section). Any missing, inside-repository, unreadable, mismatched or invalid file renders an explicit refusal; the fixture is never used in its place. - Private datasets and the donor HTML oracle are never committed; only digests are recorded, in gitignored custody. ## Browser-local state `src/client` supplies the localStorage `BoardStorageAdapter` (denied storage reads as unavailable), the `storage`-event bridge, the `BoardStoreProvider` (`useSyncExternalStore`, StrictMode-safe) and the shell: storage status and blocked reason, full backup and untouched recovery exports, backup import with merge preview or confirmed replace, participant-response import (always a new unreviewed case) and reset, which stays refused until the required export is done. Downloads are the only browser effect. The legacy key `lssm-funding-workspace-iteration11` and backup format `lssm-funding-workspace` are kept. ## Views Six-view navigation (`#nav` at 1000px and wider, `#mobile-nav` below) with `body[data-page]`. The module views (decisions, documents, applications, memory, tools, people) are open-deferred in founder-intelligence; the host says so instead of re-implementing them. People shows one module `BoardIntakeForm` preview per profile context. ## Offline intake `bun run build:intake` bundles the module intake form into one self-contained HTML file per context in `.generated/intake/` (gitignored, never committed): one inline script and style allowed only by their CSP sha256 hashes, `connect-src 'none'`, `form-action 'none'`, no storage or request API. `bun run verify:intake` rebuilds and compares byte for byte. `/intake/` serves the file as a download behind admission; an unknown context is 404. ## Checks - `bun test packages/apps/lssm-board` (colocated unit tests under `src/**` and `scripts/**`). - `bun run --cwd packages/apps/lssm-board test:journeys`: Playwright `e2e/*.journey.ts` on synthetic data against `next build && next start`, plus servers without the flag and with `authos`. --- ## @lssm-tech/app.lssm-ecosystem-web Description: Host-aware acquisition and invite-only LSSM OS web shell. Path: packages/apps/lssm-ecosystem-web URL: /llms/app.lssm-ecosystem-web # LSSM ecosystem web Host-aware Next.js acquisition and identity shell for the LSSM ecosystem. | Host | Purpose | | ------------------- | -------------------------------------------------------------------- | | `lssm.co` | Company, projects, operating model, partnerships | | `lssm.world` | Large Social Systems Model, worldview, manifesto, evidence | | `lssm.tech` | Product ecosystem, architecture, contracts, integrations, developers | | `os.lssm.tech` | LSSM OS acquisition, features, personas, trust, waitlist | | `console.lssm.tech` | Invite-only LSSM OS session surface | ## Identity `os.lssm.tech` is an OIDC relying party of `https://id.lssm.co`. Its dedicated `https://api.os.lssm.tech` authority owns the host-scoped product session and local membership; no cookie is shared with the identity host or another product. Runtime activation is fail-closed behind: - `NEXT_PUBLIC_LSSM_OS_RP_ENABLED=1` in this web app. - `NEXT_PUBLIC_LSSM_OS_API_ORIGIN=https://api.os.lssm.tech` in this web app. - `LSSM_OS_RP_ENABLED=1`, `LSSM_OS_RP_SECURITY_REVIEW_REF`, and a 32+ character `LSSM_OS_RP_CLIENT_SECRET` in the dedicated LSSM OS API deployment. The private console checks `/api/lssm-os/auth/session`, which requires an active product-local membership. A generic Better Auth identity session is not sufficient. The protected production replay is fail-closed. `bun run test:production-oidc-canary` skips unless `LSSM_OS_PRODUCTION_CANARY_AUTHORIZED=1`, the exact `E2E_PRODUCTION_BASE_URL=https://console.lssm.tech`, and secret-managed `E2E_TEST_EMAIL` / `E2E_TEST_PASSWORD` values are all present. It verifies central sign-in and optional consent, the `os.lssm.tech` callback, active local membership, the console session and module surface, product-local sign-out, denied post-sign-out session resolution, and independent Passport sign-out. Credentials stay process-local and are never written to evidence output. Waitlist requests use the central product-scoped lifecycle with `applicationId=app_lssm_os`. ## Local development `bun run dev` defaults `localhost` to the LSSM OS host narrative. Set `LSSM_LOCAL_SITE` to `company`, `world`, `technology`, or `console` to inspect another host locally. ## Provider preview For a bounded hosting-recovery canary, set `LSSM_ATLAS_PREVIEW_SITE=company`. The application accepts that selection only when the request host exactly matches `RAILWAY_PUBLIC_DOMAIN` or `VERCEL_URL`; an arbitrary provider-domain suffix remains unrecognized. Production hosts and canonicals are unchanged. ### Better Auth 1.7 callback forwarding The existing public LSSM callback alias forwards only its bounded authorization response to the fixed API owner's `/auth/callback/` endpoint, replacing the removed `/auth/oauth2/callback/` path. Existing issuer and parameter checks remain in force. API token exchange, provider registrations, cookies and account-identity migration still require live qualification before cutover. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. --- ## @lssm-tech/app.managed-companyos-mcp Description: Managed MCP server for CompanyOS operations and governed agent access. Path: packages/apps/managed-companyos-mcp URL: /llms/app.managed-companyos-mcp # @lssm-tech/app.managed-companyos-mcp **MCP server that exposes Managed CompanyOS operations and resources for tenant onboarding, integration discovery, workflow status, replay, evidence, health probes, and fail-closed Managed Builder evidence tools.** ## What It Does - Hosts a ContractSpec MCP server over Managed CompanyOS contracts (`companyos/*`). - Exposes V1 read/onboarding tools, Builder readiness/replay/evidence/release tools, and one reference resource for the operator copilot. - Exposes tenant-safe, read-only fixture resources for Company Brain, temporal graph, experiment/outcome, and provider health projections. These resources require an authenticated tenant match plus an explicit authorization decision and never expose credential references. - Resolves the actor from env vars (single-tenant per process) in V1; multi-tenant HTTP transport is deferred to V2. - Fails closed until API keys are verified: a configured key yields a role-less `user`, never an admin, and commands are denied unless reference mode is on outside production. Queries and read-only resources stay available. ## V1 Tools | Tool | Contract | | --- | --- | | `tenant.onboard` | `companyos/commands/tenantOnboard.command.ts` | | `tenant.get` | `companyos/queries/tenantGet.query.ts` | | `integration.list-providers` | `companyos/queries/integrationListProviders.query.ts` | | `workflow.get-status` | `companyos/queries/workflowGetStatus.query.ts` | | `approval.list-pending` | `companyos/queries/approvalReasons.query.ts` (stub source until control-plane reuse lands) | | `replay.get-packet` | `companyos/queries/replayGetPacket.query.ts` | | `evidence.get-receipt` | `companyos/queries/evidenceGetReceipt.query.ts` | | `health.worker` | `companyos/queries/healthWorker.query.ts` | | `builder.readiness.evaluate` | `companyos/commands/builderReadinessEvaluate.command.ts` | | `builder.evidence.receipt.get` | `companyos/queries/builderEvidenceReceiptGet.query.ts` | | `builder.replay.packet.get` | `companyos/queries/builderReplayPacketGet.query.ts` | | `builder.release.capsule.get` | `companyos/queries/builderReleaseCapsuleGet.query.ts` | ## Read-only projection resources - `companyos://tenants/{tenantId}/company-brain` - `companyos://tenants/{tenantId}/temporal-graph` - `companyos://tenants/{tenantId}/experiment-outcome` - `companyos://tenants/{tenantId}/provider-health` These are deterministic reference projections only. They perform no writes or network access, fail closed for anonymous/cross-tenant/denied requests, and use only declared package exports. ## Environment Variables - `MANAGED_COMPANYOS_MCP_API_KEY` — platform API key (required in production). It is not verified yet, so it identifies a caller but grants no role. - `MANAGED_COMPANYOS_MCP_TENANT_ID` — optional tenant pin for tenant-scoped keys. - `MANAGED_COMPANYOS_MCP_REFERENCE_MODE` — set to `1` to let the deterministic reference bindings run commands (`tenant.onboard`, `builder.readiness.evaluate`). Ignored when `NODE_ENV=production`; any other value keeps commands denied. - `MANAGED_COMPANYOS_MCP_NAME` — override server name (default `managed-companyos-mcp`). - `MANAGED_COMPANYOS_MCP_VERSION` — override server version (default `0.1.0`). ## Running Locally From `packages/apps/managed-companyos-mcp`: - `bun run dev` - `bun run start` - `bun run build` - `bun run typecheck` - `bun run test` ## Architecture - `src/server.ts` boots the MCP server and stdio transport. - `src/blueprint.ts` defines the app blueprint. - `src/tools.ts` installs operation specs through `installOp`. - `src/resources.ts` exposes the reference workspace resource. - `src/prompts.ts` registers the operator copilot prompt. - `src/tenant-context.ts` resolves the actor and the fail-closed policy gate (`decide`, `createManagedToolDecider`). - `src/smoke.test.ts` asserts the registry registers the expected number of tools and that the gate denies commands from an unverified key. ## Status Handlers are deterministic reference bindings for V1. Until `lib.auth-os` verifies API keys, commands run only in reference mode (`MANAGED_COMPANYOS_MCP_REFERENCE_MODE=1`, never in production). Builder-specific handlers are live fail-closed evidence tools: they reject raw-looking credentials, report missing provider/webhook refs as blockers, and emit Builder-scoped readiness/replay/receipt/release packets without replacing agent/workflow. --- ## @lssm-tech/app.marketing-operations Description: Thin Marketing Operations API and durable-worker application shell. Path: packages/apps/marketing-operations URL: /llms/app.marketing-operations # Marketing Operations application shell This thin Bun/Node shell runs the canonical Marketing Operations API and installation workers. It requires a trusted deployment module; there is no default authentication, permitting policy, provider credential or live-spend configuration. Set `MARKETING_INSTALLATION_MODULE` to a local module whose default async factory returns `createMarketingOperationsInstallation(...)` from the marketing bundle. Compose its server with `createMarketingOperationsServer(host)` and supply readiness checks for configured persistence/authentication. Worker registrations install existing durable schedulers/queues and must drain callbacks on stop. Startup failure stops registrations already started. API readiness stays unavailable during startup/shutdown. Run `bun run start`, or build and run `bun run start:node`. `HOST` defaults to loopback and `PORT` to 3000. Configure the public origin and an authenticated reverse proxy for external access. Requests are bounded by the installation's maximum body size; browser mutations from other origins are rejected. Health endpoints expose liveness/readiness without tenant or credential details. Managed and self-hosted installations use the same registry and host interfaces. This is an API/worker shell: the standalone command-center frontend, managed provisioning, turnkey installation configuration and live provider qualification are still incomplete. A trusted installation that declares `deployment: 'managed'` is started through the managed-ecosystem composition (`src/managed-composition.ts`). It uses the same shell, registry and canonical operation server, but before anything listens or any worker starts it refuses (`MARKETING_MANAGED_BINDING`) a public origin that is not HTTPS or is a loopback or unspecified host (`localhost`, `*.localhost`, 127.0.0.0/8, `0.0.0.0`, `::1`, `::` and IPv4-mapped loopback). The HTTPS public origin is the only origin the shell admits browser mutations from. Cross-tenant learning is already refused by the installation schema, which only accepts `crossTenantLearning: false`. Self-hosted installations keep the existing path. --- ## @lssm-tech/app.meeting-effect-worker Description: (none) Path: packages/apps/meeting-effect-worker URL: /llms/app.meeting-effect-worker # Meeting Effect Worker Deployable worker for approved CompanyOS, Pactena, and hCircle meeting effects. It claims owner-scoped SQL outbox leases, reloads encrypted meeting state, reproves authority, rollout, approval, and artifact digests, then invokes a provider-neutral delivery port. Failed work uses the runtime's bounded retry and terminal-failure rules. Set `OPA_MEETING_EFFECT_WORKER_COMPOSITION_MODULE` to an installed package in the allowlisted `@lssm-tech/integration.meeting-effect-worker-*` namespace. The module must export a default `MeetingEffectWorkerComposition`. The executable exposes `/healthz`, `/readyz` and `/metrics` on `OPA_MEETING_EFFECT_WORKER_PORT` (default `3003`). `/readyz` answers `ready`, `paused` (operator kill switch, 200) or `not-ready` (503: no recent successful cycle) with cumulative totals. `/metrics` exposes Prometheus counters for effects by status (`delivered`, `retrying`, `dead_letter`, `stale`), errors by failure code and failed cycles. Each non-empty cycle writes one aggregate JSON log line; a failed cycle is logged by error code and retried with backoff instead of exiting. The production image includes `@lssm-tech/integration.meeting-effect-worker-postgres-http`. Set the composition module to that exact package and configure its documented PostgreSQL, BYOK, authority, rollout, and HTTPS provider-delivery boundary variables. The CompanyOS API can host the same cycle in process as the cron `/api/cron/opa-meeting-effects` (see the API README). Both hosts share `processMeetingEffectLease` from `@lssm-tech/lib.organization-planning-runtime`. Run exactly one host per database: when the API cron is enabled, do not deploy this worker, and vice versa. --- ## @lssm-tech/app.meeting-intake-worker Description: (none) Path: packages/apps/meeting-intake-worker URL: /llms/app.meeting-intake-worker # OPA Meeting Intake Worker Deployable, provider-neutral host for recurring calendar and meeting-recorder intake. It claims owner-scoped PostgreSQL executions, calls an allowlisted deployment composition, and completes, retries, or terminally settles each job with its exact lease token. Set `OPA_MEETING_INTAKE_WORKER_COMPOSITION_MODULE` to an allowlisted `@lssm-tech/integration.meeting-intake-worker-*` package. The composition owns fresh authority, protected configuration and credential resolution, provider construction, durable occurrence/review ports, and the governed `opa.recording.source_bind` call. This host never accepts browser sessions or raw credentials and never logs meeting content. `/healthz` answers liveness. `/readyz` answers `200` only when the worker has assigned scopes, completed a cycle recently and skips no scope. Its body lists `provisioningBlockers` from the composition's optional `provisioningBlockers()` (`{ code, tenantRef, workspaceRef, jobRef? }`, closed codes and opaque references only). Readiness fails closed: while a blocker remains it answers `503` with `state: "not-ready"`, although the other scopes keep running. Point liveness and restart probes at `/healthz`; a restart does not resolve a provisioning conflict (see `docs/operations/founder-ops-v2/meetings-enable.md`, section 3). The production image includes `@lssm-tech/integration.meeting-intake-worker-postgres-http`. It uses the canonical SQL queue and a strict bearer-authenticated HTTPS execution boundary; see that package for required environment variables and receipt semantics. ## Hosting choice CompanyOS runs the same queue cycle in-process through the API cron `/api/cron/meeting-intake` (kill switch `OPA_MEETING_INTAKE_ENABLED=1`; see `docs/evidence/opa/meeting-intake-prep-2026-10-19.md`). Deploy this worker only where a long-running host is preferred, and never alongside the cron for the same owner scopes: jobs are unique per owner and connection. --- ## @lssm-tech/app.mobile-monolith Description: Expo ContractSpec native superapp foundation with contract-driven auth, workspace, remote-config, RoleMorph, and managed CompanyOS proof surfaces Path: packages/apps/mobile-monolith URL: /llms/app.mobile-monolith # @lssm-tech/app.mobile-monolith The native auth client uses Better Auth 1.7's core social flow for generic OAuth; it no longer registers the removed generic-OAuth client plugin. This dependency compatibility fix does not establish native OPA/capture production parity. **Expo ContractSpec native superapp foundation with contract-driven auth, workspace, remote-config, RoleMorph, and managed CompanyOS proof surfaces.** The root route now enters a narrow, native proof flow: - Reframes the former mobile landing companion into a native superapp shell foundation. - Keeps the first proof intentionally narrow: auth/session entry, remote tenant/workspace config, workspace selection, ContractSpec-driven surfaces, RoleMorph personalization, and managed CompanyOS view-model adapters. - Uses Expo Router for native routes while keeping route files thin; shell decisions should come from app-local contracts, handlers, runtime ports, and registries rather than route-level fixtures. - Reuses shared marketing/catalog content only as secondary documentation/discovery surfaces, not as the primary shell purpose. - A preview-registry entry or shared example preview is discovery-only; it is not a standalone Special Ops app shell. - Prefers `@lssm-tech/bundle.managed-companyos/view-models/*` exports plus React Native adapters over direct SSR/web UI imports. - Keeps provider execution fail-closed: no raw secrets in fixtures, snapshots, event payloads, or view-models. This package intentionally does **not** attempt full web-monolith parity. It reuses shared CompanyOS view-model/data exports and avoids SSR/web UI imports unless RN compatibility is separately proven. ## Special Ops managed app gate Special Ops is a managed CompanyOS production candidate, not a standalone native shell. Mobile promotion must follow [`docs/runbooks/special-ops-monolith-production.md`](../../../docs/runbooks/special-ops-monolith-production.md) and prove the native route enters through AuthOS/session projection, remote workspace config, RoleMorph filtering, provider-safe degraded states, and the shared bundle view-model exports. Native AuthOS discovers the same enabled login-method projection as web and supports email/password, email OTP, email magic link, and the six built-in social providers through bearer-backed Better Auth sessions and deep-link callbacks. The linked-accounts persona route provides the explicit link required before TikTok or a missing-email social identity can be used for login. Required evidence before claiming mobile parity: - `bun test --cwd packages/apps/mobile-monolith` - `bun run --cwd packages/apps/mobile-monolith typecheck` - import-boundary evidence showing no direct `@lssm-tech/bundle.managed-companyos/ui`, Next, DOM, or example-package runtime imports in the managed Special Ops path - RoleMorph denial evidence for blocked/provider-impacting actions and no standalone Special Ops route outside the managed native shell ## BillingOS native proof The example preview registry includes a dedicated `billingos-france-sme` native proof. It renders quote, invoice, paid payment, France readiness, and operator approval-packet summary data through React Native primitives backed by deterministic `src/examples/billingos-native-proof-data.ts` constants. This is a native-safe proof path only: it must not import `@lssm-tech/module.billing-os/ui`, provider SDKs, credentials, network submission paths, PA submission, payment processing, or autonomous production billing execution. Targeted BillingOS proof evidence: ```bash bun test packages/apps/mobile-monolith/src/examples/native-preview-registry.test.ts packages/apps/mobile-monolith/src/examples/billingos-native-proof.test.ts bun run --cwd packages/apps/mobile-monolith lint:check ``` Package-wide `typecheck` remains a separate mobile-host gate and is currently blocked by pre-existing workspace config/type issues unrelated to the BillingOS proof (`bun:test` and Node test/global types). The managed CompanyOS `./product-surfaces` subpath is exported and covered by the mobile registry/import-boundary tests. ## App submission readiness The native proof is configured for read-first App Store / Google Play review paths without committing provider credentials or production submission secrets. - `app.config.js` declares the stable iOS bundle id (`io.contractspec.expo-demo`), Android package (`io.contractspec.expo_demo`), 1024×1024 proof icon/splash assets, and legal review links (`https://contractspec.io/privacy`, `https://contractspec.io/terms`, `https://contractspec.io/support`) under `extra.appReview`. It remains JavaScript so Expo SDK 57 can load it on Node 26 without relying on Node's removed TypeScript `transform` mode. - iOS encryption and privacy posture is explicit: `usesNonExemptEncryption: false`, `ITSAppUsesNonExemptEncryption: false`, and an Expo `ios.privacyManifests` block that materializes `PrivacyInfo.xcprivacy` during prebuild/EAS. The current proof declares no tracking domains, no collected data types, and the UserDefaults required-reason API (`CA92.1`) used by the native shell/SDK layer. - Android proof builds deny optional sensitive permissions by default (`CAMERA`, `RECORD_AUDIO`, fine/coarse location, contacts) and keep the permission list empty until a reviewed feature needs one. - `eas.json` keeps build profiles and production submit profile credential-free; App Store Connect / Google Play submission credentials must remain in EAS/CI secret stores rather than source. Targeted readiness evidence: ```bash bun test packages/apps/mobile-monolith/src/app-submission-readiness.test.ts bun run --cwd packages/apps/mobile-monolith lint:check bun run --cwd packages/apps/mobile-monolith typecheck ``` ## Safety boundaries - `bun run dev` - `bun run start` - `bun run test` - `bun run typecheck` - `bun run lint:check` ## Architecture - `src/app/` contains Expo Router entry points and should remain thin. - `src/contracts/` defines mobile ContractSpec shell/session/config/workspace/surface contracts as they are introduced. - `src/handlers/` adapts deterministic local data and shared catalogs into operation results. - `src/screens/` owns React Native screen composition for shell, workspace, managed CompanyOS proof, and degraded states. - `src/examples/` and example preview components remain secondary discovery surfaces. ## Public Entry Points - Deployable Expo app with no published library exports. - Primary runtime surfaces are Expo routes, mobile contracts/registries, and deterministic local handlers/ports. ## Guardrails - No full web-monolith parity in the mobile foundation pass. - No unrelated API auth/database edits from this package lane. - No direct `@lssm-tech/bundle.managed-companyos/ui`, `next`, `react-dom`, DOM global, or SSR-only component imports into the Expo shell unless compatibility is intentionally proven. - Auth/session and remote config ports must be safe locally, redacted, deterministic in tests, and fail-closed when production credentials are unavailable. - RoleMorph/persona differences must preserve denial evidence for blocked/provider-impacting actions. ## Notes This package may still carry legacy landing/example routes while the superapp shell is being built, but docs, metadata, and guardrail tests now track the approved superapp foundation direction. ## Live OPA microphone workflow `/(persona)/meetings/[meetingRef]` opens the live, authenticated recording workflow for a canonical meeting reference. Example deep link: `contractspec-demo://meetings/meeting:example?locale=fr`. The server must already recognize the meeting in the selected workspace. This is separate from the existing deterministic proof panels. The screen loads effective server capture policy, requires recording/participant-notice acknowledgment, requests OS microphone access, records M4A into app-private document storage, and uploads digest-bound chunks through existing capture operations. Backgrounding stops and saves foreground capture; three hours is the recording ceiling for the configured transcription path. Upload failures preserve media and checkpoints. Resume rehashes acknowledged chunks before skipping them. Accepted uploads expose transcript refresh; no empty response is called a successful transcript. Recovery manifests use AES-GCM with account-bound additional data; their keys live in Expo SecureStore. Completed recordings are sealed into independently authenticated AES-GCM chunks before upload. The raw temporary file is removed only after all encrypted chunks and their durable manifest are verified. Interrupted sealing retains a recoverable raw or encrypted copy. Active recording still uses the SDK’s app-private temporary file. Device backup exclusion, automatic local retention, active-recording crash recovery and storage-pressure behavior still require implementation/qualification. Deleting the local copy does not delete server media. The SDK-compatible Expo audio/filesystem/crypto modules and microphone config plugin are installed. Background recording/playback are disabled; iOS privacy declarations now include audio and user content. Worklets and Babel preset dependencies required by the existing mobile bundler are explicit. `EXPO_PUBLIC_COMPANYOS_API_URL` selects the HTTPS API; native requests use refreshed bearer credentials without browser origin/cookie simulation. Validation is separate: unit tests cover upload retry/tamper/source binding and auth/config; TypeScript checks pass. iOS and Android Metro exports now produce Hermes bytecode after isolating the AuthOS preview bridge plan from Better Auth server initialization. This is bundle validation only; signed-device behavior and runtime performance remain unqualified. No signed iOS/Android audio-permission, interruption, screen-reader, physical-device or app-store acceptance is claimed. Implementation references: [Expo Audio](https://docs.expo.dev/versions/latest/sdk/audio/) and [Expo FileSystem](https://docs.expo.dev/versions/latest/sdk/filesystem/). Expo documents device-disconnect interruption and document-directory recording; neither substitutes for device testing. ### Completed-recording encryption Sealed audio uses the account’s SecureStore-backed AES key and additional data binding account, local recording ID, server capture ID and chunk index. Upload decrypts only a bounded chunk at a time. Digests detect corrupted or substituted chunks before raw cleanup or transfer. Recovery distinguishes partial sealing, a committed sealed copy awaiting raw cleanup, and encrypted media with cleanup complete. Explicit local deletion removes raw remnants and the sealed recording directory. This protects completed local recordings; it does not establish uninterrupted streaming encryption during microphone capture, backup exclusion, or legal-hold/retention behavior on devices. Those remain release gates. ### Recording backup protection Recording and local media preparation require the compiled OpaRecordingStorage module. On iOS it excludes and verifies the app documents directory, including temporary recordings and encrypted OPA files. Android disables legacy backup and provides explicit cloud/device-transfer exclusions; the native verifier checks the installed manifest resource and both exclusion sections. Old binaries and Expo Go without the module fail closed before microphone access. Rebuild native projects after installing the config plugin. Existing backups are not retroactively removed. Physical-device backup/restore behavior, OEM differences and retention/legal-hold qualification remain open. When native backup protection is missing or fails, the recording screen presents a localized protection-unavailable state and disables capture. Native failure details are not exposed. Transient capture/upload errors remain distinct and retain recoverable local media. ### Exact recording reconciliation Recorded transcript display requires both the canonical meeting and the exact sourceCaptureRef. Refresh recording status rechecks the saved capture identity and rejects stale revisions or changed consent/policy binding. Only an authenticated matching deleted state triggers local raw/encrypted-file cleanup; denial or unavailability preserves recoverable media. This is explicit refresh-based reconciliation, not a claim of push revocation or automatic retention. Raw-file reads, encryption and deletion now require canonical SDK-generated recording paths under the current document audio directory. Arbitrary document files, sibling-prefix paths, encoded traversal and remote URLs are rejected before file access. iOS simulator application build and Android storage-module Kotlin compilation pass; neither proves physical-device backup/restore or recording behavior. Recording startup is fenced across asynchronous protection, permission, consent, recorder preparation and manifest writes. A screen that backgrounds or unmounts cannot later activate the microphone from a stale continuation. Interrupted prepared recorders are stopped and recording audio mode is disabled. Foreground return requires a new explicit start; OS permission interruptions and cleanup still require signed-device QA. Failed recording startup attempts release partially prepared native recorder resources and disable recording audio mode. If the server capture identity is known but the microphone never started, cleanup attempts an idempotent cancellation. A failed cancellation does not claim server cleanup succeeded; expired/orphaned capture recovery remains a server qualification requirement. Automatic SDK completion and media-service-reset events enter the same recovery finalization as manual stop. Already-stopped recordings are not stopped twice; a nonempty file checkpoint is persisted before encryption. Empty or failed recording finalization remains an error, and failed encryption preserves the completed file for recovery. Device-specific interruption behavior still requires runtime QA. Recorder errors, media-service resets and crash-recovered active recordings remain marked interrupted. The screen warns that recovered audio may be incomplete and requires explicit acknowledgment before upload. The upload protocol independently enforces that acknowledgment before network access, and encrypted checkpoints preserve interruption status. This is not a claim that a truncated or damaged native recording is playable; device recovery QA remains required. A live recording screen pins its verified session token in memory and uses the same client for consent, upload, status reconciliation and transcript reads. If secure storage changes to another token or sign-out removes it, subsequent requests fail before network access. Reopen the screen to verify a new session; recovery manifests never contain credentials. This does not replace server membership/workspace checks or signed-device account-switch QA. Credential change notifications carry no token payload. They abort recording-screen requests, invalidate startup continuations, clear displayed private content and stop active microphone capture while preserving the original account’s encrypted recovery files. A delayed SecureStore hydration cannot overwrite a newer sign-out, and pending manifest writes cannot restore a cleared screen. Device-level sign-out and workspace-switch behavior remain separate acceptance tests. Secure session writes/deletions are serialized in call order. Sign-out invalidates in-memory authority immediately, then waits behind earlier storage writes before deleting the credential. A current persistence failure clears memory and blocks hydration in that process until a later successful mutation repairs storage. This does not guarantee durable deletion when the OS rejects Keychain/Keystore access; server-side revocation and cold-start verification remain required. Upload receipts preserve source identity and nondecreasing revisions and chunk counts. Every acknowledged chunk count must describe the exact contiguous byte prefix of the sealed recording. A finish response must report processing or ready with the complete expected count and byte total; invalid receipts retain the last recovery checkpoint and cannot become accepted uploads. ### Android application build evidence The full debug application assembles successfully with the compiled OPA storage module and all four Android architectures. APK signature verification and inspection of the compiled manifest/data-extraction XML confirm the debug signature and backup/transfer exclusions. See `docs/evidence/opa/android-native-assembly-2026-09-06.md` at the repository root for the artifact checksum and exact scope. Release signing, installed-device audio behavior, backup/restore and provider journeys remain unqualified. ### Private ad-hoc meetings The native home opens Private meetings. The screen verifies the current session, reads a server-derived private scope guard, and persists a secure request intent before calling the creation API. Network retries keep the same request key; concurrent screens serialize the intent, and an unobserved completed request is resumed. Users can continue to recording or explicitly create another meeting. Creating the workspace does not grant recording consent or start a microphone. The API persists a real private workspace before capture lookup. Session changes clear the screen and abort requests; a changed workspace guard requires reloading. Intent metadata is isolated by account and owner-scope digest in native secure storage. Installed-device and provider journeys remain release gates. The native dependency catalog pins Babel 7.29.7 for Expo SDK 57 / Worklets 0.10.1 compatibility. The Worklets plugin uses Babel 7 presets internally; Babel 8 fails that pipeline. A transform-level regression test checks the resolved Babel majors and actual worklet metadata generation. Recording requires both foreground app state and navigation focus. Leaving the capture screen stops and checkpoints active audio as interrupted, even when the navigation stack keeps the screen mounted. Returning never auto-resumes or revives an earlier permission/consent request. Recovered audio still requires explicit incomplete-recording acknowledgment before upload. This behavior is covered by lifecycle/start-protocol tests; physical-device navigation, audio interruption and screen-reader acceptance remain required. The saved-recording controls now distinguish local discard from confirmed server deletion. Server deletion reads the exact current capture and uses its revision in the existing transition operation; a lost response retains local recovery media until retry observes an authenticated deleted state. Legal holds and denial remain failures. Confirmed deletion then removes the local copy. This applies to the capture and associated transcript; derived meeting notes/outcomes and backup erasure still require their separate retention/deletion qualification. Encrypted recording manifest initialization and mutations serialize across mounted screens using the shared native storage queue. Saves reject a different active recording identity, stale capture revision or shorter acknowledged chunk prefix. Clears require the expected local recording identity, so an older screen cannot erase a newer recording's checkpoint. This is an in-process mobile-runtime guard, not a cross-process filesystem lock. Interrupted encryption preserves the entire verified chunk-digest prefix while rechecking raw and encrypted media. Recovery never truncates later checkpoint evidence or rewrites an already verified chunk. Manifest guards reject changed digests, protection regression and changed finalized byte length. Published ciphertext is immutable even when its manifest write was interrupted: identical concurrent retries authenticate and reuse it, while different bytes fail without replacement. Raw media is removed only after the complete encrypted copy verifies. Hardware crash/recovery qualification remains required. Completed native transcripts can now be edited as reviewed copies and explicitly approved or rejected through the existing transcript-review operation. The screen reuses the shared headless review hook with the pinned native capture client and Expo request IDs. Only server-derived review permission exposes mutation controls. Every request binds source and review revisions; responses must preserve the exact private capture and owner scope. Edited copies do not reuse original timestamps. Review creates no outcomes, Work tasks or outbound messages. English, French and Spanish copy distinguishes read-only, loading, denied, missing and uncertain-review states. Complete downstream-journey and physical-device acceptance remain open. Native approved transcripts now connect to private meeting drafts using the shared outcome client and hook. Users can generate summaries, decisions, proposed actions and follow-up drafts, inspect source quotes and uncertainty, edit draft prose and action titles/details, and explicitly approve or request changes. Expo SHA-256 hashing preserves the existing browser retry identity. Accepted background jobs continue server-side; unmounting the screen aborts polling rather than cancelling accepted work. Responses remain private and bound to the exact approved source. The native client exposes these operations under `outcomes` with the same pinned bearer session. Native Work task-detail navigation, message delivery, full citation navigation and signed-device acceptance remain open. Approved proposed actions now expose explicit creation in the selected CompanyOS Work workspace when the server supplies projection permission and target. Native users acknowledge workspace disclosure and separately confirm uncertain actions. The shared `useProjectMeetingAction` hook sends only approved source references and acknowledgment fields through `opa.task.project`; titles/details remain server-selected from the approved proposal. It verifies action, target, source revision and Work object/event references before reporting creation. Lost replies retry the same request, while changed source/target/client aborts stale completion. Server denial is distinct from an uncertain failure. Task-detail navigation and signed-device execution acceptance remain open. Confirmed meeting-action projections now expose “Open task in Work” using the canonical Work object reference from the receipt. The native detail route reads the exact UUIDv7 object through the authenticated Work endpoint, shows server title/details/status/dates/estimate, and clears private data on session invalidation. Missing, denied and retryable states remain distinct. The screen is currently read-only; native editing/completion and signed-device acceptance remain open. Work detail now reloads on each navigation focus. Blur aborts pending reads, unsubscribes session observers and clears displayed data; returning resolves current session authority again. Tests cover blur during session setup, token invalidation while reading, late response rejection and separate denied/missing/error states. This does not yet qualify physical-device navigation or workspace switching. Work task detail now exposes canonical status choices when the authenticated read projection supplies `canUpdateStatus`. Missing permission is read-only. Native updates bind the displayed revision and reuse the same request key for an uncertain retry of the same status. Verified event identity, next revision, status and original workspace scope are required before reloading the task. Session invalidation and blur abort the client request without claiming to undo a possible server commit. Signed-device completion/reopening acceptance remains open. OPA recording uploads now use the shared organization-planning-react/capture-media-upload protocol. The native wrapper preserves encrypted manifest ownership, interrupted-recording acknowledgment and MP4 source binding. Existing native recovery tests pass; this extraction does not qualify a signed device journey or activate processing. ### Better Auth 1.7 native client The native client uses the supported `signIn.social` and `linkSocial` methods for custom OAuth. The removed generic OAuth plugin is no longer imported. Local tests cover the social request shape and existing MFA authority transport; device login, provider registration and account migration are separate qualification requirements. TOTP enrollment explicitly requests `method: totp` and rejects a different result. Unlink requires a specific linked account and resolves its unique current provider mapping before sending Better Auth's stored account ID. Missing or ambiguous mappings fail before the unlink request. --- ## @lssm-tech/app.notion-mcp Description: MCP server exposing governed Notion workspace operations. Path: packages/apps/notion-mcp URL: /llms/app.notion-mcp # Notion MCP Thin ContractSpec MCP package for Notion surfaces. This scaffold registers the canonical Notion MCP tool catalog and leaves execution as fail-loud pending handlers until the provider-backed integration is wired. --- ## @lssm-tech/app.organization-planning-host Description: Thin OPA host: mounts the organization-planning operation registry on REST, GraphQL, and MCP surfaces via the shared contracts-runtime adapters. Path: packages/apps/organization-planning-host URL: /llms/app.organization-planning-host # @lssm-tech/app.organization-planning-host Website: https://contractspec.io **Thin OPA host — mounts the organization-planning operation registry on REST, GraphQL, and MCP.** ## What It Provides - **Layer**: `app.` (thin deployable host; transport wiring only). - Exposes `buildOpaOps()` (from `@lssm-tech/lib.organization-planning-runtime`) identically on three surfaces via existing contracts-runtime adapters: - **REST** — `createOpaRestHandler(ctxFactory)`, served by the Next App Router catch-all at `app/api/ops/[...route]/route.ts`. - **GraphQL** — `createOpaGraphqlBuilder()` returns a Pothos builder with the OPA query/mutation fields. - **MCP** — `mountOpaMcp(server, ctxFactories)` registers the OPA tools. - Serves the **public booking page** at `app/book/[link]/page.tsx`. The page speaks the OPA v2 public booking protocol through `@lssm-tech/opa-booking-react` (`useOpaBooking` plus the typed `./availability` projections): anonymous visitors load the availability quote, pick a slot and create a booking intent bound to its `availabilityRef`/`slotRef`. The booking link must allowlist this host's origin; only name, email, timezone and locale are sent. A host embedding a narrower workflow can pass exact `{ key, version }` refs as `createOpaRestHandler`'s `operations` option. The resulting REST mount uses the selected canonical handlers and their existing policy. Unselected operations are absent, and selecting a handler missing its runtime dependencies fails at composition time. The host still supplies the authenticated context and RBAC port. Omitting `operations` preserves the full installed registry. ## Auth Fail-closed at every step. The REST route (`app/api/ops/[...route]/route.ts`) composes three pieces: 1. **Session projection** (`src/session-context.ts`, `createOpaHostSessionContext`). An `Authorization: Bearer` token is checked against AuthOS (`/api/auth/get-session`, through `createBetterAuthBearerSessionReader`) and then against the caller's own CompanyOS authority (`GET /api/companyos/auth/authority`, same bearer, no cookies or redirects, 1.5 s budget, answer at most 5 s old). The session and active organization must match, and the identity is read again after the authority read. The result is `{ actor: 'user', userId, organizationId, tenantId, workspaceId, roles }`, where `tenantId`/`workspaceId` use the OPA ref grammar (`tenant:`, `workspace:`) and `roles` is the CompanyOS persona (`grantRole`). Anything else is `{ actor: 'anonymous' }`, which the REST adapter rejects with 401 on every non-public operation. **Module entitlement** (`src/opa-workspace-module.ts`). Like the monolith's `requireWorkspaceModule(session, 'opa')`, the host requires `opa` in the authority read's `enabledModules`. When the list is missing or lacks `opa`, the user ctx gets a `decide` that answers 403 on every non-public operation, whatever the persona; public operations stay reachable as for an anonymous caller. A malformed `enabledModules` is treated as no authority (401). 2. **RBAC binding** (`src/opa-host-rbac.ts`, `createOpaHostRbac`). Identity RBAC's `RBACPolicyEngine` plus one user-bound, tenant-tagged binding per CompanyOS persona. `opa.loop.execute` (admin, founder approver, operations manager) and `opa.booking.approve` (admin, founder approver) follow the api-application-monolith bindings. The profile capabilities (`opa.profile.read`/`manage`/`publish`) and every capability of the meeting-workspace operations a deployment can install through `OpaBuildDeps` (`opa.meeting_policy.*`, `opa.meeting_workspace.*`, `opa.meeting_context.*`, `opa.meeting_artifact.*`, `opa.meeting_work_session.*`, `opa.meeting_outcome.*`, `opa.meeting_dispatch.*`, `opa.meeting_share.*`, `opa.recording.source_bind`) go to the OPA personas of the managed-companyos coverage manifest (founder approver, operations manager) and the admin. The manifest gives the other personas no OPA coverage, so they get only the meeting capabilities of their AuthOS built-in role template: | Persona | Meeting operations allowed | | --- | --- | | `expert_reviewer` | `opa.meeting_workspace.get`, `opa.meeting_artifact.list`/`get`, `opa.meeting_artifact.review_decide` | | `auditor` | `opa.meeting_workspace.get`, `opa.meeting_artifact.list`/`get` (read-only) | | `frontline_staff` | `opa.meeting_workspace.get` | | `ai_operator` | none (not an assignable AuthOS role) | Every other operation answers 403 for these personas, including `opa.meeting_work_session.*`, policy, context, dispatch and sharing, and unknown roles get no binding at all. The runtime authority port still checks the actor's own grant on each meeting resource. An operation group whose capabilities have no persona grant answers 403 for every persona until its capabilities are mapped in `src/opa-host-rbac.ts`. 3. **Policy decision point** (`src/opa-host-policy.ts`). When `createOpaRestHandler(ctxFactory, { rbac })` is given an RBAC port, every request context gets a `decide` that requires the operation's declared capability for a resolved tenant and workspace actor. Public (`policy.auth: 'anonymous'`) operations pass, unknown operations and missing grants are 403, and a context `decide` can only narrow the result. Bindings are tenant-scoped like the runtime's `authorizeOpaOperation` (`src/opa-host-tenant-scope.ts`): grants tagged, scoped or targeted to another tenant are dropped, and own-tenant `tenantId` or `tenant`-scope grants are honored. The runtime authority port still rejects a resource from another workspace (403). Without an RBAC port, `createOpaRestHandler` is default-deny: a non-anonymous ctx that brings no `decide` of its own (such as the one `createOpaHostSessionContext` projects) gets one that answers 403 on every non-public operation. Pair the session projection with `{ rbac }`. Known scope: the CompanyOS authority read does not return the selected team or sub-workspace, so the host scopes OPA to the active organization's workspace (`workspace:`). The route binds no profile or meeting persistence, so it serves only the operation groups a deployment configures through `OpaBuildDeps`. | Variable | Purpose | | --- | --- | | `OPA_HOST_AUTHOS_BASE_URL` | Origin (no path) of the CompanyOS API, which serves AuthOS and the authority read. Unset → every caller is anonymous. HTTPS only, except `http://localhost`. A value that is not an exact origin (trailing slash, path, credentials, HTTP on another host) is logged once as `opa_host.invalid_authos_base_url` when the route loads, and every caller is then anonymous; public operations keep working. | | `OPA_HOST_INSECURE_DEV` | `1` enables the LOCAL-ONLY `x-opa-dev-user`/`-tenant`/`-workspace`/`-roles` headers when no bearer is sent. Ignored when `NODE_ENV=production`; the dev subject still needs a persona in `x-opa-dev-roles`. | The MCP mount (`mountOpaMcp`) still takes the caller's `toolCtx`; it does not use this session projection yet. ## Local Commands - `bun run test` — smoke tests (3 surface mounts + REST round-trip), session projection, REST default-deny and RBAC tests - `bun run typecheck` — TypeScript check - `bun run lint:check` — Biome check --- ## @lssm-tech/app.osint-api Description: (none) Path: packages/apps/osint-api URL: /llms/app.osint-api # OSINT API REST/OpenAPI composition root for scoped OSINT and governed self-improvement operation handlers. This app owns no domain rules. `OSINT_PORT` defaults to `3108`. By default the standalone service uses the managed composition: OIDC/JWKS verification, a fresh authority decision, FORCE-RLS PostgreSQL reads, and the durable mutation queue. Configure `OSINT_DATABASE_URL`, `OSINT_AUTHOS_ISSUER`, `OSINT_AUTHOS_AUDIENCE`, `OSINT_AUTHOS_JWKS_URL`, and `OSINT_AUTHORITY_URL`. Deployments may instead set an allowlisted `OSINT_API_COMPOSITION_MODULE` matching `@lssm-tech/integration.osint-api-*`. Set `OSINT_DEPLOYMENT_PROFILE_ID` for an explicit managed profile. Deployment profiles come from the governance catalog `osint.deployment-profiles@1` (`@lssm-tech/lib.lssm-os-spec/catalog/osint-deployment-profiles`), loaded once at startup into the registry `OSINT_DEPLOYMENT_PROFILE_REGISTRY_V0`; an unknown profile id fails startup with `OSINT_DEPLOYMENT_PROFILE_UNKNOWN`. Registered data-isolated deployment IDs are also recognized from the authenticated scope and enforced even when the optional environment value is absent; disallowed vertical reads fail before SQL. The catalog grants no collection authority. The managed composition polls the canonical append-only outbox for scope-isolated, replayable SSE and WebSocket sessions. `OSINT_STREAM_POLL_INTERVAL_MS` and `OSINT_STREAM_BATCH_SIZE` tune bounded delivery without changing authority. The composition supplies the authenticated context resolver, shared headless operation handler, dependency readiness probe, optional scoped stream broker, and graceful shutdown hook. `/livez` reports process liveness while `/readyz` fails closed on dependency health. `OSINT_READYZ_SCHEMA_LEVEL=enforce` also requires every OSINT store migration of the build in the migration ledger (`checks.schema`); the default `off` reads no ledger. Turn it on only after the ledger baseline and the reader grant (packages/platform/delivery/app-config-runtime/ADOPTION.md). Authenticated SSE and WebSocket sessions both bind replay cursors to the exact resolved scope; WebSocket upgrades are accepted only at the generated event path and detach from the scoped broker on close. Browser WebSocket origins default to the request origin; deployments with a separate console origin set the explicit comma-separated `OSINT_ALLOWED_ORIGINS`. An allowlisted composition may also supply `selfImprovement` with its own authenticated context, headless handler, and scoped broker. The host then serves the generated `/api/self-improvement/v1` REST/OpenAPI surface plus program-bound SSE and WebSocket replay. The generated OpenAPI remains discoverable when the runtime is absent, but every call and stream fails closed with `503`; production qualification requires a concrete governed module/store/authority composition. The managed host now supplies that composition when `SELF_IMPROVEMENT_CONTROL_URL` and `SELF_IMPROVEMENT_WORKLOAD_TOKEN` are both set. `SELF_IMPROVEMENT_AUTHORITY_URL` may select a separate fresh-authority endpoint and otherwise uses `OSINT_AUTHORITY_URL`. HTTP callers provide the explicit `x-self-improvement-*` ecosystem, tenant, workspace, optional program, jurisdiction, and purpose headers. Readiness remains red until the FORCE-RLS `self_improvement_*` tables have been migrated; the app never auto-migrates a runtime database role. The managed composition also supplies the program-scoped event broker and publishes declared lifecycle events only after successful headless mutations. Governed organization subject bindings (D-154b, EXCHANGE-01l) are mounted at `/internal/osint/governed-subject-bindings`: `GET` is the identity host read (`osint.governed_subject_binding.list`) and `POST .../set` and `POST .../withdraw` record a new append-only binding version. The read requires `Authorization: Bearer` equal to `OSINT_GOVERNED_SUBJECT_BINDINGS_READ_TOKEN` (32+ characters, distinct from `OSINT_SOURCE_RIGHTS_INGRESS_TOKEN` and `SELF_IMPROVEMENT_WORKLOAD_TOKEN`) and an `x-lssm-application-id` that is an `active` AuthOS ecosystem registration. The managed host binds the osint-store binding store in the `OSINT_SOURCE_RIGHTS_DISPATCH_SCOPE` scope; without that scope every binding route answers `503 subject_bindings_unavailable`. Writes answer `403 operator_required` until an OSINT operator authority is composed. Source-rights internal routes (EXCHANGE-01m, D-160, D-163b) are internal service routes, not registered in the public osint-spec registry: `GET /internal/osint/source-rights-outbox/attention`, `POST .../redrive` and `POST .../resolve` (`osint.source_rights_outbox.*`) require `Authorization: Bearer` equal to `OSINT_SOURCE_RIGHTS_OPERATOR_TOKEN`, and writes answer `403` until an OSINT operator authority is composed. `POST /internal/osint/governed-subject-binding-refs` records identity's keyed `org_` subjectRef for the current active binding version with the bearer `OSINT_GOVERNED_SUBJECT_BINDING_REFS_WRITE_TOKEN` (same value as identity's `LSSM_GOVERNED_ORGANIZATION_SUBJECT_BINDING_REFS_WRITE_TOKEN`). All bearers are 32+ characters and mutually distinct. Without `OSINT_SOURCE_RIGHTS_DISPATCH_SCOPE` every such route answers `503 source_rights_internal_unavailable`. When the osint-worker owns the expiry sweep (`OSINT_SOURCE_RIGHTS_EXPIRY_SWEEP_SCOPE`, optional `OSINT_SOURCE_RIGHTS_EXPIRY_SWEEP_INTERVAL_MS`), set `OSINT_SOURCE_RIGHTS_EXPIRY_SWEEP_OWNER=worker` here so the api tick skips its sweep. The osint-worker governed company projection reader factory reads `OSINT_GOVERNED_COMPANY_PROJECTION_{READER_ACTOR_ID,SOURCE_APPLICATION_ID,MAX_AGE_SECONDS}`; it is not yet composed into the managed worker because no worker port consumes it. --- ## @lssm-tech/app.osint-cli Description: (none) Path: packages/apps/osint-cli URL: /llms/app.osint-cli # OSINT CLI Thin generated-SDK client for OSINT and governed self-improvement. Configure `OSINT_API_URL` and optionally `OSINT_API_TOKEN`, then call an `osint.*` or `self-improvement.*` operation key followed by `--key value` flags. A separate `SELF_IMPROVEMENT_API_URL` and `SELF_IMPROVEMENT_API_TOKEN` may be supplied; otherwise the OSINT endpoint and token are reused. Output is newline-delimited JSON for automation. Every contract-generated mutation fails closed unless `--yes` is supplied explicitly; generated read operations do not prompt. Typed self-improvement arguments include integer `expectedRevision`, comma-separated or JSON `evidenceRefs`, and JSON `payload`. --- ## @lssm-tech/app.osint-console Description: (none) Path: packages/apps/osint-console URL: /llms/app.osint-console # OSINT Console Thin responsive host around `@lssm-tech/bundle.osint` and `@lssm-tech/bundle.self-improving-system`. The reusable controllers cover loading, empty, degraded, unauthorized, conflict, stale, review, shadow, canary, observation, promoted, rolled-back, killed, and evidence states with design-system primitives. The deployable Next.js host uses `OSINT_PUBLIC_API_URL` when the API is on a separate authenticated origin and otherwise defaults to the browser's same origin. It sends same-origin credentials through the generated SDK, provides responsive dataset, company, job, people, curation, improvement program, signal, candidate, review, gate, canary, observation, rollback, and exact-replay navigation. Candidate- and program-specific views require an explicit resource identifier before fetching. The command center is organized into independently addressable intelligence, acquisition, governance, recovery, and self-improvement areas. URL parameters preserve the active view, explicit resource identifier, and master/detail record selection across refresh and browser history. The acquisition area covers source health, acquisition activity, research, and evidence. Recovery covers dead letters and webhook delivery; jobs expose freshness/reconciliation actions; and governed improvement covers evaluation, review, shadow, canary, observation, promotion, rollback, kill, and exact replay. Actions are never inferred by this host. It renders only server-authoritative action descriptors which also match the route's operation allowlist. Descriptors carry their exact input, authorization reference, idempotency key, optional disabled reason, and optional confirmation phrase. Confirmation phrases match byte-for-byte and concurrent double activation is coalesced before the SDK call. `SELF_IMPROVEMENT_PUBLIC_API_URL` optionally points improvement controllers at a separately hosted surface; otherwise they reuse `OSINT_PUBLIC_API_URL` and same-origin credentials. The console never decides policy or promotion state. --- ## @lssm-tech/app.osint-mcp Description: (none) Path: packages/apps/osint-mcp URL: /llms/app.osint-mcp # OSINT MCP Contract-derived MCP tools for all OSINT operations and an optional governed self-improvement composition. The host must resolve authenticated contexts; tool calls enforce the same grants as REST. By default the standalone service uses the same managed OIDC, fresh-authority, FORCE-RLS PostgreSQL handler as REST. HTTP callers provide exact scope headers; local stdio uses the separately configured `OSINT_MCP_STDIO_ACTOR_ID` and `OSINT_MCP_STDIO_GRANTS` workload scope. Deployments may instead set an allowlisted `OSINT_MCP_COMPOSITION_MODULE` matching `@lssm-tech/integration.osint-mcp-*`. It serves authenticated, stateless Streamable HTTP at `/mcp` by default, or local stdio when `OSINT_MCP_TRANSPORT=stdio`. Both modes reuse the contract-derived tool and resource registry, propagate cancellation, and invoke the same scoped headless handler as REST and the worker. `OSINT_DEPLOYMENT_PROFILE_ID` optionally pins a managed deployment profile from the governance catalog `osint.deployment-profiles@1`, loaded once at startup into `OSINT_DEPLOYMENT_PROFILE_REGISTRY_V0`. Registered isolated deployment IDs are always inferred from the authenticated or stdio scope, so MCP cannot expose a vertical disabled by that profile. When `selfImprovement` is present, HTTP resolves both contexts concurrently and stdio resolves two explicit workload contexts before connecting. The same MCP session then exposes all generated improvement tools and program/candidate/replay resources. If either configured identity cannot be resolved, connection fails closed; the MCP app never translates OSINT grants into improvement authority. The managed MCP host enables the concrete governed runtime with the same `SELF_IMPROVEMENT_CONTROL_URL`, workload token, and optional authority URL as the API. Local stdio additionally requires `SELF_IMPROVEMENT_STDIO_WORKSPACE_ID` and `SELF_IMPROVEMENT_STDIO_GRANTS`; actor identity defaults to the explicit OSINT stdio actor and an optional `SELF_IMPROVEMENT_STDIO_PROGRAM_ID` restricts both scope and allowed program identifiers. Readiness verifies the FORCE-RLS store tables before accepting production traffic. --- ## @lssm-tech/app.osint-worker Description: (none) Path: packages/apps/osint-worker URL: /llms/app.osint-worker # OSINT Worker Durable queue consumer for scoped OSINT operation requests. Queue adapters own leases, retry policy, and DLQ movement; the worker acknowledges only after the headless handler succeeds. By default the standalone service uses the managed PostgreSQL composition with fresh AuthOS effect authorization and transactional metadata mutations. It requires the database, authority/workload, worker identity, exact scope, and grant `OSINT_*` variables documented by `managed-composition.ts`. Deployments may instead set an allowlisted `OSINT_WORKER_COMPOSITION_MODULE` matching `@lssm-tech/integration.osint-worker-*`. The composition supplies the fenced queue, shared headless handler, worker identity, and bounded concurrency. The service heartbeats claims, abandons lost leases, retries transient failures, dead-letters exhausted jobs, drains on shutdown, and never acknowledges an effect after ownership is stale. `OSINT_WORKER_ENABLED` defaults to `false`, and an active `OSINT_GLOBAL_KILL_SWITCH` always wins. In this intentionally disabled state the process does not load credentials, connect to PostgreSQL, or claim work, while `/livez` and `/readyz` stay green and report `state: "disabled"`. Provider and program kill-switch lists are exact comma-separated identifiers; a killed provider is rejected before its adapter can execute. The rights deletion loop is independently default-disabled through `OSINT_RIGHTS_WORKER_ENABLED`. Enabling it requires migration 0011, a distinct `OSINT_RIGHTS_DATABASE_URL` authenticated as the `osint_rights` non-owner role, `OSINT_RIGHTS_WORKER_ID`, the configured S3 object store, and an HTTPS cache purge endpoint through `OSINT_CACHE_DELETE_URL` and `OSINT_CACHE_DELETE_TOKEN`. `OSINT_CACHE_DELETE_TIMEOUT_MS` defaults to five seconds. Startup fails closed when any required target is absent. `OSINT_RIGHTS_DATABASE_ROLE` may name an explicitly provisioned equivalent and defaults to `osint_rights`; readiness verifies the exact `current_user` and rejects `SUPERUSER` or `BYPASSRLS` before the first claim. The rights loop claims deadline-prioritized tasks independently from ordinary operation work. It executes projection, embedding, export, cache, and object deletion, heartbeats the database-clock lease, and records completion only after one final exact owner/attempt fence check. Lost leases are abandoned; redacted failures retry with bounded backoff and settle terminally after the attempt limit. Main and rights work drain together during shutdown. Local conformance does not prove the fifteen-minute production deletion SLO; that requires managed non-owner RLS and destination receipts. Worker compositions must expose `handleFenced`. Every call receives the exact lease ID, owner, attempt, expiry, request ID, and idempotency key; canonical stores must validate that fence atomically with each effect. Jobs without an idempotency key are dead-lettered before handler execution. Provider-backed discovery, qualification, revalidation, sync, and deep research use direct fetch or a qualified Bright Data, Massive, Browserbase, Serper, Linkup, Tavily, Reworkd, Firecrawl, Apify, or Oxylabs adapter selected by the request. Configure the explicit provider key variables plus `OSINT_S3_*`; the worker binds fresh authority evidence and bounded budgets, stores redacted results in the content-addressed evidence bucket, and commits canonical sources, lifecycle receipts, candidates, assertions, research receipts, and outbox events before acknowledging. Discovery never activates a source. Qualification requires explicit reviewed policy findings, activation is a separate governed transition, and schema drift revalidation degrades the source rather than silently promoting changed data. Deep research accepts one to six qualified active provider sources. Each provider has an explicit sub-budget, the aggregate is bounded by the research budget and duration, and statements remain untrusted until the configured number of independent providers corroborate the same normalized claim. Managed exports page through the authorized canonical read store, write JSON, CSV, or Parquet content-addressed objects, and exclude restricted fields unless both the grant and a destination-specific field policy reference are present. Missing accounts return `OSINT_PROVIDER_ACCOUNT_GATED`; unsupported methods are never simulated. Fetch ingestion is direct-first when the credential-free adapter is enabled. The legacy single-fallback path may use the qualified requested provider only after retryable upstream unavailability or timeout. HTTP 403, authentication, rate-limit, quota, policy, unsafe-target, malformed-content, cancellation, and unknown failures stop without rotating providers. Rendering or anti-bot escalation requires the immutable `JobAcquisitionPlanV1` path and an explicit `render_required` classification. The result provenance records the adapter that actually acquired the evidence. Named-source sync payloads may carry the strict secret-free `acquisitionPlan` plus its exact `budgetRef` and bounded `budget`. The worker recomputes the connector request digest, checks the current installation revision, credential reference and rate policy, then binds the plan to fresh authority before an adapter executes. Unknown plan fields—including raw keys or provider options—are rejected during durable input parsing. The built-in managed composition replaces its environment bootstrap gate with `PostgresJobSourceAcquisitionRateGateV1`. All replicas therefore share scoped concurrency leases and minimum-interval state; crashed claims expire and exact owner/claim release is fenced. The process-local gate remains available only for single-process custom compositions and deterministic tests. Reworkd and Apify routes use explicit secret-free profiles: - `OSINT_REWORKD_CONNECTION_REF` with `OSINT_REWORKD_DATASET_ID`; - `OSINT_APIFY_CONNECTION_REF` with `OSINT_APIFY_ACTOR_ID`; - optional bounded `OSINT_APIFY_MAX_POLLS` and `OSINT_APIFY_POLL_INTERVAL_MS`. Partial profile pairs fail startup. Credentials remain in the existing provider secret environment and never enter acquisition plans or profiles. Account-gated ATS credential adapters remain a separate official-API path and currently reject a generic Web Access acquisition plan rather than pretending its credential effect was plan-governed. Optional webhook delivery composition materializes subscription/outbox pairs, claims them with database-clock leases, resolves signing secrets through an opaque injected port, sends one signed attempt, and persists retry or terminal evidence. Operator replay requires the exact durable revision and attempt. Job-listing recovery commands use the same fenced worker path and can close a listing only from explicit evidence or repeated successful absence plus a direct detail receipt. Revalidation consumes the typed, installation- and listing-bound `revalidationResult`; closure-only top-level fields are ignored, unknown availability fails closed, and revalidation alone can never close a listing. `osint.source.sync` payloads carrying a validated `jobSourceKey` now activate the named France/ATS connector inside the same durable ingestion transaction. The connector owns its canonical listing/detail route, parser fingerprint, conditional checkpoint headers, evidence locators, and deployment targeting filter; unknown source keys fail before provider execution. Sources that require policy or account qualification remain blocked by their executable matrix cell. Account-gated named sources retain only an opaque source `credentialRef`. Taleez and Teamtailor routes can execute through an injected credential-aware acquisition adapter; the default managed provider path rejects those requests instead of leaking the reference into provider payloads or silently issuing an unauthenticated request. `OSINT_SCHEDULER_ENABLED=true` activates the managed source scheduler. It reads qualified source/program state under the worker scope, applies the provider-free TTL/failure/drift scheduler, and enqueues discovery, qualification, ingestion, and revalidation independently. Each due stage requires an explicit `sourceStrategies[sourceId].stageInputs[stage]` plan; missing stage input is reported as blocked and is never invented. Time-bucket idempotency prevents duplicate scheduled effects. `OSINT_SCHEDULER_POLL_INTERVAL_MS` is bounded from one second to one hour and defaults to one minute. Every successful source sync now rebuilds its current projection from canonical assertions and authorized evidence. Restricted assertions and restricted evidence are excluded in SQL before projection. Managed embeddings remain default-disabled through `OSINT_EMBEDDING_ENABLED`; enabling them requires an explicit `openai` or `mistral` provider, model, dimensions, batch/token limits, pricing reference and currency, maximum batch cost, immutable generation time, destination policy decision, and redaction/extractor/chunker fingerprints. Provider-specific API keys remain constructor-only secrets. Custom provider base URLs must be credential-free HTTPS. Before any knowledge or vector write or provider request, the worker obtains a fresh authority decision for a digest binding the originating sync, scope, grants, provider/model/dimensions, generation fingerprint, destination policy, budget, and exact document content hashes. A missing, stale, or mismatched decision fails closed before the billable effect. Embedding generations are registered as `shadow` only. The worker writes policy-bound knowledge documents, finite vectors, and provider usage/cost receipts but never activates a generation. Content hashes skip unchanged work. Migration 0012 records each provider batch, fresh decision/evidence/expiry, and append-only transition under FORCE RLS; a concurrent claim, changed request digest, crash after dispatch, or uncertain provider result fails closed instead of silently repeating a billable call. Promotion remains a separate governed self-improvement decision. Deployment profiles come from the governance catalog `osint.deployment-profiles@1`, loaded once at startup into `OSINT_DEPLOYMENT_PROFILE_REGISTRY_V0` (`src/deployment-profiles.ts`). Registered data-isolated profiles are inferred from `OSINT_DEPLOYMENT_ID`; an explicit `OSINT_DEPLOYMENT_PROFILE_ID` may pin the same profile, and an unknown one fails with `OSINT_DEPLOYMENT_PROFILE_UNKNOWN`. A registered profile's startup requires exact queue, index, credential, region, network, database, object, and export policy binding attestations. Its worker concurrency is capped by the profile and person collection is rejected before provider execution. A profile's `jobTargetingRef` selects a job-targeting classifier from a closed host table (`job-targeting.france-early-career@0` binds the France internship/apprenticeship taxonomy) that job results must match before materialization; an unknown reference fails with `OSINT_JOB_TARGETING_UNKNOWN` and a deployment without a reference stays untargeted. ## Ownership This app is a thin delivery host: environment/config binding, queue and poll loops, lease heartbeats, PostgreSQL store scoping, provider and secret binding, and deployment targeting. Domain policy lives with its owners — `@lssm-tech/lib.osint-runtime` (source lifecycle input, embedding projection, scheduled work, operational recovery, webhook/deletion retry, research evidence, search observations) and `@lssm-tech/lib.job-source-runtime` (operator job reconciliation, job-source OSINT observations). Add new rules to those owners, not here; see `docs/refactoring/lssm-ecosystem/app-ownership-audit.json`. --- ## @lssm-tech/app.patio-web Description: Thin, host-aware and fail-closed Patio product host for bundle.patio: the seven Patio identities and www.mailpatio.com in one app (D-103). Path: packages/apps/patio-web URL: /llms/app.patio-web # @lssm-tech/app.patio-web Private, thin Patio product host (WEB-01, D-100 and D-103). One host-aware, fail-closed Next.js app replaces the eight donor Vercel projects (seven Patio sites and `www.mailpatio.com`). Unknown hosts fail closed. - It composes `@lssm-tech/bundle.patio`; product behavior lives in the bundle, customer-support and platform owners. - Copy is served in English, French and Spanish. - The donor operator lookup route is not carried over: `/api/website/operator/*` must return 404. Skeleton only (WEB-01-INT0): a root layout, no routes, no build script and no runtime yet. --- ## @lssm-tech/app.personalos-api Description: (none) Path: packages/apps/personalos-api URL: /llms/app.personalos-api # PersonalOS API Thin Elysia host for subject-bound PersonalOS commands, minimized experience projections, event cursors, and online rights operations. The host fails closed until an AuthOS-compatible token verifier and runtime ports are injected. Session subject/actor identity, full delegation scopes, command names, and idempotency are checked before domain execution. Delegation identifiers alone never confer authority. `@lssm-tech/integration.personal-os-authos` is the canonical production identity adapter. Its Better Auth bearer verifier rechecks the provider session for every request and emits the strict pseudonymous PersonalOS session shape consumed by `tokenVerifier`. Executable qualification issues a real magic-link session in a SQLite-backed Better Auth instance, calls `GET /v1/projection` with the issued bearer, revokes the provider session, and proves the same bearer receives `401`. The projection contains neither the bearer, email address, raw provider user ID, nor raw provider session ID. `/v1/health` is a public readiness endpoint, not a liveness fiction: it returns `503 not_ready` when its injected readiness probe fails or reports unavailable, and every response is marked `no-store`. The API accepts command envelopes with payload digests only. Sensitive command material belongs in an encrypted host channel and raw provider payloads are not part of the public contract. Authenticated life administration is additive under `GET /v1/life-admin`, `POST /v1/life-admin/commands`, and `POST /v1/life-admin/search`. Reads return only the shared bounded projection with `private, no-store`; commands require the exact session actor, subject, idempotency key, canonical payload digest, revision, and server authority. The projection may include an exact-actor assigned-care window. Owner reads are subject-bound; delegated reads require a current explicit `personal.life.care.read` capability and fail closed on actor/version drift, expiry, or revocation. Concrete composition is opt-in through `lifeAdminForSubject`, which supplies the encrypted transaction, two-phase authority, verifier, audit, crypto, and identifier ports. Encrypted content references, provider credentials/payloads, receipts, and evidence never enter the response contract. Search requires a fresh exact session-bound query, online connectivity, active consent IDs, and a separately injected expiring authority issuer/verifier. Production composition reads only metadata from the encrypted aggregate; stale, unsupported, malformed, or unavailable rows never enter results. Subject-owned support incidents use `POST /v1/support/incidents/commands` and `GET /v1/support/incidents/:incidentId`. The command route accepts only the strict support command wrapper; a client-supplied receipt or undeclared field is rejected. The authenticated session must exactly match the subject, actor, and idempotency header. The server runtime prepares the exact before/proposed state digests, obtains and independently verifies authority, atomically commits an allowed transition, or records a no-effect denial/confirmation audit. Reads return only the minimized incident cursor and are always `no-store`. PersonalOS domain activation (RT-008) is fail-closed. Private finance, health and life-admin aggregates stay dormant until the composition injects `domainActivation` (activation store, consent facts, key-recovery probe and outbox-processor probe) and the subject has an active, consented activation record. `GET /v1/activation/:domain` returns the exact decision; blocked decisions carry only a stable reason such as `host_binding_missing`, `activation_missing` or `consent_missing`. Finance requires the activation boundary at composition time; there is no plaintext or parallel runtime path. Activation-gated finance routes reuse the durable encrypted finance runtime: `POST /v1/finance/commands` executes typed finance commands (committed or replayed return `202`), and `POST /v1/finance/tax-recovery/dossiers` returns a `tax-recovery-v1` proposal whose items cite original encrypted documents. The dossier is never filed, submitted, paid or externally confirmed; submission is an explicit human action outside PersonalOS. Activation lifecycle: `POST /v1/activation/:domain` lets the subject (never a delegate) activate a domain on named, currently granted consents, and `POST /v1/activation/:domain/revocations` revokes it. Health authorization, `domain: 'health'` workspace commands, life-admin and finance routes are all gated. Existing subjects are migrated by the idempotent PostgreSQL carry-forward backfill before the gate is enabled; the loopback E2E server activates its consented subject through the same carry-forward path. `health-routine-v1`: `POST /v1/health/routine/commands` records typed signals, withdraws one, sets context or erases the routine into the encrypted subject aggregate; `GET /v1/health/routine/proposal` returns the subject-only view; `GET /v1/health/routine/export` returns the subject export. Export and `erase_routine` remain available after consent withdrawal. Remote health authorization uses these locked routes: - `POST /v1/health/connection-authorizations` accepts only provider kind, categories, an allowlisted relative return path, request/idempotency IDs, and request time. Subject, actor, and session assurance come from authentication; browser-supplied PKCE, OAuth state, credentials, and authority are rejected. - `GET /v1/health/connection-authorizations/:ticketId` returns a subject-bound, secret-free status. - `GET|POST /v1/health/connection-authorizations/callback/:providerKind` passes raw provider code/state directly to the injected host broker without persistence. The broker consumes stored PKCE/state once, deletes both, atomically persists a bound secret-free connect dispatch before deletion. The API may then return `303` to a trusted configured PersonalOS web origin plus the ticket's allowlisted relative path; a separate worker can recover delivery if the callback process stops. Begin and status use `{ data }`; errors use `{ error: { code } }`. No route returns a credential reference, authorization code, PKCE verifier, or raw provider payload. `createPersonalOsProductionApiInput()` accepts the concrete `healthAuthorizationBrokerFactory`, active consent resolution, subject state, encryption, two-phase authority, receipt verification, and decision-audit ports. The factory injects the workspace-backed command issuer into the broker; hard-coded consent/revision/receipt fixtures are not a production seam. Provider OAuth clients, secrets, redirect registration, and production canaries remain deployer-owned and unqualified locally. `GET /v1/projection` validates the host projection at the wire boundary and rejects any subject or exact-actor mismatch before returning it. Loader and schema failures return only the stable no-detail `projection_unavailable` response; internal RoleMorph diagnostics never cross the HTTP boundary. `POST /v1/domain-commands` accepts the typed PersonalOS workspace or health command wrapper and checks the authenticated subject/actor, delegation, idempotency header, payload digest, revision, and final receipt binding before returning `202`. `GET /v1/workspace` returns only the minimized subject-owned workspace cursor with bounded, count-preserving planning, delegation, goal-scoped support, connection-status, and coach-adaptation summaries. When the deployer binds the wellbeing-goal query port, the same read composes an exact-subject bounded goal window before RoleMorph filtering. Invalid counts, subject-version drift, and adapter failures fail closed; raw measurements, evidence, target values, and provider fields never cross the endpoint. Every workspace read revalidates the current exact RoleMorph presentation. A missing, stale, invalid, differently bound, denied-area, or denied-component projection returns cursor metadata only and strips every sensitive domain summary through the shared fail-closed DataView adapter. Its planning summary includes current outcome value, confidence, collection mode, minimized evidence IDs, and correction/removal counts without reasons or prior values. The executable outcome journey records, corrects, and removes a self-reported observation, rejects payload substitution without revision drift, and proves the current projection changes without losing immutable history. The same endpoint accepts the high-risk `consent` workspace domain. Its loopback qualification proves digest substitution denial, exact grant, missing-revocation no-data-loss recovery, durable revocation receipts, replay, and denial of a goal write after its adopted consent is revoked. Workspace reads expose only active/revoked/expired counts and affected-consumer IDs. The same authenticated route accepts online-only guardrail and goal-conflict commands. Loopback qualification proves payload substitution denial, immediate goal pause, pre-authority progress denial with unchanged revision, minimized guardrail counts, evidence-bound resolution, and resumed progress. Support commands remain high-risk, human-required, and online-only; the runtime rejects stale goal evidence, inactive or substituted members, missing consent, and foreign actors before authority or persistence. Coach proposal and activation are online-only, presentation-only, expiry/consent bound, and default to human authority; any policy-governed mode requires exact feature or task scope. Inspect, undo, and reset remain human-required and online-only. Stale coach or adaptation revisions are denied before authority. The directly usable `createPersonalOsProductionApiInput()` factory wires those routes to subject-bound state, encryption, authority, and ID factories; it does not require the dynamic composition-module environment seam. The legacy V1 routes and deployer-owned loader remain compatible. The executable HTTP qualification submits the shared household constructor through invitation, activation, delegation, digest-substitution denial with an unchanged revision, recovery, and revocation before reading the minimized experience projection. A second loopback qualification executes household bootstrap, mission, goal, Today plan, habit, check-in, missed-day recovery, and weekly review through the production composition. It substitutes the Today payload without rebinding its digest, proves the revision and prior state stay unchanged, then resumes the same journey to its minimized projection. Production startup requires `PERSONAL_OS_API_COMPOSITION_MODULE`, whose module must export `createPersonalOsApiInput()`. Startup fails before binding a port if the composition is missing or malformed. This keeps AuthOS, PostgreSQL, rights, and command execution wiring explicit and deployer-owned. ## Migrations `bun run --cwd packages/apps/personalos-api migrate` is the packaged PersonalOS install step (founder-ops install-sequence step 5). Run it with the migrator credential in `PERSONAL_OS_MIGRATOR_DATABASE_URL` before enabling the activation gate. It applies the ledgered store migration and then the activation carry-forward for every AuthOS subject supplied by `PERSONAL_OS_MIGRATION_COMPOSITION_MODULE`, a deployer-owned module exporting `createPersonalOsMigrationInput()` (subjects plus consent facts from the host key service). `PERSONAL_OS_MIGRATION_STORE_ONLY=true` replaces the module only when no AuthOS subject exists yet; exactly one of the two is required. `PERSONAL_OS_DATABASE_SSL_MODE` (`require` by default, `prefer` or `allow`) and `PERSONAL_OS_STORE_SCHEMA` (default `public`) are optional. Re-runs are idempotent. The JSON report holds ledger ids and outcome counts only; exit code `2` means a usage or execution error. Afterwards founder-ops `qualify-migrations` reads the `public.personal_os_schema_migrations` ledger and forced RLS on every subject table. `bun run --cwd packages/apps/personalos-api migrate:rehearse` rehearses the same step against `PERSONAL_OS_TEST_DATABASE_URL`, which must be a loopback database whose name contains `test`, `disposable` or `rehearsal`. It works in a throwaway schema with synthetic subjects, replays the run, checks forced RLS and the exact ledger, drops the schema and exits `0` only when rehearsed. ## Local E2E qualification host `start:e2e` runs an explicitly non-production, loopback-only host with the real production route composition, workspace reducers/projections, two-phase authority, AES-GCM encrypted in-memory state, and a durable in-process health authorization queue: Its experience projection also injects explicit allow decisions for the six PersonalOS `*.manage` action boundaries and non-default presentation preferences so surface tests can exercise the complete journey. Those decisions exist only in the E2E composition; production composition remains fail-closed until its verified host supplies RoleMorph decisions and personalization inputs. The executable projection suite also replaces those decisions with missing and lookalike tuples over real HTTP and proves that display-only views remain available while every governed action stays blocked and decision reasons remain absent from the wire projection. A forbidden generated-UI marker forces the entire invalid presentation to be suppressed behind the same generic `projection_unavailable` response. The local host additionally emits an opaque test-only tenant/consent binding so surface session-boundary tests can exercise exact Personalization retirement without exposing a raw tenant label or consent artifact. It also runs the real support-incident runtime with an in-memory exact-subject transaction adapter. Qualification covers confirmation recovery, distinct person/support-agent transitions, bounded information exchange, resolution, appeal, closure, minimized reads, and pre-authority identity/idempotency denial. This does not qualify managed durable case custody, support staffing, notification delivery, accessibility operations, manual acceptance, or a production canary. ```sh PERSONAL_OS_E2E_PORT=3199 \ PERSONAL_OS_E2E_WEB_ORIGIN=http://127.0.0.1:3000 \ PERSONAL_OS_E2E_NATIVE_AUTH_NONCE= \ bun run --cwd packages/apps/personalos-api start:e2e ``` Use `Authorization: Bearer valid`. The selected web origin is the only browser origin accepted by CORS. `GET /v1/projection` hydrates the real encrypted workspace and returns the current subject/actor, revision, journey progress, area readiness, and privacy counts. E2E rights completion is explicit and idempotent rather than inferred from pending work. Health begin returns a provider-shaped HTTPS URL with server-generated opaque OAuth state and an S256 challenge; it never returns the PKCE verifier, callback code, credential reference, receipt, or dispatch. Before the first persisted command, `GET /v1/workspace` returns a minimized revision-zero projection with absent domain revisions; it does not persist or authorize state, and create-household remains the only runtime bootstrap mutation. When the optional native nonce is configured, the loopback host also accepts one exact no-store `POST /__e2e/native-authos/session` exchange using the `x-personalos-e2e-native-auth-nonce` header. The route is disabled when the nonce is absent, is never registered by production startup, and exists only so a development client can exercise the real authenticated mobile boundary without embedding a bearer token. For deterministic provider simulation, copy `state` from that URL into the normal callback route: - authorize: `GET /v1/health/connection-authorizations/callback/:provider?state=…&code=authorization_code_e2e_success` - deny: `GET /v1/health/connection-authorizations/callback/:provider?state=…&error=access_denied` To qualify durable retry, add `x-personalos-e2e-fail-domain-commit-once: true` to one callback. The E2E host strips this header before invoking the production API, fails exactly one state commit, retains the secret-free dispatch, and retries it through the normal ticket status route. This control does not exist in any production request schema or production startup path. `bun run --cwd packages/apps/personalos-api test:operations-rehearsal` runs a bounded loopback performance and capacity rehearsal through the same executable host. It evaluates a 750 ms local-loopback API p95 ceiling and zero-error budget plus steady, burst, injected dependency-failure, and recovery scenarios with the governed `personal-operations` qualifier. This is local E2E evidence only: it does not replace representative devices, production RUM, soak or retry-storm tests, managed dependency failure, cost validation, or production canaries. ## Life-admin channel effects `createPersonalCalendarEffectExecutor` and `createPersonalNotificationEffectExecutor` execute leased life-admin outbox effects for the worker. Both check the subject's `life_admin` activation before the encrypted aggregate is loaded (`loadGatedLifeAdminEffectState`; `createLifeAdminEffectStateLoader` binds the encrypted store). Calendar `calendar_reconciliation` effects write back to the subject's own active, read-write provider connection resolved by the deployment host, pass the effect idempotency key as the provider request id, and report a provider error as `indeterminate` for reconciliation before any retry; declines are refused. Mail and in-app `notification_delivery` effects are routed through the CommunicationOS product producer: email only with PersonalOS email consent, otherwise the in-app terminal, and push is refused. A notification whose `scheduledAt` is still in the future returns `{ status: 'deferred', availableAt }` without admitting anything; the worker must release the lease with that `availableAt` rather than acknowledge it. Without a calendar host or CommunicationOS host every effect fails closed. --- ## @lssm-tech/app.personalos-desktop Description: Premium Tauri 2 desktop shell for PersonalOS. Path: packages/apps/personalos-desktop URL: /llms/app.personalos-desktop # PersonalOS Desktop Tauri 2 shell for PersonalOS on macOS, Windows, and Linux. It composes the canonical Personal Calm design pack, golden journey, privacy center, and offline authority policy with typed goal, productivity, household, and health read models. Household invitation, activation, delegation, and revocation use the same browser-safe runtime constructor as web and mobile; desktop supplies exact native identity, revision, human evidence, timestamp, and opaque IDs. ## Safety boundaries - Only low-risk commands with an explicit undo command may queue offline. - Consent, sharing, health connection, delegation, rights, deletion, and authority changes require online revalidation. - Credentials are stored through the operating-system keychain. They are never placed in SQLite or browser storage. - Local projections are AES-256-GCM encrypted in Rust with subject, projection, and revision-bound additional authenticated data. The encryption key is held by the operating-system keychain. - Tauri grants only event listen/unlisten and current deep-link reads. There is no shell, process, filesystem, clipboard, arbitrary HTTP, SQL, menu, tray, image, or window-command permission. The CSP permits inline style attributes because the shared design-system theme runtime applies audited CSS variables through React. Scripts remain `self`-only with no `unsafe-inline` or `unsafe-eval`, and production network access is limited to Tauri IPC. ## Runtime composition The app exports `DesktopPersonalOsApp`, `DesktopPersonalOsApiClient`, and `bootstrapNativeDesktopHost` so the native AuthOS product host can bind an exact subject and provision an OS-keychain credential reference. Credential acquisition is `native_authos_only`: the webview port can check or remove a reference but cannot receive or store a raw bearer. The canonical client validates server experience/workspace projections, sends full domain commands with their exact idempotency key, and never exposes the bearer token to the webview. Tauri permits only the projection, workspace, domain-command, and exact health-authorization API paths over a compile-time HTTPS origin; localhost HTTP is debug-only. The clickable Personal Calm journey starts on the next incomplete golden step, uses an accessible design-system action and provider picker, and submits canonical shared-schema commands for household creation, mission and goals, Today planning, habits, check-ins, missed-day recovery, weekly review, coach proposal/activation/inspection/undo/reset, limited household support, and export/deletion. Remote wellbeing connections use the server authorization broker and expose only its validated HTTPS authorization URL; missing and unknown providers are rejected before that broker is contacted. Coach commands derive coach and adaptation revisions from the authenticated workspace instead of trusting hidden or caller-provided values. Per-action drafts survive denial and revision conflicts for recovery. The goals view renders minimized outcome baselines, targets, latest confidence, and correction/removal counts. Its record, correct, and remove actions submit the exact shared metric commands online; corrections reuse the current observation identity and retain prior values in encrypted server state. The privacy view renders the same minimized consent dashboard with localized purpose and downstream-consumer labels, expiry, and lifecycle status. Evidence, receipt identifiers, and subject metadata remain outside the desktop cache. Its action panel can grant the fixed one-year PersonalOS planning scope and revoke only a currently active consent. Both actions remain high-risk, human-required, online-only commands and are never written to the desktop offline queue. The wellbeing view consumes the shared minimized category summaries: localized category and status, observation/quarantine counts, and an optional latest source-observation timestamp. Raw measurements, provider payloads, credentials, and clinical conclusions never enter the desktop workspace model. The same view renders the optional bounded wellbeing-goal window with localized safe metric, lifecycle, direction, dates, observation count, and uncertain outcome. It states that observations do not establish cause or medical advice; raw targets, values, evidence, and provider fields never enter the local model. Goal-scoped support is distinct from household membership: the subject selects an active `propose_support` delegation, current goal, consent, and purpose before the shell constructs the canonical scope digest. Grant, revoke, block, and categorical report commands are high-risk, human-required, online-only actions; the desktop never queues them or widens their proposal-only fields and actions. The desktop consumes the server-issued PersonalOS presentation projection rather than resolving local roles or preferences. Display-only areas remain usable when legacy projections omit presentation metadata, but every governed mutation then fails closed. When a projection is present, denied areas and referenced components suppress their data, hidden actions disappear, blocked actions are disabled, and approval-required actions remain explicit requests to server authority. Preference and explanation rendering is presentation-only; its local reset preview is reversible and cannot alter action authority. Low-risk reconnect work is stored as a complete canonical domain command in an AES-GCM sealed v2 outbox. Replay decrypts and revalidates its subject, registry classification, payload digest, expected server revision, and idempotency key, then submits to `/v1/domain-commands` for fresh server authority. A 202 response is the only acknowledgement. Denial, confirmation, scope, and revision failures remain durably blocked for recovery; authentication/network/service failures remain pending without data loss. The native host shares one encrypted queue between command submission and workspace reads. A browser `online` event invokes the reconnect port, which replays and revalidates that queue before refreshing the canonical projection; initial load never dispatches queued effects, and concurrent reconnect notifications coalesce into one replay/refresh operation. The standalone entry loads native-only AuthOS session metadata and verifies its keychain credential reference before composing the canonical workspace and journey ports. Missing, expired, or invalid native identity fails closed; the app never invents a demo identity or silently falls back to local authority. The React host owns one shared Personalization identity boundary and refreshes native AuthOS session metadata when the window regains focus. Exact account, actor, opaque tenant, consent, or sign-out changes discard retiring buffers before the new projection is accepted; loading, reconnect, and retryable errors preserve the current scope. Collection cannot attach without granted consent. The updater seam is also fail-closed. `DesktopUpdatePort` reports `not_configured` until release engineering injects a signed update feed and its public verification key. A local Vite or Cargo build is not signed-installer, store-review, real-device, accessibility-certification, or update-feed evidence. ## Commands ```bash bun run --cwd packages/apps/personalos-desktop lint:check bun run --cwd packages/apps/personalos-desktop clean bun run --cwd packages/apps/personalos-desktop typecheck bun run --cwd packages/apps/personalos-desktop test bun run --cwd packages/apps/personalos-desktop build bun run --cwd packages/apps/personalos-desktop pack:check cargo fmt --manifest-path packages/apps/personalos-desktop/src-tauri/Cargo.toml -- --check cargo check --manifest-path packages/apps/personalos-desktop/src-tauri/Cargo.toml cargo test --manifest-path packages/apps/personalos-desktop/src-tauri/Cargo.toml ``` --- ## @lssm-tech/app.personalos-mobile Description: Premium Expo Router iOS and Android shell for PersonalOS. Path: packages/apps/personalos-mobile URL: /llms/app.personalos-mobile # PersonalOS Mobile Premium Expo Router shell for the PersonalOS golden journey on iOS and Android. It composes `@lssm-tech/module.personal-experience` with the goals, productivity, household, and health module view-model seams. The mounted shell now loads the authenticated subject-bound experience and workspace projections from the canonical PersonalOS API. Guided native forms build schema-validated, domain-separated commands for the complete golden journey instead of presenting inert affordances. Server denial and revision conflicts fail closed; accepted commands refresh the authoritative projection. The shell consumes the integrity-bound `presentation` member of that projection for exact area, component, and `.manage` boundaries. Missing or malformed presentation metadata, plus resolutions older than five minutes, are discarded so safe display-only state remains usable, while every governed action fails closed until a current bound presentation permits it. Presentation preferences change only density, detail, guidance, control explanation, media feedback, pace, and narrative display; they cannot grant authority and can be reset or restored without clearing form drafts. Household invitation, activation, delegation, and revocation use the shared runtime draft constructor before Expo Crypto performs the native domain-separated SHA-256 binding. Mobile does not redefine their risk, authority, offline eligibility, or excluded-action policy. The embedding native host registers its AuthOS login/deep-link exchange through `registerPersonalOsNativeAuthBootstrap`; the returned opaque session enters the device-only vault before projection loading. A clean standalone install without that host seam stays signed out and fails closed—no development token or public environment secret is accepted. For isolated simulator qualification, Metro resolves an ephemeral AuthOS bootstrap only when `PERSONAL_OS_MOBILE_E2E_AUTH=enabled`; the bootstrap exchanges a run-specific nonce with the loopback API host. Normal production exports resolve a no-op module instead, and the export command scans both Hermes bundles for the route, header, token, and E2E error sentinels before succeeding. The native runtime is pinned to the Expo 57-compatible React Native 0.86 line. SecureStore identifiers use only Expo-supported letters, numbers, periods, hyphens, and underscores, so both opaque sessions and SQLCipher keys survive the real native boundary instead of failing only after installation. ## Product surfaces - Today: capacity-aware plan, check-in, and missed-day recovery. - Goals: personal mission, observable goals, minimized outcome measurements, and online-authorized record/correct/remove controls that preserve history. - Health: accessible, non-clinical category history with minimized status, observation/quarantine counts, and latest source timestamp plus native HealthKit/Health Connect host ports; raw measurements and provider payloads never enter the view contract. A separate native summary renders the optional exact-subject wellbeing-goal window with localized safe metric, lifecycle, direction, observation count, and uncertainty-aware outcome plus explicit non-causal/non-medical copy. - Household: membership plus explicit, expiring, revocable support, including one-goal proposal-only grants and immediate revoke, block, and categorical report controls. - Privacy: minimized purpose/downstream-consumer/expiry/status consent dashboard, fixed one-year PersonalOS planning grant, active-grant revocation, coach explanation/undo, and online-only rights operations. Consent controls use the shared lifecycle schema and never enter the offline outbox. - Review: progress and wellbeing reflection without medical or causal claims. The shared Personal Calm design pack drives comfortable density, calm motion, platform-native navigation, progressive disclosure, 44-point touch targets, and light/dark readiness. Copy is typed in English, French, and Spanish; layout direction is derived independently so RTL locales can be added without restructuring screens. ## Trust boundaries - Session tokens use device-only `expo-secure-store` custody. - The last authenticated subject marker uses the same device-only custody. An offline process relaunch can load only that subject's exact encrypted experience/workspace pair; foreign subjects, mismatched revisions, missing rows, and malformed projections fail closed. - Local projections use SQLCipher. A 256-bit random key is generated by `expo-crypto`, stored in device-only secure storage, and applied before schema access. - Projection payload policy rejects tokens, credentials, secrets, and raw provider payload keys. - Only commands in the shared exact-action registry can enter the encrypted offline outbox. Caller-provided risk or undo metadata is never authoritative. - Presentation `allowed`, conditional, approval, blocked, and hidden boundaries are enforced before canonical command construction and again at the authenticated session boundary. Preferences never widen those boundaries. - Conditional and approval-required actions remain disabled until an exact condition or approval artifact and submission route exist; they cannot fall through to direct governed-command dispatch or offline queuing. - Missing or invalid presentation metadata leaves generic display state usable but blocks all governed actions. Sensitive and high-risk actions always require current online authority, regardless of presentation preferences. - Form drafts live above pending, denial, and conflict screen transitions. Hidden or blocked actions suppress their controls without deleting drafts, and reduced-motion mode removes modal slide animation. Draft storage is bound to the exact subject and actor refs and clears synchronously on sign-out or identity change, preventing a person's or delegate's draft from appearing in another authority context. - The mounted session also observes the server-issued opaque tenant/consent binding. Exact subject, actor, tenant, and consent changes discard retiring Personalization buffers before the next scope can collect; transient checking, denial, offline, and error states preserve the current scope. Buffer attachment is unavailable without granted consent. - The outbox validates the complete PersonalOS command envelope, authenticated subject, expected revision, canonical payload SHA-256 digest, and registry-owned undo command before its SQLCipher write. - Canonical command binding uses the `@lssm-tech/lib.personal-os-runtime/digest-port` lane (runtime domain map and canonical JSON) with an expo-crypto SHA-256 adapter, so every shared workspace domain is mapped exactly as on the server, including private `progress_celebration` and high-risk `guardrails` domains. Both remain online-only and are not exposed as offline or silently authoritative actions. - Replay runs the owner `@lssm-tech/module.personal-experience/offline-replay` state machine (25 commands per pass, 5 attempts, backoff, policy re-check). It reconstructs and validates the exact workspace command from the trusted registry, authenticated subject, revision, envelope, idempotency key, and domain-separated payload digest, then submits it to the canonical `/v1/domain-commands` authority boundary. Server denial and revision conflict remain blocked for recovery; transient failures use bounded retry and preserve order. - Concurrent reconnect/session refresh triggers share one in-flight load and one replay pass, preventing duplicate transport attempts before server idempotency is needed. - Version-one outbox rows are retained but marked `legacy_envelope_missing` because they cannot be proven safe to replay. - Consent, sharing, native health connections, delegation, authority, export, and deletion revalidate online. - HealthKit and Health Connect are real host ports, not mocked production adapters. Unavailable or denied native authorization fails closed. ## Commands ```bash bun run lint:check bun run typecheck bun run test bun run build bun run ios bun run android ``` Maestro definitions live in `tests-mobile/flows`. On 2026-08-13, bounded flows passed on an iPhone 16 Pro simulator running iOS 18.5: clean-install AuthOS denial; an ephemeral loopback AuthOS exchange followed by authenticated navigation across all six tabs and every canonical golden-journey action entry; the authenticated missed-day recovery form; and a source-bound native mutation run that durably created the household, mission, and first active goal through the production-composition API. These runs qualify native startup, navigation, guided-form reachability, and that exact revision-three mutation foundation. An additional iPhone 16 Pro simulator sequence established an authoritative workspace, disconnected the app from the preserved authority server, relaunched the app from an encrypted subject-bound projection pair, queued one reversible check-in, restored connectivity to that same server, and committed exactly one replay at expected revision 2. The server advanced to revision 3 with one minimized check-in and zero pending low-risk commands. These runs do not prove the remaining mutation journey, broader denial/recovery, Android, assistive technology, a real device, production AuthOS, provider accounts, store signing, or a canary and must not be counted as `live_verified` evidence. The earlier navigation and recovery replay remains a historical artifact, but later mobile source changes invalidate its current source binding. The current matrix therefore credits only the newer source-bound mutation run until those broader flows are rerun on the latest source commit. ContractSpec Connect was unavailable to this lane. The release capsule records the resulting review gap; it is not treated as approval evidence. The remaining native mutation and broader denial/recovery journeys, Android simulator, VoiceOver, TalkBack, real-device, provider-account, store-signing, deployed-host, and canary evidence remain pending and are not inferred from local tests or native bundle exports. Maintainers can replay a current-source iOS simulator flow with the manually dispatched `PersonalOS Native Qualification` GitHub Actions workflow. The job creates an isolated simulator, builds the current Expo development client, starts the real PersonalOS E2E API and Metro hosts with a run-specific masked nonce, runs the selected Maestro flow, validates the authoritative workspace, and retains JUnit plus minimized test-state diagnostics for 14 days. A workflow run is qualification evidence only after its exact commit, result, artifact digest, simulator/runtime, and observed time are recorded in the PersonalOS source-bound qualification ledger. --- ## @lssm-tech/app.personalos-web Description: Private, accessible Next.js and PWA shell for PersonalOS. Path: packages/apps/personalos-web URL: /llms/app.personalos-web # `@lssm-tech/app.personalos-web` Private Next.js/PWA delivery shell for the PersonalOS golden journey. It composes PersonalOS goals, productivity, health, household, privacy, and experience modules without duplicating their authority or offline policy. The app exposes executable Today, goals, health, household, review, and privacy routes, including every exact shared golden-journey deep link. Authenticated Server Components load the strict subject/actor-bound experience and workspace projections with `no-store`; Server Actions submit shared, schema-validated domain commands with expected revisions, idempotency, payload digests, and action classification. Missing AuthOS sessions, invalid payloads, scope mismatches, and stale revisions fail closed without discarding entered data. The goals surface also renders minimized baseline, target, unit, confidence, correction, and removal counts and exposes explicit online-only controls to record, correct, or remove self-observed outcome values without overwriting their encrypted history. The health surface also renders the optional bounded wellbeing-goal window with localized status, safe metric, direction, dates, observation count, and uncertainty-aware outcome. It explicitly states that observations do not prove cause and are not medical advice; raw targets, values, evidence, and provider fields are absent from the browser contract. Privacy routes render the minimized consent dashboard with human-readable purpose, downstream consumer destinations, expiry, and lifecycle status. The browser never receives consent evidence or authority receipts; truncated views retain exact totals and clearly disclose that the list is bounded. The subject can grant one fixed, typed PersonalOS planning scope for one year and revoke an active grant from the same route. Both controls construct the shared consent lifecycle command, require current online human authority, and preserve the selected grant when authority or revision checks deny the request. The scope transparently includes optional coach adaptations and private progress celebration for the PersonalOS and coach runtimes. The goals route then offers a separate opt-in celebration form: the subject selects an active goal, active consent, one or more contract-defined evidence kinds, points per verified event, and a total cap. Configure and disable commands are online-only, human-required, revision-bound, and preserve every entry after denial. The minimized browser summary exposes no consent evidence or receipts, cannot grant authority, and states that the policy is private, presentation-only, leaderboard-free, and free of pay-to-win or artificial scarcity. Household invitation, activation, delegation, and revocation use the shared runtime constructor; web supplies only authenticated context, human evidence, form values, and opaque command IDs instead of redefining household policy. `/today/organize` composes the encrypted life-administration host through a strict subject-bound, private/no-store projection. It renders bounded calendar and reminder metadata, exact-actor assigned-care rows, and knowledge and connection counts. Care uses design-system list semantics, translated empty copy, exact actor binding, and never exposes purpose text, capabilities, or authority receipts. The route submits only canonical online calendar/reminder commands with the current life-admin revision. Unified search is consent-bound and metadata-only across calendar, reminder, knowledge, file, and project sources; unavailable sources are reported without leaking their rows. Denials and conflicts preserve entries. Encrypted content, provider records, cursors, receipts, and evidence never enter the browser contract. Every privacy surface links to a dedicated human-support route. The route opens and reloads exact subject-owned support incidents through the shared operations contract and the authenticated PersonalOS API. It selects only an active consent from the current bounded workspace projection, offers accessible contact channels and accessibility preferences, and submits only canonical SHA-256 summary, appeal, or evidence references—never free-form personal narrative. Mutations re-fetch the no-store incident projection, bind its exact revision, and preserve form values after confirmation, authority, or revision denial. Incident state is minimized to status, requested-response state, accessibility preferences, and allowed person transitions; support-agent acknowledgement, escalation, and resolution remain host-owned. The shell consumes the subject/actor-bound `presentation` projection for all six area/component access decisions, all `${area}.manage` boundaries, and the seven presentation preferences. Hidden actions are omitted, blocked actions remain visibly unavailable, and approval-required actions need an explicit per-submission confirmation. Every Server Action re-fetches the no-store projection before an effect, so missing, invalid, duplicate, or stale decisions cannot be bypassed with a handcrafted browser request. Missing presentation still permits a calm, truthful display-only fallback. Preference reset and undo are local presentation changes and never grant authority or weaken API policy. The root client provider keeps one shared Personalization identity boundary across route navigation. Authenticated projections bind it to the exact subject, actor, opaque tenant, and consent tuple. A confirmed missing AuthOS session discards the retiring buffers, while loading, projection denial, offline, and reconnect states preserve them without changing identity. This boundary exposes buffer attachment only after granted consent; no telemetry is collected when the host omits the exact binding. Household routes also expose goal-scoped support as a separate governed layer after membership and `propose_support` delegation. The subject chooses one active goal, consent, trusted member, and purpose; the browser submits the exact shared support command with current goal-source revision and a canonical scope digest. Revoke, block, and categorical report controls remain high-risk, human-required, and online-only. The shipped `en`, `fr`, and `es` catalogs are left-to-right. An `ar` readiness option intentionally uses the English fallback catalog while exercising RTL document direction and logical layout semantics; this is RTL browser evidence, not a claim of translated Arabic copy. Workspace cards consume the minimized planning, delegation, aggregate wellness, and coach summary contracts. Coach adaptation inspection, undo, and reset remain human-required. Remote wellness connection starts only through the host broker: the browser sends its exact client-safe request, receives an opaque ticket and HTTPS redirect, then polls the subject-bound status through a same-origin route. Provider state, PKCE verifiers, credentials, raw measurements, and raw payloads never enter the browser contract. HealthKit and Health Connect remain native-only. The health route renders only consented category status, observation and quarantine counts, and the latest source-observation timestamp. It never renders raw measurements, provider payloads, credentials, or clinical conclusions. All personal responses carry `private, no-store` headers. The service worker caches only public shell assets and the data-free offline page; private navigations and APIs stay network-only. Low-risk offline commands are validated against the trusted shared registry, sealed with a non-extractable AES-GCM key in IndexedDB, and replayed through a same-origin proxy. The server revalidates authority and revision; conflicts or confirmation decisions remain blocked in the outbox without data loss. ## Local verification ```bash bun run lint:check bun run typecheck bun run test bun run build bun run verify:browser-artifacts bun run test:browser-contract bun run test:e2e ``` The browser-contract command builds first, then starts an isolated API fixture and the production Next server. It checks the authenticated golden command journey, denial/conflict preservation, opaque remote-provider begin and status behavior, sealed offline/reconnect replay, and an automated axe scan in desktop Chromium. Tailwind scans the exact published design-system button leaf as well as workspace sources, so sparse-worktree builds retain the foreground and hover utilities required for button contrast. The fixture is contract-valid test evidence; it is not evidence for a production provider, database, deployment, or canary. The production build also scans every emitted browser chunk and fails if internal design ownership, RoleMorph registry, task-fixture, or private execution markers enter the public artifact graph. Production builds use Next.js's default Turbopack. Tailwind tracks the UI kit's `ui/` and `src/` trees explicitly, avoiding recursive package-root scans through Bun's linked `node_modules`. Run the Next.js compiler under genuine Node.js, including when launching Turbo; do not use `bun --bun` for the parent build launcher, which can inject a Node shim and force compiler workers onto Bun. The browser-artifact check still runs with Bun. `next.config.ts` uses Next's built-in config transpiler and the dedicated `@lssm-tech/lib.presentation-runtime-core/next` entrypoint to load workspace TypeScript helpers without a custom loader or the runtime root barrel. `test:e2e` is reserved for the actual PersonalOS API production composition and must not be replaced with the fixture harness. Its four-minute scenario budget does not relax the ten-second action and revision assertions; it prevents the full multi-domain journey from being cancelled merely because secure server actions complete sequentially on a constrained qualification host. Root and segment error documents remain provider-independent, redact thrown details, and never require authenticated personalization context to render recovery. The actual production-composition Playwright journey also configures and disables private progress celebration, verifies bounded minimized state and goal-history preservation, and runs axe on the labelled opt-in surface plus the final journey. These automated checks do not replace manual screen-reader, zoom, visual, real-device, or cross-browser accessibility qualification. The production journey includes the human-support denial/recovery path: an `other` category requires authority confirmation and preserves the form, then an accessibility case can be opened with the same active consent and checked with axe. If local Chromium cannot launch, that run must be recorded as an environment gap rather than substituted with fixture evidence. Set `PERSONAL_OS_API_BASE_URL` to the HTTPS API host and provide an AuthOS Bearer session or Better Auth session-token cookie. Production provider callback and credential exchange are host-owned. HTTPS PWA installation, Safari/Firefox, real-provider qualification, production restore/deletion propagation, canary, and real-device evidence remain release-environment gates and are not claimed by this package. Next's global `typedRoutes` switch remains disabled because the current shared design-system `Link` intentionally accepts general internal and external URLs. The app instead fail-closes through its typed route inventory and exact shared golden-journey projection. Enabling framework-global route types requires a separate shared Link contract evolution. --- ## @lssm-tech/app.personalos-worker Description: (none) Path: packages/apps/personalos-worker URL: /llms/app.personalos-worker # PersonalOS Worker Bounded transactional-outbox worker for PersonalOS projections, revocation, rights, and provider-sync destinations. It uses lease ownership, retries with a bounded backoff, and dead-letters poison work. Payloads are never embedded in outbox records; handlers reload authorized subject state from durable stores. Production startup requires `PERSONAL_OS_WORKER_COMPOSITION_MODULE`, exporting `createPersonalWorkerRuntime()`. The host supplies subject-bound outbox stores, destination handlers, telemetry, and cadence. Cycles never overlap, destinations settle independently, and SIGINT/SIGTERM stop the loop after the active cycle. `createPersonalOsDurableWorkerRuntime()` is the direct production factory for the independently leased `personal.workspace.projection`, `personal.rights.export`, `personal.rights.delete`, and `personal.support.effect` destinations. Its injected support executor reloads the immutable event and encrypted subject state, then returns evidence receipts bound to content-free notification intents for both-party grant/revoke/block delivery or subject plus safety recovery for reports. The worker requires the exact audience set, canonical event-derived intent IDs and templates, distinct provider assurance evidence, exact subject/recipient binding, and delivery inside the intent window. Extra audiences, incomplete, substituted, duplicate, or replayed proofs retry instead of acknowledging. Each handler reloads the immutable event by subject and event ID before effects. Projection work reloads and re-encrypts the composite workspace cursor; rights work binds the exact export/deletion event and delegates idempotent artifact or propagation effects to an injected rights executor. Provider deployment, artifact storage, and deletion-propagation canaries remain deployer evidence. Concrete notification provider credentials, provider callbacks, manual receipt reconciliation, and production delivery canaries remain host qualification; this package proves the fail-closed contract and acknowledgement boundary only. `PersonalGovernedProjectionTransportV1` binds the bundle's minimized Pactena and hCircle packets to the canonical governed data plane. The worker resolves the exact pairwise product authority, invokes the governed gateway before encryption, seals only its returned field allowlist with the receiving product key, and writes the strict encrypted materialization. Revocation acknowledges only an exact applied product receipt at or above the current watermark. The qualified harness sends the ciphertext through the bounded HTTPS source port and product ingress, proving the same request, idempotency, authority, and receipt boundaries used by host composition without sharing a database. The same harness sends each exact revocation through the bounded recovery port and product ingress before constructing the source acknowledgement; local lease metadata never crosses the product boundary. The host still owns durable authority stores, product databases, regions, KMS custody, recovery workers, rights processors, and production qualification. When `healthAuthorization` is supplied, the same factory also composes an independent periodic consumer for the broker's durable, secret-free connection dispatches. It revalidates receipt, authority-proposal, and dispatch digests, executes through the subject workspace runtime, and settles by exact lease. Revision conflicts request a fresh authority decision and atomically supersede the old dispatch without reusing an OAuth code or PKCE verifier. This consumer must run even when callback API instances are unavailable so persisted completions remain recoverable after process failure. --- ## @lssm-tech/app.provider-ranking-mcp Description: MCP server for provider discovery, evaluation, and ranking workflows. Path: packages/apps/provider-ranking-mcp URL: /llms/app.provider-ranking-mcp # @lssm-tech/app.provider-ranking-mcp **MCP server that exposes provider-ranking operations and resources for benchmark ingestion, ranking refreshes, and leaderboard queries.** ## What It Does - Hosts a ContractSpec MCP server over provider-ranking contracts and runtime registries. - Exposes benchmark ingest, custom benchmark run, and ranking refresh operations. - Publishes leaderboard and model-profile resources backed by the ranking store. - Enriches incomplete ranking data with metadata from `@lssm-tech/lib.ai-providers`. ## Running Locally From `packages/apps/provider-ranking-mcp`: - `bun run dev` - `bun run start` - `bun run build` ## Usage ```bash bun run dev ``` ## Architecture - `src/server.ts` boots the MCP server and transport wiring. - `src/index.ts` exposes the package entrypoints for reuse or embedding. - The server composes provider-ranking contracts, module orchestration, and MCP resource/tool exposure. ## Public Entry Points - Exports `.` and `./server` for embedding or direct server startup. - Primary MCP surfaces are benchmark-ingest tools, ranking refresh tools, leaderboard resources, and model-profile resources. - Export `.` resolves through `./dist/index.mjs`. - Export `./server` resolves through `./dist/server.mjs`. - Export `./*` resolves through `./*`. ## Local Commands - `bun run dev` — tsdown --watch - `bun run start` — node dist/server.js - `bun run build` — tsdown - `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 clean` — rm -rf dist ## 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 AI provider ranking system with ranking-driven model selection. ## Notes - The current implementation uses an in-memory store; restart the process to clear rankings and benchmark results. --- ## @lssm-tech/app.registry-packs Description: Registry application for discovering and distributing ContractSpec agent packs. Path: packages/apps/registry-packs URL: /llms/app.registry-packs # @lssm-tech/app.registry-packs Website: https://agentpacks.dev **Agentpacks registry server for pack publishing, discovery, reviews, dependency graphs, and MCP access.** ## What It Does - Hosts the pack registry API, MCP layer, artifact storage, and publishing workflows. - Supports versioning, reviews, organizations, quality scoring, GitHub integration, and webhooks. - Supports both SQLite and PostgreSQL deployment paths with rate-limiting and auth middleware. - `src/mcp/` contains MCP handlers, tools, prompts, and resources. - `src/routes/` contains HTTP or API route definitions. - `src/services/` contains business logic services and workflows. ## Running Locally From `packages/apps/registry-packs`: - `bun run dev` - `bun run start` - `bun run build` - `bun run test` ## Usage ```bash bun run dev ``` ## Architecture - `src/routes/` owns HTTP endpoints for packs, versions, publishing, organizations, dependencies, and GitHub flows. - `src/services/` contains business workflows for registry operations, search, scoring, reviews, and webhooks. - `src/mcp/` exposes registry tools, prompts, and resources over the MCP protocol. - `src/db/`, `src/storage/`, `src/auth/`, and `src/middleware/` hold persistence and platform adapters. - `src/index.ts` is the root public barrel and package entrypoint. - `src/server.ts` is the main server bootstrap entrypoint. ## Public Entry Points - Deployable API app with HTTP routes, MCP tools/prompts/resources, and registry publishing flows. - Primary public surface is the HTTP route tree under `src/routes/`. - This app exposes MCP-facing tools, prompts, resources, or transport handlers. ## Local Commands - `bun run dev` — bun run --watch src/index.ts - `bun run start` — bun run ./dist/index.js - `bun run build` — bun build --minify-whitespace --minify-syntax --target bun --outfile dist/index.js src/index.ts - `bun run test` — bun test --pass-with-no-tests - `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 db:generate` — drizzle-kit generate - `bun run db:migrate` — drizzle-kit migrate - `bun run db:studio` — drizzle-kit studio - `bun run clean` — rm -rf dist - `bun run db:generate:pg` — drizzle-kit generate --config=drizzle-pg.config.ts - `bun run db:migrate:pg` — drizzle-kit migrate --config=drizzle-pg.config.ts - `bun run db:seed` — bun run src/db/seed.ts ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Resolve lint and build errors in workspace bundle and integrations lib. - Test runner. - Resolve lint/test regressions after voice capability updates. - Phase 4 production hardening — rate limiting, security, E2E tests, versioning polish. - Add dependency graph, webhooks, GitHub App, and PostgreSQL support (Phase 3b). ## Notes - REST API routes are consumed by external clients — do not change paths or response shapes without versioning. - MCP tool schemas are a protocol contract — coordinate changes with MCP clients. - Database migrations must be backwards-compatible. --- ## @lssm-tech/app.registry-server Description: Registry server for ContractSpec packages, contracts, and ecosystem metadata. Path: packages/apps/registry-server URL: /llms/app.registry-server # @lssm-tech/app.registry-server Website: https://contractspec.io **ContractSpec registry server. Serves contract specs and metadata over HTTP for IDE plugins, CLI tools, and other consumers.** ## What It Does - Built with Elysia (Bun HTTP framework). - Uses `@lssm-tech/lib.contracts-spec` for contract definitions. - Uses `@lssm-tech/lib.logger` for structured logging. - Separate handlers for ContractSpec and LSSM routes. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `packages/apps/registry-server`: - `bun run dev` - `bun run start` - `bun run build` ## Usage ```bash bun run dev ``` ## Architecture - Built with Elysia (Bun HTTP framework). - Uses `@lssm-tech/lib.contracts-spec` for contract definitions. - Uses `@lssm-tech/lib.logger` for structured logging. - Separate handlers for ContractSpec and LSSM routes. - `src/index.ts` is the root public barrel and package entrypoint. - `src/server.ts` is the main server bootstrap entrypoint. ## Public Entry Points - This package is a deployable application rather than a library with published subpath exports. - Registry packages include the portable `src/` entrypoints for Bun. Host-native `dist/server` executables and `.bun-build` scratch files are local build artifacts and are not included in npm or GitHub Packages tarballs. ## Local Commands - `bun run dev` — bun run --watch src/server.ts - `bun run start` — ./server - `bun run build` — bun build --compile --minify-whitespace --minify-syntax --target bun --outfile dist/server src/index.ts - `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 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 server ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - API routes are consumed by IDE plugins and CI — do not change paths or response shapes without versioning. - Filesystem access must use the `src/utils/` helpers for consistent path resolution. --- ## @lssm-tech/app.sarla-web Description: Thin hiring host (D-112a, D-122 H layer): serves the Sarla brand composition over the shared hiring experience; no reusable screens. Path: packages/apps/sarla-web URL: /llms/app.sarla-web # @lssm-tech/app.sarla-web Private, thin hiring host (D-112a, D-122 H layer, SARLA-02a). One Next.js app serves the `@lssm-tech/bundle.sarla` brand composition by hostname over the shared hiring experience (`@lssm-tech/bundle.talent`). - Hostnames resolve in the D117-COMP-01 `BrandHostResolution` shape (`@lssm-tech/lib.contracts-library/app-config/brand-composition`): canonical origins serve, aliases answer 308, unknown hosts fail closed. - Screens come from the experience bundle selected by the brand composition; this app holds no reusable screens, writers, stores or migrations. - A composition grants no authority: admission comes from AuthOS with a trusted `productApplicationId`. ## Host binding (SARLA-02a) - `src/proxy.ts`: the `host` header is the only brand selector (never `X-Forwarded-Host`, a query hint or a cookie). Unknown or conflicting hosts answer 421 with an empty body, no cookie and `no-store`; registry aliases answer 308; a served host goes through the route-map dispatch. Legacy donor paths answer 308. - `src/host/registry-index.ts`, `host-index.ts`, `resolve.ts`: hosts derive from the real application/origin/package registries only. At the current base the registries have no origin route and no package binding for this host, so every host answers 421 until those rows land. - `src/host/locale.ts`: reading locale from the path, then the neutral `ui_locale` cookie, then the injected `AccountLocaleLookup` seam (absent by default). Invalid values are ignored and never reflected. - `src/host/trusted-context.ts`: presentation-only headers (brand key, host role and origin, reading locale, original path). The proxy strips them inbound and sets them; they are never admission, session or authorization input. - `src/host/session.ts`, `area-guard.ts`: the default session seam resolves no actor, so every protected route fails closed to `/acces-refuse`. SARLA-02b binds the real AuthOS resolver. - `src/host/dispatch.ts`: unported donor routes answer an explicit not-available state (pages: 200 rewrite with `noindex`; APIs: 501 `{error:'not_available'}`). No donor journey is ported here. - `src/host/composition-check.test.ts`: records the real-catalog `checkBrandComposition` refusal set at the current base. - `src/app/api/health`: anonymous liveness/readiness (`degraded` answers 503). --- ## @lssm-tech/app.storybook Description: Private dogfood Storybook for ContractSpec package catalogs and the canonical design matrix. Path: packages/apps/storybook URL: /llms/app.storybook # ContractSpec Storybook Private dogfood host for `@lssm-tech/integration.storybook`. The app owns only catalog selection and host configuration; reusable scenarios, bindings, providers, and styling live in their publishing packages. The canonical design suite is 30 built-in design packs × 8 surface families × 2 governed web profiles, producing 480 Chromatic snapshots. Native profiles remain in their existing qualification lanes. The host explicitly opts into four catalogs: - `@lssm-tech/lib.design-catalog/storybook` — 480 design-matrix stories. - `@lssm-tech/lib.design-system/storybook` — 30 canonical-family stories. - `@lssm-tech/lib.ui-kit-web/storybook` — 16 web-primitive stories. - `@lssm-tech/module.communication-os/storybook` — 480 migrated product stories. The host also owns the cross-catalog runtime: Storybook Docs and MDX, React Docgen, class-based light/dark themes, official and ContractSpec viewport presets, deterministic locale/context/flag/API-state toolbars, isolated query caches and browser storage, strict MSW network handling, portal isolation, Storybook MCP, and Chromium/WebKit/reduced-motion browser profiles. The authoring-pattern stories exercise typed fixtures, inferred controls, meta- and story-local render/decorator/lifecycle behavior, `fn()` spies, named interaction steps, keyboard and pointer flows, scoped portal queries, and composed play workflows. The design matrix uses eight distinct production-shaped fixtures and the real Tailwind, ThemeSpec, design-pack, locale, semantic-token, reduced-motion, and self-hosted font pipeline. Browser-default or placeholder rendering is a release failure. Repository governance also inventories every other React package. Catalog and host status live in package-local `contractspec.catalog.visualTesting` metadata; deferred packages carry an accountable owner, rationale, and rollout wave rather than disappearing from Storybook adoption checks. ```sh bun run generate bun run generate:check bun run storybook bun run storybook:build bun run test:visual-browser bun run test:browser:webkit bun run test:browser:reduced-motion bun run test:browser:coverage ``` `test:visual-browser` builds the static host and verifies the sixteen canonical reference cases in Chromium: eight Editorial light/mobile surfaces and eight Executive Ledger dark/desktop surfaces. It checks computed Tailwind layout, semantic colors and radii, self-hosted font resources, theme-global propagation, viewport-specific composition, console cleanliness, and non-empty screenshots against `references/design-matrix.json`. The sixteen reviewed local PNG goldens are committed under `references/screenshots`; the manifest locks every byte size and SHA-256 hash. Set `STORYBOOK_REFERENCE_OUTPUT` to retain a fresh browser run elsewhere. Chromatic remains the cross-platform pixel-diff authority because Chromium and font rasterization vary across hosts. Chromatic is optional. `bun run chromatic` reads `CHROMATIC_PROJECT_TOKEN` from the environment; no project token is stored in this package. TurboSnap remains disabled until the repository records ten successful full builds and explicitly opts in. Storybook, Vitest browser profiles and Chromatic launch under Node.js. Use the runner profile's pinned Node toolchain; on Apple Silicon it must match the native dependency architecture. Bun remains the package manager and catalog/unit-test runner. The packed-consumer proof uses the same Node-based Storybook launcher. The local development commands preload the pinned `tsx` loader for workspace TypeScript exports. The packed-consumer proof runs ordinary Node against published JavaScript export maps, preserving the distinction between development and release. ## Builder company-context workflow `src/builder/company-context.stories.tsx` exercises the shared Builder panel with deterministic, in-memory context responses. It covers explicit retrieval, release-authority messaging, loading, unavailable configuration, denied access, conflicting sources, untrusted text, and UTF-8 question limits. These are UI qualification fixtures; they do not qualify a live knowledge provider or grant release authority. Run the focused Chromium lane with: ```sh bun run test:browser:builder bun run test:browser:builder:mobile bun run test:browser:builder:webkit ``` The focused lane indexes only these seven stories with one Chromium worker, using the same Next.js-Vite framework and shared preview as the full host. It preserves strict MSW, sandbox isolation, fonts/themes, and accessibility checks; it supplements rather than replaces the full catalog gates. The mobile and WebKit profiles use a 390 × 844 viewport and check horizontal overflow in every state. WebKit here qualifies the browser engine at that viewport; it does not establish physical iOS-device or native-app support. Accessibility violations are errors for these stories. Reviewed visual baselines and live grounding remain separate release requirements. The focused Builder catalog also includes `candidate-execution.stories.tsx`: a controlled prepare/approve/run/status journey and unavailable/unknown states. These are deterministic UI fixtures; live authority, retained artifacts and AgentHost execution require separate end-to-end qualification. --- ## @lssm-tech/app.supportos-api Description: (none) Path: packages/apps/supportos-api URL: /llms/app.supportos-api # SupportOS API Ownership: AuthOS claim-to-grant projection is owned by `@lssm-tech/lib.customer-support-spec/authos-claim-projection`; this host keeps the OIDC/JWKS verifier, issuer binding and live session checks that call it. Standalone managed or self-hosted SupportOS HTTP host. A custom production composition may be injected through `SUPPORT_OS_COMPOSITION_MODULE`. Without one, the included zero-argument managed composition requires `DATABASE_URL`, `SUPPORT_OS_AUTHOS_ISSUER`, `SUPPORT_OS_AUTHOS_JWKS_URL`, `SUPPORT_OS_AUTHOS_SESSION_STATUS_URL`, `SUPPORT_OS_AUTHOS_SESSION_EXCHANGE_URL`, `SUPPORT_OS_AUTHOS_DOWNSTREAM_EXCHANGE_URL`, `SUPPORT_OS_AUTHOS_WORKLOAD_TOKEN`, `SUPPORT_OS_ALLOWED_ORIGINS`, `SUPPORT_OS_DATA_PROTECTION_KEY`, `COMMUNICATION_OS_API_ORIGIN`, `SUPPORT_OS_COMMUNICATION_SERVICE_TOKEN`, `SUPPORT_OS_CONNECT_DECISION_URL`, and `SUPPORT_OS_CONNECT_SERVICE_TOKEN`; it fails closed when any authority dependency is absent. When `support.opa-handoffs` is enabled it additionally requires `COMPANYOS_OPA_API_ORIGIN`. Internal-note verification exchanges the workload credential for a grant lasting no more than five minutes and bound to the `communicationos-support` audience, tenant, workspace, actor, and verify capability; OPA destination resolution uses a separate short-lived `companyos-opa-support` grant bound to the exact tenant, workspace, case, handoff, and destination. When `support.service-profiles` is enabled, managed composition additionally requires `COMPANYOS_SUPPORT_API_ORIGIN`. It exchanges the SupportOS workload credential for a grant lasting no more than five minutes and bound to the `companyos-support` audience, tenant, workspace, actor, exact profile, and verification capability. The CompanyOS verification request contains only party/context references, consent/source evidence, and the mutation digest; encrypted or plaintext field values are never forwarded. Startup and readiness fail closed until the dependency is configured and healthy. Readiness probes the dedicated CompanyOS service-profile readiness route, not a generic product root, so an origin without the evidence receiver stays out of rotation. When `support.company-actions` is enabled, managed composition additionally requires `COMPANYOS_SUPPORT_API_ORIGIN`, `CONNECT_OS_SUPPORT_API_ORIGIN`, and `WORKFLOW_OS_SUPPORT_API_ORIGIN`. It exchanges the workload credential for separate grants bound to the exact action plan and digest in the `companyos-support`, `connect-support`, and `workflow-support` audiences. CompanyOS returns only a minimized case/profile/entitlement evidence projection; Connect decides; Workflow alone starts effects and verifies outcomes. All three dedicated readiness routes must advertise the exact capability set with fresh evidence before the API enters rotation. The API stores and returns opaque references only and exposes no amount, customer body, provider payload, grant, or credential. When `support.notifications` is enabled, managed composition additionally requires `SUPPORT_OS_NOTIFICATION_POLICY_URL`, `SUPPORT_OS_NOTIFICATION_POLICY_READY_URL`, `SUPPORT_OS_NOTIFICATION_DELIVERY_EVIDENCE_URL`, `SUPPORT_OS_NOTIFICATION_DELIVERY_EVIDENCE_READY_URL`, `SUPPORT_OS_NOTIFICATION_WORKER_READY_URL`, and `SUPPORT_OS_QUEUE_READY_URL`. Policy and delivery responses must echo the exact authenticated scope, resource references, and request digest over bounded HTTPS calls. Readiness requires the SupportOS worker to advertise `notification.deliver`; a scoped workspace flag can never override the global kill switch. When `support.data-lifecycle` is enabled, managed composition additionally requires `SUPPORT_OS_ERASURE_PROTECTION_ORIGIN`, `SUPPORT_OS_ERASURE_PROTECTION_TOKEN`, `SUPPORT_OS_ERASURE_PROTECTION_READY_URL`, `SUPPORT_OS_ERASURE_WORKER_READY_URL`, and `SUPPORT_OS_QUEUE_READY_URL`. Protection and Connect calls are bounded HTTPS requests and must echo their exact scope, resource, digest, decision, and idempotency bindings. Readiness requires durable-deletion protection capabilities and a SupportOS worker that advertises `erasure.execute`; scoped flags cannot override the global kill switch. The API never receives or returns the plaintext erasure subject. `createPostgresSupportOsApiInput` remains the injectable self-hosted factory. The included managed composition verifies short-lived AuthOS OIDC grants against HTTPS JWKS, checks live AuthOS session status, intersects grant capabilities with current PostgreSQL membership, verifies every membership mutation against the configured Connect decision endpoint, uses scope-bound AES-GCM protected references, and connects to CommunicationOS through an authenticated bridge. In-memory authority and the deprecated HMAC compatibility resolver are never selected implicitly. The managed composition also recognizes a dedicated AuthOS bootstrap grant for `POST /api/support/v1/workspaces/onboard`. It verifies issuer, audience, validity, revocation/session state, and the non-delegable `support.workspace.onboard` capability without performing the impossible pre-creation membership lookup. The PostgreSQL authority then requires an independent scoped flag and a state-bound Connect response before creating the workspace and founding administrator atomically. The portable API is versioned at `/api/support/v1`. Browser hosts exchange an AuthOS session cookie through `POST /api/support/v1/auth/session-exchange`; the managed adapter permits only configured HTTPS origins, requires a CSRF token, forwards no caller authorization header, and authorizes the returned grant against live session and membership state before returning it. Tenant and workspace scope always comes from the authenticated composition, never from request bodies or query parameters. Protected `POST /cases` and `POST /cases/{caseRef}/transitions` operations require bounded idempotency headers; transitions also require an expected revision. Responses carry a correlation ID, and malformed, oversized, unauthorized, stale, conflicting, rate-limited, and degraded requests use stable error envelopes. DecisionGraph lifecycle management is available under `/api/support/v1/decisions` only when both `support.contracts` and `support.decisioning` are enabled. Managed PostgreSQL composition supplies the typed lifecycle authority; authenticated scope is server-derived, mutations use bounded idempotency headers and draft revision fences, and list continuation is bound to a database-issued watermark. When a host injects `workspaceMigrationGovernance`, the PostgreSQL composition also exposes protected workspace-migration preview, get, start, advance, and rollback operations. Managed deployment leaves this authority absent until a real Connect bridge is configured; there is no implicit allow-all decision path. The independent `support.workspace-migration` global/workspace flag is checked at both HTTP and PostgreSQL authority boundaries. `GET /healthz` reports process liveness only. `GET /readyz` and the compatibility `/api/support/v1/health` projection fail closed unless the current PostgreSQL migration and every required worker, queue, feature-flag, and adapter probe are ready. The managed composition reads worker and queue probe URLs from `SUPPORT_OS_WORKER_READY_URL` and `SUPPORT_OS_QUEUE_READY_URL`. Enabling `support.sla-clocks` additionally requires `SUPPORT_OS_SLA_WORKER_READY_URL`; that endpoint must identify itself as the SupportOS worker, report `ready`, and advertise the registered `sla.clock` handler. Internal-note, SLA, and notification worker probes are conjunctive when their lanes are enabled. Every non-liveness request has a bounded deadline (`SUPPORT_OS_REQUEST_DEADLINE_MS`, default 15 seconds). `SIGINT` and `SIGTERM` stop new work, abort in-flight request signals, wait up to `SUPPORT_OS_SHUTDOWN_GRACE_MS` (default 30 seconds), and force-close connections only after the grace period. Uncooperative timed-out work remains counted until it actually settles, so drain status cannot become falsely healthy. Every configured authority origin (`*_ORIGIN`, `SUPPORT_OS_ALLOWED_ORIGINS`) and endpoint URL is checked by one validator (`src/https-origin.ts`) on the raw value: `https://` (or `wss://` for the realtime origin) written out, no whitespace, control characters, backslashes or userinfo (not even a bare `@`), no percent-encoded, numerically rewritten or trailing-dot host, and an explicit port only in 1-65535 (the default port is normalized away). IDN hosts are accepted and compared as punycode. An origin carries no path, query or fragment, not even an empty `?` or `#`; endpoint URLs never carry a fragment. Values the URL parser would silently repair, such as a trailing newline, fail startup. The API starts the shared OpenTelemetry SDK as `supportos-api` (or the bounded operator-supplied `OTEL_SERVICE_NAME`) and exports to `OTEL_EXPORTER_OTLP_ENDPOINT` when configured. A configured collector must be a credential-free HTTPS URL; malformed, plaintext, credential-bearing, query, or fragment endpoints fail startup. Non-liveness request metrics use only method, finite route family, status family, success/failure, and bounded duration. Raw paths, path identifiers, query strings, headers, cookies, grants, case data, messages, answers, contacts, prompts, errors, and secrets are never dimensions. Telemetry failure never changes request authority. Distributed tracing, worker/provider/ AI/SLA signals, dashboards, alerts, retention/residency enforcement, load cardinality, burn-rate gates, and production canaries remain open. The explicitly armed load/soak harness and its privacy boundary are documented in [`docs/load-qualification.md`](./docs/load-qualification.md). It creates a non-overwriting, digest-bound aggregate artifact for the current readiness, case-list, case-detail, and search surfaces. A one-hour or eight-hour local run is not a substitute for governed production evidence, backlog recovery, provider, outbox, export, AI, capacity, or canary qualification. --- ## @lssm-tech/app.supportos-desktop Description: Tauri 2 standalone desktop shell for SupportOS. Path: packages/apps/supportos-desktop URL: /llms/app.supportos-desktop # SupportOS desktop Minimal Tauri 2 shell for the standalone SupportOS operator product. The local bootstrap accepts only an explicitly allowlisted, credential-free HTTPS origin and then navigates to its canonical `/support` surface. No SupportOS grant, case, message, profile, attachment, or offline mutation is persisted by this shell, and only Tauri's default core capability is granted. Required build configuration: - `VITE_SUPPORT_OS_WEB_ORIGIN` - `VITE_SUPPORT_OS_DESKTOP_ALLOWED_ORIGINS` - `SUPPORT_OS_DESKTOP_ALLOWED_NAVIGATION_ORIGINS` at Rust build time, including only the exact SupportOS and AuthOS HTTPS origins needed for sign-in Native notifications, secure updater signing, offline projections, deep links, store notarization/signing, device accessibility, and production canaries remain qualification blockers. --- ## @lssm-tech/app.supportos-web Description: Standalone SupportOS web and PWA operator product. Path: packages/apps/supportos-web URL: /llms/app.supportos-web # SupportOS web Standalone, installable SupportOS operator product. It exchanges the current AuthOS browser session for a short-lived SupportOS-audience grant, keeps that grant in memory, and mounts the shared governed management workspace only after the exchange succeeds. The service worker caches shell assets only. API responses, grants, case data, messages, profiles, attachments, and mutation requests are never cached. The PWA emits the local `supportos:performance` browser event with only a finite metric name (`interaction` or `progressive-load`), bounded duration, and budget verdict. It never includes a URL, route, case, actor, query, body, or grant. Interaction fixture budgets are 100 ms and progressive load is 2.5 seconds. When connectivity returns, retryable sessions and grants within 30 seconds of expiry are refreshed through the existing single-flight AuthOS exchange; signed-out and denied states are never retried automatically. `/support/onboarding` is independently hidden unless both the authority and workspace-onboarding flags are enabled. It requires an AuthOS bootstrap grant with `support.workspace.onboard` and passes only the in-memory authorization header to the governed, atomic isolated-workspace onboarding operation. `/support/settings/company-actions` is independently hidden unless `support.authority` and `support.company-actions` are both enabled. It requires the current browser grant to carry `support.company-actions.read` and `support.company-actions.manage`, renders English/French/Spanish chrome, and submits only opaque plan and revision references. Connect remains the decision authority and Workflow remains the execution and compensation authority. Required production configuration: - `NEXT_PUBLIC_SUPPORT_OS_API_ORIGIN` - `NEXT_PUBLIC_AUTH_OS_ORIGIN` - `NEXT_PUBLIC_AUTH_OS_SIGN_IN_URL` - `SUPPORT_OS_FLAGS` Production promotion still requires an AuthOS relying-party canary, revocation test, browser/assistive-technology journeys, installability, Core Web Vitals, and rollback evidence. --- ## @lssm-tech/app.supportos-worker Description: (none) Path: packages/apps/supportos-worker URL: /llms/app.supportos-worker # SupportOS Worker Deployable, abortable SupportOS background worker. It claims tenant-scoped jobs through fenced leases, dispatches only registered typed handlers, retries with deterministic bounded backoff, and isolates poison work in the dead-letter queue. Set `SUPPORT_OS_WORKER_COMPOSITION_MODULE` to an installed deployment composition in the allowlisted `@lssm-tech/integration.supportos-worker-*` namespace exporting `default: SupportWorkerServiceInput`. SIGINT and SIGTERM stop new claims; in-flight aborted leases are recovered only after lease expiry. The provider-free worker loop, handler contracts, and reusable handler registrations are owned by `@lssm-tech/lib.supportos-worker-runtime`. This app keeps its established exports as compatibility re-exports and owns only the deployable composition loader, configuration, health server, and process lifecycle. Delivery is at-least-once. Every handler receives a stable `effectIdempotencyKey` for downstream effects. Handler execution is aborted before lease expiry; an overrun stays unsettled and is tracked until it drains. While an overrun remains active, the service fails closed and claims no new work. SLA clock deployments compose `createSupportSlaClockRegistration` into the worker. Its pre-claim hook scans every server-assigned workspace, enqueues due clocks idempotently, and registers the only `sla.clock` handler. Deployment composition remains responsible for supplying authorized workspace scopes, PostgreSQL queue/breach authority, the SOP-to-Workflow resolver, Workflow authority, and deployment probes. The executable exposes process liveness at `/healthz` and fail-closed readiness at `/readyz` on `SUPPORT_OS_WORKER_PORT` (default `3002`). Readiness stays unavailable until a queue cycle succeeds, and becomes unavailable on stale heartbeats or active handler overruns. Its projection contains counts and registered job kinds only; tenant, workspace, job, payload, and evidence references are never returned. Notification deployments compose `createSupportNotificationRegistration`. New notification intents create a distinct `notification.deliver` job in the same PostgreSQL transaction as their immutable evidence. The handler loads only a body-free dispatch projection, sends the stable effect-idempotency key to the CommunicationOS channel authority, and records verified settlement evidence before completing the lease. Terminal evidence is replayed after a worker crash without redelivery. Deployment composition, feature gates, provider credentials, and historical queued-intent backfill remain required before rollout. Case-lifecycle deployments compose `createSupportCaseUnsnoozeRegistration`. The handler accepts only service-scoped `case.unsnooze` leases with `support.jobs.execute`, forwards the durable effect identity unchanged, and settles only after the PostgreSQL authority has rechecked the case revision, snoozed state, resume status, and database-clock deadline under the case lock. Exact retries replay the immutable receipt; obsolete work terminates without mutating the case. Enabling `support.case-lifecycle` requires worker and queue readiness, and the worker probe must advertise `case.unsnooze`. Erasure deployments compose `createSupportErasureHandler`. The handler starts one pinned Workflow revision, records terminal evidence from SupportOS, CommunicationOS, Forms, Knowledge, and CompanyOS, and completes only after the PostgreSQL authority rechecks live worker membership, legal holds, and the exact Connect decision under the case lock. Downstream effects use identities derived from the immutable erasure plan rather than the ambiguous delivery attempt. Deployment composition must supply the PostgreSQL execution authority, owner adapters through Workflow, durable-deletion protection, authorized scopes, and readiness probes before registering `erasure.execute`. Retention deployments compose `createSupportRetentionRegistration`. Its rotating pre-claim scan gives every assigned workspace a bounded share, while PostgreSQL fixes one daily database-time watermark and advances an ordered keyset cursor. Only closed-case subject values and closed-case event payloads owned by SupportOS are candidates; messages, Forms answers, Knowledge content, attachments, and provider data never enter this executor. Queue payloads contain only opaque work references. The handler rechecks its active fencing token, current policy and case revision, live global-plus-scoped rollout, and active legal holds under the case lock, then passes the exact worker, lease generation, deadline, and stable effect key to durable-deletion protection. Per-scope scan failures are reported without stopping unrelated tenant scheduling. Immutable dispositions make crash replay exact. Enabling retention must also set `retention.enforce` as a required handler kind, which the registration does by default, so readiness fails closed if deployment composition drops the handler. Audited export deployments compose `createSupportExportRegistration` with the PostgreSQL execution authority and a protected object-store adapter. The handler reads immutable snapshot rows through bounded keyset pages, streams formula-safe BOM-prefixed UTF-8 CSV without buffering the result set, passes one stable effect identity to artifact storage, and completes only after the exact current durable job lease is revalidated and the store digest/byte count match the hash computed over the emitted stream. Permanent generation defects transition the domain export to a failed outcome with an exact event receipt instead of leaving it running. `export.generate` is a required handler kind. Artifact retrieval, expiry deletion, retry-exhaustion/cancellation orphan cleanup, and production object-store soak remain explicit deployment blockers. SLO automation deployments compose `createSupportSloQualificationRegistration` and `createSupportSloIncidentEventPublishRegistration`. Qualification plans are content-addressed and authorized before enqueue; the worker asserts the exact database-clock lease before protected plan access, records immutable assessment and incident evidence, reserves paging with a server-minted fence, and publishes typed semantic events through a separate durable job. Both `qualification.evaluate` and `qualification.event.publish` are required handler kinds. The managed composition supplies live AuthOS scope refresh, exact global- and-scoped rollout receipts, scoped lookup-HMAC, short-lived provider grants, bounded dependency readiness, and handler-kind-isolated queue claims. --- ## @lssm-tech/app.tafio-web Description: Thin career host (D-112a, D-122 H layer): serves every career brand composition by hostname through resolveBrandHost; no reusable screens. Path: packages/apps/tafio-web URL: /llms/app.tafio-web # @lssm-tech/app.tafio-web Private, thin career host (D-112a, D-122 H layer, D-123, TAFIO-APP-00). One Next.js app serves every career brand composition (Tafio and the public career brands) by hostname. - Hostnames resolve to a career application in the D117-COMP-01 `BrandHostResolution` shape (`@lssm-tech/lib.contracts-library/app-config/brand-composition`): canonical origins serve, aliases answer 308, unknown hosts fail closed. Registry-derived bindings stand in until real compositions exist (`indexBrandHosts`/`resolveBrandHost`). - Screens come from the experience bundles (`bundle.job-application`) selected by the brand composition; this app holds no reusable screens, writers, stores or migrations. - Sessions are host-only per brand host over one shared identity and profile; a composition grants no authority. ## Host binding (BRAND-01d) - `src/proxy.ts` resolves the `host` request header only (never `X-Forwarded-Host`, query hints or cookies) through `src/host/`. The served set is derived from the registries: lssm-os career product facts that compose `job-application` and are not `exploring`/`retired`, joined by the `app_` convention to exactly one AuthOS application and one origin route. No brand or hostname is listed in this package. - Canonical hosts are each route's `marketingOrigin` (role `marketing`) and `appOrigin` (role `app`). Redirects come only from `listAuthOsEcosystemOriginRedirects`: 308 to the registry origin with the request path and query kept verbatim, for GET/HEAD outside `/api`. - Workspace paths (BRAND-01f): on a marketing-role host (canonical `www`, apex, alternate apex/`www`), GET/HEAD requests whose path matches the route's registry `appPathPrefixes` (segment boundary, case-sensitive, undecoded, never `/api`) answer 308 to the route's `appOrigin` with path and query verbatim, in one hop from aliases. Rules come only from `listAuthOsEcosystemAppPathRules`; a rule whose target is not a canonical app host fails at boot (`app-path-target-not-canonical`). App hosts never path-redirect. Alias refusal precedence is unchanged (`alias-method`, then `alias-api`). - Unknown hosts, conflicting hosts, non-GET/HEAD and `/api/*` on alias hosts answer 421 with an empty body and `Cache-Control: no-store`. An invalid registry fails at module load with `CareerHostRegistryError`. - `.localhost` serves the app role outside production only; plain `localhost` is always unknown. - The trusted-context headers (`TRUSTED_CONTEXT_HEADER_NAMES`) are stripped from every request and set only from the hostname resolution. They are presentation-only and never admission, session or authorization input. ## Native authenticated delivery candidate The host now mounts the native RP browser catch-all, registered OIDC callback, login start and the server-rendered workspace home route. Shared must admit the server dependencies and reviewed client/resource/DB configuration before this lane can be enabled. This source does not enable draft catalog registrations. `src/auth/runtime.ts` resolves the canonical request host through the existing registry, selects one server-configured native RP, and creates Better Auth with its own PostgreSQL-backed session/account custody. It disables implicit email linking and password login, keeps cookie caching off, and encrypts native OAuth access/refresh tokens. The browser routes withhold token/account-info APIs; server code calls the native session/account/token APIs directly. `src/auth/current-principal.ts` calls the authenticated central `auth.productSession.resolve` operation through the integration-owned transport. The product server authenticates with its registered confidential client; the user access token travels in a separate header. Central cookies, local RP user ids and emails never become central identity. The exact RP account pairwise subject must match the fresh central response. Protected server consumers use `principalRef` as the actor and re-read before each stage. The workspace home currently renders the shared session boundary. Successful identity without the owner-approved governed processor binding is explicitly `candidate_binding_unavailable`; no candidate feature panels or consent are inferred from login. The canonical principal and all tokens remain server-only. `CAREER_RP_BINDINGS` is server-secret JSON configuration: one reviewed row per configured application with `productApplicationId`, exact registered `clientId`, `clientSecret`, `authSecret`, `databaseUrl`, `audience`, `securityReviewRef`. The database must already have its native Better Auth schema through the owner migration workflow; the runtime never migrates or seeds it. The login of `databaseUrl` must be the dedicated least-privilege role of `deploy/career-relying-party` (`career_rp_runtime`: DML on the four native tables of that one database). The host checks the login role before the first connection is used (`careerLeastPrivilegePgPoolV1`, `src/server/pg-pool.ts`) and never serves a query for a superuser, a role with `BYPASSRLS`, `CREATEROLE`, `CREATEDB` or `REPLICATION`, a member of another role or an owner of relations: sign-in then answers `503` and the workspace is unavailable. The same check guards the public job inventory reader. Missing configuration or a production-disabled registration remains unavailable. No build/deploy or provider/client/resource mutation is performed by this code. A signed-in identity that is not admitted to the application (not invited, invitation not accepted, another identity) sees the session boundary, not a sign-in loop. The identity authority gives any verified identity a code, so a completed sign-in can still yield no central principal. The workspace route starts a sign-in only when the request has no relying-party session, or one older than the settle window (an expired access token); a session that a sign-in created moments ago and that still has no principal is refused (`decideCareerWorkspaceAdmissionV1`, `src/auth/workspace-admission.ts`). ## Production packaging (D-220) - `vercel.json` follows the peer prebuilt hosts: Git deployments disabled, Next.js, Bun 1.4.2, frozen workspace install, `bun run build`. Delivery goes only through `scripts/delivery/vercel-stage` from a qualified local SHA. - `GET`/`HEAD /` on a canonical app host answers `307` to the registry session boundary (path-only `Location`, query kept); marketing roots are unchanged. - Every proxy response carries `nosniff`, `X-Frame-Options: DENY` and `strict-origin-when-cross-origin` (`src/host/security-headers.ts`, kept equal to `next.config.mjs` by test). - `release/env-matrix.ts` lists every environment variable name (never values); its test fails when the host or a direct workspace dependency starts or stops reading one. - `bun run smoke:release -- --mode local|deployment|production --origin ` runs the release packet S1-S8 read-only checks. It refuses every origin that is not the Tafio app origin, an immutable `tafio-web-*.vercel.app` URL or a loopback `next start`. In every mode a workspace request without cookies is redirected by the host proxy to the sign-in page (S5, `307` to `/connexion?return=%2F`, BC6.6). In `production` mode the host must also have a working sign-in: the sign-in start redirects to the identity authority (S5b). A host that still renders the session boundary, or whose start answers `503`, fails. S5b begins one sign-in and abandons it (one short-lived state record, no personal data); the report keeps only the origin and path of that redirect. - `bun run probe:pg -- --url-from [--rp-bindings-from ]` opens the `pg` databases of the host (the relying-party database of `CAREER_RP_BINDINGS` and `CAREER_JOB_INVENTORY_DATABASE_URL`), each read by name from a private custody file, through the host's own pool factory (`src/server/pg-pool.ts`, login-role check included) and runs `select 1`. Run it before a domain move: with `pg` 8, `sslmode=require` alone is full certificate verification, which `psql` does not show. A superuser or otherwise privileged login fails the probe (`CAREER_PG_ROLE_…`), and so does a login that can connect to another application database of the same server (`CAREER_PG_ROLE_FOREIGN_DATABASE`). The report holds names, the TLS form and an error code, never a host, a credential or a message. - `bun run custody:env -- get|digest|names [NAME...]` reads a private (`0600`) `NAME=value` custody file without shell evaluation, so a JSON or URL value reaches a CLI on stdin byte-exact. `get` refuses a terminal. --- ## @lssm-tech/app.taketide-web Description: Thin public Taketide host over the reviewed bilingual product composition. Path: packages/apps/taketide-web URL: /llms/app.taketide-web # Taketide public web The first ContractSpec Taketide host serves the reviewed French and English overview through the Taketide bundle. The visible workspace-unavailable notice describes the current release. Set `TAKETIDE_PUBLIC_ENV` explicitly to `staging` or `production`. The trusted runtime `VERCEL_URL`, when supplied, identifies one exact immutable deployment. Staging accepts `taketide-staging.vercel.app`; production accepts `taketide.app`. Explicit `local` mode accepts only loopback with no hosted runtime binding and supports local built-server qualification. The proxy guards every path, including build assets. Only GET and HEAD reach the two locale roots, robots, the three reviewed brand files and safe framework static assets. Root negotiation defaults to French and preserves the query. Unknown hosts and routes return a terminal response before page rendering. Shared Foundations runs the sealed build, browser and hosted checks through the central resource queue. Both targets require a verified project/root/runtime binding and exact artifact evidence. --- ## @lssm-tech/app.teams-mcp Description: MCP server exposing governed Microsoft Teams collaboration operations. Path: packages/apps/teams-mcp URL: /llms/app.teams-mcp # Teams MCP Thin ContractSpec MCP package for Microsoft Teams surfaces. This scaffold registers the canonical Teams MCP tool catalog and leaves execution as fail-loud pending handlers until the provider-backed integration is wired. --- ## @lssm-tech/app.tellshift-site Description: Thin public Tellshift website host (www.tellshift.com) for the bundle.tellshift-studio public site (D-100). Path: packages/apps/tellshift-site URL: /llms/app.tellshift-site # @lssm-tech/app.tellshift-site Private, thin public Tellshift website host for `www.tellshift.com` (WEB-01, D-100). It hosts the public site of `@lssm-tech/bundle.tellshift-studio` and declares `@lssm-tech/module.auth-os` for its hosting slice. It is distinct from `@lssm-tech/app.tellshift-web`, the Tellshift product host. Skeleton only (WEB-01-INT0): a root layout, no routes, no build script and no runtime yet. --- ## @lssm-tech/app.tellshift-web Description: Thin Tellshift product host for the Tellshift Studio bundle and the converged growth bundles, with AuthOS admission. Path: packages/apps/tellshift-web URL: /llms/app.tellshift-web # @lssm-tech/app.tellshift-web Thin Tellshift product host (D-091): it hosts `@lssm-tech/bundle.tellshift-studio` and the converged growth bundles behind AuthOS admission. Routes, server composition, the owner migrator order and the single-database-per-deployment startup check land in TS-01-HOST; the AuthOS registration lands in TS-01-INT3P. Skeleton only (TS-01-INT0): no routes, no build and no runtime yet. --- ## @lssm-tech/app.video-studio Description: (none) Path: packages/apps/video-studio URL: /llms/app.video-studio # @lssm-tech/app.video-studio **Thin Remotion Studio wrapper. Re-exports the Remotion entry point from `@lssm-tech/lib.video-gen`.** ## What It Does - **Layer**: app (Remotion Studio) - **Consumers**: internal — video preview and rendering ## Running Locally From `packages/apps/video-studio`: - `bun run dev` - `bun run build` ## Usage ```bash bun run dev ``` ## Local Commands - `bun run dev` — bunx remotionb studio src/index.ts - `bun run build` — echo 'No build step needed for Remotion Studio' - `bun run clean` — rimraf out .turbo - `bun run test` — standalone host test: imports the Remotion entry and lists its compositions through Remotion's composition manager in happy-dom (no frame render) - `bun run render` — bunx remotionb render src/index.ts - `bun run render:all` — bunx remotionb render src/index.ts ApiOverview out/api-overview.mp4 && bunx remotionb render src/index.ts SocialClip out/social-clip.mp4 && bunx remotionb render src/index.ts SocialClipSquare out/social-clip-square.mp4 && bunx remotionb render src/index.ts SocialClipPortrait out/social-clip-portrait.mp4 && bunx remotionb render src/index.ts TerminalDemo out/terminal-demo.mp4 ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - Improve agentpacks - Switch Remotion CLI to bunx remotionb for Bun runtime support ## CompanyOS film workflow Three ordered authoring-time scripts produce a locale-matched render for the "Room for the real work" campaign: 1. **`bun run companyos:narrate`** — synthesizes narration through ElevenLabs once per content-hash and caches audio under `public/companyos/narration/`. Writes a `manifest.json` recording each take's locale, key, text, hash, duration, and voice cast. `ELEVENLABS_API_KEY` is required only for lines not yet cached; cached lines are replayed for free. **Narration is generated once at authoring time. Never call this at build time or page load.** 2. **`bun run companyos:mix`** — reads the narration manifest, builds each locale's final WAV mix (narration + procedural sound design + music bed with ducking), normalizes loudness, and writes render props to `public/companyos/mix/owners-first-article-{locale}.props.json`. The props JSON carries the audio path and the computed `OwnersFirstArticleTimeline` derived from measured narration durations. 3. **`bun run companyos:render [locale…]`** — renders `CompanyOsOwnersFirstArticle-{locale}` via `bunx remotionb` for each requested locale (all three if none specified), reading props from the mix output. Outputs go to `out/companyos/`. Run the scripts in order: narrate → mix → render. The mix script depends on the narration manifest; the render script depends on the mix props. Voice casting is recorded in `scripts/companyos/narrate.ts` (`VOICE` constant). Change the `voiceId` there to recast; the hash changes and the new lines are synthesized on the next narrate run. ## Notes - Do NOT add compositions here. All compositions live in `@lssm-tech/lib.video-gen`. - This package exists solely to provide a Remotion Studio entry point and authoring-time scripts. - Uses `remotionb` CLI for Bun runtime support. Known caveat: SSR scripts may not auto-quit (see [Remotion Bun docs](https://www.remotion.dev/docs/bun)). - Narration is generated once at authoring time from cached content hashes. Never call `companyos:narrate` at build or page load. `ELEVENLABS_API_KEY` is only required for uncached lines. --- ## @lssm-tech/app.web-application-monolith Description: (none) Path: packages/apps/web-application-monolith URL: /llms/app.web-application-monolith # Managed CompanyOS Web Application Monolith Real Next.js App Router web entrypoint for Managed CompanyOS, the invite-led AI operating system for companies built on the ContractSpec substrate. It renders the public `/companyos` managed landing plus an authenticated cockpit whose organization and workspace scope comes from verified session authority: onboarding, admin, AuthOS, integration hub, operating graph, composite workflow, replay, evidence, lifecycle, knowledge, team, analytics, finance, special ops, and degraded-state navigation. The public login route discovers enabled AuthOS methods from the API and renders email/password, email OTP, email magic link, and the enabled social providers without exposing provider credentials. Supported provider IDs cover Apple, Discord, Facebook, GitHub, Railway, Google, Linear, LinkedIn, Microsoft, Notion, PayPal, Reddit, Slack, TikTok, Twitter/X, and Vercel; each requires its own live server configuration and production callback qualification. The authenticated AuthOS account page supports explicit social account linking and unlinking. Authentication-audit listing and bounded CSV export stay same-origin in the browser. The web BFF forwards only the HttpOnly session cookie and allowlisted filters to the API; tenant and actor authority remain server-derived. `/companyos/auth/mfa` is both the session-bound second-factor challenge and the authenticated MFA management surface. Credential accounts confirm their current password before setup or disablement. Setup returns an authenticator URI, verifies the first six-digit code, and reveals recovery codes only after success. Sign-in can use either TOTP or a single-use recovery code without client-supplied tenant or challenge authority. The security page reads the server-owned `twoFactorEnabled` state rather than a fixture flag. The app stays thin by composing `@lssm-tech/bundle.managed-companyos` and design-system primitives. Provider decisions remain approval-gated. Credential values are never displayed — only redacted references (`'********'`) appear, enforced by `assertRedactedSecretDisplay` in the bundle. ## Embedded CommunicationOS The embedded CommunicationOS pages clear deterministic preview data before rendering live mode. Their scoped same-origin typed client loads the selected room plus persisted contacts, governed work, and journal evidence. Authorized action, handoff, and identity decisions use canonical idempotent APIs and then reconcile the live projection; denied or failed mutations never update a fixture-backed success state. The legacy `/companyos/inbox`, `/threads`, `/actions`, `/handoffs`, `/contacts`, and `/compose` entry points are compatibility redirects into that authenticated route family. Thread-detail redirects preserve the opaque room identifier. No legacy collaboration URL renders static demo-tenant data. `/companyos/communication-os/agents` is the persisted managed-agent registry. Authorized organization managers propose, activate, reject, and revoke agent records through the same tenant-scoped governed-work journal. Non-manager creation and lifecycle writes are denied by the API, and the UI remains read-only. Legacy `/companyos/agents/**` pages redirect to the corresponding live agent, action, governance, handoff, audit, or compose surface. ## Public booking browser posture The public booking route keeps availability custody same-origin and renders explicit unavailable/degraded states. Time choices expose DST-disambiguating labels, and operator repair controls retain a 44px minimum touch target. Browser tests exercise these repository-owned contracts without live provider writes. The dynamic Server Component reads the declared adapter posture at request time. Unset, invalid, or sandbox-only posture is projected as degraded availability with no selectable slots; only `adapter_ready` enables the interactive lifecycle client. Current screenshot baselines, deployed-domain journeys, and tenant activation remain external proof gates; local or detached-worktree screenshots are not production-readiness evidence. The protected OPA Booking hub proxies per-link embed-origin changes only after same-origin validation and current-session resolution. Owners can replace an active link's full exact-HTTPS allowlist under optimistic revision control; saving an empty list disables widget code without changing the hosted URL. The protected `/companyos/admin/google-calendar` journey is enterprise-admin only. It loads selectable calendar identifiers from the authenticated API, never offers a free-text provider identifier, and persists explicit Europe/Paris working hours, buffers, notice, horizon, and approval mode through the same-origin server action. It does not run OAuth or provider writes. The protected public-profile editor previews the exact persisted revision through `GET /api/v2/opa/profile/preview?revision=`. The no-store BFF derives tenant authority from the current session and strips tenant, profile, link, event-type, scheduling-resource, and connection refs before the browser renders desktop and mobile candidates. The editor page uses the same server-authoritative Better Auth subject as protected mutations. It derives an opaque authority fingerprint, keys the client subtree with that value, and requires every initialize/save/publish/revoke command to echo it. A stale tab or pre-switch draft receives `409 profile_context_changed` with `no-store` before the destination profile is read or written; no raw authority value is rendered. The protected `/companyos/opa-os` page reads request-time planning-store and active-workspace Google Calendar readiness through a no-store BFF. It renders runtime failures as unavailable/error rather than as ordinary setup gaps. Daily-operation and briefing-preference BFF mutations validate the browser's exact configured web origin before resolving a session or synthesizing the trusted upstream origin. Missing, sibling, suffix-confused, and hostile origins receive a no-store `403` and never reach the API host. Authorized enterprise admins, founder approvers, and operations managers can submit authority-free meeting intent and receive a durable agenda, availability-aware proposed times, and a redacted pending-approval receipt. The responsive en/fr/es UI labels cached or unavailable calendar data and states explicitly that preparation created no calendar event or Google Meet link. A validated route-selected `meetingRef` binds the written-first surface to live OPA state; the API re-proves the current session and tenant instead of treating route state as authority. Enterprise admins and founder approvers can then approve, deny, cancel, or reschedule through same-origin CSRF-protected BFF routes. Operations managers can prepare and manually refresh status but do not see lifecycle mutation controls. Pending provider work is refreshed only by an explicit user action; the page does not poll automatically. A confirmed Google Meet link is rendered only from authenticated canonical booking status. See [`docs/runbooks/opa-smart-meeting.md`](../../../docs/runbooks/opa-smart-meeting.md). Production uses persisted membership for the live `lssm` and `companyos` organizations plus the owner's personal context. The `ndconsulting` and `hirly` organizations were decommissioned on 2026-10-20 ([evidence](../../../docs/evidence/authos/decommission-hirly-ndconsulting-2026-10-20.md)), so the context switcher offers only Personal, LSSM, and CompanyOS. NDconsulting's Special Ops history and physical tenant/workspace identity stay reserved for local/reference fixtures; sibling organizations cannot enumerate it. This README does not claim that domains, data authority, support ownership, or a release has been activated. The authenticated shell maps the server-resolved physical tenant to the contract-owned LSSM or CompanyOS brand (the ND Consulting brand mapping is retained for local/reference fixtures only). That mapping changes visible labels, breadcrumbs, command headings, graph workspace labels, and the shell title without changing fixture ids, navigation evidence, or provider authority. Personal, future, and unknown tenants render the neutral `CompanyOS workspace` identity rather than a fictive ContractSpec company. Behavior signals use the authenticated tenant subject and a fresh correlation id; they no longer attribute production entry events to a shared demo tenant. ## Special Ops production cutover Use [`docs/runbooks/special-ops-monolith-production.md`](../../../docs/runbooks/special-ops-monolith-production.md) for the database-first Special Ops, AI Ops Sprint, and all-in-one work-graph promotion gates. The web app remains a thin shell: render production-owned bundle/API projections, preserve redaction and AI-dispatch blocks, and do not import `examples/*` at runtime. ## Managed CompanyOS production path Use [`docs/runbooks/managed-companyos.md`](../../../docs/runbooks/managed-companyos.md) as the cross-lane production-path evidence ledger for DB lifecycle, auth/session runtime, route conversion, UX richness, Special Ops, bundle boundary, and docs/contract gates. This README documents the current web surface; it is not a release gate for any DB-backed route. Current route status: - Most deterministic reference pages remain `force-static`; integration, onboarding, root, evidence, and other session/persona-sensitive route sections document `force-dynamic` where implemented. - DB-backed route promotion requires local/test migrate + seed + verify output, not static workspace builders alone. - Auth/session promotion requires unauthenticated denial, authenticated access, role-gate, session revoke, auditor read-only, and tenant-mismatch evidence. - Special Ops promotion requires database-first capability graph/workspace/seed-run receipt evidence or an explicit known-gap note in the evidence packet. - Replay and evidence routes remain read-only; adding mutation affordances there is a breaking contract change. Do not hide mock/reference data behind production wording. If a page still reads deterministic bundle projections, call it deterministic/reference in release notes and attach the follow-up lane rather than claiming runtime persistence. ## Personal, company, team, and workspace switching The authenticated shell consumes `GET /api/companyos/contexts`, a fresh server-owned projection of the user's personal context and current company, team, and workspace memberships. The browser receives only opaque references and a signed five-minute one-use authority token. It never receives or submits a physical tenant identifier. - An empty account can call the idempotent personal-context ensure route and enter a private, non-shareable workspace without joining a company. The authenticated layout renders this narrow bootstrap before tenant authority exists and does not render protected CompanyOS children until the server confirms the new context. - Joining LSSM, CompanyOS, or another company adds a context; it does not move or merge personal data. - Company, team, and workspace changes use one atomic `POST /api/companyos/contexts/set-active` command. The selector disables duplicate input, awaits the committed projection, invalidates previous/next cache namespaces, and renders only the confirmed destination. - First authenticated load selects a deterministic authorized context and its default workspace when the session has no active selection. Organization and team changes carry their default workspace in the same authority mutation, so protected routes never render against a half-selected session. - Team scope can only narrow authority. The next protected API request freshly intersects organization, team, and workspace capabilities and fails closed if membership or a canonical grant was revoked. - The grouped picker includes an explicit company-scope choice. Clearing team scope is an authoritative transition and never relies on a local-only UI reset; the compact trigger omits redundant `Company-wide` copy. - Browser transport uses `credentials: include` and `cache: no-store`; hostile Origins, malformed projections, inconsistent active refs, expired tokens, and raw provider error details are rejected. - One shell-owned context trigger opens the grouped organization, team, and workspace picker. Search appears above eight destinations. Its account-wide `topbar` (default) or `sidebar-footer` placement is hydrated on the server; the footer remains an icon trigger when collapsed and is repeated in the mobile navigation dialog. All forms retain 44px targets and accessible names. - The account menu owns explicit `View as`, language, and preference radio submenus. Persona preview is server-confirmed, session-scoped, disclosed by a banner, and intersects the preview projection with the real subject so it can narrow presentation/actions but never widen authorization. - Existing organization list/set-active and workspace-list routes remain compatibility surfaces. Retained ND design-partner route names remain isolated under `ndconsulting`. The browser transport and cache lifecycle have repository-local tests, but this README does not claim that a live production deployment, migration, visual baseline approval, or organization cutover is clear. Follow [`docs/runbooks/real-organizations-rollout.md`](../../../docs/runbooks/real-organizations-rollout.md) for the separately gated migration and operator evidence. G006 real-route regression evidence is configured in `playwright.g006.config.ts`. It starts the actual Next routes with a deterministic synthetic API seam, writes only to `.playwright-output/g006`, and compares committed 320/375/768/1280px en/fr/es light/dark public and admin baselines without snapshot updates. The three-test run also checks axe serious/critical findings, responsive overflow, 44px target height, arbitrary public handles, non-enumerating absence, and browser-visible private-reference exclusion. The older component harness is supplemental evidence only and is not separately configured as a Playwright project. ## CompanyOS marketing contract boundary The `(marketing)` route group is wrapped with the shared marketing contract boundary and backed by the full CompanyOS route contract registry from `@lssm-tech/bundle.marketing/content`. The seven PRD CompanyOS pages remain adapter-rendered; bespoke marketing pages stay copy-owned by their existing components while being contract-addressable through the inert boundary. Public legal/trust pages (`/mentions-legales`, `/privacy`, `/terms`, `/cookies`, `/security`) are part of this unauthenticated marketing surface and must stay aligned with the blueprint, sitemap, robots/LLMO artifacts, footer links, and static `public/llms.txt` fallback. SEO discovery is always on. `/sitemap.xml` is an XML index, `/sitemaps/static.xml` contains the exact 24 indexable blueprint routes, and profile shards live below `/sitemaps/profiles//.xml`. Unavailable or stale profile discovery deliberately returns a valid static-only index with `X-Sitemap-Status: degraded`, `no-store`, and `Retry-After: 60`; directly unavailable profile shards return `503`. Configure only server-side `API_ORIGIN` in the web deployment. See the [SEO discovery runbook](../../../docs/runbooks/companyos-seo-discovery.md). ## Route inventory ### Persona home pages (Phase 2 boil-lake) | Route | File | Persona | Purpose | |---|---|---|---| | `/companyos/founder` | `src/app/companyos/founder/page.tsx` | `founder_approver` | Mission intelligence, pending approvals, evidence readiness, governance alerts | | `/companyos/ops` | `src/app/companyos/ops/page.tsx` | `operations_manager` | Operational dashboards, workflow status, team assignments, performance metrics | | `/companyos/frontline` | `src/app/companyos/frontline/page.tsx` | `frontline_staff` | Task queue, shift information, training resources, quick-access tools | | `/companyos/auditor` | `src/app/companyos/auditor/page.tsx` | `auditor` | Audit findings, compliance status, risk assessments, evidence trails (read-only) | | `/companyos/admin` | `src/app/companyos/admin/page.tsx` | `enterprise_admin` | System configuration, user management, integration hub, workspace settings | ### Core feature routes | Route | File | Purpose | |---|---|---| | `/` | `src/app/page.tsx` | Cockpit landing; persona dispatcher; bundle proof + governance report | | `/companyos` | `src/app/companyos/page.tsx` | Public managed landing; renders bundle-owned Managed CompanyOS view-model/template with deterministic reference posture | | `/companyos/onboarding` | `src/app/companyos/onboarding/page.tsx` | Authenticated 3-step role, working-style, and display-preference setup; completion waits for durable tenant-scoped persistence | | `/companyos/admin/public-comms` | `src/app/companyos/admin/public-comms/page.tsx` | Force-dynamic persisted profile editor with same-origin authenticated mutations and optimistic revision recovery | | `/u/[handle]` | `src/app/u/[handle]/page.tsx` | Force-dynamic arbitrary published profile; unknown, draft, and revoked handles share the same non-enumerating 404 | | `/companyos/integrations` | `src/app/companyos/integrations/page.tsx` | Force-dynamic Integration Hub catalog using bundle view-models/templates and per-request role morph resolution | | `/companyos/integrations/connections` | `src/app/companyos/integrations/connections/page.tsx` | Force-dynamic global connections view with redacted credential references | | `/companyos/integrations/syncs` | `src/app/companyos/integrations/syncs/page.tsx` | Force-dynamic sync health/config view with redacted credential references | | `/companyos/integrations/runtime` | `src/app/companyos/integrations/runtime/page.tsx` | Force-dynamic deployment topology passport; separates semantic validation from provider receipt evidence | | `/companyos/integrations/[integrationId]` | `src/app/companyos/integrations/[integrationId]/page.tsx` | Force-dynamic integration detail overview with role-gated actions | | `/companyos/integrations/[integrationId]/credentials` | `src/app/companyos/integrations/[integrationId]/credentials/page.tsx` | Force-dynamic security-class credentials tab; never statically render | | `/companyos/integrations/[integrationId]/secrets` | `src/app/companyos/integrations/[integrationId]/secrets/page.tsx` | Force-dynamic security-class secrets tab; never statically render | | `/companyos/integrations/[integrationId]/config` | `src/app/companyos/integrations/[integrationId]/config/page.tsx` | Force-dynamic integration configuration tab | | `/companyos/integrations/[integrationId]/audit` | `src/app/companyos/integrations/[integrationId]/audit/page.tsx` | Force-dynamic integration audit tab | | `/companyos/opa-os` | `src/app/companyos/opa-os/page.tsx` | Force-dynamic Organization Planning surface; reads tenant-scoped store/Google readiness through the authenticated BFF, renders the bundle-owned responsive smart-meeting prepare/approval/status/cancel/reschedule flow with role-accurate controls and manual refresh, and emits `surface_viewed` / `role_morph_resolved` with server-only tenant hashing | | `/companyos/nav-map` | `src/app/companyos/nav-map/page.tsx` | Power-user navigation topology; renders all nav surfaces + edges as interactive DAG; capability-gated | | `/companyos/workflow/[runId]` | `src/app/companyos/workflow/[runId]/page.tsx` | Composite workflow run; graph nodes + steps; approval/deny affordances role-gated; AI-dispatch blocked | | `/companyos/replay/[runId]` | `src/app/companyos/replay/[runId]/page.tsx` | Deterministic replay viewer; events ordered by sequence; **read-only** — no approve/deny/request affordances | | `/companyos/evidence/[runId]` | `src/app/companyos/evidence/[runId]/page.tsx` | Auditor-safe evidence receipt; metadata counts, verification hash, redaction summary | | `/companyos/auth` | `src/app/companyos/auth/page.tsx` | In-app account surface: active sessions (skeleton, retryable error, empty state, sibling-session revoke), sign-out and linked accounts | | `/companyos/auth/sessions` | `src/app/companyos/auth/sessions/page.tsx` | Compatibility alias; redirects to `/companyos/auth` | | `/companyos/auth/security` | `src/app/companyos/auth/security/page.tsx` | Force-dynamic security settings: server-resolved contact + MFA status, active sessions with loading/error/empty states, user-agent device labels (browser + OS); location is shown only when known | | `/companyos/auth/passkeys` | `src/app/companyos/auth/passkeys/page.tsx` | Force-dynamic authenticated WebAuthn passkey enrollment backed by `@better-auth/passkey` and persisted credential metadata | | `/companyos/auth/invitations` | `src/app/companyos/auth/invitations/page.tsx` | Force-dynamic persisted organization invitation administration with list, send, token-rotating resend, and terminal revoke actions | | `/companyos/auth/audit` | `src/app/companyos/auth/audit/page.tsx` | Read-only AuthOS audit projection | | `/companyos/auth/locked` | `src/app/companyos/auth/locked/page.tsx` | Public-safe account lockout recovery; no tenant or actor projection, with keyboard-safe password-reset and sign-in actions | | `/companyos/lifecycle` | `src/app/companyos/lifecycle/page.tsx` | Lifecycle stages and milestone visibility with role redaction | | `/companyos/knowledge` | `src/app/companyos/knowledge/page.tsx` | Canonical force-dynamic Company Intelligence overview backed by the authenticated tenant-free surface descriptor | | `/companyos/knowledge/sources` | `src/app/companyos/knowledge/sources/page.tsx` | Authenticated source connections/jobs read surface | | `/companyos/brain` | `src/app/companyos/brain/page.tsx` | Authenticated Brain projection | | `/companyos/knowledge/graph` | `src/app/companyos/knowledge/graph/page.tsx` | Authenticated graph capability surface; queries remain user-triggered | | `/companyos/knowledge/assistant` | `src/app/companyos/knowledge/assistant/page.tsx` | Authenticated grounded-answer capability surface; model calls remain user-triggered | | `/companyos/knowledge/learning` | `src/app/companyos/knowledge/learning/page.tsx` | Authenticated evidence and learning-health read surface | | `/companyos/knowledge/operations` | `src/app/companyos/knowledge/operations/page.tsx` | Authenticated operational-health read surface | | `/companyos/company-intelligence`, `/companyos/graph` | compatibility redirects | Redirect to the canonical knowledge overview and graph routes | | `/companyos/team` | `src/app/companyos/team/page.tsx` | Team directory and assignment visibility with contact redaction | | `/companyos/analytics` | `src/app/companyos/analytics/page.tsx` | Operational analytics; blocked roles receive empty denied view models | | `/companyos/finance` | `src/app/companyos/finance/page.tsx` | Finance queues with amount redaction and founder-only approval affordances | | `/companyos/special-ops` | `src/app/companyos/special-ops/page.tsx` | Incident and escalation cockpit; blocked roles receive empty denied view models | | `/companyos/special-ops/design-partner-readiness` | `src/app/companyos/special-ops/design-partner-readiness/page.tsx` | Force-dynamic thin shell over the persisted API projection when activated; the fictive packet remains test/demo only. | | `/error` | `src/app/error.tsx` | Global error boundary (Client Component); renders `stateCopy.error` with "Try again" | | `/loading` | `src/app/loading.tsx` | Global loading state; renders `stateCopy.loading` with `role="status"` | | `/not-found` | `src/app/not-found.tsx` | Global 404 page; renders `stateCopy.empty` with home link | Public auth flows have one canonical route each. The proxy redirects signed-out visitors to `/login`, Better Auth emails link to `/reset?token=…` and `/accept-invite`, and the AuthOS adapter requests resets with `redirectTo: '/reset'`, so the `src/app/(auth)/**` tree is canonical. The legacy `/companyos/auth/*` duplicates are server redirects (`src/routing/companyos-auth-aliases.ts`, covered by `companyos-auth-aliases.test.ts`) that forward only a same-origin `redirect` path and the reset `token`: | Legacy alias | Canonical route | | --- | --- | | `/companyos/auth/sign-in?redirect=` | `/login?redirect=` | | `/companyos/auth/magic-link?redirect=` | `/magic-link?redirect=` | | `/companyos/auth/forgot-password` | `/reset` | | `/companyos/auth/reset-password?token=` | `/reset?token=` | `/companyos/auth/{sign-up,verify-email,mfa,locked,connect-lssm,sign-out}` have no `(auth)` duplicate and stay canonical. `src/app/auth/**` is the separate `id.lssm.co` central-login surface, not a duplicate. ### Design-partner readiness route The `/companyos/special-ops/design-partner-readiness` route renders the session-scoped API projection. The deterministic identifiers `tenant_ndconsulting_design_partner_demo`, `workspace_ndconsulting_desliance_demo`, and `Atlantique Industrie — mission retournement` are fixture-only and must never be a production fallback. Route availability is design-partner readiness, not proof that the private pilot is activated. Boundary: it must not import API handlers, DB code, providers, examples, or app-owned reusable domain components. It must not add WebSocket, SSE, EventSource, interval polling, or automatic refresh. Replay and evidence links remain read-only. Role behavior rendered by the route: - `operations_manager` may prepare non-dispatch drafts. - `expert_reviewer` may attest the decision packet. - `founder_approver` may founder-approve the packet. - `auditor` is read-only. - `ai_operator` can propose/summarize only and sees `aiCannotDispatch`. - `frontline_staff` cannot mutate. - `enterprise_admin` can inspect but does not count as founder approval. Deterministic reference pages use `export const dynamic = 'force-static'`. Session/persona-sensitive pages declare `force-dynamic`; the Integration Hub catalog, detail, connections, syncs, config, audit, credentials, and secrets routes are dynamic so role morphs and security-class tabs resolve per request. Dynamic replay/workflow routes may still pre-render `runId: 'corr_internal_approval_service_delivery_001'` via `generateStaticParams()` when their route file declares that behavior. ## Role-aware screens ### Onboarding (`/companyos/onboarding`) The Executive Ledger wizard derives identity and tenant context from the authenticated shell. It never accepts those authority selectors from browser input. Completion writes the versioned `companyos.onboardingPreferences.complete` command with one stable idempotency key, stays on the final step when storage is unavailable, and navigates only after commit or exact replay. On reload, the shell query validates and merges the persisted tenant-scoped preferences into the canonical personalization profile. `roleAffordances(role)` gates UI actions per role: | Role | `canConfigure` | Action label | |---|---|---| | `enterprise_admin` | `true` | Configure | | `operations_manager` | `false` | View status | | `frontline_staff` (default) | `false` | Request access | ### Admin / integration setup (`/companyos/admin`) `adminRoleAffordances(role)` gates management actions: | Role | `canManage` | Secret action | Role label | |---|---|---|---| | `enterprise_admin` | `true` | Rotate secret ref | Enterprise admin | | `operations_manager` | `false` | View audit trail | Operations manager | | `frontline_staff` (default) | `false` | Request support | View only | ### Workflow (`/companyos/workflow/[runId]`) `workflowStepAffordances(step, policyDecisions, viewerRole)` gates per-step actions: | Role | `canApprove` | `canDeny` | Notes | |---|---|---|---| | `enterprise_admin` | depends on step boundary | depends on step boundary | Can approve `approval_required` steps | | `operations_manager` | depends on step boundary | depends on step boundary | Default viewer role | | `founder_approver` | depends on step boundary | depends on step boundary | `requiresFounderApproval: true` when step actor is `founder_approver` | | `auditor` | **always `false`** | **always `false`** | Read-only — "Auditor read-only" label shown | | Any role | **always `false`** | **always `false`** | When step boundary is `denied` + `actorRole` is `ai_operator`: `aiCannotDispatch: true` for **every role including enterprise_admin** | ### Replay (`/companyos/replay/[runId]`) Read-only auditor surface. Zero approve / deny / request-approval affordances for any role. ### Evidence (`/companyos/evidence/[runId]`) Shows metadata counts (replay events, policy decisions, graph nodes), `verificationHash` in monospace, `redactionSummary`, and a "Verify receipt" affordance. No mutation affordances. ## Dual-mode integration UX (`/companyos/admin`, `/companyos/integrations`) Managed and BYOK integrations render with equal setup, audit, and support workflow. The standalone `/companyos/integrations/*` routes consume reusable bundle view-models/templates and require explicit managed vs BYOK choice before configuration: - Ownership mode badge: cyan `managed` or violet `byok` - Credential display: always `'********'` — raw values never rendered - `custodySummary`: existing field name for the credential-handling owner summary (differs by mode) - `supportContactLabel`: differs by mode (managed → platform support, BYOK → customer-managed) - `capabilities`: same list per integration regardless of mode - Security-class routes (`credentials`, `secrets`) are always `force-dynamic`; do not move them to static generation or cache rendered output. - Rendered output, fixtures, snapshots, logs, and behavior signals may include only redacted credential references such as `********` or opaque `secretref://...` identifiers. - The configure API route uses verified Better Auth context in production; `x-managed-companyos-session-id` is accepted only in local/test fixture mode. Anonymous and cross-site mutation attempts return deny responses. ## Degraded-state handling Every page checks `shell.degradedBanner`: - Present → renders an `aria-live="polite"` amber banner (`role="status"`) with the degraded reason - Absent → no banner; normal render `shell.stateCopy` provides all four state strings: `loading`, `empty`, `error`, `degraded`. ## Accessibility and responsiveness - Page root: `aria-labelledby` tied to the `H1` `id` - Navigation cards: `aria-label` on container and each article with health status - Status badges: explicit `aria-label` (e.g. `"Ownership mode: managed"`, `"Health status: healthy"`) - Degraded banner: `role="status"` + `aria-live="polite"` - Responsive padding: `p-4 sm:p-8`; card widths: `w-full sm:w-64` or `w-full sm:w-80` - No raw `
`, `
`, `
`, `
` — layout via design-system primitives only ## Vercel-only production readiness The managed CompanyOS web monolith runs on Vercel with request-time/manual-refresh snapshots. Production pages consume bundle-owned `vercelSnapshot` readiness and API snapshot routes; they must not require browser WebSocket/SSE/EventSource connections, interval polling, or automatic polling to prove readiness. Key operator expectations: - Status and cockpit surfaces are request-time (`force-dynamic`) where readiness must reflect current API snapshots. - Manual refresh/navigation is the only refresh affordance for the cost-capped topology. - The bundle remains the source of truth for shell/view-model/status UI shapes. - The standalone Bun realtime runtime is a non-production/future VPS mode, not a Vercel production dependency. - Vercel functions run on the **Node.js** runtime (project setting `24.x`): `vercel.json` deliberately has no `bunVersion`. On the beta Bun runtime, a client that disconnected mid-stream kept the function open until the 300 s limit (`Task timed out after 300 seconds`). Bun still installs and builds the app. Evidence: `docs/evidence/opa/close-the-loop-deploy-3-2026-10-15.md`. ## Design-system rule Use design-system primitives exclusively: ```ts // Layout import { Box, HStack, VStack } from '@lssm-tech/lib.design-system/components/layout'; // Typography import { H1, H2, P, Text } from '@lssm-tech/lib.design-system/components/typography'; ``` No raw HTML markup in app shells. No imports from `@radix-ui/*` or native-only packages in web-only files. ## Environment variables Production must follow the environment contract in [`docs/runbooks/managed-companyos.md`](../../../docs/runbooks/managed-companyos.md). The API/auth origins must be exact HTTPS values, and production must fail closed instead of falling back to localhost, a fixture URI, or a demo tenant. | Variable | Purpose | |---|---| | `AUTH_PROVIDER_MODE` | `better-auth` in production; `fixture` is local/CI only. | | `BETTER_AUTH_BASE_URL` | Exact server-side API/auth origin: `https://api.companyos.run` for CompanyOS; the reviewed identity API origin for the identity profile. | | `LSSM_IDENTITY_WEB_PROFILE` | Identity web deployment only: set to `1` to enforce the exact `id.lssm.co` host and Passport-only route inventory. Omit from CompanyOS deployments. | | `LSSM_IDP_UPSTREAM_API_ORIGIN` | Identity web deployment only: exact HTTPS origin of the reviewed Elysia identity API. Enables same-origin auth and discovery rewrites on `id.lssm.co`; omit from CompanyOS deployments. | | `MANAGED_COMPANYOS_PROFILE_CONTEXT_SECRET` | Server-only HMAC key for profile context binding. Required in production and at least 32 bytes. | | `MANAGED_COMPANYOS_INTEGRATION_TOPOLOGY_PROFILE` | Optional server-only deployment declaration for `/companyos/integrations/runtime`: `lssm_managed`, `vertical_managed`, `customer_hosted`, or `hybrid`. It never counts as provider proof. | | `MANAGED_COMPANYOS_PUBLIC_BOOKING_ADAPTER_STATUS` | Leave unset for dry-run. `adapter_ready` is permitted only after the provider/vault evidence gate in `docs/runbooks/opa-public-booking.md`; it does not itself activate live traffic. | | `NEXT_PUBLIC_BETTER_AUTH_BASE_URL` | Same API/auth origin for browser Better Auth calls and organization switching. Set explicitly to the identity origin for the identity web deployment. | | `NEXT_PUBLIC_LSSM_IDENTITY_SIGNUP_TURNSTILE_SITE_KEY` | Public Cloudflare Turnstile site key for the central identity host. Required when registration options require CAPTCHA. The verification secret stays on the identity API. | | `NEXT_PUBLIC_MANAGED_COMPANYOS_API_BASE_URL` | API base URL for session-scoped request-time snapshots when web/API are deployed separately. | | `NEXT_PUBLIC_MANAGED_COMPANYOS_DEFAULT_TENANT_ID` | Fixture/dev preview only. Leave empty in production; it is never organization or tenant authority. | The `id.lssm.co` web profile exposes only the bounded Passport inventory, including the authenticated `/auth/privacy` governed-share center: account, sign-in, magic-link recovery, consent, invitation acceptance, post-login access, resume, public signup, email verification, missing-email registration completion, password reset, MFA challenges, security management, and private access administration. Unknown paths return `404`, and a request carrying a foreign host returns `421`. Invitation acceptance proxies only the bounded product-access endpoint to the reviewed identity API. The access page never offers an OAuth continuation when entitlement evidence is absent; it routes the person back to the relevant product waitlist instead. Central registration reads `/api/identity/registration/options` and fails closed when admission configuration is unavailable. CAPTCHA proofs stay in component memory and authorize a single signup, social start, OTP send, magic-link send, or pending-email request. Password sign-in and verification of an already issued challenge do not reuse a CAPTCHA proof. `/auth/complete-registration` accepts no provider subject, pending ID, or email through query parameters; it uses the HttpOnly pending cookie, an email code, and explicit confirmation plus a fresh verified session when an existing identity must be linked. Registration grants no product membership. `/auth/mfa?callback=` supports a fresh challenge for an already enrolled account. The `/auth/security` route exposes security management and a verify-again action. Credential identities retain their real password proof. Passwordless identities use canonical account metadata and a recent verified sign-in to begin enrollment; the API enforces freshness and CSRF. A stale session returns through sign-in to this bounded security route while preserving the original Passport continuation. No placeholder password is generated. Enrolled factor changes require fresh MFA assurance on the API. Account sign-out removes the current account by default; other browser accounts remain selectable. During audited impersonation, the account page exposes a return-to-operator action without granting ordinary admin navigation to the impersonated identity. ## Local commands ```bash bun run --cwd packages/apps/web-application-monolith dev bun run --cwd packages/apps/web-application-monolith test bun run --cwd packages/apps/web-application-monolith typecheck bun run --cwd packages/apps/web-application-monolith lint:check bun run --cwd packages/apps/web-application-monolith build ``` For the full operator runbook (deploy, start/stop, degraded triage, replay regen, evidence verification), see [`docs/runbooks/managed-companyos.md`](../../../../docs/runbooks/managed-companyos.md). ## Local authenticated E2E lane (`bun run e2e:local`) `bun run e2e:local` runs the logged-in journeys against a real local stack, with nothing reaching production, Google or a mail provider. It needs Docker and Playwright Chromium (`bunx playwright install chromium`). ```bash cd packages/apps/web-application-monolith bun run e2e:local # provision, run every spec, tear down bun run e2e:local -- account.spec.ts # extra args go to `playwright test` E2E_LOCAL_REUSE_BUILD=1 bun run e2e:local # skip an identical `next build` bun run e2e:local -- --stack-only # keep the stack up for manual QA (Ctrl+C stops) ``` Each run (`tests-e2e/support/local-stack/run-local-stack.ts`): 1. starts a throwaway `postgres:16-alpine` container on a random loopback port (tmpfs, `--rm`; containers left by a crashed run are reaped next time) and generates every secret and persona password; 2. runs the API's own `local-test-lifecycle.ts reset` (migrate + seed + verify), `scripts/bootstrap-admin.ts` and `scripts/e2e-local/seed-e2e-local.ts` (fake connected Google calendar per canonical workspace with tokens in the encrypted OPA vault, the canonical booking surfaces, and the `member`, `account`, `security` and `signin` personas in `companyos`); 3. serves an in-memory Resend-compatible mail sink (`GET /mail.json?to=`) and ticks the API cron routes every 3 s (booking calendar writes, booking email, profile cache); 4. starts the API through `scripts/e2e-local/e2e-api-server.ts`, where the googleapis client is answered by a deterministic in-memory Google Calendar fake (every working-hours slot is free); 5. builds and serves the web app in production mode (`next build` + `next start`, dist dir `.next-e2e-local`) with every production-pointing value of the tracked `.env.local` overridden; 6. runs `playwright.local-stack.config.ts` (headless Chromium, `tests-e2e/local-stack/`, retries 1 on CI, traces/screenshots/video kept on failure, HTML report in `playwright-report/local-stack`). | Port | Service | Override | | --- | --- | --- | | 3617 | web (`next start`) | `E2E_LOCAL_WEB_PORT` | | 3618 | API | `E2E_LOCAL_API_PORT` | | 3619 | mail sink | `E2E_LOCAL_MAIL_PORT` | Run logs and the per-run manifest live in the gitignored `.e2e-local//`; the manifest (it holds the generated passwords) is deleted at teardown. With `--stack-only`, point a separate `bunx playwright test -c playwright.local-stack.config.ts` at it with `E2E_LOCAL_STACK_MANIFEST=`. Without a manifest every local-stack spec skips, and the default Playwright configs ignore `tests-e2e/local-stack/`. The API runs with the test-only `COMPANYOS_AUTH_PROFILE=local-e2e-v1` auth topology (`@lssm-tech/lib.companyos-spec` `defineCompanyOsLocalE2eAuthTopology`): plain-HTTP loopback origins, host-only cookies. The readiness gate refuses it on `NODE_ENV=production`, any `VERCEL_ENV`/`RAILWAY_ENVIRONMENT`, a cookie domain, the LSSM IdP/RP flags or a non-loopback database. The CommunicationOS specs run without a CommunicationOS backend and check the degraded states. Helper checks: `bun run test:e2e-local-support` and `bun run typecheck:e2e-local`. ## Theme & runtime wiring ### CSS `src/app/globals.css` bootstraps the CSS pipeline and provides the SSR-safe fallback for `contractspec.design.executive-ledger@2.0.0`. The canonical palette uses parchment, carbon, mineral blue, oxblood, and brass; dark mode has its own carbon, bone, mineral, oxblood, and brass values. Newsreader, IBM Plex Sans, and IBM Plex Mono are loaded through `next/font`. ### Theme provider `src/app/providers.tsx` makes `next-themes` the sole light/dark/system authority. The resolved mode is passed into `DesignSystemThemeProvider`; CSS variables are applied only after mount, while the class-scoped fallback tokens keep the first paint visible and consistent. CompanyOS defaults to Executive Ledger 2.0 while the design-selection policy remains available for tenant/user preview. ### PostHog observability `PostHogProvider` activates only when `NEXT_PUBLIC_POSTHOG_KEY` is set. When absent, no PostHog requests are made and the provider wrapper is omitted. SSR-safe: init runs inside `useEffect` with a `typeof window` guard. Browser capture uses `/ingest` while the PostHog UI host remains `https://eu.posthog.com`; `next.config.mjs` rewrites `/ingest` to `https://eu.i.posthog.com` and `/ingest/static` to EU assets. Server-side SDK capture uses `POSTHOG_HOST=https://eu.i.posthog.com`. When enabled, add `connect-src https://eu.i.posthog.com` to your CSP (S2 concern). ### Global state routes | Route | File | Type | Notes | |---|---|---|---| | `/error` | `src/app/error.tsx` | Client Component | Error boundary — renders `stateCopy.error` + "Try again"; logs `error.digest` only | | `/loading` | `src/app/loading.tsx` | Server Component | Renders `stateCopy.loading` with `role="status"` | | `/not-found` | `src/app/not-found.tsx` | Server Component | Renders `stateCopy.empty` + home link | ### Enforcement tests Three mechanical tests added in S1: - **`src/__tests__/import-boundaries.test.ts`** — fails CI if `next-themes` or `@posthog/react` appear outside `layout.tsx` / `providers.tsx`. - **`src/__tests__/raw-color-baseline.test.ts`** — asserts raw Tailwind color class count ≤ 391 (2026-05-16 baseline). S3 target: 0. - **`src/__tests__/providers.test.tsx`** — asserts `posthog.init` is not called when `NEXT_PUBLIC_POSTHOG_KEY` is unset. Test infra: `src/__tests__/setup-next-mocks.ts` stubs `next/font/google` for bun's test runner, preloaded via `bunfig.toml`. ## How to add a new route 1. **Define the nav item in bundle**: Create `NavSurfaceItemSpec` in `@lssm-tech/bundle.managed-companyos/src/web-shell.ts` ```typescript defineNavSurfaceItem({ id: 'my-feature', route: { web: '/companyos/my-feature' }, capability: { surface: 'navigation', key: 'companyos:my_feature:view' }, groupKey: 'operations', iconKey: 'briefcase', densityHint: 'compact', }) ``` 2. **Register the capability**: Ensure the capability is registered in `CapabilityRegistry` with `surface: 'navigation'` 3. **Create the page**: `src/app/companyos/my-feature/page.tsx` ```typescript export const dynamic = 'force-static'; export default function MyFeaturePage() { return ; } export const myFeaturePageDocBlock = { id: 'my-feature-page', title: 'My Feature Page', body: '...', kind: 'goal', route: 'packages/apps/web-application-monolith/src/app/companyos/my-feature/page.tsx', visibility: 'public', } satisfies DocBlock; ``` 4. **Emit signals**: In your component, emit behavior signals on mount ```typescript useEffect(() => { const id = crypto.randomUUID(); void emitCompanyOsBehaviorSignal({ surfaceId: 'my_feature', signal: 'surface_viewed', correlationId: id, tenantId: 'demo', actorKind: 'founder_approver', }); }, []); ``` 5. **Verify**: `bun run lint:check && bun run lint:signals && bun run typecheck` ## How to add a new persona 1. **Document in PERSONAS.md** (repo root): Define persona responsibilities, default preferences (density/guidance/pace) 2. **Create the home page**: `src/app/companyos/{persona}/page.tsx` - Either wrap a candidate template (e.g., `FounderHome` wraps `MissionLandingFunnel`) - Or compose custom shell with nav items and module grid 3. **Register nav subset**: In bundle `web-shell.ts`, set `personaVisibility` on nav items ```typescript defineNavSurfaceItem({ // ... personaVisibility: { founder_approver: true, operations_manager: false, // ... } }) ``` 4. **Update persona dispatcher**: Modify `/companyos/page.tsx` to route to new persona home 5. **Add E2E test**: Create Playwright test for persona happy-path (signin → home → navigate → signout) ## Thin app shell This app follows the [package-architecture layering rules](../../.claude/rules/package-architecture.md): apps stay thin by composing bundles, not owning shared UI. Thin-shell rule is **active**. The `src/components/` directory is **intentionally absent** — all 427+ shared React components have been migrated to `packages/bundles/managed-companyos/src/ui//` via PR series `chore/migration/slice-*` (Slices 1–13). **Do not recreate `src/components/`.** All shared UI belongs in the bundle's `./ui` subpath, imported as `@lssm-tech/bundle.managed-companyos/ui` or `@lssm-tech/bundle.managed-companyos/ui/`. Boundary rules enforce this at error level in CI. ## Integration Points ### Embedding Managed CompanyOS Surfaces The web app exposes individual screens as React Server Components that can be embedded in other Next.js applications: ```typescript import { CompanyOsOnboarding } from '@lssm-tech/app.web-application-monolith/companyos/onboarding'; // Embed in another app's page export default function AdminPanel() { return ; } ``` Each screen route (`/companyos/*`) is independently renderable and passes tenant context through layout context/props. ### API Dependency All screens fetch data from the API app via fetch: ```typescript // Inside a screen component const response = await fetch('/api/companyos/workspace', { headers: { 'x-managed-companyos-session': sessionToken } }); const workspace = await response.json(); ``` The web app assumes the API is available at the same origin. For separate deployments, override `NEXT_PUBLIC_MANAGED_COMPANYOS_API_BASE_URL` env var. ### Manual snapshot refresh Screens render request-time snapshots from the API/bundle seam. Operators and users refresh by navigating or manually refreshing the page; the app must not introduce WebSocket, SSE, EventSource, interval polling, or automatic polling for managed CompanyOS production readiness. For separate web/API deployments, configure `NEXT_PUBLIC_MANAGED_COMPANYOS_API_BASE_URL` and keep session authority on the API side. ### MCP Integration For AI agents and CLI tools that need to read Managed CompanyOS state without opening the web UI, use the planned `@lssm-tech/app.managed-companyos-mcp` server. It exposes tenant graph queries, approval lists, replay packets, and evidence receipts as MCP tools and resources. ## Environment Copy `deploy/env/web.env.example` into the deployment secret-manager backed environment group. Public values may identify API endpoints, but raw provider credentials never belong in web env files. - Set `NEXT_PUBLIC_POSTHOG_KEY` only when browser analytics are intended. - Set server `POSTHOG_HOST` to EU Cloud capture: `https://eu.i.posthog.com`. - Omit `DATABASE_URL` unless a dedicated least-privilege/read-only proof credential exists; never use the API admin/migrator Supabase URL in the web project. The OPA web proxy forwards the declared capture/consent routes with fresh session authority and same-origin mutation checks. Chunk uploads have a 1,410,000-byte JSON transport limit; other requests retain the 128 KiB limit. Both are enforced while streaming, including requests without a Content-Length header. ### Private reviewed meeting outcomes The existing meeting-workspace routes accept `x-opa-owner-view: private` to derive individual ownership from the verified user within the selected workspace. Omitting the header preserves context ownership; arbitrary owner selectors are rejected. Use the same private view for outcome analysis and subsequent artifact reads. The web BFF forwards this selector after its existing authentication and mutation-origin checks. CompanyOS outcome analysis loads the persisted approved transcript review, verifies exact source and review bindings, and checks current `intelligence.generate` policy before generation and commit. Rejected, changed, unauthorized or workspace-widened sources fail closed. The adapter uses the caller transaction and does not publish private capture text. Model calls run outside aggregate transactions. Finalization reloads current state and rechecks authority and the reviewed source before saving. Durable outcome jobs are available behind explicit configuration; downstream effects and live quality qualification remain open. ### Reviewed outcome drafts in CompanyOS The approved transcript panel can generate and read private meeting drafts through existing OPA operations. Generation controls use server-derived `canGenerateOutcomes`; authority and automation policy are rechecked server-side. Draft generation creates no messages or Work tasks. French, English and Spanish copy distinguishes loading, generation, retry, denied access and empty history. Artifact list 2.2.0 accepts optional `reviewRef`, selecting the current review before source reproof so stale historical drafts do not block current results. Transcript get 2.2.0 adds the generation capability projection. The client pins private ownership and an exact review-derived retry key, including across reloads. Interactive generation has a bounded 180-second request deadline; the web proxy allows a 300-second function budget. Persisted background jobs, signed-native presentation and full browser/accessibility qualification remain incomplete. ### Durable outcome processing Analyze 3.1.0 accepts `executionMode: background` on its existing route. Repeating the exact request observes the same persisted job; processing responses carry `processingJobRef`, while completion returns the saved outcome. The private draft client selects background mode when the server advertises it and can stop polling without cancelling accepted work. Terminal failures remain failures. Apply additive migration 0080, configure a dedicated `companyos_outcome_dispatcher` login, and enable `OPA_OUTCOME_JOBS_ENABLED=1` only with approved pinned `OPA_MEETING_AI_*` EU processing. The every-minute `/api/cron/opa-outcome-processing` route requires `CRON_SECRET`. Runtime credentials must not be superuser, BYPASSRLS or a member of `opa_migrator`. The queue admits four global jobs and one per owner, bounds pending owner jobs at 25, retries at most five times and uses six-minute fenced leases. Current membership, module entitlement, intelligence policy, source consent/review and model binding are rechecked before generation and commit. Outcome persistence and completion share a transaction; model calls are outside SQL. Queue rows contain references and authorization evidence, not transcript text or credentials. Model cost may repeat after a crash before commit. Terminal-job self-service repair, queue retention/deletion propagation, live model/provider qualification and production rollout remain open. No production activation is implied by the local tests. ### Approved action to canonical Work `opa.task.project` 3.0.0 projects one approved structured action through the existing task route. The request binds artifact revision/digest, approval receipt, action reference and selected workspace. It requires explicit workspace disclosure acknowledgment and confirmation for an uncertain proposal. The UI exposes this action only for approved task lists and server-derived projection permission. Only the reviewed title and details are transferred; raw/private transcript text and source quotes are not copied into Work. Assignees and deadlines remain unset. Current `outcome.commit` policy, transcript review/consent and Work workspace write authority are rechecked. Work event/idempotency/outbox and the OPA projection receipt commit in one transaction. Repeated projection returns the existing Work object; a receipt represents committed task creation, not task completion or realtime projection convergence. New owner capability manifests include `opa.task.project`; existing grants require an authorized update and are not silently widened. Legacy input-only projection clients must update to 3.0.0. CommunicationOS delivery, assignment/due-date controls, real-authority deployment qualification and full release gates remain open. ### Better Auth 1.7 callback forwarding The existing public LSSM callback alias forwards only its bounded authorization response to the fixed API owner's `/auth/callback/` endpoint, replacing the removed `/auth/oauth2/callback/` path. Existing issuer and parameter checks remain in force. API token exchange, provider registrations, cookies and account-identity migration still require live qualification before cutover. TOTP enrollment explicitly requests `method: totp` and rejects a different result. Unlink requires a specific linked account and resolves its unique current provider mapping before sending Better Auth's stored account ID. Missing or ambiguous mappings fail before the unlink request. ### Memory import transport `createAgentMemoryImportClient` wires prepared import references to a configured Agent Host origin. It requires HTTPS except for loopback development, sends an explicit short-lived bearer credential, disallows redirects and automatic retries, and validates the response proposal digest. Lost responses and timeouts remain indeterminate. The client does not prepare work orders, upload memory contents, store tokens or grant authority. Route composition must supply reviewed prepared requests and obtain credentials through the application's authenticated session. The `/api/companyos/builder/*` web bridge exposes existing authoring operations through same-origin session requests. It does not expose release execution. The API retains capability and tenant enforcement; uncertain mutations are not automatically retried. Configure `MANAGED_COMPANYOS_API_BASE_URL` for the API host. The Builder Sources tab can query company context through the authenticated BFF. The host must configure the API grounding service before retrieval is available; an unconfigured service is presented explicitly. Requests are member-triggered, bounded, and never automatically replayed. Changing workspace clears the view and ignores responses from the previous workspace. Retrieved evidence is text for review and cannot grant permission to ship. The Builder workbench client submits intent, blueprint, plan, preview and readiness actions through the authoring bridge. Confirmed writes refresh server-owned data; unknown outcomes block further mutations for reconciliation. Page-level session loading and deployment activation remain separate integration requirements. `/companyos/builder` now offers explicit workspace creation; `?workspace=` loads saved state after session resolution and tenant/workspace checks. Lost creation responses retain a workspace recovery link. This is an authoring pilot, not proof that production deployment actions are activated. Member creation returns an opaque, context-bound workspace ID. Recovery may use the original request ID; the loader accepts the API's explicit matching resolution receipt and still verifies tenant identity and snapshot structure. Missing grants or a changed company/team/workspace context deny access. The API must have the pilot's exact authoring grants configured before this journey is usable. For `COMPANYOS_AUTH_PROFILE=preview-v1`, configure the same explicit `COMPANYOS_PREVIEW_WEB_ORIGIN` and `COMPANYOS_PREVIEW_API_ORIGIN` as the API. The web app's `NEXT_PUBLIC_BETTER_AUTH_BASE_URL` equals the web origin, while server-side `BETTER_AUTH_BASE_URL` and `MANAGED_COMPANYOS_API_BASE_URL` equal the API origin. Auth and enumerated context endpoints are rewritten to that API. Never add a broad `/api/companyos/*` afterFiles rewrite: it runs before dynamic BFF routes and would bypass Builder session mediation. Do not inherit `LSSM_IDP_UPSTREAM_API_ORIGIN` or select preview on a production Vercel deployment. The API target must admit the web proxy under its configured access controls; a build-ready deployment alone does not prove login works. Authentication callbacks resolve against this configured preview origin. Builder sign-in retains its workspace return path rather than sending the member to a different environment or losing the work item. The login page uses configured API login-method discovery for email-code and magic-link controls. When discovery is unavailable, delivery controls are omitted; password login remains available. Password reset is shown only when an email delivery method is configured. Edge cookie presence and server session-token forwarding both select the configured profile prefix. Preview cookies are not accepted as production cookies or vice versa; the API still validates the session and current authority. Builder workbench mounts its existing locale catalog locally, delegating non-Builder keys to the parent application runtime. No duplicate translation strings are defined. Builder BFF responses expose numeric Server-Timing phases: auth, input, upstream (response headers), and total. Streamed response-body time is excluded. Compare these with client elapsed time before changing deadlines; uncertain writes remain non-retryable until their saved outcome is reconciled. After an uncertain workbench mutation, “Check saved workspace” reloads server-owned state without repeating the write. Inspect that state before submitting another action. Builder company context is available through the host-owned `builder.companyContext.resolve` query and POST `/api/companyos/builder/context/resolve`. It accepts an owned workspace ID and a nonempty question up to 4096 UTF-8 bytes. Missing grounding configuration returns 503. The web BFF preserves authentication and response status; the client treats this as a query, never a saved mutation, and does not auto-retry. Context grants no execution authority. Provider configuration, a visible member control and live qualification remain required before advertising it. Public booking isolates client state by booking token and embed origin. Refresh responses are revision-guarded: an older request or an unmounted session cannot replace current availability or emit ready/error callbacks. This does not qualify provider availability or durable booking effects. Public booking routes use booking-specific localized loading text. LINK_NOT_FOUND offers guidance to request a replacement link; temporary availability failures retain retry. Refresh fencing preserves typed failures without letting stale requests replace current state. Committed CompanyOS organization/workspace switches synchronously unmount the previous shell and private content before document reload. If reload fails or returns, the cleared transition screen remains; its localized Reload workspace action retries only the document reload and never restores the previous context. This protects committed selector changes, not remote revocation events that the host has not observed. ## Builder candidate journey The Builder Plan tab exposes Prepare candidate, Approve candidate, Run candidate and Check status through the existing authenticated BFF. Requests carry the reviewed plan reference and an idempotency correlation ID, never provider credentials or caller-selected authority. Responses are scope/digest checked; uncertain effects are not retried automatically. Queued/running work receives up to twenty status refreshes at three-second intervals, then remains manually refreshable. Workspace or plan changes discard stale responses. The API must install the concrete candidate service before execution becomes available. The separate export controls remain unconnected to actual export effects; candidate completion never implies a deployed preview or shipped release. ## Build compute policy Automatic Vercel Git builds are disabled for this app. Build compute is assigned to Railway; this does not change the existing runtime or domain topology. See the [operator policy and evidence](../../../deploy/lssm-ecosystem/build-compute-policy.md) for configuration scope and the unqualified Vercel prebuilt delivery gap. --- ## @lssm-tech/app.web-founder-suite-monolith Description: (none) Path: packages/apps/web-founder-suite-monolith URL: /llms/app.web-founder-suite-monolith # Tendframe Founder Intelligence web Standalone Next.js web boundary for `tendframe.me` and `app.tendframe.me`. The authenticated `/meetings` surface projects the shared OPA meeting workspace with adaptive profile rationale, confidence, and founder override visibility. Private guidance remains separate from shared artifacts, and AI output stays advisory: humans retain approval, publication, link, and dispatch authority. An opaque route-selected `meetingRef` loads live OPA state with the current Tendframe session, and context refresh requires fresh origin and session evidence. The same deployment uses host-based rewrites: - `www.tendframe.me`, `tendframe.run`, and `www.tendframe.run` redirect to `tendframe.me`, preserving the path and query - `tendframe.me` serves the marketing and verified-waitlist surface (the AuthOS `WaitlistJoinForm` from `@lssm-tech/module.auth-os`: consent is an explicit required checkbox, never implied; the Tendframe adapter fixes the product scope, consent-text version and source) - `app.tendframe.me` serves the invite-only product workspace - `app.tendframe.run` redirects to `app.tendframe.me` - `pactena.run` still redirects to `www.pactena.run`; the legacy marketing and app hosts remain explicit compatibility routes during the origin cutover Unknown hosts are rejected before internal route handling. No wildcard product domains or callback destinations are admitted by this rename. A Railway recovery canary treats only the exact injected `RAILWAY_PUBLIC_DOMAIN` as a marketing host. It does not widen trust to the provider suffix, activate the product host, or change production canonicals. The approved one-page homepage remains the canonical `/` experience. Additive EN/FR/ES acquisition routes cover feature, founder-persona, and decision-use intent under `/features/*`, `/personas/*`, and `/solutions/*`; each publishes a canonical URL, hreflang alternates, direct-answer content, JSON-LD, and an explicit privacy/evidence boundary. Canonical product topics include cockpit, portfolio, operating domains, weekly review, conversations and meetings, executive collaboration, talent, forms and intake, and purpose-bound sharing. The invited-founder persona and `/trust` boundary explain that one LSSM account still requires a Tendframe entitlement, membership, and product-local session. `sitemap.xml`, `robots.txt`, and `llms.txt` are generated from the same typed registry. The app host does not render the private workspace until the Tendframe API confirms a Better Auth session. Reviewed LSSM OIDC uses the browser callback at `/auth/callback/lssm`; invited-email magic links remain available for existing local identities. The central provider must confirm an active `app_pactena` entitlement before it emits an authorization code. The access threshold and session seal negotiate EN/FR/ES from the app request. Signing out in Tendframe closes only the product-local session; it does not imply that the LSSM Passport session was closed. The seal links to the separate Passport account controls so both boundaries remain visible and independently operable. The protected production replay is fail-closed. `bun run test:production-oidc-canary` skips unless `PACTENA_LSSM_PRODUCTION_CANARY_AUTHORIZED=1`, the exact `E2E_PRODUCTION_BASE_URL=https://app.tendframe.me`, and secret-managed `E2E_TEST_EMAIL` / `E2E_TEST_PASSWORD` values are all present. It exercises central sign-in and optional consent, Tendframe callback and local session, protected cockpit routes, product-local sign-out, denied post-sign-out session resolution, and independent Passport sign-out. Credentials are read only from process environment variables and are never written to evidence output. Until the API database is configured, the UI presents an honest activation-pending state and does not emulate persistence or identity. The Executive room consumes the live CompanyOS metrics projection through the Tendframe API peer boundary. Missing, stale, degraded, and denied values remain explicit; the web app does not copy canonical metric state or access the founder-private vault. ## Environment ```text NEXT_PUBLIC_PACTENA_API_URL=https://api.tendframe.me NEXT_PUBLIC_PACTENA_API_ORIGIN=https://api.tendframe.me NEXT_PUBLIC_LSSM_IDENTITY_ORIGIN=https://id.lssm.co NEXT_PUBLIC_PACTENA_LSSM_RP_ENABLED=0 ``` Setting `NEXT_PUBLIC_PACTENA_LSSM_RP_ENABLED=1` renders only the reviewed LSSM Passport handoff. The invited-email form is rendered only when the central RP is disabled for an explicit local rollback; the API must use the matching authority mode so a deployment never presents two sign-in authorities. ### Better Auth 1.7 callback forwarding The existing public LSSM callback alias forwards only its bounded authorization response to the fixed API owner's `/auth/callback/` endpoint, replacing the removed `/auth/oauth2/callback/` path. Existing issuer and parameter checks remain in force. API token exchange, provider registrations, cookies and account-identity migration still require live qualification before cutover. ### Tendframe origin migration The public name and canonical marketing origin are Tendframe and `https://tendframe.me`. Existing `PACTENA_*` environment keys, package names, application IDs, client IDs, scopes, HTTP headers, database keys, and storage keys remain stable. Both public API environment variables above retain precedence over the new defaults, allowing an explicit legacy deployment while DNS and identity are prepared. Reconcile the existing `pactena-web` client from the AuthOS catalog before switching to the new product origins. The web callback accepts only the exact registered app origins: `app.tendframe.me` forwards to `api.tendframe.me`, and `app.pactena.run` forwards to `api.pactena.run`. The API chooses its registered callback from `APP_WEB_BASE_URL`; it does not use a browser-supplied destination. Deploy the API and web with matching canonical origins, then qualify the protected sign-in, product session, sign-out, waitlist, and callback flows. Source tests do not establish that DNS, TLS, or the live identity client is ready. The acquisition registry retains its original capability-review `proofDate`. That date is not evidence of the new domain's deployment or authentication. --- ## @lssm-tech/app.web-landing Description: (none) Path: packages/apps/web-landing URL: /llms/app.web-landing # @lssm-tech/app.web-landing **Next.js delivery shell for the public ContractSpec website: technical substrate marketing, docs, registry pages, `/llms*`, and selected operate/sandbox surfaces.** ## What It Does - Owns the app shell, metadata, OG generation, route wrappers, and public site delivery. - Publishes the marketing experience while delegating most page-body composition to `@lssm-tech/bundle.marketing`. - Serves docs, registry, sandbox, and operate surfaces while keeping their shared shell consistent with the public brand system. - Shares example preview rendering across docs, `/templates`, and `/sandbox`, with rich UI for UI-backed examples and fallback cards for the rest of the discoverable catalog. - Hosts the CompanyOS adaptive Request-to-Verified-Proof journey through an app-owned preview override, allowlisted same-origin no-store operation route, and browser-safe fetch client while keeping runtime composition server-only and Playwright outside the client graph. - Publishes `/llms`, `/llms.txt`, `/llms-full`, `/llms-full.txt`, and package-specific `/llms/[slug]` endpoints for agent-friendly repo guidance. - Keeps Managed CompanyOS agent guidance aligned with the real-organization rollout runbook: Better Auth membership and active organization are authoritative, NDconsulting history is preserved, and rollout/canary/rollback remain operator-gated. - Documents design-system adoption guidance for shared interaction patterns such as `ObjectReferenceHandler` and `AdaptivePanel`, including human-readable docs and agent-facing `/llms*` prompts. - Documents ContractSpec translation runtime guidance, including the optional i18next adapter, SSR/hydration rules, production checks, and an agent implementation prompt. - Documents data-exchange flexible import-template guidance at `/docs/guides/data-exchange-import-templates`, including developer templates, user remapping flows, server dry-runs, format profiles, verification commands, and copy-ready prompts. ## Template preview and LLMS sync workflow Public example preview changes must keep human and agent-facing surfaces aligned: - `/templates`, `/docs/examples/`, and `/sandbox?template=` consume the same module examples preview surface so inline UI and fallback behavior stay consistent. - `/llms`, `/llms.txt`, `/llms-full`, `/llms-full.txt`, and `/llms/[slug]` must be regenerated or verified after README changes that document example exports, preview support, route inventory, or release workflow expectations. - Rich previews are deterministic local fixtures by default. The CompanyOS proof demo is the explicit governed exception: the host override injects the same-origin runtime client into the generic preview. Live mode starts an ephemeral loopback fixture and never targets production. The reliable public path is the committed validated recording; live Chromium is opt-in and must pass a real preflight. - Public key or alias changes are compatibility-sensitive. Preserve existing `examples.*` and normalized lookup behavior unless a release capsule explicitly documents and tests the migration. ## Architecture - `src/app/` contains route groups for marketing, docs, sandbox, operate, registry, and API endpoints. - `src/components/` contains app-local shell concerns such as header, footer, SEO helpers, and local route UI. - `public/llms*.txt` contains machine-readable monorepo guidance exposed directly from the site. - `scripts/generate-llms-full.mjs` regenerates the public aggregated README corpus used by `/llms-full.txt`. This package should stay thin: - marketing page narratives belong in `@lssm-tech/bundle.marketing` - docs and library composition belong in `@lssm-tech/bundle.library` - shared reusable UI primitives belong in lower layers ## Public Entry Points and Topics Static and generated public surfaces currently delivered by this app: - **Marketing and conversion**: `/`, `/product`, `/pricing`, `/templates`, `/contact`, `/cofounder`, `/contribute`, `/design-partner`, plus legal pages at `/legal/privacy` and `/legal/terms`. - **Release and registry**: `/changelog`, `/changelog/[version]`, `/registry/featured`, `/registry/packs`, `/registry/packs/[name]`, `/registry/packs/[name]/versions/[version]`, and `/registry/publish`. - **Feature catalog**: `/features`, `/features/[key]`, and feature detail routes for operations, events, forms, presentations, and DataViews. - **Docs shell**: `/docs` and topic groups for getting started, specs, guides, libraries, the first-class Agent Ecosystem at `/docs/agents`, domains, safety, knowledge, integrations, architecture, advanced operation, comparisons, ecosystem, examples, Studio, intent pages, generated reference, manifesto, and ops. - **Agent Ecosystem docs**: `/docs/agents` plus focused guides for getting started, two all-in-one examples, multi-agent operation, governed self-improvement, durable runtime, self-maintaining APIs, replaceable deployment topologies, and production readiness. The Release Steward guide covers verified, human-approved migration pull requests. The Company Intelligence Scout guide covers bounded public-web research, source citations, 30-day person/contact retention, and policy-controlled recruiting or sales drafts and sends. - **Docs guide topics**: installation, private registry access, Hello World, compatibility, developer tools, DataViews, troubleshooting, Next.js endpoint adoption, imported codebases, contract intelligence, codebase graphs, validation/typing, ContractSpec theme, contract-driven forms, i18n, Drizzle database setup, data-exchange import templates, docs/client/schema generation, docs pipeline, module bundles, mobile navigation, Builder workbench/spec packs/intelligence, Connect, provider-backed knowledge, release capsules, and CI diff gating. - **Docs library topics**: contracts, schema, runtime, translation runtime, UI kit, UI kit web, design system, application shell, cross-platform UI, data views, personalization, observability, resilience, multi-tenancy, workflow composer, workflows, AI agent, analytics, content generation, cost tracking, data backend, evolution, GraphQL, growth, overlay engine, SLO, support bot, and testing. - **Docs integration topics**: setup/model docs plus OpenAI, Mistral, Qdrant, Gmail, Google Drive, Google Calendar, Stripe, Twilio, GitHub, Slack, Postmark, Powens, Resend, S3, ElevenLabs, WhatsApp Meta, WhatsApp Twilio, circuit breakers, and health routing. - **Examples and sandbox**: `/docs/examples`, `/docs/examples/[exampleKey]`, `/docs/examples/data-grid-showcase`, `/templates`, `/sandbox`, and `/graph-showcase`. - **Operate surfaces**: `/operate/builder/workspaces/[workspaceId]`, `/operate/builder/workspaces/[workspaceId]/mobile-review/[cardId]`, `/operate/pm/issues/[issueId]`, and API proxy routes under `/api/operate/builder/*`. - **Agent-facing discovery**: `/llms`, `/llms.txt`, `/llms-full`, `/llms-full.txt`, `/llms/[slug]`, and `/docs/llms.txt` via static files and rewrites. - **Public APIs**: `/api/changelog`, `/api/chat`, `/api/graphql/*`, `/api/mcp`, `/api/og`, `/api/examples/companyos-ai-solutions-engineer-poc/[operation]`, and operate builder API routes. Route changes here affect SEO, external links, sitemap output, and agent-discovery flows. Keep `src/app/sitemap.ts`, `next.config.mjs` rewrites, `public/llms*.txt`, this README, and route wrappers aligned. ## Marketing contract boundary The `(landing-marketing)` route group is wrapped with the shared marketing contract boundary and backed by the ContractSpec route contract registry from `@lssm-tech/bundle.marketing/content`. Static routes, deterministic feature/changelog routes, and runtime-only registry pack families must stay covered by `src/marketing-contract-system.test.ts` when route files move or change. ## Local Commands - `bun run dev` — bun --bun next dev - `bun run start` — bun --bun next start - `bun run build` — bun --bun next build - `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 clean` — rimraf .next dist .turbo - `bun run llms:generate` — bun scripts/generate-llms-full.mjs - `bun run build:types` — tsgo --noEmit - `bun run test:unit` — invoke Bun’s test runner directly from the repository root, scoped to this app. The command must begin with `bun test`; placing `--cwd` before `test` invokes the root package script and unrelated suites. - `bun run test` — run the root-safe unit suite, then the package-context CompanyOS route proof. - `bun run test:companyos-route` — verify the CompanyOS browser client and server-only live route proof with the package-local Bun test configuration. For a customer-call rehearsal, run: `bun run --cwd examples/companyos-ai-solutions-engineer-poc precall` This validates the example/profile, committed recording and hashes, Chromium plus fixture behavior, and the same-origin host route. Optional request analysis is host-only, disabled by default, and requires `CONTRACTSPEC_COMPANYOS_LIVE_ANALYSIS=1` plus approved provider configuration. It has no tools and returns analysis-only authority. Live proof is separately disabled unless `CONTRACTSPEC_COMPANYOS_LIVE_BROWSER=1`; even then, the route requires a successful `ready-live` probe and an exact prepared-generation session binding before it creates the loopback fixture. The live CompanyOS route proof is opt-in during generic `bun test` discovery. Run it through `test:companyos-route`: Bun's repository-root project configuration can corrupt the loopback Playwright proof state before mutation, while the package-local server test configuration observes and resets the exact expected state. The scoped command remains part of `bun run test`, so CI keeps the live-browser source, status, observed-state, and reset assertions. ## Notes - Branding changes in this package must stay aligned with root docs, generated root AGENTS content, and `public/llms.txt`. - When updating the public shell, verify that docs and `/llms*` remain readable; this package serves more than the marketing homepage. - Keep `/docs/libraries/design-system` and `/llms/lib.design-system` aligned when documenting object references, adaptive panels, or other interaction primitives that downstream apps should adopt consistently. - Keep `/docs/libraries/translation-runtime`, `/llms/[lib.translation-runtime]`, and `@lssm-tech/lib.translation-runtime` README guidance aligned when documenting i18n runtime or adapter behavior. - Keep `/docs/guides/data-exchange-import-templates`, `/llms/lib.data-exchange-core`, `/llms/lib.data-exchange-client`, and `/llms/lib.data-exchange-server` aligned when documenting import templates, flexible column mapping, dry-runs, or mapping-review prompts. ## Static-generation resource budget `bun run build` retains the required TypeScript prebuild and generates every configured route. `CONTRACTSPEC_BUILD_CPU_BUDGET` accepts a positive integer allocation; page-data/static generation use at most four workers and two page renders per worker. Without an allocation, the worker count follows local `availableParallelism()` up to the same four-worker cap. Invalid overrides fail configuration instead of starting an oversized pool. Turbo hashes both the allocation and the budget helper. The failed Railway build had compiled successfully before launching 47 workers against a 4-CPU/16-GB allocation. A local full build with budget four completed all 1,644 static tasks in 58.41 seconds overall, including the TypeScript gate. The route count reflects that release snapshot; live runner memory/cgroup qualification remains required and should use the current route inventory. --- ## @lssm-tech/app.worker-application-monolith Description: (none) Path: packages/apps/worker-application-monolith URL: /llms/app.worker-application-monolith # Managed CompanyOS Worker Application Monolith > **Production status (Vercel-only Managed CompanyOS):** this package is not part of the managed CompanyOS production deployment while the cost-capped Vercel topology is active. Production duties are absorbed by `packages/apps/api-application-monolith` through API snapshots and Vercel Cron, and the web app uses manual refresh/request-time snapshots. Keep this Bun runtime for deterministic proofs, local monitoring, and future VPS mode only; do not wire it as a production readiness dependency for Vercel. This deferral is part of the canonical [`private-pilot contract`](../../../docs/managed-companyos-private-pilot.md). Do not activate this worker for the first design-partner pilot. VPS-suitable Bun worker and WebSocket runtime for Managed CompanyOS background jobs. It publishes deterministic operating-graph snapshots, tracks worker supervision health, and keeps all job projection side-effect-free until production queue, persistence, and provider adapters are approved. No queue, provider, network, or credential side effects start at module load. The runtime starts only through `bun src/server.ts` / `bun run start`. ## Special Ops projection contract The worker-side Special Ops production contract is documented in [`docs/runbooks/special-ops-monolith-production.md`](../../../docs/runbooks/special-ops-monolith-production.md). Worker projections must consume a repository-compatible tenant/workspace/capability snapshot, preserve correlation IDs across jobs, WebSocket events, replay, and evidence, and surface degraded/stale Special Ops state instead of hiding it behind a green worker response. ## Runtime surface | File | Purpose | |---|---| | `src/server.ts` | Bun HTTP + WebSocket runtime; all route handlers and WebSocket server | | `src/index.ts` | Deterministic job projection: worker runtime, job lifecycle, correlation ID proof, degraded-state evaluation, idempotency store | | `src/live-client.ts` | WebSocket client with exponential-backoff reconnect for proof and monitoring | ## HTTP endpoints | Method | Path | Query params | Response | |---|---|---|---| | `GET` | `/health` | `tenantId`, `degraded`, `lastSyncMs`, `nowMs`, `staleAfterMs` | `ManagedCompanyOsWebSocketMessage` (200) | | `GET` | `/graph-snapshot` | `tenantId`, `idempotencyKey`, `degraded`, `lastSyncMs`, `nowMs`, `staleAfterMs` | `ManagedCompanyOsWebSocketMessage` (200) | | `GET` | `/worker-supervision` | `tenantId`, `degraded`, `nowMs`, `lastSyncMs`, `staleAfterMs` | `ManagedWorkerSupervisionHealth` (200) | | `WS` | `/ws` | `tenantId` | Upgrades to WebSocket; emits `ManagedCompanyOsWebSocketMessage` on open and each message | Unknown paths return `{ error: "…" }` with status 404. ## Worker supervision health `GET /worker-supervision` returns a `ManagedWorkerSupervisionHealth` object: | Field | Type | Meaning | |---|---|---| | `alive` | `boolean` | `true` when proof is healthy and not stale | | `last_heartbeat_at` | `string` (ISO 8601) | Timestamp of the latest worker run | | `in_flight_jobs` | `number` | Count of jobs still in `queued` or `running` state | | `stale_job_count` | `number` | Count of jobs marked `stale` | | `replay_freshness` | `'fresh' \| 'stale' \| 'degraded'` | Replay output health | | `websocket_connected` | `boolean` | `false` when proof is degraded or stale | ## WebSocket message schema Every `/ws` push and `/graph-snapshot` response is a `ManagedCompanyOsWebSocketMessage`: ```ts { type: 'managed-companyos.graph.snapshot'; tenantId: string; correlationId: string; // links jobs, replay events, and evidence receipt nodeCount: number; edgeCount: number; replayEventCount: number; replayEventIds: readonly string[]; evidenceReceiptId: string; workerJobIds: readonly string[]; workerStatus: 'queued' | 'running' | 'completed' | 'degraded' | 'stale'; degraded: boolean; stale: boolean; idempotentReplay: boolean; // true when the same idempotencyKey was replayed degradedReasons: readonly string[]; } ``` ## WebSocket event stream `projectWorkerWebSocketEvents(proof)` projects the worker proof into an ordered sequence of typed events. All events carry `correlationId` and `sequence`: | Event type | Payload extras | When emitted | |---|---|---| | `job-started` | `jobId`, `kind`, `status: 'queued'` | Each job enters queued state | | `job-progress` | `jobId`, `kind`, `status: 'running'` | Each job transitions to running | | `job-completed` | `jobId`, `kind`, `status: 'completed'`, `degraded: false` | Job succeeds | | `job-failed` | `jobId`, `kind`, `status: 'degraded'\|'stale'`, `degraded: true` | Job fails or goes stale | | `replay-emitted` | `replayEventId` | Each replay event in the proof | | `evidence-issued` | `evidenceReceiptId`, `verificationHash` | Evidence receipt issued | Events are ordered by ascending `sequence` numbers. Degraded proofs emit `job-failed` instead of `job-completed`. ## Worker job inventory | Job kind | Purpose | |---|---| | `integration_sync` | Integration provider sync (side-effect-free until provider approved) | | `replay_generation` | Deterministic replay packet generation from workspace state | | `evidence_generation` | Evidence receipt derivation from replay events; receipt carries `verificationHash` | | `websocket_graph_update` | Publishes graph snapshot to connected WebSocket clients | Job lifecycle: `queued` → `running` → `completed` (healthy) or `degraded` / `stale` (unhealthy). ## Correlation ID contract A single `correlationId` links the entire proof chain: ``` proof.correlationId == each job.correlationId == each WS event.correlationId == each replay event.correlationId == evidenceReceipt.correlationId ``` Validate with `assertManagedWorkerCorrelation(proof)` — returns `{ valid: boolean, reasons: string[] }`. ## Degraded-state detection The runtime surfaces degraded and stale conditions instead of hiding them behind healthy status: | Condition | Trigger | Effect | |---|---|---| | Forced degraded | `?degraded=true` query param | All jobs report `degraded`; supervision `alive: false` | | Stale sync | `nowMs - lastSyncMs > staleAfterMs` | All jobs report `stale`; supervision `stale_job_count = 4`, `replay_freshness: 'stale'` | | Bundle health degraded | Propagated from `@lssm-tech/bundle.managed-companyos` | `degradedReasons` populated; supervision `alive: false` | In future VPS mode, a green API response must not hide a degraded realtime runtime. In the active Vercel-only topology, `/api/companyos/health/degraded` reports API and scheduled snapshot duty health instead of requiring this package. ## Stale-job cleanup and idempotency The deterministic in-memory store (`createDeterministicManagedWorkerStore`) enforces idempotency: - A run with the same `idempotencyKey` returns the cached proof with `idempotentReplay: true`. - Stale jobs are counted and surfaced — they are not silently discarded. - Pass a fresh `idempotencyKey` to force a new run: `GET /graph-snapshot?idempotencyKey=fresh-key-001` ## WebSocket reconnect client ```ts import { connectManagedCompanyOsLiveClientWithReconnect } from './src/live-client'; const proof = await connectManagedCompanyOsLiveClientWithReconnect({ url: 'ws://worker.host/ws?tenantId=tenant_id', maxAttempts: 3, // default: 3 initialBackoffMs: 100, // default: 100ms; doubles each retry (100 → 200 → 400) timeoutMs: 1000, // per-attempt timeout; default: 1000ms }); // proof.connected, proof.attempts, proof.lastBackoffMs, proof.message ``` ## Environment variables | Variable | Default | Purpose | |---|---|---| | `MANAGED_COMPANYOS_WORKER_HOST` | `0.0.0.0` | Bind address for the HTTP/WebSocket server | | `MANAGED_COMPANYOS_WORKER_PORT` | `8787` | Bind port | | `MANAGED_COMPANYOS_DEFAULT_TENANT_ID` | `tenant_managed_companyos_reference` | Fallback tenant when `tenantId` query param is absent | Copy `deploy/env/worker.env.example` to `/etc/managed-companyos/worker.env` and fill values from the secret manager. Never write raw provider credentials to logs, fixtures, or API responses. ## Local commands ```bash bun run --cwd packages/apps/worker-application-monolith dev bun run --cwd packages/apps/worker-application-monolith test bun run --cwd packages/apps/worker-application-monolith typecheck bun run --cwd packages/apps/worker-application-monolith lint:check bun run --cwd packages/apps/worker-application-monolith build ``` Build output: `dist/index.js` (Bun target). Production start: `bun dist/index.js`. ## Integration Points ### WebSocket Client Integration External systems receive real-time graph updates by connecting a WebSocket client to `/ws`: ```typescript import { connectManagedCompanyOsLiveClientWithReconnect } from '@lssm-tech/app.worker-application-monolith/src/live-client'; const proof = await connectManagedCompanyOsLiveClientWithReconnect({ url: 'ws://worker.host/ws?tenantId=tenant_123', maxAttempts: 3, initialBackoffMs: 100, // doubles each retry timeoutMs: 1000 }); // proof.message is ManagedCompanyOsWebSocketMessage // proof.connected indicates success ``` Each message carries a `correlationId` that links to API requests, replay packets, and evidence receipts. ### Health Polling External monitoring can poll worker health via HTTP: ```bash # Instant health snapshot (no stale-job cleanup) curl http://worker.host/health?tenantId=tenant_id # Worker supervision health (includes job/replay/WebSocket metrics) curl http://worker.host/worker-supervision?tenantId=tenant_id # Graph snapshot (deterministic projected state) curl http://worker.host/graph-snapshot?tenantId=tenant_id&idempotencyKey=key_xyz ``` A degraded Bun runtime returns `{ degraded: true, degradedReasons: [...] }` for local/future-VPS monitoring. In the active Vercel-only topology, production readiness is proven by API snapshot routes and Vercel Cron evidence rather than this process. ### MCP Tool Integration For AI agents, the planned `@lssm-tech/app.managed-companyos-mcp` server exposes worker health, job status, replay packet fetching, and evidence verification as MCP tools. Agents can query job state and fetch replay/evidence receipts without holding open a WebSocket connection. ## Correlation ID Guarantees Every worker run produces a `correlationId` that persists across: - Job execution (`job.correlationId`) - WebSocket messages (`ManagedCompanyOsWebSocketMessage.correlationId`) - Replay events (`replayEvent.correlationId`) - Evidence receipts (`evidenceReceipt.correlationId`) Validate the full chain with `assertManagedWorkerCorrelation(proof)` in production health checks. Build output: `dist/index.js` (Bun target). Production start: `bun dist/index.js`. For the full operator runbook (deploy, start/stop, degraded triage, replay regen, evidence verification), see [`docs/runbooks/managed-companyos.md`](../../../../docs/runbooks/managed-companyos.md). --- ## @lssm-tech/app.worker-data-transmission-realtime Description: (none) Path: packages/apps/worker-data-transmission-realtime URL: /llms/app.worker-data-transmission-realtime # `@lssm-tech/app.worker-data-transmission-realtime` Bun WebSocket worker for the Data Transmission CRDT realtime proof. This worker is intentionally ephemeral: no durable production database, no multi-region guarantees, no managed-service SLA, and no Vercel Functions WebSocket hosting. It exists to prove ContractSpec realtime contracts, runtime guardrails, and demo collaboration flow with bounded public-demo controls. --- ## @lssm-tech/example.shim-delete-ci Description: CI test that verifies promoted symbols are importable from canonical locations (B2/B3). When this test passes it is safe to delete the example shims. Path: examples/__tests__ URL: /llms/example.shim-delete-ci (No README.md) --- ## @lssm-tech/example.agent-application-foundation Description: Reference applications showing how to compose durable ContractSpec agents. Path: examples/agent-application-foundation URL: /llms/example.agent-application-foundation # @lssm-tech/example.agent-application-foundation Filesystem-authored reference app for the agent application foundation lane. ## What it demonstrates - Compiling `agent/{instructions.md,agent.ts,tools,skills,connections,sandbox,channels,subagents,schedules}` plus `evals/` with `@lssm-tech/agentpacks/application`. - Running a credential-free orchestrator-plus-verifier eval against a single-agent baseline with `@lssm-tech/lib.agent-evals/runner`. - Executing the CommunicationOS-shaped `draft → approval wait → send → receipt` lifecycle, including an exactly-once replay proof for the side effect. - Exercising the local development sandbox honestly: network allowlist claims are rejected and durable artifacts are extracted and reloaded without making an isolation claim. - Composing the EVE adapter with the independently conformance-tested production `DockerAgentSandbox`, while keeping the native EVE sandbox's narrower losses explicit. - Exercising both public adapter targets: Workflow DevKit plus EVE, with replay, cost, latency, and redaction evidence without serializing secrets. - Composing credential-free enterprise topology choices for Vercel + Supabase, Railway + Supabase, Vercel + Railway + Supabase, and Docker isolation while preserving provider roles, unresolved operator requirements, and candidate-only qualification truth. ## Enterprise topology example Import `composeReferenceAgentPlatform` from `@lssm-tech/example.agent-application-foundation/enterprise-platform`. The returned plan includes explicit enterprise controls and a qualification report; it remains a candidate until the consumer supplies and passes live suites for the exact environment. ## All-in-one agents The package includes two credential-free product scenarios in addition to the low-level reference fixture. ### Autonomous Release Steward Mission: keep a consumer codebase compatible with external APIs and dependencies by producing safe, verified, human-approved migration pull requests. ```bash bun run example:release-steward ``` Import `runReleaseStewardExample` and `RELEASE_STEWARD_STAGE_IDS` from `@lssm-tech/example.agent-application-foundation/release-steward`. The result includes the immutable source digest, affected usages, isolated subagent evidence, digest-bound approval, exactly-once patch receipt, CI and draft-PR evidence, durable worker and governed-improvement evidence, deployment composition, and `candidateReadiness`. It never auto-merges. The filesystem source is also a Protocol V1 application with the stable installation ID `release-steward`. `signReleaseStewardApplicationV1` accepts an injected signer so private key material stays in the caller's KMS/HSM or signing service. Local examples remain unsigned unless the caller explicitly composes that port; a test key never qualifies a production installation. ### Company Intelligence Scout Mission: continuously build source-cited company, offering, mission, goal, location, job, professional-person, and eligible public-contact intelligence. ```bash bun run example:company-intelligence-scout ``` Import `runCompanyIntelligenceScoutExample` from `@lssm-tech/example.agent-application-foundation/company-intelligence-scout`. Fixture mode reads only committed content and performs no network request or outreach. The default autonomy mode is `draft-only`; retained person/contact records expire after at most 30 days. Live discovery, fetching, rendering, suppression, and outreach require explicit policy and consumer-supplied ports: ```bash bun run example:company-intelligence-scout:live -- \ --policy ./company-scout.policy.json \ --ports-module ./company-scout.ports.ts \ --seed-url https://allowed-company.example ``` Publicly visible personal data is not unrestricted data. Consumers own purpose, lawful basis, transparency, rights, suppression, deletion, jurisdictional requirements, and live provider qualification. Automated hiring decisions, candidate rejection, job applications, protected-trait inference, and sensitive-data enrichment stay outside the example. Start with the public [Agent Ecosystem guide](https://www.contractspec.io/docs/agents), then use the repository [enterprise agent platform guide](../../docs/tutorials/enterprise-agent-platform.md) for the complete copy-ready source. Both cover multiplayer, governed improvement, continuous loops, self-maintaining APIs, provider composition, and production qualification. ## Local commands - `bun run build` - `bun run typecheck` - `bun run test` - `bun run preflight` - `bun run example:release-steward` - `bun run example:company-intelligence-scout` --- ## @lssm-tech/example.agent-console Description: Agent Console example - AI agent orchestration with tools, runs, and logs Path: examples/agent-console URL: /llms/example.agent-console # @lssm-tech/example.agent-console Website: https://contractspec.io **Agent Console example - AI agent orchestration with tools, runs, and logs.** ## What This Demonstrates - **Rich Landing Screen**: Product introduction explaining agent management concepts, demo path, and navigation. - **Navigation Rail**: Clear sidebar navigation between Overview, Agent Fleet, Tool Registry, Run History, Metrics, and Proof. - **Agent Entity**: Full lifecycle management with status tracking (draft, active, paused, retired). - **Run Tracking**: Event-driven execution with status enums and state transitions. - **Tool Registry**: Typed schemas and operation handlers for agent capabilities. - **Contract-Backed Visualizations**: Charts and metrics derived from run activity. - **Deterministic Replay**: Offline-safe demo runtime with proof evidence. - **Presentation Layer**: React UI components, hooks, modals, overlays, and DataTable for run history. - **Multi-Surface Output**: Markdown and React renderers for different contexts. - **Seeded Local Data**: Mock agents, tools, and runs for immediate demo usage. ## Canonical Demo Path - Default sandbox route: `/sandbox` - Explicit sandbox route: `/sandbox?template=agent-console` - Proof artifact: `examples/agent-console/proofs/agent-console-meetup.replay.json` The canonical walkthrough is deterministic and local-first: 1. **Landing Screen** - Start on the product introduction explaining agent management concepts. 2. **Navigation** - Use the sidebar rail to navigate between sections. 3. **Agent Fleet** - Inspect seeded agents (Customer Support Bot, Code Review Assistant, Data Analyst, Meeting Scheduler). 4. **Tool Registry** - Browse available tools and their schemas. 5. **Run History** - View execution history with status and metrics. 6. **Metrics** - See contract-backed visualizations of run activity. 7. **Proof** - Inspect deterministic replay evidence. ### New Features - **LandingScreen**: Product-style introduction with value proposition and demo path. - **AgentConsolePreviewV2**: Enhanced preview with sidebar navigation and dedicated screens. - **AgentConsoleNav**: Navigation rail for moving between sections. - **Navigation**: Clear paths from landing to specific agent, tool, and run views. ## Runtime Boundaries - React hooks and the sandbox use `createAgentConsoleDemoHandlers(...)` for the meetup path. - Markdown renderers prefer runtime-fetched data and fall back to the same deterministic demo handlers. - The demo runtime is intentionally mocked and offline-safe by default. - Database-backed `createAgentHandlers(db)` remains available for non-demo runtime wiring. ## Running Locally From `examples/agent-console`: - `bun run dev` - `bun run build` - `bun run test` - `bun run proof` - `bun run typecheck` - `bun run preflight` From the repository root: - `bun run meetup:agent-console:policy` - `bun run meetup:agent-console:proof` - `bun run meetup:agent-console:preflight` ## Usage Use `@lssm-tech/example.agent-console` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/agent` is part of the package's public or composition surface. - `src/agent.capability.ts` defines a capability surface. - `src/agent.feature.ts` defines a feature entrypoint. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/proof/` contains the exported meetup proof scenario and suite. - `src/ui/AgentConsolePreview.tsx` is the cross-platform preview component used by web and mobile example surfaces. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./agent` resolves through `./src/agent/index.ts`. - Export `./agent.capability` resolves through `./src/agent.capability.ts`. - Export `./agent.feature` resolves through `./src/agent.feature.ts`. - Export `./agent/agent.entity` resolves through `./src/agent/agent.entity.ts`. - Export `./agent/agent.enum` resolves through `./src/agent/agent.enum.ts`. - Export `./agent/agent.event` resolves through `./src/agent/agent.event.ts`. - Export `./agent/agent.handler` resolves through `./src/agent/agent.handler.ts`. - Export `./agent/agent.operation` resolves through `./src/agent/agent.operation.ts`. - Export `./agent/agent.presentation` resolves through `./src/agent/agent.presentation.ts`. - Export `./proof` resolves through `./src/proof/index.ts`. - Export `./proof/meetup-proof.scenario` resolves through `./src/proof/meetup-proof.scenario.ts`. - Export `./proof/meetup-proof.suite` resolves through `./src/proof/meetup-proof.suite.ts`. - The package publishes 72 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `bun run test` — bun test - `bun run proof` — bun ../../scripts/generate-agent-console-meetup-proof.ts - `bun run preflight` — bun run build && bun run typecheck && bun run test && bun ../../scripts/check-agent-console-meetup-policy.ts && bun run proof - `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 - Unified the meetup demo around a single seeded runtime. - Added focused handler tests, a sandbox smoke test, and a harness replay proof. - Added a slice-scoped meetup preflight instead of relying on the repo-wide policy backlog. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.runtime-sandbox`, `@lssm-tech/lib.schema`, ... --- ## @lssm-tech/example.agent-workflow-command-center Description: Agent Workflow Command Center - All-in-one operator cockpit for supervised AI agents in business workflows Path: examples/agent-workflow-command-center URL: /llms/example.agent-workflow-command-center # @lssm-tech/example.agent-workflow-command-center Website: https://contractspec.io **Agent Workflow Command Center - All-in-one operator cockpit for supervised AI agents in business workflows.** ## What This Demonstrates Agent Workflow Command Center is a ContractSpec example for operating supervised AI agents inside business workflows. It combines: - **Agent Management:** Fleet overview, configuration, tool permissions, lifecycle controls - **Workflow Orchestration:** State-machine workflows with agent assignments - **Human Review:** Review queue with approve/reject/escalate actions - **Governance:** Tool policies, risk thresholds, blocked actions - **Audit Trail:** Complete event timeline with deterministic evidence - **ROI & Handover:** Adoption metrics and handover readiness checklist ## Business Scenario A PME industrielle (85 employees) undergoing finance transformation: - Finance team under pressure with RAF departure - Cash tension and reporting delays - Fragmented Excel/BI tooling - Weak or outdated finance procedures NDconsulting installs supervised AI-assisted workflows and helps the client operate the system after handover. ## Core Demo Message "ContractSpec delivers a controllable operating system where the client team can: - Manage agents and assign them to workflows - Review AI-generated outputs before operational use - Enforce governance policies and block risky actions - Inspect audit logs and track adoption/ROI - Prove what happened through deterministic evidence" ## Included Agents 1. **Cash Aging Agent** - Prioritizes receivables follow-up using deterministic aging rules 2. **Reporting Narrative Agent** - Drafts reporting commentary with variance analysis 3. **Procedure Draft Agent** - Structures finance procedures with roles and controls 4. **Mission Intake Agent** - Triages transformation requests and classifies urgency 5. **AI Adoption Coach** - Tracks use cases and ROI without employee surveillance ## Workflows 1. **Cash Recovery Prioritization** - Intake → Agent Analysis → Human Review → Approved/Changes Requested 2. **Monthly Reporting Narrative** - Data Input → Narrative Draft → Variance Review → Finalization 3. **Finance Procedure Drafting** - Request → Procedure Structure → Control Review → Publication 4. **Mission Intake Triage** - Request → Classification → Priority Assignment → Follow-up 5. **AI Adoption / ROI Logging** - Usage Event → Impact Calculation → Trend Analysis ## Canonical Demo Path 1. Open `/sandbox?template=agent-workflow-command-center` 2. Start on the Landing screen - understand the value proposition 3. Enter the Command Center Overview - see active agents and workflows 4. Inspect the Cash Aging Agent - review allowed tools and governance 5. Open the Cash Recovery workflow - see state machine 6. Assign the Cash Aging Agent to the workflow 7. Trigger a deterministic agent run 8. Inspect run logs and emitted events 9. Open the review queue 10. Approve one recommendation, request changes on another 11. Show workflow state transition 12. Simulate a high-risk tool call - show it's blocked 13. Pause an agent, then resume after policy review 14. Open ROI & Handover - generate checklist 15. Export or display replay/audit proof ## Replay Proof The `./proof` export now exposes a deterministic replay contract for the canonical Managed CompanyOS journey: - `happyPath`: create/configure a synthetic agent, assign a deterministic tool, compose a review-gated workflow, dispatch a simulator run, submit human approval, and inspect audit replay evidence. - `blockedPath`: request a high-risk external tool and attempt a run with that blocked tool; both events must stay authorization-required with no external side effect. - `managedCompanyOsRouteRefs`: documents app-relative `pillarRoute` values and host-prefixed `hostRoute` values for agent, tool, and workflow managed surfaces without importing the managed bundle at runtime. - `atomicCrudCoverage`: proves the example covers tool, agent, and workflow list/create/update/detail expectations plus loading, empty, error, denied, read-only, allowed, dirty-invalid, review-required, and blocked states. - `assertCommandCenterReplayProof()` validates stable audit event IDs, evidence refs, correlation IDs, a human-review gate, a blocked path, and redacted/synthetic-only proof metadata. ## Tool Management Loop The command-center preview includes a Tools surface that demonstrates the full controlled loop: create/edit/archive deterministic tools, inspect governance readiness, assign tools to demo agents or host-owned workflow projections, and simulate calls with audit/replay evidence. The demo uses `@lssm-tech/module.agent-fleet` reusable presentation contracts with local state only; it performs no provider, network, backend, ERP, email, payment, or secret-storage side effects. ## Safety Boundaries - All agent outputs require human review before operational use - No real emails, payment instructions, or accounting entries sent - No connection to live finance systems - Synthetic fixtures only - no real client or financial data - Deterministic and offline-safe - Drafts/recommendations only, not operational commands - Tracks workflow ROI, not intrusive employee surveillance ## Core Entities - **AgentProfile** - Agent configuration, status, autonomy level, allowed tools - **WorkflowTemplate** - Workflow definitions with steps and transitions - **WorkflowInstance** - Running workflow with current state and assignments - **AgentAssignment** - Links agents to workflow steps - **AgentRun** - Execution record with inputs, outputs, events - **HumanReview** - Review queue with decisions and feedback - **ToolPolicy** - Governance rules for tool usage - **AuditEvent** - Immutable event log - **AdoptionMetric** - ROI and usage tracking ## Public Entry Points - Export `.` resolves through `./src/index.ts` - Export `./agent` resolves through `./src/agent/index.ts` - Export `./workflow` resolves through `./src/workflow/index.ts` - Export `./review` resolves through `./src/review/index.ts` - Export `./governance` resolves through `./src/governance/index.ts` - Export `./fixtures` resolves through `./src/fixtures/index.ts` - Export `./proof` resolves through `./src/proof/index.ts` - Export `./ui` resolves through `./src/ui/index.ts` - Export `./example` resolves through `./src/example.ts` - Export `./docs` resolves through `./src/docs/index.ts` ## Code Quality Review Review date: 2026-05-20. - The example package exposes deterministic domain, fixture, proof, UI, example, and docs surfaces; the root export also re-exports `./docs` for consumers that import the aggregate package. - Preview screens render from static PME finance fixtures and do not call live LLM, ERP, CRM, BI, email, payment, or accounting systems. Provider names in the fixture are labels only. - Governance and human-review screens are part of the default demo path, so supervised operation is visible before ROI or handover claims. - Replay proof stays under `src/proof/` and should be extended with any new workflow path before release. ## Production readiness evidence Use [`docs/agent-workflow-command-center-production-readiness.md`](../../docs/agent-workflow-command-center-production-readiness.md) as the release-facing checklist for the boil-lake command-center slice. It defines the promotion gates, verification command matrix, redaction/import-boundary proof, replay determinism evidence, and authority gates that must be attached before claiming production readiness. ## Validation Checklist Before publishing changes to this template, run from `examples/agent-workflow-command-center`: 1. `bun run lint:check` - package lint and formatting gate 2. `bun run typecheck` - public TypeScript entrypoint validation, including `./docs` 3. `bun run test` - preview shell, adaptive agent-fleet DataView tests, and `AgentFleetScreen` EntityWorkspace behaviour tests (search, filters, detail actions, create/edit/clone/delete, bulk pause, agents-prop reconciliation) 4. Open `/sandbox?template=agent-workflow-command-center` and follow the canonical demo path ## Local Commands - `bun run dev` - Development build - `bun run build` - Production build - `bun run test` - Run tests - `bun run typecheck` - TypeScript check - `bun run lint` - Lint and fix - `bun run preflight` - Full validation ## Architecture - `src/agent/` - Agent profile domain - `src/workflow/` - Workflow template and instance domain - `src/review/` - Human review domain - `src/governance/` - Tool policies and governance - `src/fixtures/` - Synthetic demo data - `src/proof/` - Replay evidence - `src/ui/` - Preview components and screens ## Notes Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.schema`. ### Tool Effects The Tools screen demonstrates typed tool effects: `contract_effect` entries select a ContractSpec operation, and `integration_effect` entries select an already-integrated provider catalog item. The example validates and simulates effects deterministically by default. Real execution is represented as an explicit adapter boundary so the template stays secret-free and provider/network-free unless a host wires an adapter deliberately. ### Tool Effect Workbench The Tools screen now demonstrates a decision-quality operation workbench for tool effects. Operators can inspect richer ContractSpec and integration-call fixtures, compare candidates, configure input mappings, validate readiness, and simulate deterministically before saving. Real execution remains an explicit host-adapter boundary so the example stays provider-free, backend-free, and secret-free by default. --- ## @lssm-tech/example.ai-chat-assistant Description: Focused AI chat assistant template with MCP tools, reasoning, chain of thought, sources, and suggestions. Path: examples/ai-chat-assistant URL: /llms/example.ai-chat-assistant # @lssm-tech/example.ai-chat-assistant Website: https://contractspec.io **Focused AI chat assistant example with MCP tools, reasoning, sources, suggestions, and reusable dashboard UI.** ## What This Demonstrates - Demonstrates how `@lssm-tech/module.ai-chat` can power a focused assistant experience. - Publishes feature, contracts, handlers, docs, example, and dashboard UI entrypoints. - Provides a search-backed, source-aware assistant template for example consumers and docs. - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/ai-chat-assistant`: - `bun run dev` - `bun run build` - `bun run test` - `bun run smoke` - `bun run typecheck` ## Usage Use `@lssm-tech/example.ai-chat-assistant` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/ai-chat-assistant.feature.ts` defines the example feature surface. - `src/contracts/` contains the assistant operation contract exports. - `src/handlers/` contains the demo assistant handlers wired to the example feature. - `src/ui/` contains the packaged dashboard UI for embedding or demonstration. - `src/docs/` and `src/example.ts` provide docblock and runnable example entrypoints. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Exports the feature surface, contract barrels, handlers, docs entrypoints, runnable example, and dashboard UI. - Export `.` resolves through `./src/index.ts`. - Export `./ai-chat-assistant.feature` resolves through `./src/ai-chat-assistant.feature.ts`. - Export `./contracts` resolves through `./src/contracts/index.ts`. - Export `./contracts/assistant.operation` resolves through `./src/contracts/assistant.operation.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/ai-chat-assistant.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./handlers/assistant.handlers` resolves through `./src/handlers/assistant.handlers.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - The package publishes 11 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `bun run test` — bun test - `bun run smoke` — bun test src/example.smoke.test.ts - `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` — 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. - Stability. - Vnext ai-native. ## Notes - Works alongside `@lssm-tech/lib.ai-agent`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/module.ai-chat`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.ai-support-bot Description: AI support bot example: classify and resolve a support ticket using @lssm-tech/lib.support-bot. Path: examples/ai-support-bot URL: /llms/example.ai-support-bot # @lssm-tech/example.ai-support-bot Website: https://contractspec.io **AI support bot example: classify and resolve a support ticket using @lssm-tech/lib.support-bot.** ## What This Demonstrates - Ticket classification pipeline with AI-driven resolution. - Integration of support-bot lib with knowledge base. - DocBlock documentation for in-app help. - Setup and example entry points for quick cloning. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/ai-support-bot`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.ai-support-bot` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/ai-support-bot.feature.ts` defines a feature entrypoint. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/setup.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./ai-support-bot.feature` resolves through `./src/ai-support-bot.feature.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/ai-support-bot.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./setup` resolves through `./src/setup.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.knowledge`, `@lssm-tech/lib.logger`, `@lssm-tech/lib.support-bot`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.analytics-dashboard Description: Analytics Dashboard example with widgets and query engine for ContractSpec Path: examples/analytics-dashboard URL: /llms/example.analytics-dashboard # @lssm-tech/example.analytics-dashboard Website: https://contractspec.io **Analytics Dashboard example with widgets and query engine for ContractSpec.** ## What This Demonstrates - Dashboard feature with presentation, schema, enum, and test-spec. - Query engine with typed operations and handlers. - PostHog datasource adapter. - React UI with hooks, renderers, markdown output, and a shared ContractSpec `DataTable` for saved queries. - Client-mode table capabilities including sorting, pagination, column visibility, column resizing, pinning, and expandable row details. - Event definitions for analytics tracking. - Seeders for demo data. ## Running Locally From `examples/analytics-dashboard`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` - `bun run preflight` ## Usage Use `@lssm-tech/example.analytics-dashboard` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/dashboard` is part of the package's public or composition surface. - `src/dashboard.feature.ts` defines a feature entrypoint. - `src/datasource` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./dashboard` resolves through `./src/dashboard/index.ts`. - Export `./dashboard.feature` resolves through `./src/dashboard.feature.ts`. - Export `./dashboard/dashboard.enum` resolves through `./src/dashboard/dashboard.enum.ts`. - Export `./dashboard/dashboard.operation` resolves through `./src/dashboard/dashboard.operation.ts`. - Export `./dashboard/dashboard.presentation` resolves through `./src/dashboard/dashboard.presentation.ts`. - Export `./dashboard/dashboard.schema` resolves through `./src/dashboard/dashboard.schema.ts`. - Export `./dashboard/dashboard.test-spec` resolves through `./src/dashboard/dashboard.test-spec.ts`. - Export `./datasource/posthog-datasource` resolves through `./src/datasource/posthog-datasource.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - The package publishes 37 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 preflight` — bun run build && bun run typecheck && bun run test - `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 data visualization capabilities. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.runtime-sandbox`, ... --- ## @lssm-tech/example.app-submission-readiness-mobile-proof Description: Deterministic ReviewReady proof that audits the real brownfield Expo app packages/apps/mobile-monolith. Path: examples/app-submission-readiness-mobile-proof URL: /llms/example.app-submission-readiness-mobile-proof # @lssm-tech/example.app-submission-readiness-mobile-proof Deterministic ReviewReady proof that audits the **real** Expo app at `packages/apps/mobile-monolith` and emits a stable readiness report. This proves ReviewReady works on a real brownfield mobile app, not a toy fixture: the proof **reads and parses the actual mobile-monolith source files from disk** at run time, maps them into the runtime's audit input, and runs `@lssm-tech/lib.app-submission-readiness-runtime`. If the real app config changes, the parsers pick it up and the inline expected values in the test will catch the drift. ## Real files it reads `parse-mobile-monolith.ts` reads these files via `node:fs` (no Expo execution, no mutation): | Source file | Parsed signal | | --- | --- | | `app.config.js` | app name `ContractSpec`, version `0.1.1`, native identifiers, legal URLs, encryption posture, and Expo `ios.privacyManifests` | | `eas.json` | credential-free `submit.production` posture | | `assets/{icon,adaptive-icon,splash-icon}.png` | asset presence detection | The Expo config is parsed as source text without executing the application or requiring generated native projects. ## Honest gaps surface as findings Declared-in-repo items are `pass`; genuinely absent submission materials become real findings: - `legal.account-deletion` — no account-deletion URL in the Expo config. - `assets.screenshots.store` — `assets/` holds only icon/adaptive-icon/splash. - `review.google.dataSafety` — no Google Play Data Safety answers in repo. ## Deterministic outcome Fixed `checkedAt = 2026-06-07T00:00:00.000Z`, fixed ids, no `Date.now()` / `Math.random()`. Current real audit outcome: - decision: `blocked` - score: `60` - findings: `3` - stores: `apple-app-store`, `google-play` (`store: "both"`) ## Usage ```ts import { buildMobileMonolithReadinessReport, describeMobileMonolithProof, } from "@lssm-tech/example.app-submission-readiness-mobile-proof"; console.log(describeMobileMonolithProof()); const { report } = buildMobileMonolithReadinessReport(); console.log(report.decision, report.score); ``` ## Verify ```bash cd examples/app-submission-readiness-mobile-proof tsgo --noEmit bun test ``` The proof asserts: real parsed values, real findings for absent materials, deterministic deep-equality across two runs, no secret-like strings in the serialized report, and inline expected decision/score/finding ids. --- ## @lssm-tech/example.authos-command-center Description: Rich AuthOS command center template for identity, MFA, organizations, Better Auth bridge planning, and Connect with LSSM. Path: examples/authos-command-center URL: /llms/example.authos-command-center # AuthOS Command Center Rich ContractSpec example for AuthOS capabilities: identity, sign-in, MFA, OTP, phone/profile/security settings, organization/team/admin, Better Auth bridge planning, and Connect with LSSM account linking. The example is deterministic and credential-free. It composes AuthOS contracts, runtime projections, the Better Auth bridge, and the reusable AuthOS module; it does not implement a bespoke authentication engine. ```bash bun run preflight ``` --- ## @lssm-tech/example.authos-user-relation-graph Description: Entity-relation graph example built on Layer-2 defineContractEntity + defineContractEdge — RBAC structure (User ↔ Role ↔ Resource) Path: examples/authos-user-relation-graph URL: /llms/example.authos-user-relation-graph # @lssm-tech/example.authos-user-relation-graph **Entity-relation graph example built on Layer-2 `defineContractEntity` + `defineContractEdge`. Models an RBAC structure: User ↔ Role ↔ Resource.** ## What This Demonstrates - Defining a `DataViewGraphSpec` with an `entity-declarative` graph source. - Using `defineContractEntity` and `defineContractEdge` to describe nodes and edge types. - Modeling a simple RBAC graph: User → has Role → grants access to Resource. ## Running Locally From `examples/authos-user-relation-graph`: ```bash bun run typecheck ``` ## Architecture - `src/index.ts` — root public barrel and package entrypoint. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`. - Blocked on P1-RECON/B (Layer-2 `defineContractEntity`). Full `DataViewGraphSpec` export lands in task P5/W5.C. --- ## @lssm-tech/example.billingos-france-sme Description: Smallest BillingOS French SME quote-to-cash replay proof without providers or production PA submission. Path: examples/billingos-france-sme URL: /llms/example.billingos-france-sme # BillingOS V0 package Additive BillingOS V0 surface. Core contracts stay country-neutral; France-specific readiness lives only in `@lssm-tech/lib.billing-france`. Runtime helpers are deterministic, backend-neutral, provider-free, and do not execute high-impact billing actions. France readiness metadata is not PA accreditation, production PA submission, legal advice, or tax advice. ## CompanyOS module proof The example exports `./companyos` as a first-class CompanyOS V1 operating-loop composition for BillingOS France SME. It models finance-owner authority, draft/dry-run-only agent operations, operator inbox routing, work graph hooks, and weekly review evidence around the replayed quote -> invoice -> payment -> France readiness path. Production invoice submission and France e-invoicing submission stay approval-gated; the module contains no provider credentials, network calls, or autonomous high-impact execution. ## Preview / export workflow BillingOS France SME previews must stay deterministic, backend-neutral, provider-free, and approval-gated. The current `./ui` export wraps local quote-to-invoice, payment/reconciliation, France readiness, and CompanyOS approval-packet screens in the shared `NestedCommandShell` from `@lssm-tech/lib.example-shared-ui`; keep that reusable nested-safe shell as the outer preview frame for compatible BillingOS UI work. Preview screens must not introduce production PA submission, provider credentials, payment processing, legal/tax advice, or autonomous high-impact billing execution. Keep the France readiness pack as metadata and replay proof only. Preview docs, release notes, and `/llms*` guidance must repeat that the package is not PA accreditation and does not execute production e-invoicing. ## Data-fetching engine integration `src/proof/data-fetching-integration.test.ts` proves BillingOS drives the canonical data-fetching engine (`@lssm-tech/lib.contracts-runtime-core` + `@lssm-tech/lib.contracts-runtime-server-rest`) end-to-end without weakening the safety model. All engine wiring lives in that `.test.ts` harness on purpose: the production example files must stay free of `fetch(`/`process.env`/credential literals (enforced by `safety.test.ts`), so the proof uses the real `createRestTransport` driven by an in-memory `fetch` double — deterministic, provider-free, no network. The proof asserts: the `QueryResultEnvelope` read path (no `422`); one admitted draft mutation via `submitBillingMutation`; the admission gate parametrized over the **entire** `BillingActionKind` union (only `read`/`draft_quote`/`draft_invoice` reach `engine.mutate`; all 11 approval-gated kinds fail closed to a `pending approval` operator-review with no optimistic write); server-wins conflict rollback (never a silent overwrite); and offline queue-then-replay on reconnect. Two decisions are load-bearing and documented in [`specs/billingos-consumer-guide/09-data-fetching-integration.md`](../../specs/billingos-consumer-guide/09-data-fetching-integration.md): **draft writes carry no `versionToken` this pass** (the event-log `version` is never mapped to the engine etag), and **pending-approval is not an optimistic / read-your-writes state** (approval-gated actions perform no local write). Production hosts inject a real `Transport`; the example never executes providers or production PA submission. ## UI boundary The preview UI is intentionally thin. It adapts the French SME fixture data into reusable workspaces from `@lssm-tech/module.billing-os/ui`, including quote creation/editing, invoice review, payment reconciliation, France readiness, and CompanyOS review screens. Example-local UI should stay limited to data mapping and preview shell wiring. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. Full `build` regenerates JavaScript and declarations in one output transaction, restoring previous `dist` if either stage fails. Standalone `build:bundle` still preserves declarations; use full `build` to reconcile obsolete output layouts. --- ## @lssm-tech/example.calendar-google Description: Google Calendar integration example: list and create events. Path: examples/calendar-google URL: /llms/example.calendar-google # @lssm-tech/example.calendar-google Website: https://contractspec.io **Google Calendar integration example: list and create events.** ## What This Demonstrates - OAuth-based Google Calendar API wiring. - Event listing and creation flows. - Sync logic for calendar data. - Integration provider pattern with ContractSpec contracts. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/calendar-google`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.calendar-google` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/calendar-google.feature.ts` defines a feature entrypoint. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/run.ts` is part of the package's public or composition surface. - `src/sync.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./calendar-google.feature` resolves through `./src/calendar-google.feature.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/calendar-google.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./run` resolves through `./src/run.ts`. - Export `./sync` resolves through `./src/sync.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-calendar`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.communication-os Description: Standalone CommunicationOS examples, fixtures, and replay proof for external adopter flows. Path: examples/communication-os URL: /llms/example.communication-os # @lssm-tech/example.communication-os Standalone CommunicationOS examples, fixtures, replay proof, and composition adapters. This package consumes public CommunicationOS surfaces as an adopter would, keeps example data out of the module package, and imports reusable UI from `@lssm-tech/module.communication-os/ui`. ## Entry Points - `.` - `./docs` - `./example` - `./examples` - `./fixtures` - `./proof` - `./contracts` - `./handlers` - `./ui` - `./ui/CommunicationOsPreview` - `./ui/communication-os-preview.data` - `./ui/communication-os.types` - `./communication-os.feature` ## Preview / export workflow CommunicationOS preview work must keep this package as the source of truth for example fixtures and replay proof. Public preview discovery requires compatible `./example`, `./docs`, `./examples`, `./fixtures`, and `./proof` publish exports before an inline `./ui` surface can be generated. `./ui` is a thin example adapter: it builds deterministic local communication fixture data and passes it into `@lssm-tech/module.communication-os/ui`. Adapter tests assert that actions/drafts remain review-gated and fixture-owned. Do not duplicate reusable screen components here and do not move example data back into the module package. The adapter also mounts the CommunicationOS translation catalog, because the reusable module UI reads its copy through `useI18n` and never mounts a provider. It follows the host's active locale (en, fr, es) and falls back to the host translator for keys it does not own, so the preview shows real copy instead of `commOs.*` keys in any host. Once the preview has mounted on the client, its root carries `data-communication-os-preview-ready="true"`; hosts and browser tests wait for it before interacting. The Compose policy ribbon evaluates the draft body 300 ms after the last edit and evaluates each body once. The replay proof also covers command-inbox fail-closed behavior: blocked send commands become persisted inbox evidence with no outbound message, provider call, credential access, shell execution, or external mutation. ## Operation keys Contracts use the canonical `communication.*` keys. The 23 keys renamed from `communicationOs.*` stay resolvable as `meta.aliases`: `OperationSpecRegistry.get('communicationOs.inbox.list')` returns the `communication.inbox.list` operation and its bound handler. Each operation is registered once under its canonical key, and the MCP manifest lists canonical keys only. Move direct callers to `communication.*`. ## Commands - `bun run test` - `bun run typecheck` - `bun run build` - `bun run lint:check` ## VoiceOps fixture integration This example now carries a `voiceSignal` summary through the reusable CommunicationOS module UI. The fixture models the Rivage Retail voice escalation from the hackathon proof as CommunicationOS evidence first: redacted source text, blocked customer-promise language, and a receipt reference. The example still imports only public module surfaces and remains provider-free. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. Full `build` regenerates JavaScript and declarations in one output transaction, restoring previous `dist` if either stage fails. Standalone `build:bundle` still preserves declarations; use full `build` to reconcile obsolete output layouts. --- ## @lssm-tech/example.companyos-ai-os-proofs Description: CompanyOS AI OS deterministic sandbox proofs for generic, EngineeringOS, support-to-product, and Incident Brain scenarios. Path: examples/companyos-ai-os-proofs URL: /llms/example.companyos-ai-os-proofs # CompanyOS AI OS Proofs Deterministic sandbox proofs for the CompanyOS operating graph. This package demonstrates one claim: > CompanyOS turns messy company workflows into a permissioned operating graph where AI and humans can inspect, approve, replay, and prove work across multiple workflows. The demo is local, deterministic, provider-free, credential-free, and side-effect-free. It does not call AI providers, send network requests, load credentials, or write to production systems. ## Canonical demo flow The primary UI export is `CompanyOsAiOsProofsPreview` from `@lssm-tech/example.companyos-ai-os-proofs/ui`. It follows exactly six top-level steps: 1. **Executive Story** — explains the proof in one sentence. 2. **Scenario Workbench** — selects the default `support-to-product` workflow and inspects the raw messy signal. 3. **Operating Graph** — shows explicit signals, actors, capabilities, policies, approvals, evidence, and graph edges. 4. **Permission + Redaction** — proves unsafe agent actions are blocked, sensitive data is redacted, and PM approval is required where needed. 5. **Replay** — replays the deterministic run with timeline events, state diffs, graph diffs, blocked actions, redactions, approvals, correction replay, and stale/conflict fail-closed checks. 6. **Evidence Receipt** — exports structured JSON proving what happened, including runbook selection/compilation and outcome attribution. Do not add dashboards, settings, onboarding, or extra top-level proof steps to this flow. ## Default proof scenario The fully wired scenario is **Support-to-Product**: > A customer support signal becomes a product gap. The agent selects and compiles a dry-run runbook, CompanyOS queries a permissioned graph view, redacts sensitive data, fails closed on stale/conflicting write paths, requires PM approval, replays the corrected path, attributes the outcome, and exports a receipt. Canonical metadata: | Field | Value | | --- | --- | | Run ID | `run_support_to_product_001` | | Receipt ID | `receipt_support_to_product_001` | | Scenario | `support-to-product` | | Graph schema | `companyos.graph.v0` | | Proof version | `ai-os-proof.v0.1.0` | | Sandbox mode | `true` | | External calls | `false` | | Production writes | `false` | Other scenario previews may exist for comparison, but `support-to-product` is the canonical end-to-end proof path. ## What the receipt proves The Evidence Receipt is derived from the same deterministic replay events used by Step 5. It includes: - run and scenario metadata - graph nodes and edges created - actors involved - permissions checked, including permissioned graph query results - data redactions applied - selected and compiled dry-run runbook - stale/conflict fail-closed checks - allowed and blocked actions - approval gates still pending - correction replay state changes - outcome attribution from support signal through approval to product gap - verification metadata, including event count and replay path The receipt intentionally does **not** prove production integration, real customer usage, external provider execution, or legal compliance certification. ## Safety and trust boundaries User-facing copy should consistently make these boundaries clear: - Deterministic sandbox - No provider calls - No credentials - No production writes - Replayable run - Evidence receipt - Blocked by policy - Redacted before agent access - Requires PM approval - Stale runbooks stay blocked Avoid user-facing copy such as “fake adapters”, “AI agent magic”, “trust me”, or unqualified production claims. ## Package surfaces Important source areas: - `src/shared-core.ts` — shared deterministic proof-building primitives. - `src/scenarios/*` — scenario-level proofs using the shared core. - `src/ui/CompanyOsAiOsProofsPreview.tsx` — demo shell. - `src/ui/proof-app.navigation.ts` — canonical six-step navigation. - `src/ui/support-to-product-proof.data.ts` — shared canonical proof data. - `src/ui/support-to-product-replay.data.ts` — deterministic replay events. - `src/ui/proof-app.receipts.ts` — receipt derivation from replay events. ## Local commands Run from `examples/companyos-ai-os-proofs`: ```bash bun run lint:check bun run typecheck bun run test bun run build:bundle ``` Use `bun run build` when type artifact generation is needed for release validation. Published browser conditions select the emitted browser artifacts alongside existing Node/Bun/type targets. Export keys and source behavior are preserved; this packaging metadata does not activate providers or grant execution authority. --- ## @lssm-tech/example.companyos-ai-solutions-engineer-poc Description: Deterministic provider-free CompanyOS request-to-verified-proof example with explicit approvals and loopback-only evidence. Path: examples/companyos-ai-solutions-engineer-poc URL: /llms/example.companyos-ai-solutions-engineer-poc # Request to Verified Proof Experimental CompanyOS example that turns a fixed enterprise request into a reviewed Outcome Pack, curated capability map, one approval-bound loopback mutation, exact structured read-back, and replayable technical evidence. ## Current architecture The package version is `2.0.1`. Its browser-safe exports are listed below; the Node/Bun-only execution graph stays behind `./runtime` and `./runtime/server`. The current path is: 1. `RequestToVerifiedProofPreview` renders the single adaptive **Understand → Shape → Match → Bound → Verify** journey. 2. Without host composition, it uses `createPreparedDemoRuntime`: prepared analysis and the committed recording remain available, while live browser execution is reported unavailable. 3. `@lssm-tech/module.examples` resolves the package preview generically. Its `ExamplePreviewOverridesProvider` lets an application replace one inline preview without importing app code into the generic examples module. 4. `web-landing` registers `CompanyOsDemoPreview`, which injects `companyOsDemoRuntimeClient`. The client calls the same-origin `/api/examples/companyos-ai-solutions-engineer-poc/[operation]` route for preflight, analysis, proof, fallback, and reset. 5. The route validates the browser-safe request contracts and delegates to the server-only runtime. For proof, the server resolves the allowlisted profile, recompiles the canonical prepared plan, verifies the exact approval binding, creates an ephemeral loopback fixture, substitutes only that fixture origin, then executes Harness through Playwright. 6. The live result is a bounded projection of the real Harness receipt. The recorded result is loaded from the committed SHA-256-validated manifest and its real screenshot artifact. `/templates` and `/sandbox?template=companyos-ai-solutions-engineer-poc` use the same hosted override. The package-only preview remains an honest prepared/recorded experience when the provider is absent. ## Safety and truthfulness - The default generator is deterministic and provider-free. It requires no API key and owns no provider configuration. - The Node-only runtime composes canonical `HarnessRunner` with `PlaywrightBrowserHarnessAdapter`, accepts only `http://127.0.0.1` or `http://localhost`, installs an exact-origin route before navigation, sends no invitations or communications, and resets its fixture around every run. - The proof records real Chromium screenshot, DOM, console, keyed structured output, step IDs, exact Harness assertions, and separate product postcondition assertions. In-memory replay identifiers are not transported as inspectable evidence. - The host accepts a strict, Zod-validated `ProofIntent`, resolves the allowlisted profile and scenario, recompiles the reviewed canonical mappings and proof plan, and rejects stale revisions or a mismatched SHA-256 execution binding before fixture creation. Live proof also requires a bounded, raw-request-free session authority created by the exact prepared generation result. - Live UI evidence is a bounded projection of the actual Harness receipt. Screenshot evidence is a capped inspectable data URL; assertion expected and actual values, verdict, mutation status, artifact IDs, and timestamps are not recalculated in the browser. - Outcome Pack approval and proof approval are separate. Missing, denied, or mismatched approval fails closed before mutation. - Live generation, proof, reset, and cleanup return within their configured timeout even when a dependency ignores `AbortSignal`; each session permits only one active proof across idempotency keys. - Completed idempotency results, prepared session authorities, and run nonces use bounded TTL/LRU stores. Timed-out work keeps its session quarantined until the underlying operation settles. - A `verified` product receipt is technical test evidence. It is **not** customer acceptance, release, handoff, or evidence of business impact. ## Public exports Browser-safe exports: `.`, `./example`, `./companyos-ai-solutions-engineer-poc.feature`, `./outcome-pack`, `./capabilities`, `./proof`, `./profiles`, `./runtime-contract`, `./view-model`, `./ui`, and `./docs`. `./runtime` is Node/Bun-only and is never re-exported by the root barrel. The focused `./runtime/server` entrypoint exposes only server-host composition helpers and avoids CLI/demo entrypoints in framework type graphs, including `CompanyOsProofSessionAuthority` (TTL/LRU prepared-session registry whose `requireExact()` rejects any proof intent that differs from the registered binding) and `requireLiveProofReady`. The Builder delivery-loop and acceptance-evidence projections are runtime exports because their canonical runtime dependency is not browser-safe. ## Website demo The package owns one shared capability/proof engine and one adaptive browser journey used by both public surfaces: - `/templates` — open **Request to Verified Proof** from the template catalog. - `/sandbox?template=companyos-ai-solutions-engineer-poc` — open the same package-native preview directly. The journey moves through five visual transformations: understand the request, shape the outcome and boundaries, map proof-ready capabilities, disclose one bounded action, and compare intended versus observed state. A quiet source and approval cue remains visible throughout. Exact assumptions, source records, approval facts, and evidence open from the relevant visual object instead of competing with the primary story. Both Customer Copilot and AI Solutions Engineer framings use this same adaptive journey, data, approval, proof, and source policy. Prepared analysis is deterministic; pasted unrelated requests remain analysis-only. Every result is labeled as `live-ai`, `prepared-profile`, `live-browser`, `validated-recording`, or `prepared-simulation`; failed and blocked verdicts remain distinct from verified results. The legacy `DemoSurfaceMode` type and named Call/Expert stage exports remain available for compatibility but are deprecated. The primary preview, safe session export, and presentation telemetry identify the surface as `adaptive`. ### Presenter paths Audience mode is the default. It has no presenter entry button, failure selector, internal diagnostics, or safe-export control. A host must explicitly set `presenterEnabled` to expose framing, recorded/live/auto selection, preflight, deliberate failure scenarios, reset, explicit fallback, and safe local export. This does not restore a Call/Expert surface split. Auto mode never silently loads a recording. The final audience-facing scene asks to **Prepare this proof for your product** with one redacted request, one test or staging account, relevant documentation or API information, and one acceptance owner. See [CALL_RUNBOOK.md](./CALL_RUNBOOK.md) for the two-minute rehearsal, live-unavailable recovery path, and Arkia/Théo acceptance checklist. ## Privacy and host integration - Raw request text stays in the in-memory UI session and is excluded from telemetry, logs, storage, errors, URLs, and the default export. - The request and sandbox subtrees use PostHog no-capture/sensitive markers. - Telemetry accepts only allowlisted operational metadata. - The web host exposes an allowlisted, same-origin, capped JSON operation route at `/api/examples/companyos-ai-solutions-engineer-poc/[operation]`. - Host responses are `no-store`, return stable error codes, and never reflect rejected request text. ### Optional live AI analysis Live AI request analysis belongs only to `web-landing` and is disabled unless `CONTRACTSPEC_COMPANYOS_LIVE_ANALYSIS=1` and an approved host provider is configured through `CONTRACTSPEC_AI_PROXY_URL` or `ANTHROPIC_API_KEY`. The host uses the repository AI-provider abstraction, supplies no tools, validates the structured result, enforces a bounded cancellable timeout, and returns only an analysis-only pack. It cannot attach the prepared scenario or create proof authority. The UI retains the operator's pasted request locally if the provider is absent, malformed, unavailable, or times out. The failure is stable and the prepared example is an explicit alternative, never a silent substitution. Hosts should pass `analysisProviderDisclosure` when enabling this boundary. ## Local runbook ```bash bun run --cwd examples/companyos-ai-solutions-engineer-poc test bun run --cwd examples/companyos-ai-solutions-engineer-poc typecheck bun run --cwd examples/companyos-ai-solutions-engineer-poc lint:check bun run --cwd examples/companyos-ai-solutions-engineer-poc build bun run --cwd examples/companyos-ai-solutions-engineer-poc demo ``` Before a customer call, use the consolidated gate: ```bash bun run --cwd examples/companyos-ai-solutions-engineer-poc precall ``` It validates the package/profile, recording manifest and hashes, Chromium, fixture behavior, and the host route. It is intentionally stricter than the reliable recorded-call requirement. Install Chromium once for the explicit browser lane, then run it without any provider credentials: ```bash bunx playwright install chromium bun run --cwd examples/companyos-ai-solutions-engineer-poc test:browser ``` Capture and validate the committed last-known-good recording: Repeat capture after a package-version bump: verification binds the recording to the current manifest version and checks the captured artifact hashes. ```bash bun run --cwd examples/companyos-ai-solutions-engineer-poc record:demo bun run --cwd examples/companyos-ai-solutions-engineer-poc recording:verify ``` The capture starts the real loopback fixture, compiles the canonical prepared binding, executes Harness through Playwright, persists the real screenshot and safe receipt, and records SHA-256 artifact hashes. Synthetic negative presets are labeled `prepared-simulation`; only the committed successful capture is `validated-recording`. ## Deliberate failures - Wrong administrator, missing onboarding project, disabled weekly reporting, missing selectors, or a nonzero external-send counter produce `failed`. - Denied/missing approval, unsupported capabilities, non-loopback targets, or redirect escape produce `blocked` before the proof mutation. - Failed and blocked receipts retain reason codes and the evidence that is safe and truthful for their execution stage; neither projects passed acceptance evidence. Hosts may inject a result-returning `DemoRuntime`. Deprecated generation and run callbacks remain observers only; callback return values never control progression. `DemoRuntimeResult.data` is authoritative for rendered proof evidence; selected recording presets cannot replace a live-browser result. Without a host runtime, the browser-safe prepared runtime provides deterministic analysis, explicit live-unavailable fallback, validated recording, preflight, and reset behavior. ## Supported call configurations ### Reliable recorded call - Use the public or hosted preview. - Run `recording:verify` before the call. - Select or explicitly accept the `validated-recording` path. - Do not claim a live browser dependency or live execution. ### Local live call - Run the local `web-landing` host with `CONTRACTSPEC_COMPANYOS_LIVE_BROWSER=1`. - Install Chromium and require a fresh `ready-live` preflight. - Use the injected same-origin API client, real loopback fixture, and `live-browser` receipt. - If live execution fails, keep that failure visible and load the validated recording only after explicit acceptance. ## Deliberate limitations This POC supports one allowlisted profile, one prepared executable scenario, one loopback fixture, and one committed successful recording. It does not crawl, index, generate arbitrary Playwright actions, target production systems, store customer requests, establish customer acceptance, or prove ROI or other business impact. Public/serverless hosting is recorded-ready by default and is live-ready only when that deployed runtime genuinely launches Chromium and passes the fixture probe. --- ## @lssm-tech/example.companyos-communicationos-operating-cockpit Description: Deterministic combined CompanyOS and CommunicationOS operating cockpit example for governed conversation-to-work loops. Path: examples/companyos-communicationos-operating-cockpit URL: /llms/example.companyos-communicationos-operating-cockpit # CompanyOS + CommunicationOS Operating Cockpit Deterministic combined example that turns CommunicationOS thread/action evidence into a CompanyOS work execution plan, runs it through policy-gated dry-run execution, and feeds the result back into a CommunicationOS audit/action state. ## Boundaries - Provider-free by default: no network I/O, credentials, outbound messages, deployments, or production actions. - Imports reusable modules/libs only; it does not import other examples. - Package-local `src/contracts` describe proof fixtures for this example, not canonical reusable cross-OS contracts. - CompanyOS execution uses deterministic module adapters from `@lssm-tech/module.companyos`. - Message-originated commands enter the CommunicationOS command inbox as evidence only; production sends and CompanyOS high-impact bypass attempts are blocked before execution. ## Rich cockpit proof - The UI exports an app-like `TemplateShell` cockpit from `@lssm-tech/lib.example-shared-ui/TemplateShell` with ten named screens: home, dashboard, CommunicationOS inbox, thread detail, evidence map, CompanyOS work graph, policy gate, dry-run console, audit feedback, and starter-kit guide. - The start/home and dashboard screens introduce the cross-OS story, deterministic safety boundaries, metrics, production-readiness checks, command lanes, operator notes, and quick actions before the deeper workflow screens. - Sidebar navigation, thread selection, evidence drill-down, workflow-stage inspection, policy approval, dry-run execution, audit viewing, operator notes, and reset are backed by a pure reducer so the preview is interactive without providers or side effects. - Selecting a CommunicationOS thread advances deterministic state into CompanyOS work mapping; running the dry-run advances the proof into CommunicationOS audit feedback without outbound effects. - Reusable starter-kit proof imports CompanyOS and CommunicationOS UI/runtime surfaces from `@lssm-tech/module.companyos` and `@lssm-tech/module.communication-os`; scenario copy and fixtures remain package-local. - The proof summary includes `commandInboxStatus: blocked` and `companyOsBridgeStatus: blocked` so release evidence catches any accidental execution bypass. ## Public integration surfaces Import the package-native cockpit UI from `@lssm-tech/example.companyos-communicationos-operating-cockpit/ui` when a host wants the combined proof without depending on another example package. The `./ui` subpath exports: - `OperatingCockpitPreview` for the deterministic app-like cockpit. - `OperatingCockpitScreen`, `OPERATING_COCKPIT_SCREEN_HREFS`, and `operatingCockpitNavigation` for host routing, docs anchors, and preview catalogs. - `createInitialOperatingCockpitState`, `reduceOperatingCockpitState`, `serializeOperatingCockpitState`, `parseOperatingCockpitState`, and `createInMemoryOperatingCockpitPersistence` for host-owned state snapshots. The example never writes to browser storage, disk, or a backend by itself; hosts provide persistence adapters explicitly. - `OriginChip`, `OriginChipProps`, and `COCKPIT_ORIGIN_KINDS` for rendering source-origin context from CompanyOS action-origin types while falling back safely for unknown kinds. Public discovery is integrated through `@lssm-tech/module.examples`: registry entries point at this package's `./docs`, feature entrypoint, sandbox link, LLMS guide, and package-native `./ui` preview. Regenerate the example registry after changing these exports or discovery fields. ## Commands ```bash bun run --cwd examples/companyos-communicationos-operating-cockpit test bun run --cwd examples/companyos-communicationos-operating-cockpit typecheck bun run --cwd examples/companyos-communicationos-operating-cockpit build bun run --cwd examples/companyos-communicationos-operating-cockpit lint:check bun run --cwd examples/registry generate:registry bun test packages/bundles/marketing/src/components/templates/template-catalog.test.ts packages/bundles/marketing/src/components/templates/template-preview.test.ts ``` ## VoiceOps operating cockpit story The cockpit fixture now starts from the Rivage Retail voice escalation: CommunicationOS holds the redacted voice evidence, CompanyOS drafts an internal security-documentation product gap, and customer-facing promises/security claims remain blocked. The dry-run remains deterministic and side-effect free while surfacing the same receipt/proof language as the VoiceOps workbench. ## Roadmap: UI/UX refresh The example is still intentionally thin around `@lssm-tech/bundle.managed-companyos` cockpit templates. The next refresh should make the cockpit feel like a proper operator product surface while keeping the package deterministic and provider-free: - Implement the reusable UI work in `packages/bundles/managed-companyos/src/ui/cockpit/templates/operating-cockpit`, then let this example provide fixtures and proof coverage. - Upgrade the home/dashboard into an operator-grade command center with loop state, selected thread, policy, dry-run, audit, contact identity, and evidence context. - Add richer CommunicationOS inbox/thread/contact affordances inspired by the messaging workspace: searchable conversations, contact-to-conversation navigation, detail drawers, edit/delete actions, and evidence-aware actions. - Keep provider adapters host-owned; the example must remain no-network, no-credential, no-send, and no-production-action by default. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. Full `build` regenerates JavaScript and declarations in one output transaction, restoring previous `dist` if either stage fails. Standalone `build:bundle` still preserves declarations; use full `build` to reconcile obsolete output layouts. --- ## @lssm-tech/example.companyos-gtm-learning-loop-conformance Description: Vertical-neutral, no-network composed conformance fixture for the GTM Learning Loop, plus two fake research-provider adapters for Harness scenario execution. Path: examples/companyos-gtm-learning-loop-conformance URL: /llms/example.companyos-gtm-learning-loop-conformance # CompanyOS GTM Learning Loop Conformance Vertical-neutral, no-network composed conformance scenario for the CompanyOS learning loop (Ultragoal G002), built from the GTM Learning Loop consumer contract (Story G001, `docs/contracts/gtm-platform-consumer-contract-v0.md`). ## Ownership split | Concern | Owner | |---|---| | Company context, experiment/change-set ref, preview action-packet + unknowns, review decision, branch comparison/promotion, execution plan/receipt, routing-rule learning | `@lssm-tech/lib.companyos-spec` (`./fixtures`) | | Provider binding + cost-observation ref | `@lssm-tech/lib.provider-spec` (`./fixtures`) | | Normalized communication record + outcome-event ref | `@lssm-tech/lib.communication-spec` (`./fixtures`) | | Composed scenario + fake research-provider adapters | this package (`./fixtures`, adapters) | | Generic scenario/run/replay execution | `@lssm-tech/lib.harness` | Each sibling spec package exports only its own atomic slice and imports none of the others. This package is the only place all three slices meet. ## Fixtures `composedNeutralLearningLoopScenario` (`./fixtures`) merges the three atomic slices into the same shape as `docs/contracts/fixtures/companyos-learning-loop-neutral-v0.json`, so the Story G001 documented fixture and this package's composed fixture cannot silently drift apart. ## Conformance expectation Per the "Expected conformance" section of the consumer contract, a Harness scenario built on this fixture must run twice with two fake research providers, produce identical replay output under shuffled input, and perform no network or external writes. --- ## @lssm-tech/example.companyos-knowledge-graph Description: Runtime managed-graph example consuming CompanyOS ManagedGraphNode/Edge via DataViewGraphSpec Path: examples/companyos-knowledge-graph URL: /llms/example.companyos-knowledge-graph # @lssm-tech/example.companyos-knowledge-graph **Runtime managed-graph example consuming `ManagedGraphNode`/`ManagedGraphEdge` via `DataViewGraphSpec` with the `two-op` source variant.** ## What This Demonstrates - Defining a `DataViewGraphSpec` with a `two-op` graph source. - Fetching nodes and edges via separate query operations at runtime. - Modeling a CompanyOS knowledge graph structure. ## Running Locally From `examples/companyos-knowledge-graph`: ```bash bun run typecheck ``` ## Architecture - `src/index.ts` — root public barrel and package entrypoint. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`. - Full `DataViewGraphSpec` export lands in task P5/W5.B. --- ## @lssm-tech/example.companyos-product-engineering-loop Description: Deterministic CompanyOS V1 operating review replay using public spec and pure runtime APIs. Path: examples/companyos-product-engineering-loop URL: /llms/example.companyos-product-engineering-loop # @lssm-tech/example.companyos-product-engineering-loop Deterministic CompanyOS V1 product/engineering operating-loop example using public `@lssm-tech/lib.companyos-spec` and pure `@lssm-tech/lib.companyos-runtime` APIs. ## What this demonstrates A provider-free replay of the CompanyOS V1 fixture: ```txt onboarding-confusion signal -> product feedback -> customer commitment -> quarterly objective drift -> temporal memory snapshot -> weekly operating review packet -> company brain entry / gap -> candidate decision -> proposed engineering work -> ContractSpec proposal -> scoped agent organization -> handoff/delegation policy -> agent-native operation authority/autonomy classification -> product-lead review surface selection -> draft-only agent action -> operator inbox approval -> V1 operating review summary ``` The example validates the V1 fixture with CompanyOS public validation helpers before building the replay. It uses pure runtime projections for authority, autonomy, inbox routing, and operating-review summarization. It does not bind real providers, send customer messages, perform filesystem/network I/O, or execute production work. The optional `./ui` surface is a deterministic compatibility preview adapter over the package replay data while canonical reusable CompanyOS UI is promoted into `@lssm-tech/module.companyos/ui`. ## Preview / export workflow This package stays provider-free and replay-led. It must not add live provider bindings, network I/O, filesystem I/O, outbound sends, or production mutation paths. `./ui` is a thin deterministic compatibility adapter for the focused example: it derives preview metrics from `buildCompanyOsProductEngineeringReplay()` and preserves draft-only, dry-run, approval-gated semantics. New reusable/canonical CompanyOS UI should live in `@lssm-tech/module.companyos/ui`; this example should consume that module-owned surface once available rather than growing new canonical screens here. ## Running locally From `examples/companyos-product-engineering-loop`: - `bun run build` - `bun run typecheck` - `bun run test` - `bun run smoke` - `bun run preflight` ## Usage ```ts import { buildCompanyOsProductEngineeringReplay } from '@lssm-tech/example.companyos-product-engineering-loop/replay'; const replay = buildCompanyOsProductEngineeringReplay(); console.log(replay.reviewPacket.runtimeSummary); console.log(replay.steps.map((step) => step.label)); ``` ## Public entry points - `@lssm-tech/example.companyos-product-engineering-loop` - `@lssm-tech/example.companyos-product-engineering-loop/example` - `@lssm-tech/example.companyos-product-engineering-loop/companyos-product-engineering-loop.feature` - `@lssm-tech/example.companyos-product-engineering-loop/replay` - `@lssm-tech/example.companyos-product-engineering-loop/docs` - `@lssm-tech/example.companyos-product-engineering-loop/ui` ## Safety boundaries - The replay consumes public CompanyOS fixture, validation, and runtime APIs only. - Agent-native operations remain draft-only, dry-run constrained, and approval-gated. - Customer-facing action execution is represented as an operator inbox approval, not a provider write. - No real providers, network I/O, filesystem I/O, outbound sends, or production mutation paths are included. - `./ui` remains a deterministic preview adapter and must not become the canonical reusable CompanyOS UI surface. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. --- ## @lssm-tech/example.companyos-voiceops-workbench Description: Deterministic CompanyOS VoiceOps workbench example adapted from the Hackathon Voice AI UI/UX ingest lane. Path: examples/companyos-voiceops-workbench URL: /llms/example.companyos-voiceops-workbench # CompanyOS VoiceOps Workbench Deterministic example package for Hackathon Voice AI web-app parity inside the CompanyOS examples registry. The package adapts the hackathon app's product shape into a safe, provider-free CompanyOS preview. `VoiceOpsWorkbenchPreview` now renders a package-local app shell with deterministic screen navigation for Workbench, Company, Work, Inbox, Integrations, Settings, Contracts, Receipt Viewer, and Receipt Verify. The Workbench screen keeps the core demo concepts together: source pills, redacted transcript replay, redaction proof, policy/action table, graph canvas, replay scrubber, receipt evidence, and an explicit live-mode-disabled safety banner. This package intentionally does not ship live provider SDKs, API keys, production endpoints, generated media, raw quarantined source, browser audio capture, network behavior, or production writes. Live/provider ideas are represented only as fixture-backed disabled or reference-only view-model data. ## Source traceability The UI model records source-path references from the Hackathon Voice AI ingest lane, including original workbench panels such as `TranscriptPanel.tsx`, `RedactionDiff.tsx`, `ReplayScrubber.tsx`, `ReceiptPanel.tsx`, `WorkTable.tsx`, and the sixty-second demo spec. Conceptual screen-map material is marked `reference-only`, while live/provider controls such as `LiveAudioRecorder.tsx` and `GradiumTtsButton.tsx` are marked `rejected-live` so hosts can audit parity without executing unsafe behavior. ## Public surface - `VoiceOpsWorkbenchPreview` remains the public preview entrypoint. - `initialScreenId` can render any deterministic app-shell screen for tests or host previews. - `voiceOpsWorkbenchFixture` contains all screen, contract, approval, receipt, graph, replay, provider-readiness, and source-reference data. ## Safety boundary All behavior is fixture/view-model only. Browser audio capture, speech recognition, live model/provider calls, router dependencies, environment reads, network requests, and production writes are represented as disabled explanatory cards rather than executable code. Future fixture changes should keep each adapted concept source-traceable and should classify unsafe/live-only files as reference-only or rejected rather than executable package behavior. Examples of unsafe/live-only concepts include live audio recorders, provider test buttons, provider runtime wiring, environment/configuration files, production URLs, and credential-bearing readiness checks. ## Public exports Preserve these package exports when evolving the example: - `CompanyOsVoiceOpsWorkbenchExample` - `voiceOpsWorkbenchFixture` - `VoiceOpsWorkbenchPreview` - `./fixtures` - `./ui` - `./ui/VoiceOpsWorkbenchPreview` Additive fixture/type growth is preferred so downstream registry and sandbox consumers can keep importing the existing surface. ## Verification commands Run package-local checks before claiming changes: ```bash bun run typecheck bun run test bun run smoke bun run lint:check ``` If example metadata or exported registry fields change, also regenerate/check the examples registry from the repository root. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. --- ## @lssm-tech/example.content-generation Description: Content generation example using @lssm-tech/lib.content-gen. Path: examples/content-generation URL: /llms/example.content-generation # @lssm-tech/example.content-generation Website: https://contractspec.io **Content generation example using @lssm-tech/lib.content-gen.** ## What This Demonstrates - Content generation pipeline with typed contracts. - Integration with the content-gen library. - Structured logging for generation steps. - DocBlock documentation for the generation flow. - Deterministic provider-free preview data for content, image, video, TTS, STT, and conversation workflow artifacts. - `src/docs/` contains docblocks and documentation-facing exports. ## Preview / export workflow Content Generation previews use deterministic local pipeline fixtures for brief/prompt editing, generation review, publishing/version snapshots, and audit status. The `./ui` export must not call LLM providers, production endpoints, or live storage. The first-class preview packet covers these local artifact kinds: - `content` — blog, email, landing, social, and SEO draft outputs from typed briefs. - `image` — campaign hero image fixture references. - `video` — launch teaser storyboard fixture references. - `tts` — narration script fixture references. - `stt` — transcript fixture references. - `conversation` — human review assistant handoff fixture references. Public key behavior is compatibility-sensitive because current catalog consumers may resolve both `examples.content-generation` and normalized keys. Document and test any alias migration before release. The Phase 0 compatibility gate lives in `.omx/plans/content-generation-compatibility-matrix.md`. ## Compatibility / Migration Notes - Keep `content-generation` as the canonical feature key; any registry alias cleanup is major-version-only. - Prefer future contract-source imports from `@lssm-tech/lib.contracts-spec/content-generation` once the contracts lane lands them; existing `@lssm-tech/lib.content-gen` generator imports remain valid for this example. - Provider credentials are non-goals for this package. Real provider adapters belong in integration packages and are injected by apps/modules, while this example stays deterministic. - Keep this README synchronized with `packages/apps/web-landing/public/llms-packages/example.content-generation.txt` until generated docs own the mirror. ## Running Locally From `examples/content-generation`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.content-generation` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/content-generation.feature.ts` defines a feature entrypoint. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/generate.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 `./content-generation.feature` resolves through `./src/content-generation.feature.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/content-generation.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./generate` resolves through `./src/generate.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - Export `./ui/content-generation-preview.data` resolves through `./src/ui/content-generation-preview.data.ts`. - Export `./ui/ContentGenerationPreview` resolves through `./src/ui/ContentGenerationPreview.tsx`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.content-gen`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.logger`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.contract-graph Description: Static build-time graph example for ContractSpec: contracts → events → presentations, reusing graph-artifacts link kinds Path: examples/contract-graph URL: /llms/example.contract-graph # @lssm-tech/example.contract-graph **Static build-time graph example: contracts → events → presentations using `DataViewGraphSpec`.** ## What This Demonstrates - Defining a `DataViewGraphSpec` with an `inline-op` graph source. - Connecting ContractSpec artifacts (contracts, events, presentations) as nodes and edges via `graph-artifacts` link kinds. - Build-time graph — no managed-graph runtime or entity registry required. ## Running Locally From `examples/contract-graph`: ```bash bun run typecheck ``` ## Architecture - `src/index.ts` — root public barrel and package entrypoint. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`. - Implementation of the full `DataViewGraphSpec` export lands in task P5/W5.A. --- ## @lssm-tech/example.creator-platform-ai-native Description: (none) Path: examples/creator-platform-ai-native URL: /llms/example.creator-platform-ai-native # AI-native creator campaign example Deterministic reference for the governed loop: ingest evidence, score a creative signal, propose coaching, require a person for consequential actions, and record outcomes. It uses no provider credentials, network calls, or app-owned records. The proof also resolves a RoleMorph-driven campaign-manager experience and asserts that all 44 capability paths are covered while personalization remains presentation-only. Run `bun test` from this package. --- ## @lssm-tech/example.creator-platform-foundation Description: Credential-free reference composition for the creator-platform bundle. Path: examples/creator-platform-foundation URL: /llms/example.creator-platform-foundation # Creator Platform Foundation Example Credential-free reference composition for every optional creator-platform surface. `CreatorPlatformReference` demonstrates design selection, analytics, AuthOS, Momentum Rail/gamification, and human review under the design-system theme and locale providers. `GOVERNED_PUBLISHING_EXAMPLE` documents an inert publishing request without credentials or provider execution. This is a composition example, not the Creator Platform application. --- ## @lssm-tech/example.crm-pipeline Description: CRM Pipeline - Contacts, Companies, Deals, Tasks Path: examples/crm-pipeline URL: /llms/example.crm-pipeline # @lssm-tech/example.crm-pipeline Website: https://contractspec.io **CRM Pipeline - Contacts, Companies, Deals, Tasks.** ## What This Demonstrates - Multi-entity domain model (Contact, Company, Deal, Task). - Deal pipeline with stage enums, operations, and test-specs. - Event-driven architecture (contact, deal, task events). - Presentation layer with dashboard and pipeline views. - React UI with pipeline board, hooks, modals, overlays, renderers, and a server-mode shared `DataTable` for deals. - Shared table capabilities including sorting, pagination, multi-row selection, column visibility, pinning, resizing, and expandable deal details. - Feature definition and capability pattern. - Seeders and mock data. - LinkedIn contact and company URL storage as a downstream example. Production ingestion uses the governed `externalProfiles` contract from `@lssm-tech/lib.contracts-integrations/integrations/providers/crm`; the example is not the LinkedIn integration implementation. ## Running Locally From `examples/crm-pipeline`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.crm-pipeline` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/crm-pipeline.feature.ts` defines a feature entrypoint. - `src/deal` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events` is part of the package's public or composition surface. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./crm-pipeline.feature` resolves through `./src/crm-pipeline.feature.ts`. - Export `./deal` resolves through `./src/deal/index.ts`. - Export `./deal/deal.enum` resolves through `./src/deal/deal.enum.ts`. - Export `./deal/deal.operation` resolves through `./src/deal/deal.operation.ts`. - Export `./deal/deal.schema` resolves through `./src/deal/deal.schema.ts`. - Export `./deal/deal.test-spec` resolves through `./src/deal/deal.test-spec.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/crm-pipeline.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - The package publishes 44 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 validate` — contractspec validate "src/**/*" - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.identity-rbac`, `@lssm-tech/lib.runtime-sandbox`, ... --- ## @lssm-tech/example.data-fetching-ecosystem Description: UX wiring proof: useContractQuery → QueryState → design-system components, all lifecycle states. Path: examples/data-fetching-ecosystem URL: /llms/example.data-fetching-ecosystem (No README.md) --- ## @lssm-tech/example.data-grid-showcase Description: Focused data-grid example for ContractSpec table capabilities Path: examples/data-grid-showcase URL: /llms/example.data-grid-showcase # @lssm-tech/example.data-grid-showcase Website: https://contractspec.io **Canonical data-table example for the ContractSpec stack.** ## What This Demonstrates - The same account-grid example across `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.ui-kit`, `@lssm-tech/lib.ui-kit-web`, and `@lssm-tech/lib.design-system`. - Client-mode and server-mode table controllers with sorting, pagination, single and multiple selection, column visibility, resizing, left/right pinning, and row expansion. - Loading states, empty states, design-system header actions, toolbar/footer slots, and a visible row-interaction log. - A declarative `DataViewSpec` table contract that adapts onto the same headless table stack. - Sandbox-friendly UI packaging for a focused canonical example instead of a full business template. ## Running Locally From `examples/data-grid-showcase`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.data-grid-showcase` as the canonical reference for ContractSpec table capabilities, or import its exported contracts and UI into docs, sandboxes, and internal examples. ## Live surfaces - Sandbox: `/sandbox?template=data-grid-showcase` - Docs example: `/docs/examples/data-grid-showcase` - Generated reference: `/docs/reference/data-grid-showcase/data-grid-showcase` ## Architecture - `src/contracts/` owns the sample query contract and declarative data view spec. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the example manifest surfaced by `@lssm-tech/module.examples`. - `src/ui/` contains the table showcase component, the primitive/composed table lanes, and demo data/helpers. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./contracts` resolves through `./src/contracts/index.ts`. - Export `./contracts/data-grid-showcase.data-view` resolves through `./src/contracts/data-grid-showcase.data-view.ts`. - Export `./contracts/data-grid-showcase.operation` resolves through `./src/contracts/data-grid-showcase.operation.ts`. - Export `./data-grid-showcase.feature` resolves through `./src/data-grid-showcase.feature.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - Export `./ui/DataGridShowcase` resolves through `./src/ui/DataGridShowcase.tsx`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 ## Data table contract example The declarative contract lane uses the same account-grid example exposed in the interactive showcase: ```ts import { defineDataView } from '@lssm-tech/lib.contracts-spec/data-views'; import { ListDataGridShowcaseRowsQuery } from './data-grid-showcase.operation'; export const DataGridShowcaseDataView = defineDataView({ meta: { key: 'examples.data-grid-showcase.table', version: '1.0.0', entity: 'account', title: 'Data Grid Showcase Table', description: 'Declarative DataViewSpec for the ContractSpec table showcase.', domain: 'examples', owners: ['@platform.core'], tags: ['examples', 'table', 'data-grid'], stability: 'experimental', }, source: { primary: { key: ListDataGridShowcaseRowsQuery.meta.key, version: ListDataGridShowcaseRowsQuery.meta.version, }, }, view: { kind: 'table', executionMode: 'client', selection: 'multiple', columnVisibility: true, columnResizing: true, columnPinning: true, rowExpansion: { fields: ['notes', 'renewalDate', 'lastActivityAt'], }, initialState: { pageSize: 4, hiddenColumns: ['notes'], pinnedColumns: { left: ['account'], }, sorting: [{ field: 'arr', desc: true }], }, fields: [ { key: 'account', label: 'Account', dataPath: 'account', sortable: true }, { key: 'owner', label: 'Owner', dataPath: 'owner', sortable: true }, { key: 'status', label: 'Status', dataPath: 'status', sortable: true }, { key: 'notes', label: 'Notes', dataPath: 'notes' }, ], }, }); ``` ## Notes - This package is intentionally narrow: it exists to showcase the full table stack, not to simulate a full vertical business template. - The same table stack is reused by the larger examples in `analytics-dashboard`, `crm-pipeline`, `integration-hub`, and `agent-console`, but this package is the canonical source of truth. --- ## @lssm-tech/example.draft-and-send-agent Description: CommunicationOS-shaped draft-and-send reference agent: draft a message, wait for approval, then send it through an approval-gated ContractSpec operation. Path: examples/draft-and-send-agent URL: /llms/example.draft-and-send-agent # @lssm-tech/example.draft-and-send-agent CommunicationOS-shaped **draft-and-send reference agent** for ContractSpec. It exercises exactly the primitives that already exist: approval-gated external effect (`execution.approval`) and draft-only-by-default agent tools (`automationSafe` / `requiresApproval`). The domain is intentionally trivial — a message body plus a target channel — so no product-specific schema leaks into core packages. ## Surfaces - **`DraftAndSendAgent`** (`src/agent/draft-and-send.agent.ts`) — one `AgentSpec` with a `draftMessage` tool (`operationRef`, automation-safe) and a `sendMessage` tool (`operationRef`, `requiresApproval: true`). - **`DraftAndSendWorkflow`** (`src/workflow/draft-and-send.workflow.ts`) — one `WorkflowSpec` wiring `draft → approval-wait → send → receipt`, executed through the Workflow DevKit runtime adapter (`runWorkflowSpecWithWorkflowDevkit`). - **Operations** (`src/contracts/`) — `draftAndSend.draftMessage` and the approval-gated `draftAndSend.sendMessage`. - **`createDraftAndSendRegistry()`** (`src/handlers/`) — an `OperationSpecRegistry` with both commands and trivial handlers bound. ## Proof - `src/draft-and-send.workflow.test.ts` runs the full lifecycle through the Workflow DevKit adapter, issuing a real approval receipt for the send step. - `src/mcp-smoke.test.ts` starts a real MCP server (`registerMcpTools`) over an in-memory transport and drives one allowed `sendMessage` call plus denied calls (missing / tampered receipt → `APPROVAL_REQUIRED`). ```bash bun test ``` --- ## @lssm-tech/example.email-gmail Description: Gmail integration example: inbound threads and outbound messages. Path: examples/email-gmail URL: /llms/example.email-gmail # @lssm-tech/example.email-gmail Website: https://contractspec.io **Gmail integration example: inbound threads and outbound messages.** ## What This Demonstrates - OAuth authentication flow for Gmail API. - Inbound email thread processing. - Outbound message composition and sending. - Integration provider pattern with ContractSpec contracts. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/email-gmail`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.email-gmail` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/auth.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/email-gmail.feature.ts` defines a feature entrypoint. - `src/example.ts` is the runnable example entrypoint. - `src/inbound.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/outbound.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./auth` resolves through `./src/auth.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/email-gmail.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./email-gmail.feature` resolves through `./src/email-gmail.feature.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./inbound` resolves through `./src/inbound.ts`. - Export `./outbound` resolves through `./src/outbound.ts`. - Export `./run` resolves through `./src/run.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-email`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.feature-hub-composition Description: Deterministic all-nine Feature Hub composition reference for web and React Native hosts. Path: examples/feature-hub-composition URL: /llms/example.feature-hub-composition # Feature Hub Composition Example This deterministic reference installs all nine Feature Hubs, projects identical semantic routes to Next.js and React Native, imports a granular Integration Hub view-model, and applies a hybrid route/component override. ```bash bun run --cwd examples/feature-hub-composition example ``` The fixture uses inert provider-neutral adapters and is **candidate**, not production-qualified. Consumers must qualify their live providers, secrets, databases, queues, schedulers, restore/failover, canary, rollback, and security controls in their own Vercel, Railway, Supabase, Docker, or custom topology. --- ## @lssm-tech/example.finance-ops-ai-workflows Description: Deterministic finance operations AI workflow example with human review, fixed rules, and synthetic data only. Path: examples/finance-ops-ai-workflows URL: /llms/example.finance-ops-ai-workflows # @lssm-tech/example.finance-ops-ai-workflows Finance Ops AI Workflows is a public ContractSpec template for safe, deterministic, human-reviewed AI-assisted finance operations workflows. It is designed as a credible business demo for NDconsulting / Desliance style work: DAF transition, cash management, reporting, procedures, finance process improvement, training, and AI adoption ROI. ## Product Positioning This is not a chatbot, prompt collection, SaaS app, or live integration. It demonstrates how to turn finance-ops work into explicit workflows: business input -> ContractSpec operation -> deterministic handler -> simulated AI-assisted workflow -> human review -> reviewable output -> ROI/adoption log. The value is not "make an LLM talk". The value is to frame finance work, separate deterministic rules from assisted drafting, block autonomous decisions, and leave evidence that can be tested and industrialized. ## Included Workflows - `financeOps.missionIntake.triage`: fictive DAF / finance transformation mission intake. - `financeOps.cashAging.prioritize`: fixed-date aged receivables prioritization using deterministic rules. - `financeOps.procedureDraft.create`: internal finance procedure draft with roles, steps, controls and KPIs. - `financeOps.reportingNarrative.compose`: management reporting narrative with variance helpers and no invented causes. - `financeOps.aiAdoption.logUsage`: AI adoption ROI log that tracks use cases, not intrusive employee surveillance. ## Demo Script 1. Open `/templates` and preview `Finance Ops AI Workflows`. 2. Switch between the PME recovery and reporting reset scenarios from the demo command bar. 3. Run a workflow draft, select the mission item, invoice, procedure step, reporting variance, or adoption log under discussion, and use the selected-detail panel to request changes or mark the draft ready. 4. Move through Mission intake, Cash aging, Procedure, Reporting, and Adoption ROI as an operator cockpit rather than a slide sequence. 5. Reset the replay when the presenter wants to restart the story from the same synthetic fixture. ## Interactive Preview The inline template preview is intentionally demo-grade: - Command bar with scenario switching, deterministic replay reset, draft-run controls and current workflow state. - Workflow rail for Mission intake, Cash aging, Procedure, Reporting, and Adoption ROI. - Compact lists and tables instead of oversized card grids. - Selected-detail panel for every workflow click: mission evidence, invoice follow-up, procedure control, reporting variance, or adoption recommendation. - Draft-only review actions to request changes or mark the selected workflow ready. The preview recomputes from the handlers, so it demonstrates the same deterministic contract outputs that tests and replay proof cover. The interactivity is local UI state only: it simulates review and replay, not real operational execution. ## Scope Boundaries The package uses synthetic fixtures and deterministic handlers only. It does not connect to live finance systems, does not send operational communications, and does not provide production financial, legal, tax, accounting, or investment advice. Workflow outputs keep `humanReviewRequired` set to `true`. ## Public Entry Points - `@lssm-tech/example.finance-ops-ai-workflows` - `@lssm-tech/example.finance-ops-ai-workflows/contracts` - `@lssm-tech/example.finance-ops-ai-workflows/contracts/mission-intake-triage.operation` - `@lssm-tech/example.finance-ops-ai-workflows/contracts/cash-aging-prioritization.operation` - `@lssm-tech/example.finance-ops-ai-workflows/contracts/procedure-draft.operation` - `@lssm-tech/example.finance-ops-ai-workflows/contracts/reporting-narrative.operation` - `@lssm-tech/example.finance-ops-ai-workflows/contracts/adoption-roi-log.operation` - `@lssm-tech/example.finance-ops-ai-workflows/fixtures` - `@lssm-tech/example.finance-ops-ai-workflows/handlers` - `@lssm-tech/example.finance-ops-ai-workflows/proof` - `@lssm-tech/example.finance-ops-ai-workflows/ui` ## Implementation Notes - Handlers are pure deterministic functions wrapped with `HandlerForOperationSpec`. - Structured lists are returned as JSON strings where the contract surface asks for `*Json` fields. - Fixtures are fictive and tuned for a commercial demo: PME industrielle, 85 employees, 14 M EUR revenue, RAF departure, missing reporting, cash tension and fragmented Excel/Power BI tools. - The replay proof runs all five workflows and returns a compact evidence object. ## Commands - `bun run build` - `bun run typecheck` - `bun run test` - `bun run smoke` - `bun run preflight` Declaration builds use `build:types` through the shared Bun tool; `build` runs bundle and declaration generation. Declared exports are preserved. Generated artifacts exclude test-only files; tests/typecheck remain separate gates. --- ## @lssm-tech/example.form-showcase Description: Focused ContractSpec form example and template covering field kinds, conditional rules, and layout flows. Path: examples/form-showcase URL: /llms/example.form-showcase # @lssm-tech/example.form-showcase Focused ContractSpec form example and template covering field kinds, conditional rules, and layout flows. ## What This Demonstrates - Schema-backed `defineFormSpec` authoring with `fromZod`. - Every current form field kind: text, email, textarea, select, checkbox, radio, switch, autocomplete, address, phone, date, time, datetime, group, and array. - Layout variants including responsive columns, full-width spans, section flows, step flows, nested groups, horizontal/responsive orientation, and repeated group arrays. - Form metadata for input groups, password fields, read-only/computed hints, conditional visibility/enabled/required rules, custom constraints, PII hints, and submit actions. - A `FormRegistry` that downstream apps can import and filter, including entity projection form metadata. - A `FormShowcasePreview` UI that demonstrates the specs with real form controls across field kinds, sections, arrays, groups, and step layouts. ## Running Locally From `examples/form-showcase`: - `bun run build` - `bun run typecheck` - `bun run test` - `bun run smoke` - `bun run preflight` ## Usage Import the registry or individual form specs: ```ts import { FormShowcaseRegistry, FormShowcaseAllFieldsForm, FormShowcaseProgressiveStepsForm, } from "@lssm-tech/example.form-showcase/forms"; ``` Use this package as a form-only template when you want a compact reference for ContractSpec form authoring without a larger business app around it. Import `@lssm-tech/example.form-showcase/proof-config` when tooling needs the stable docs, sandbox, templates, forms, and UI entrypoint map without reaching into private preview helpers. ## Proof map and boundaries The public proof map is intentionally stable and package-local: - Docs routes: `/docs/examples/form-showcase`, `/docs/examples/form-showcase/usage`, and `/docs/examples/form-showcase/proof-config`. - Sandbox route: `/sandbox?template=form-showcase`. - Template route: `/templates?tag=forms`. - Public entrypoints: the package barrel, `./example`, `./forms`, `./docs`, `./proof-config`, and `./ui`. Private proof helpers under `src/ui/proof/*` and preview data/model files stay implementation details. Tooling should read `@lssm-tech/example.form-showcase/proof-config` instead of deep-importing those helpers. When a form-configuration panel is needed, reuse the design-system `FormConfigShell`, `FormConfigMenuBar`, and `FormConfigPanel` exports from `@lssm-tech/lib.design-system/forms`. The showcase proof should not fork a local configuration shell. No persistence, backend, auth, provider, credential custody, or production form-storage guarantee is implied by this example. Capture/readiness proof state is deterministic fixture state only. ## Public Entry Points - `@lssm-tech/example.form-showcase` - `@lssm-tech/example.form-showcase/example` - `@lssm-tech/example.form-showcase/forms` - `@lssm-tech/example.form-showcase/forms/all-fields.form` - `@lssm-tech/example.form-showcase/forms/entity-projections.form` - `@lssm-tech/example.form-showcase/forms/form-showcase.docs` - `@lssm-tech/example.form-showcase/forms/progressive-steps.form` - `@lssm-tech/example.form-showcase/proof-config` - `@lssm-tech/example.form-showcase/docs` - `@lssm-tech/example.form-showcase/ui` - `@lssm-tech/example.form-showcase/ui/FormShowcasePreview` Private proof/state helpers under `src/ui/proof/*`, any screen-model internals under `src/ui/screens/*`, and non-existent deep proof shortcuts such as `@lssm-tech/example.form-showcase/proof` are intentionally not package exports. Use `@lssm-tech/example.form-showcase/proof-config` for the stable proof map instead of deep imports. ## Notes - This package intentionally does not ship a production custom renderer. Its preview uses real controls and the same sample data to demonstrate the contract capabilities, while host apps can map `FieldSpec` objects to their own design-system components for fully interactive forms. - The example is available in the templates catalog through `surfaces.templates: true`. - The proof/config preview is deterministic and in-memory only: it does not require persistence, backend routes, authentication, credentials, or network access. Declaration builds use `build:types` through the shared Bun tool; `build` runs bundle and declaration generation. Declared exports are preserved. Generated artifacts exclude test-only files; tests/typecheck remain separate gates. --- ## @lssm-tech/example.gamification-campaign Description: Cross-vertical finance campaign using ContractSpec gamification primitives. Path: examples/gamification-campaign URL: /llms/example.gamification-campaign # Cross-vertical gamification campaign example This reference composes a personal-finance reset campaign with daily, weekly, and explicit missions; capped XP; quests and badges; friend/team streaks; cooperative goals; seeded leagues; boosts, shields, gems, gifts, and nudge intents. It also demonstrates approved-excuse policy, scheduled protection, personal records, append-only XP receipts, canonical emitted events, and promotion/demotion decisions. It is deliberately headless and persists nothing. Run `bun test`, `bun run typecheck`, or import the campaign from `@lssm-tech/example.gamification-campaign/campaign`. --- ## @lssm-tech/example.graph-showcase Description: Interactive graph-richness showcase for ContractSpec P6 primitives: mini-map, focus-mode, custom renderers, edge labels, animations, and drilldown. Path: examples/graph-showcase URL: /llms/example.graph-showcase # `@lssm-tech/example.graph-showcase` > **Showroom-grade interactive showcase** — 23 graph demos across 8 categories, > 4-engine layout (ELK DAG / Ortho / Tree + d3-force), 3-preset theme system with > full dark-mode, pointer/touch/keyboard interactions, and Playwright integration tests. ![Graph showcase — Workflow DAG, n8n-card light](./playwright/__screenshots__/responsive/desktop-after.png) ## What you'll see | Category | Demo screens | Default preset | |---|---|---| | **Templates** | Workflow DAG, Agent Tree, Conversation Graph, Engineering Loop, Person Activity | `n8n-card` | | **Filtering** | Facet Panel, Filter Chip Rack, Search Overlay, Path Highlight | `gh-slim` | | **Time** | Time Scrub, Diff Animations, Saved View Restore | `gh-slim` | | **Structure** | Clustering, Heatmap, Minimap, Focus Mode | `gh-slim` | | **AI** | AI Input, AI Suggest+Confirm | `n8n-card` | | **Annotations** | Annotations, Story Mode | `obsidian-dot` | | **Collab** | Collab Cursors, Subscribe | `obsidian-dot` | | **Export** | Export Pipeline | `obsidian-dot` | ## Interactions | Action | Pointer | Touch | Keyboard | |---|---|---|---| | Navigate sidebar | Click item | Tap item | `↑` / `↓`, then `Enter` | | Collapse sidebar | Click hamburger | Tap hamburger | `⌘B` / `Ctrl+B` | | Pan canvas | Drag background | 1-finger swipe | `Space` + drag | | Zoom in / out | Scroll wheel | 2-finger pinch | `+` / `-` via ZoomCluster | | Fit graph to view | Click Auto-fit | — | Auto-fit button | | Select node | Click | Tap | `Tab` to node, `Space` | | Deselect / close | Click empty area | Tap empty | `Escape` | | Open search | Click search bar | — | `/` | | Open command palette | Click search bar | — | `⌘K` / `Ctrl+K` | | Switch layout engine | Click pill in DemoHeader | — | Click only | | Toggle dark mode | Click ☾ / ☀ in AppBar | — | Click only | ## Shell The showcase uses a hash-based router (`useShowcaseRouter`) with 23 `SHOWCASE_ROUTES` entries (`key / label / category / recommendedTheme`). Each demo is wrapped in `` — the shell auto-selects the best visual preset per route. Global keyboard handlers in `ShowcaseShell`: `⌘K` / `Ctrl+K` → `CommandPalette`; `/` → `SearchBar`. ## Theme presets Three presets ship with WCAG AA 4.5:1 verified tokens in both light and dark. | Preset | Mode | Background | Node fill | Character | |---|---|---|---|---| | `n8n-card` | light | `#FAF4EC` warm cream | `#FFF8F0` | Rounded cards, warm workflow builder | | `n8n-card` | dark | `#0E0D0B` near-black | `#1C1A17` warm | Immersive dark workflow | | `gh-slim` | light | `#F8FAFC` cool white | `#F1F5F9` | Compact GitHub-style DAG | | `gh-slim` | dark | `#020617` near-navy | `#1E293B` slate | Dark compact DAG | | `obsidian-dot` | light | `#F5F3FF` violet tint | `#EDE9FE` | Knowledge-graph dot style | | `obsidian-dot` | dark | `#0A0110` deep violet | `#1A0B2E` | Atmospheric dark dots | Toggle dark mode via **☾** in the AppBar. This sets `DesignSystemThemeProvider mode="dark"` and the Tailwind `dark` class on ``, updating both chrome surfaces (Tailwind `dark:` utilities) and graph tokens (`--graph-*` CSS vars via `CanvasVarsInjector`). ## Architecture ```mermaid graph TD DSP["DesignSystemThemeProvider\nmode: light | dark"] Shell["ShowcaseShell\ncontext providers · dark toggle"] AppBar["AppBar 48px\nlogo · search · GitHub · CTA · ☾"] SidebarNav["SidebarNav 240px\n23 routes · 8 categories · ⌘B"] DemoHeader["DemoHeader 56px\nbreadcrumb · role · layout pills"] CanvasArea["CanvasArea\nadaptive dot-grid · border"] GTP["GraphThemeProvider\nthemeId context"] CVI["CanvasVarsInjector\n--graph-* CSS vars"] Demo["Demo Screen\nWorkflowDagDemo · AgentTreeDemo …"] GC["GraphCanvas\nSVG renderer · useGraphLayout"] Atoms["Node / Edge Atoms\nN8nCardNode · GhSlimNode\nObsidianDotNode + edges"] DSP -->|wraps| Shell Shell --> AppBar Shell --> SidebarNav Shell --> DemoHeader Shell --> CanvasArea CanvasArea --> GTP GTP --> CVI CVI --> Demo Demo --> GC GC --> Atoms ``` **Token flow:** `DesignSystemThemeProvider(mode)` → `useGraphTheme(themeId)` inside `CanvasVarsInjector` → emits `--graph-node-fill`, `--graph-kind-{kind}-{fill|stroke|label|accent}` CSS vars on a wrapper `
` → atom components read them as `var(--graph-node-fill, )`. ## Fixture data All demo screens share synthetic fixtures in `src/fixtures.ts`: - **12 nodes** spanning 4 `kind` values (`contract`, `entity`, `event`, `feature`) - **14 directed edges** — mix of labeled and unlabeled - A **focus sub-graph** (6-node cluster) for minimap + focus-mode demos - Seed `Viewport` and `selection` values ## Usage ```ts import { SHOWCASE_ROUTES } from '@lssm-tech/example.graph-showcase'; // Enumerate all 23 route keys: SHOWCASE_ROUTES.forEach(r => console.log(r.key, r.category, r.recommendedTheme)); ``` ## Commands ```bash bun run typecheck # tsgo --noEmit bun test # unit + smoke tests (bun test runner) bun run test:e2e # Playwright integration tests (showcase config, port 5999) bun run lint:check # Biome lint check ``` ### Playwright integration tests | Suite | File | Coverage | |---|---|---| | Accessibility | `playwright/a11y.spec.ts` | S8.1–S8.5: landmarks, keyboard, reduced-motion | | Lighthouse | `playwright/lighthouse.spec.ts` | S9.2: performance + ARIA structure | | Touch | `playwright/touch.spec.ts` | S9.3: iPad Mini tap-to-navigate, sidebar | | Dark-mode | `playwright/template-darkmode.spec.ts` | S9.4: 10 PNG baselines (5 templates × light/dark) | | Responsive | `playwright/responsive.spec.ts` | E3: phone / tablet / desktop viewports | Regenerate dark-mode baselines: ```bash bun exec playwright test --config playwright.showcase.config.ts \ template-darkmode.spec.ts --update-snapshots ``` Declaration builds use `build:types` through the shared Bun tool; `build` runs bundle and declaration generation. Declared exports are preserved. Generated artifacts exclude test-only files; tests/typecheck remain separate gates. --- ## @lssm-tech/example.gtm-provider-recipes Description: (none) Path: examples/gtm-provider-recipes URL: /llms/example.gtm-provider-recipes # GTM provider recipes Fixture-backed composition examples for Attio, Clay, and FullEnrich. The recipes depend on stable ContractSpec operation keys and an injected executor; they never import provider implementations or make live vendor calls. ## Included flows - FullEnrich contact enrichment → Attio record assert. - Clay routine → Attio task creation. - Attio webhook event → Clay routine with a loop-prevention hop. - Async enrichment result → idempotent Attio update. Production verticals should run capability preflight first, resolve credentials through secret references, require approval for writes or credit-bearing work, mount raw webhook ingress separately from generated REST/MCP operations, and replace the fixture executor with their ContractSpec runtime registry. --- ## @lssm-tech/example.harness-lab Description: Focused harness example for ContractSpec scenarios, suites, orchestration, and runtime adapters. Path: examples/harness-lab URL: /llms/example.harness-lab # @lssm-tech/example.harness-lab Website: https://contractspec.io **Focused harness example for scenario contracts, suites, orchestration, and real runtime adapters.** ## What This Demonstrates - Contract layer: canonical `harness-scenario` and `harness-suite` exports. - Orchestration layer: `HarnessRunner`, `HarnessEvaluationRunner`, and replay bundle generation. - Runtime layer: `SandboxedCodeExecutionAdapter`, `PlaywrightBrowserHarnessAdapter`, optional `AgentBrowserHarnessAdapter`, `DefaultHarnessTargetResolver`, and `InMemoryHarnessArtifactStore`. - A deterministic local browser fixture that stays offline and exercises Playwright, auth profile refs, visual diff evidence, and optional agent-browser evidence. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/harness-lab`: - `bunx playwright install chromium` - `bun run build` - `bun run test` - `bun run typecheck` ## Sandbox Provider Pass an `IsolatedCodeSandboxPort` as `sandbox` to `runHarnessLabSandboxEvaluation({ sandbox })` or `createHarnessLabEvaluationTools({ sandbox })`. Without a provider, code execution is blocked. Choose a container, process, or remote provider with isolation suitable for your workload. The tests execute only the checked-in fixture scripts in a separate process; that fixture is not a sandbox for untrusted code. ## Usage Use `@lssm-tech/example.harness-lab` as the focused harness reference package. It pairs with `@lssm-tech/example.agent-console`, which remains the business-oriented proof example for harness contracts. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/harness-lab.feature.ts` defines the feature entrypoint for docs/discovery. - `src/index.ts` is the root public barrel and package entrypoint. - `src/runtime/` contains the runnable sandbox and browser evaluation helpers plus the local browser fixture. - `src/scenarios/` contains sandbox, Playwright browser, authenticated browser, visual baseline, and optional agent-browser scenario contracts. - `src/suite/` contains the dual-mode harness suite contract. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/harness-lab.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./harness-lab.feature` resolves through `./src/harness-lab.feature.ts`. - Export `./runtime` resolves through `./src/runtime/index.ts`. - Export `./runtime/runAgentBrowserEvaluation` resolves through `./src/runtime/runAgentBrowserEvaluation.ts`. - Export `./runtime/runAuthenticatedBrowserEvaluation` resolves through `./src/runtime/runAuthenticatedBrowserEvaluation.ts`. - Export `./runtime/runBrowserEvaluation` resolves through `./src/runtime/runBrowserEvaluation.ts`. - Export `./runtime/runSandboxEvaluation` resolves through `./src/runtime/runSandboxEvaluation.ts`. - Export `./runtime/runVisualEvaluation` resolves through `./src/runtime/runVisualEvaluation.ts`. - Export `./scenarios` resolves through `./src/scenarios/index.ts`. - Export `./scenarios/harnessLabAgentBrowser.scenario` resolves through `./src/scenarios/harnessLabAgentBrowser.scenario.ts`. - Export `./scenarios/harnessLabAuthenticatedBrowser.scenario` resolves through `./src/scenarios/harnessLabAuthenticatedBrowser.scenario.ts`. - Export `./scenarios/harnessLabBrowser.scenario` resolves through `./src/scenarios/harnessLabBrowser.scenario.ts`. - Export `./scenarios/harnessLabSandbox.scenario` resolves through `./src/scenarios/harnessLabSandbox.scenario.ts`. - Export `./scenarios/harnessLabVisual.scenario` resolves through `./src/scenarios/harnessLabVisual.scenario.ts`. - Export `./suite` resolves through `./src/suite/index.ts`. - The package publishes 21 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 ## Notes - Browser tests use a real local Playwright run against an in-package HTTP fixture. Install Chromium locally before running `bun run test`. - Agent-browser tests are optional and skip automatically when the `agent-browser` CLI is unavailable. - Authenticated scenarios use named auth profile refs; storage state is created by the test harness and credentials are not embedded in scenario specs. --- ## @lssm-tech/example.in-app-docs Description: Example showing how to use DocBlock for in-app documentation for non-technical users Path: examples/in-app-docs URL: /llms/example.in-app-docs # @lssm-tech/example.in-app-docs Website: https://contractspec.io **Example showing how to use DocBlock for in-app documentation for non-technical users.** ## What This Demonstrates - DocBlock-driven in-app documentation pattern. - React viewer component for rendering DocBlocks. - User-facing documentation without technical jargon. - `src/docs/` contains docblocks and documentation-facing exports. - `src/ui/` contains packaged UI exports and embeddable views. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/in-app-docs`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.in-app-docs` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/in-app-docs.feature.ts` defines a feature entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/ui/` contains packaged UI exports and embeddable views. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/in-app-docs.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./in-app-docs.feature` resolves through `./src/in-app-docs.feature.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - Export `./ui/InAppDocsViewer` resolves through `./src/ui/InAppDocsViewer.tsx`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.integration-hub Description: Integration Hub example with sync engine and field mappings for ContractSpec Path: examples/integration-hub URL: /llms/example.integration-hub # @lssm-tech/example.integration-hub Website: https://contractspec.io **Integration Hub example with sync engine and field mappings for ContractSpec.** ## What This Demonstrates - Connection management with typed schemas and enums. - Integration lifecycle (create, configure, sync). - Sync engine with field mapping and status tracking. - MCP server example for tool integration. - Capability and feature definition patterns. - React UI with a cockpit-style Integration Hub command center, screen navigation, hooks, markdown renderers, and shared ContractSpec tables for connections and sync configs. - Contract-backed visualizations for integration mix, connection health, and sync-state comparison. - Client-mode table capabilities including sorting, pagination, column visibility, pinning, resizing, and expanded operational details. - Event definitions and operation test-specs. - Managed/BYOK credential setup metadata with monorepo-aware Next and Expo env aliases plus an interactive mode switch in the hub UI. - Registry-derived provider seeding from `createDefaultIntegrationSpecRegistry()` so the preview covers the complete shipped integration catalog, including BYOK-only entries with explicit managed-mode exemption metadata. - Redacted connection credential previews; handlers return secret placeholders instead of raw key material. - Runtime resolver and governance screens that explain managed/BYOK fallback, policy evidence, and release-review posture. - Managed/BYOK database mutation examples in `src/setup/database-mutation-examples.ts` route durable writes through the provider-database `./governed-mutation` helper only after an owning domain command emits `domainCommandRef`, `policyDecisionRef`, `idempotencyKey`, `transactionBoundary`, `expectedWriteSet`, `auditEventRefs`, `replayRef`, and `correlationRef` evidence; fixtures use redacted refs only and never embed raw database credentials. - Phase 5 DS1/DS4: all UI cards in the catalog use `IntegrationCardSurface` (hover elevation + focus ring) and `IntegrationHealthDot` from `@lssm-tech/bundle.managed-companyos/ui/integrations`. Empty states use `EmptyStateIllustrated`. The credential setup flow is wrapped in `WizardStepper`. A dedicated **Rich Interactions** screen demonstrates every DS1 atom and molecule in one place. ## Reusable bundle integration The example demonstrates the Integration Hub but does not own the reusable Managed CompanyOS production surfaces. Hosts should compose the canonical bundle surfaces directly: - View-model builders from `@lssm-tech/bundle.managed-companyos/view-models/integration-*`. - Templates from `@lssm-tech/bundle.managed-companyos/ui/templates`. - Capability atoms and design primitives from `@lssm-tech/bundle.managed-companyos/ui/integrations`. Example UI files should remain demo/adaptation layers over those imports. Do not fork credential, secret, connection, sync, audit, or role-morph logic locally. Managed/BYOK turn-on flows must require an explicit ownership-mode choice and may render only redacted credential references. ## Design System Integration (Phase 5 DS1) The example **imports** DS1 primitives from the bundle — it does not re-implement them. | Primitive | Origin | Usage in example | |---|---|---| | `IntegrationCardSurface` | `atoms-design` bundle | Provider catalog cards | | `IntegrationHealthDot` | `atoms-design` bundle | Status dot in catalog + rich-interactions | | `EmptyStateIllustrated` | `molecules-design` bundle | Catalog empty state, rich-interactions | | `LastRunPill` | `atoms-design` bundle | Rich interactions showcase | | `RotationCountdown` | `atoms-design` bundle | Rich interactions showcase | | `ScopeChip` | `atoms-design` bundle | Rich interactions showcase | | `SecurityShieldBadge` | `atoms-design` bundle | Rich interactions showcase | | `AffinityScoreBar` | `atoms-design` bundle | Recommended row demo | | `WizardStepper` | `molecules-design` bundle | Credential setup preview | | `DiffPreviewCard` | `molecules-design` bundle | Sync drift banner demo | **Consumers** that want to adopt these primitives directly should import from `@lssm-tech/bundle.managed-companyos/ui/integrations` — not from this example package. ## Running Locally From `examples/integration-hub`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.integration-hub` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/connection` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/integration` is part of the package's public or composition surface. - `src/setup` exposes BYOK credential manifests, secret-reference fixtures, and monorepo env aliases. - `src/ui/IntegrationDashboard.*` subpaths expose advanced UI composition pieces for hosts that want to reuse the command-center shell, navigation, screen model, or individual rich screens. The default `./ui/IntegrationDashboard` export wraps its command center in the shared `NestedCommandShell` from `@lssm-tech/lib.example-shared-ui`; keep local navigation inside that reusable nested-safe shell unless a preview-specific containment guardrail requires otherwise. Prefer `./ui/IntegrationDashboard` unless custom composition is required. - Production apps should consume bundle Integration Hub view-models/templates directly; this package remains an example adapter and documentation surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./connection` resolves through `./src/connection/index.ts`. - Export `./connection/connection.enum` resolves through `./src/connection/connection.enum.ts`. - Export `./connection/connection.operation` resolves through `./src/connection/connection.operation.ts`. - Export `./connection/connection.presentation` resolves through `./src/connection/connection.presentation.ts`. - Export `./connection/connection.schema` resolves through `./src/connection/connection.schema.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/integration-hub.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./setup` resolves through `./src/setup/index.ts`. - Export `./setup/credential-setup` resolves through `./src/setup/credential-setup.ts`. - The package publishes 52 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 validate` — contractspec validate "src/**/*" - `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 run:mcp` — bun tsx src/run-mcp.ts - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Vnext ai-native. - Missing contract layers. - Resolve lint, build, and type errors across nine packages. - Add Composio universal fallback, fix provider-ranking types, and expand package exports. - Add first-class transport, auth, versioning, and BYOK support across all integrations. - Add Integration Hub BYOK credential setup metadata and Next/Expo alias previews. - Seed Integration Hub from the shipped provider registry and expose typed ownership mode plus redacted credential previews through handler flows. - Upgrade the Integration Hub dashboard into a rich command-center demo with provider catalog, managed/BYOK credential, connection, sync, runtime governance, and assistant screens. ## Notes - Works alongside `@lssm-tech/lib.ai-agent`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.runtime-sandbox`, ... UI projection imports use existing domain-specific view-model subpaths to avoid loading unrelated server domains through the all-domain barrel. --- ## @lssm-tech/example.integration-paypal Description: Credential-free PayPal commerce integration example with deterministic policy handoffs. Path: examples/integration-paypal URL: /llms/example.integration-paypal # @lssm-tech/example.integration-paypal Credential-free PayPal commerce example built on the canonical `paypalIntegrationSpec`. ## What This Demonstrates - Canonical integration reuse from `@lssm-tech/lib.contracts-integrations`. - Deterministic checkout, buyer approval, capture, refund, subscription, webhook, and marketplace lifecycle fixtures. - Explicit human and policy handoffs for approval, refunds, seller onboarding, and payouts. - A redacted sandbox connection plus stable tenant timestamps. - No provider SDK execution, outbound network calls, or usable credentials. ## Public Entry Points - `.` — complete example barrel. - `./integration` — canonical PayPal integration re-export. - `./workflow` — deterministic commerce lifecycle. - `./blueprint` and `./tenant` — app and tenant configuration. - `./connection.sample` — redacted connection metadata. - `./integration-paypal.feature` — feature composition. - `./docs` and its alias `./docs/integration-paypal.docblock` — documentation registration. - `./example` — example registry descriptor. ## Running Locally From `examples/integration-paypal`: - `bun run test` - `bun run typecheck` - `bun run lint:check` - `bun run build` ## Host Boundary This package describes contracts only. A host must supply authenticated PayPal adapters, webhook verification, approval gateways, tenant isolation, and recorded policy evidence. Never put client secrets or access tokens in connection config. --- ## @lssm-tech/example.integration-posthog Description: PostHog analytics integration example: capture events, run HogQL, and manage feature flags. Path: examples/integration-posthog URL: /llms/example.integration-posthog # @lssm-tech/example.integration-posthog Website: https://contractspec.io **PostHog analytics integration example: capture events, run HogQL, and manage feature flags.** ## What This Demonstrates - PostHog event capture and tracking setup. - HogQL query execution pattern. - Feature flag management via PostHog API. - Integration provider pattern with ContractSpec contracts. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/integration-posthog`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.integration-posthog` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/integration-posthog.feature.ts` defines a feature entrypoint. - `src/posthog.ts` is part of the package's public or composition surface. - `src/run.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/integration-posthog.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./integration-posthog.feature` resolves through `./src/integration-posthog.feature.ts`. - Export `./posthog` resolves through `./src/posthog.ts`. - Export `./run` resolves through `./src/run.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 changesets and apply pending fixes. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-analytics`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.integration-stripe Description: Integration example – Stripe Payments (blueprint + workflow + tenant config). Path: examples/integration-stripe URL: /llms/example.integration-stripe # @lssm-tech/example.integration-stripe Website: https://contractspec.io Credential-free Stripe commerce example built on the canonical `stripeIntegrationSpec`. ## What This Demonstrates - Canonical `stripeIntegrationSpec` export, with `StripePaymentsIntegrationSpec` retained as a compatibility alias. - Integration-oriented `app-config` example via `defineAppConfig(...)`. - Deterministic authorization, capture, refund, subscription, webhook, and Connect lifecycle fixtures. - Explicit policy handoffs for authorization, refunds, connected accounts, and payouts. - Multi-tenant configuration pattern. - Connection sample for credential wiring. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/integration-stripe`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.integration-stripe` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/blueprint.ts` is part of the package's public or composition surface. - `src/connection.sample.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/integration.ts` defines the exported integration spec. - `src/index.ts` is the root public barrel and package entrypoint. - `src/integration-stripe.feature.ts` defines a feature entrypoint. - `src/tenant.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./blueprint` resolves through `./src/blueprint.ts`. - Export `./connection.sample` resolves through `./src/connection.sample.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/integration-stripe.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./integration` resolves through `./src/integration.ts`. - Export `./integration-stripe.feature` resolves through `./src/integration-stripe.feature.ts`. - Export `./tenant` resolves through `./src/tenant.ts`. - Export `./workflow` resolves through `./src/workflow.ts`. - The package publishes 9 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.integration-supabase Description: Integration example - Supabase vector store + Postgres database wiring. Path: examples/integration-supabase URL: /llms/example.integration-supabase # @lssm-tech/example.integration-supabase Website: https://contractspec.io **Integration example - Supabase vector store + Postgres database wiring.** ## What This Demonstrates - Integration blueprint for Supabase vector store + Postgres. - Multi-tenant configuration pattern. - Connection sample for credential wiring. - Runtime sample for execution context setup. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/integration-supabase`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.integration-supabase` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/blueprint.ts` is part of the package's public or composition surface. - `src/connection.sample.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/integration-supabase.feature.ts` defines a feature entrypoint. - `src/runtime.sample.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./blueprint` resolves through `./src/blueprint.ts`. - Export `./connection.sample` resolves through `./src/connection.sample.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/integration-supabase.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./integration-supabase.feature` resolves through `./src/integration-supabase.feature.ts`. - Export `./runtime.sample` resolves through `./src/runtime.sample.ts`. - Export `./tenant` resolves through `./src/tenant.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.providers-impls`, `@lssm-tech/integration.runtime`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.kb-update-pipeline Description: Example: KB update automation pipeline with HITL review and auditability. Path: examples/kb-update-pipeline URL: /llms/example.kb-update-pipeline # @lssm-tech/example.kb-update-pipeline Website: https://contractspec.io **Example: KB update automation pipeline with HITL review and auditability.** ## What This Demonstrates - HITL (human-in-the-loop) review pipeline pattern. - Entity models for KB articles and update proposals. - Event-driven pipeline with typed operations. - Feature definition with presentations and test-specs. - In-memory handlers for demo scenarios. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/kb-update-pipeline`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.kb-update-pipeline` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/kb-update-pipeline.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/kb-update-pipeline.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./entities/models` resolves through `./src/entities/models.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./handlers/memory.handlers` resolves through `./src/handlers/memory.handlers.ts`. - Export `./kb-update-pipeline.feature` resolves through `./src/kb-update-pipeline.feature.ts`. - The package publishes 14 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.knowledge-canon Description: Knowledge example – Product Canon space (blueprint + tenant config + source sample + runtime helper). Path: examples/knowledge-canon URL: /llms/example.knowledge-canon # @lssm-tech/example.knowledge-canon Website: https://contractspec.io **Knowledge example – Product Canon space (blueprint + tenant config + source sample + real `lib.knowledge` retrieval helper).** ## What This Demonstrates - Canonical `knowledge-space` export via `ProductCanonKnowledgeSpace`. - Lightweight `app-config` example via `defineAppConfig(...)`. - Multi-tenant configuration for knowledge bases. - Source sample for content ingestion. - Agent helper backed by `@lssm-tech/lib.knowledge` static retrieval. - Minimal contract-only example pattern. - `src/docs/` contains docblocks and documentation-facing exports. - The same runtime primitives can ingest Gmail and Google Drive sources through `KnowledgeRuntime` when a workspace wires provider implementations. ## Running Locally From `examples/knowledge-canon`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.knowledge-canon` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. The public `answerWithKnowledge(...)` helper now performs a real retrieval step through `@lssm-tech/lib.knowledge`, so the example is suitable as a copy-pasteable lightweight knowledge-routing pattern. For provider-backed workspaces, compose the same package with `createKnowledgeRuntime({ gmail, drive, ... })` and call `syncGmail(...)` or `syncDriveFiles(...)` before retrieval. Mutating external knowledge systems should use the governance helpers from `@lssm-tech/lib.knowledge/governance` so dry-runs, approval refs, idempotency keys, audit evidence, and outbound-send gates are captured consistently. ## Architecture - `src/agent.ts` is part of the package's public or composition surface. - `src/blueprint.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the package example manifest/metadata entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/knowledge-canon.feature.ts` defines a feature entrypoint. - `src/product-canon.space.ts` defines the exported knowledge-space spec. - `src/source.sample.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./agent` resolves through `./src/agent.ts`. - Export `./blueprint` resolves through `./src/blueprint.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/knowledge-canon.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./knowledge-canon.feature` resolves through `./src/knowledge-canon.feature.ts`. - Export `./product-canon.space` resolves through `./src/product-canon.space.ts`. - Export `./source.sample` resolves through `./src/source.sample.ts`. - Export `./tenant` resolves through `./src/tenant.ts`. - The package publishes 9 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-ambient-coach Description: Ambient coach learning journey example with contextual tips and follow-up actions. Path: examples/learning-journey-ambient-coach URL: /llms/example.learning-journey-ambient-coach # @lssm-tech/example.learning-journey-ambient-coach Website: https://contractspec.io **Ambient coach learning journey example with contextual tips and follow-up actions.** ## What This Demonstrates - Ambient coaching track definition using the learning-journey module. - Contextual tip delivery based on user activity. - Follow-up action triggers. - Lightweight track + example pattern. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-ambient-coach`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-ambient-coach` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-ambient-coach.feature.ts` defines a feature entrypoint. - `src/track.test.ts` is part of the package's public or composition surface. - `src/track.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/ambient-coach.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./learning-journey-ambient-coach.feature` resolves through `./src/learning-journey-ambient-coach.feature.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-crm-onboarding Description: Learning journey track that onboards users to the CRM pipeline example. Path: examples/learning-journey-crm-onboarding URL: /llms/example.learning-journey-crm-onboarding # @lssm-tech/example.learning-journey-crm-onboarding Website: https://contractspec.io **Learning journey track that onboards users to the CRM pipeline example.** ## What This Demonstrates - CRM-specific onboarding track with step-by-step guidance. - Feature definition with operations, presentations, and test-specs. - Demo handlers for simulated onboarding flow. - Cross-example dependency (builds on crm-pipeline). - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/learning-journey-crm-onboarding`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.learning-journey-crm-onboarding` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-crm-onboarding.feature.ts` defines a feature entrypoint. - `src/operations` is part of the package's public or composition surface. - `src/presentations` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/crm-onboarding.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/demo.handlers` resolves through `./src/handlers/demo.handlers.ts`. - Export `./learning-journey-crm-onboarding.feature` resolves through `./src/learning-journey-crm-onboarding.feature.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./presentations` resolves through `./src/presentations/index.ts`. - Export `./tests/operations.test-spec` resolves through `./src/tests/operations.test-spec.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.crm-pipeline`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.learning-journey-duo-drills Description: Drill-based learning journey example with SRS, XP, and streak hooks. Path: examples/learning-journey-duo-drills URL: /llms/example.learning-journey-duo-drills # @lssm-tech/example.learning-journey-duo-drills Website: https://contractspec.io **Drill-based learning journey example with SRS, XP, and streak hooks.** ## What This Demonstrates - Drill-based learning track with SRS scheduling. - XP and streak gamification hooks. - Lightweight track + example pattern. - Integration with the learning-journey module. - Optional generic `drillsGamificationCampaign` composition while retaining the existing learning journey track and imports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-duo-drills`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-duo-drills` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-duo-drills.feature.ts` defines a feature entrypoint. - `src/track.test.ts` is part of the package's public or composition surface. - `src/track.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/duo-drills.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./generic-campaign` resolves through `./src/generic-campaign.ts`. - Export `./learning-journey-duo-drills.feature` resolves through `./src/learning-journey-duo-drills.feature.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-managed-onboarding Description: Standalone managed onboarding reference proof for Learning Journey scenarios. Path: examples/learning-journey-managed-onboarding URL: /llms/example.learning-journey-managed-onboarding # Learning Journey Managed Onboarding Standalone reference proof for the managed onboarding foundation in `@lssm-tech/module.learning-journey`. The package turns the module-owned managed platform, SpecialOps, and AI Ops proof scenario adapters into deterministic reference UI view models. It demonstrates checklist, timeline, story, annotation, and presenter-cursor concepts without importing from other examples. ## Boundary - Imports only from `@lssm-tech/module.learning-journey` and `@lssm-tech/lib.contracts-spec`. - Does not import `@lssm-tech/example.*` packages. - Uses fixture/proof references only; no external credentials, production endpoints, provider execution, outbound sends, or real customer data. - AI Ops remains `proof-guidance-only` and exposes no sprint-product operation controls. ## Commands ```bash bun test --pass-with-no-tests bun run typecheck bun run lint:check ``` --- ## @lssm-tech/example.learning-journey-platform-tour Description: Learning journey track covering ContractSpec platform primitives. Path: examples/learning-journey-platform-tour URL: /llms/example.learning-journey-platform-tour # @lssm-tech/example.learning-journey-platform-tour Website: https://contractspec.io **Learning journey track covering ContractSpec platform primitives.** ## What This Demonstrates - Platform primitives tour with step-by-step guidance. - Feature definition with operations, presentations, and test-specs. - Demo handlers for simulated tour flow. - Interactive exploration of ContractSpec concepts. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/learning-journey-platform-tour`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.learning-journey-platform-tour` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-platform-tour.feature.ts` defines a feature entrypoint. - `src/operations` is part of the package's public or composition surface. - `src/presentations` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/platform-tour.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/demo.handlers` resolves through `./src/handlers/demo.handlers.ts`. - Export `./learning-journey-platform-tour.feature` resolves through `./src/learning-journey-platform-tour.feature.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./presentations` resolves through `./src/presentations/index.ts`. - Export `./tests/operations.test-spec` resolves through `./src/tests/operations.test-spec.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-quest-challenges Description: Time-bound quest/challenge learning journey example. Path: examples/learning-journey-quest-challenges URL: /llms/example.learning-journey-quest-challenges # @lssm-tech/example.learning-journey-quest-challenges Website: https://contractspec.io **Time-bound quest/challenge learning journey example.** ## What This Demonstrates - Quest/challenge track with time-bound objectives. - Optional generic mission-slot campaign exported beside the unchanged learning journey track. - Completion tracking and deadline enforcement. - Lightweight track + example pattern. - Integration with the learning-journey module. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-quest-challenges`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-quest-challenges` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-quest-challenges.feature.ts` defines a feature entrypoint. - `src/track.test.ts` is part of the package's public or composition surface. - `src/track.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/quest-challenges.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./generic-campaign` resolves through `./src/generic-campaign.ts`. - Export `./learning-journey-quest-challenges.feature` resolves through `./src/learning-journey-quest-challenges.feature.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-registry Description: Registry that aggregates learning journey example tracks. Path: examples/learning-journey-registry URL: /llms/example.learning-journey-registry # @lssm-tech/example.learning-journey-registry Website: https://contractspec.io **Registry that aggregates learning journey example tracks.** ## What This Demonstrates - Track aggregation and discovery via a central registry. - Feature definition pattern (`learning-journey-registry.feature`). - Progress store for cross-track state. - API and API-types separation for typed endpoints. - Presentation layer with LearningMiniApp UI. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-registry`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-registry` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/api-types.ts` is part of the package's public or composition surface. - `src/api.test.ts` is part of the package's public or composition surface. - `src/api.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-registry.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./api` resolves through `./src/api.ts`. - Export `./api-types` resolves through `./src/api-types.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-journey-registry.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./learning-journey-registry.feature` resolves through `./src/learning-journey-registry.feature.ts`. - Export `./presentations` resolves through `./src/presentations/index.ts`. - Export `./progress-store` resolves through `./src/progress-store.ts`. - Export `./tracks` resolves through `./src/tracks.ts`. - The package publishes 12 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.learning-journey-ambient-coach`, `@lssm-tech/example.learning-journey-crm-onboarding`, `@lssm-tech/example.learning-journey-duo-drills`, `@lssm-tech/example.learning-journey-platform-tour`, `@lssm-tech/example.learning-journey-quest-challenges`, ... --- ## @lssm-tech/example.learning-journey-studio-onboarding Description: Learning journey track for first 30 minutes in ContractSpec Studio. Path: examples/learning-journey-studio-onboarding URL: /llms/example.learning-journey-studio-onboarding # @lssm-tech/example.learning-journey-studio-onboarding Website: https://contractspec.io **Learning journey track for first 30 minutes in ContractSpec Studio.** ## What This Demonstrates - Studio onboarding track with time-boxed steps. - Feature definition with operations, presentations, and test-specs. - Demo handlers for simulated onboarding flow. - First-run experience pattern for new users. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/learning-journey-studio-onboarding`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.learning-journey-studio-onboarding` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-studio-onboarding.feature.ts` defines a feature entrypoint. - `src/operations` is part of the package's public or composition surface. - `src/presentations` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/studio-onboarding.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/demo.handlers` resolves through `./src/handlers/demo.handlers.ts`. - Export `./learning-journey-studio-onboarding.feature` resolves through `./src/learning-journey-studio-onboarding.feature.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./presentations` resolves through `./src/presentations/index.ts`. - Export `./tests/operations.test-spec` resolves through `./src/tests/operations.test-spec.ts`. - Export `./track` resolves through `./src/track.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.learning-journey-ui-coaching Description: Contextual coaching UI with tip cards and engagement tracking. Path: examples/learning-journey-ui-coaching URL: /llms/example.learning-journey-ui-coaching # @lssm-tech/example.learning-journey-ui-coaching Website: https://contractspec.io **Contextual coaching UI with tip cards and engagement tracking.** ## What This Demonstrates - CoachingMiniApp as a self-contained React application. - TipCard, TipFeed, and EngagementMeter components. - Multi-view layout (Overview, Progress, Steps, Timeline). - Integration with ambient-coach and crm-onboarding tracks. - Design system and UI kit usage patterns. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-ui-coaching`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-ui-coaching` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/CoachingMiniApp.tsx` is part of the package's public or composition surface. - `src/components/` contains reusable UI components and view composition. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-ui-coaching.feature.ts` defines a feature entrypoint. - `src/views/` contains view-level composition. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./CoachingMiniApp` resolves through `./src/CoachingMiniApp.tsx`. - Export `./components` resolves through `./src/components/index.ts`. - Export `./components/EngagementMeter` resolves through `./src/components/EngagementMeter.tsx`. - Export `./components/TipCard` resolves through `./src/components/TipCard.tsx`. - Export `./components/TipFeed` resolves through `./src/components/TipFeed.tsx`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-journey-ui-coaching.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./learning-journey-ui-coaching.feature` resolves through `./src/learning-journey-ui-coaching.feature.ts`. - The package publishes 15 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.learning-journey-ambient-coach`, `@lssm-tech/example.learning-journey-crm-onboarding`, `@lssm-tech/example.learning-journey-ui-shared`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, ... --- ## @lssm-tech/example.learning-journey-ui-gamified Description: Duolingo-style gamified learning UI for drills and quests. Path: examples/learning-journey-ui-gamified URL: /llms/example.learning-journey-ui-gamified # @lssm-tech/example.learning-journey-ui-gamified Website: https://contractspec.io **Duolingo-style gamified learning UI for drills and quests.** ## What This Demonstrates - GamifiedMiniApp as a self-contained React application. - FlashCard, DayCalendar, and MasteryRing components. - Multi-view layout (Overview, Progress, Steps, Timeline). - Integration with duo-drills and quest-challenges tracks. - Design system and UI kit usage patterns. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-ui-gamified`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-ui-gamified` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/components/` contains reusable UI components and view composition. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/GamifiedMiniApp.tsx` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-ui-gamified.feature.ts` defines a feature entrypoint. - `src/views/` contains view-level composition. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./components` resolves through `./src/components/index.ts`. - Export `./components/DayCalendar` resolves through `./src/components/DayCalendar.tsx`. - Export `./components/FlashCard` resolves through `./src/components/FlashCard.tsx`. - Export `./components/MasteryRing` resolves through `./src/components/MasteryRing.tsx`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-journey-ui-gamified.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./GamifiedMiniApp` resolves through `./src/GamifiedMiniApp.tsx`. - Export `./learning-journey-ui-gamified.feature` resolves through `./src/learning-journey-ui-gamified.feature.ts`. - The package publishes 15 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.learning-journey-duo-drills`, `@lssm-tech/example.learning-journey-quest-challenges`, `@lssm-tech/example.learning-journey-ui-shared`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, ... --- ## @lssm-tech/example.learning-journey-ui-onboarding Description: Developer onboarding UI with checklists and journey maps. Path: examples/learning-journey-ui-onboarding URL: /llms/example.learning-journey-ui-onboarding # @lssm-tech/example.learning-journey-ui-onboarding Website: https://contractspec.io **Developer onboarding UI with checklists and journey maps.** ## What This Demonstrates - React-based onboarding mini-app with checklist and journey map components. - Multi-view layout (Overview, Progress, Steps, Timeline). - Shared UI component reuse across learning journey examples. - DocBlock-driven documentation pattern. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-ui-onboarding`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-ui-onboarding` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/components/` contains reusable UI components and view composition. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-ui-onboarding.feature.ts` defines a feature entrypoint. - `src/OnboardingMiniApp.tsx` is part of the package's public or composition surface. - `src/views/` contains view-level composition. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./components` resolves through `./src/components/index.ts`. - Export `./components/CodeSnippet` resolves through `./src/components/CodeSnippet.tsx`. - Export `./components/JourneyMap` resolves through `./src/components/JourneyMap.tsx`. - Export `./components/StepChecklist` resolves through `./src/components/StepChecklist.tsx`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-journey-ui-onboarding.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./learning-journey-ui-onboarding.feature` resolves through `./src/learning-journey-ui-onboarding.feature.ts`. - Export `./OnboardingMiniApp` resolves through `./src/OnboardingMiniApp.tsx`. - The package publishes 15 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.learning-journey-platform-tour`, `@lssm-tech/example.learning-journey-studio-onboarding`, `@lssm-tech/example.learning-journey-ui-shared`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, ... --- ## @lssm-tech/example.learning-journey-ui-shared Description: Shared UI components and hooks for learning journey mini-apps. Path: examples/learning-journey-ui-shared URL: /llms/example.learning-journey-ui-shared # @lssm-tech/example.learning-journey-ui-shared Website: https://contractspec.io **Shared UI components and hooks for learning journey mini-apps.** ## What This Demonstrates - Reusable gamification components (XpBar, StreakCounter, BadgeDisplay, ViewTabs). - Custom hook pattern (`useLearningProgress`) for shared state. - Shared types for cross-mini-app consistency. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-journey-ui-shared`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-journey-ui-shared` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/components/` contains reusable UI components and view composition. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/hooks/` contains custom hooks for host applications. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-journey-ui-shared.feature.ts` defines a feature entrypoint. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./components` resolves through `./src/components/index.ts`. - Export `./components/BadgeDisplay` resolves through `./src/components/BadgeDisplay.tsx`. - Export `./components/StreakCounter` resolves through `./src/components/StreakCounter.tsx`. - Export `./components/ViewTabs` resolves through `./src/components/ViewTabs.tsx`. - Export `./components/XpBar` resolves through `./src/components/XpBar.tsx`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-journey-ui-shared.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./hooks` resolves through `./src/hooks/index.ts`. - The package publishes 13 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.ui-kit-web`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.learning-patterns Description: Example: drills + ambient coach + quests learning patterns, powered by Learning Journey (event-driven, deterministic). Path: examples/learning-patterns URL: /llms/example.learning-patterns # @lssm-tech/example.learning-patterns Website: https://contractspec.io **Example: drills + ambient coach + quests learning patterns, powered by Learning Journey (event-driven, deterministic).** ## What This Demonstrates - Three distinct learning track patterns: drills, ambient-coach, quests. - Event-driven track progression. - Deterministic state transitions via the Learning Journey module. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/learning-patterns`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.learning-patterns` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/learning-patterns.feature.ts` defines a feature entrypoint. - `src/learning-patterns.test.ts` is part of the package's public or composition surface. - `src/tracks` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/learning-patterns.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./learning-patterns.feature` resolves through `./src/learning-patterns.feature.ts`. - Export `./tracks` resolves through `./src/tracks/index.ts`. - Export `./tracks/ambient-coach` resolves through `./src/tracks/ambient-coach.ts`. - Export `./tracks/drills` resolves through `./src/tracks/drills.ts`. - Export `./tracks/quests` resolves through `./src/tracks/quests.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/module.learning-journey`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.lifecycle-cli Description: Lifecycle CLI demo (example): run lifecycle assessment without an HTTP server. Path: examples/lifecycle-cli URL: /llms/example.lifecycle-cli # @lssm-tech/example.lifecycle-cli Website: https://contractspec.io **Lifecycle CLI demo (example): run lifecycle assessment without an HTTP server.** ## What This Demonstrates - Headless lifecycle assessment execution via CLI. - Bundle consumption pattern (lifecycle-managed). - Logger integration for CLI output. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/lifecycle-cli`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.lifecycle-cli` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/demo.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/lifecycle-cli.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./demo` resolves through `./src/demo.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/lifecycle-cli.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./lifecycle-cli.feature` resolves through `./src/lifecycle-cli.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/bundle.lifecycle-managed`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.lifecycle`, `@lssm-tech/lib.logger`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.lifecycle-dashboard Description: Lifecycle dashboard example (snippet): how to call lifecycle-managed APIs and render a status card. Path: examples/lifecycle-dashboard URL: /llms/example.lifecycle-dashboard # @lssm-tech/example.lifecycle-dashboard Website: https://contractspec.io **Lifecycle dashboard example (snippet): how to call lifecycle-managed APIs and render a status card.** ## What This Demonstrates - Lifecycle API consumption pattern. - Status card rendering snippet. - Minimal dependency footprint for quick integration. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/lifecycle-dashboard`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.lifecycle-dashboard` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/lifecycle-dashboard.feature.ts` defines a feature entrypoint. - `src/snippets` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/lifecycle-dashboard.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./lifecycle-dashboard.feature` resolves through `./src/lifecycle-dashboard.feature.ts`. - Export `./snippets/page` resolves through `./src/snippets/page.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.locale-jurisdiction-gate Description: Example: enforce locale + jurisdiction + kbSnapshotId + allowed scope for assistant calls (fail-closed). Path: examples/locale-jurisdiction-gate URL: /llms/example.locale-jurisdiction-gate # @lssm-tech/example.locale-jurisdiction-gate Website: https://contractspec.io **Example: enforce locale + jurisdiction + kbSnapshotId + allowed scope for assistant calls (fail-closed).** ## What This Demonstrates - Canonical `policy` export via `AssistantGatePolicy`. - Canonical `form` export via `AssistantContextForm`. - Canonical `translation` exports for `en-US`, `en-GB`, and `fr-FR`. - Fail-closed policy guard pattern for AI assistant calls. - Entity models for locale/jurisdiction gating. - Event-driven policy enforcement. - Handler and operation separation with typed operations. - Feature definition pattern. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/locale-jurisdiction-gate`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.locale-jurisdiction-gate` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/forms/` contains the exported assistant context form spec. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/locale-jurisdiction-gate.feature.ts` defines a feature entrypoint. - `src/translations/` contains the exported locale catalogs. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/locale-jurisdiction-gate.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./entities/models` resolves through `./src/entities/models.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./forms` resolves through `./src/forms/index.ts`. - Export `./forms/assistant-context.form` resolves through `./src/forms/assistant-context.form.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./handlers/demo.handlers` resolves through `./src/handlers/demo.handlers.ts`. - Export `./locale-jurisdiction-gate.feature` resolves through `./src/locale-jurisdiction-gate.feature.ts`. - Export `./policy/assistant-gate.policy` resolves through `./src/policy/assistant-gate.policy.ts`. - Export `./translations` resolves through `./src/translations/index.ts`. - Export `./translations/assistant-gate.en-GB.translation` resolves through `./src/translations/assistant-gate.en-GB.translation.ts`. - Export `./translations/assistant-gate.en-US.translation` resolves through `./src/translations/assistant-gate.en-US.translation.ts`. - Export `./translations/assistant-gate.fr-FR.translation` resolves through `./src/translations/assistant-gate.fr-FR.translation.ts`. - The package publishes 21 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.lssm-id-external-app Description: Standalone OIDC relying-party example using the public LSSM ID protocol. Path: examples/lssm-id-external-app URL: /llms/example.lssm-id-external-app # External LSSM ID consumer This independently deployable Bun server uses standard Better Auth Generic OAuth, a local SQLite session store, and no monorepo runtime imports. Put it behind an HTTPS origin with persistent storage. It never shares the Passport cookie. 1. Request an operator-approved application. During production qualification, confirm the available onboarding process before relying on the planned `https://id.lssm.co/auth/applications` management surface. Register `https://YOUR_HOST/api/auth/callback/lssm`, the post-logout URL `https://YOUR_HOST/signed-out`, and your exact resource audience. Obtain the operator's approval; rotate the client secret in the owner view to reveal it. 2. Set `EXTERNAL_APP_ORIGIN`, `LSSM_APPLICATION_ID`, `LSSM_CLIENT_ID`, `LSSM_CLIENT_SECRET`, `EXTERNAL_APP_SESSION_SECRET` (32+ characters), and `EXTERNAL_APP_DATABASE_PATH` through the hosting secret manager. Use a dedicated persistent SQLite database for this application. 3. Run `bun install`, `bun run migrate`, then `bun run start`. `PORT` defaults to 3027. The migrate command changes only this consumer's database. 4. Visit `/account`, sign in, approve the central consent, and confirm that the callback creates this application's local session. `/signed-out` follows product-local logout; central account logout remains a separate user action. Use the complete `externalIdentityOptions` configuration, including its pinned compatibility fence. In Better Auth 1.7.14, `requireIdTokenVerification` alone checks discovery configuration but does not require the token endpoint to return an ID token. The fence requires a nonempty signed token and the server's exact expected nonce, validates LSSM's advertised authorization-response issuer, and disables browser-submitted ID-token sign-in. Userinfo can supplement a verified token only when its `sub` matches the signed subject. All cryptographic checks use the official `better-auth/oauth2` verifier; there is no workspace dependency. The final account identity is that same `sub`, even if discovery omits its signing-algorithm hint or the profile contains an unrelated `id` field. Trusted claims predicates still run, but cannot mutate the subject captured as proof. The provider verifies signature, issuer, audience, nonce, state and PKCE. It creates an application-local user after central admission. Product permissions remain an application responsibility; a successful identity login grants no business role. This example uses public application admission; use the reviewed entitlement policy for invitation-only applications. The browser client uses the standard `createAuthClient().signIn.social` API with `provider: 'lssm'`; this pinned SDK does not need a Generic OAuth client plugin. Keep its server-side compatibility checks when copying the example. Offline tests qualify configuration, actual database migration, PKCE-bound code exchange, signed ID-token validation, local sessions and logout. They deny missing or empty ID tokens even with a usable userinfo endpoint, replay through the direct ID-token branch, substituted userinfo subjects, missing response issuer, and invalid state, issuer, audience, nonce and expiry. Interleaved two-account callbacks preserve request-local subject proof. Discovery recovery reapplies the same constraints. Additional native regressions prove final account binding without discovery algorithm hints and preserve trusted claims predicate rejection. A production real-user consent/callback/logout receipt requires an approved registered application and its separately hosted deployment; local tests do not establish that receipt. --- ## @lssm-tech/example.managed-companyos-contract-editions Description: Managed CompanyOS contract edition lifecycle proof across specs, storage, runtime wiring, integrations, and examples. Path: examples/managed-companyos-contract-editions URL: /llms/example.managed-companyos-contract-editions # Managed CompanyOS Contract Editions Deterministic, credential-free proof that the ContractSpec edition platform is wired for an enterprise Managed CompanyOS vertical: - typed operation specs for evaluation, improvement proposals, and release projection; - file, database, and hybrid storage parity with rollback evidence; - ContractSpec Connect, harness/replay, knowledge, intelligence coach, and enterprise guardrails; - builder/runtime/integration wiring references; and - full-loop readiness surfaced as a small importable example. Run: ```bash bun run test bun run typecheck ``` --- ## @lssm-tech/example.marketplace Description: Marketplace example with orders, payouts, and reviews for ContractSpec Path: examples/marketplace URL: /llms/example.marketplace # @lssm-tech/example.marketplace Website: https://contractspec.io **Marketplace example with orders, payouts, and reviews for ContractSpec.** ## What This Demonstrates - Multi-entity domain modeling (order, payout, product, review, store). - Per-entity schema/enum/event/operations/presentation pattern. - Capability and feature definition patterns. - React UI with hooks, renderers, and dashboard component. - Contract-backed visualizations for order status, category value comparison, and recent order activity. - Seeder pattern for demo data. - Test-spec for operations validation. ## Running Locally From `examples/marketplace`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.marketplace` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/marketplace.capability.ts` defines a capability surface. - `src/marketplace.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/marketplace.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./entities/order` resolves through `./src/entities/order.ts`. - Export `./entities/payout` resolves through `./src/entities/payout.ts`. - Export `./entities/product` resolves through `./src/entities/product.ts`. - Export `./entities/review` resolves through `./src/entities/review.ts`. - Export `./entities/store` resolves through `./src/entities/store.ts`. - Export `./example` resolves through `./src/example.ts`. - The package publishes 52 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.runtime-sandbox`, `@lssm-tech/lib.schema`, ... --- ## @lssm-tech/example.meeting-recorder-providers Description: Meeting recorder provider example: list meetings, transcripts, and webhooks. Path: examples/meeting-recorder-providers URL: /llms/example.meeting-recorder-providers # @lssm-tech/example.meeting-recorder-providers Website: https://contractspec.io **Meeting recorder provider example: list meetings, transcripts, and webhooks.** ## What This Demonstrates - Provider integration pattern with connection samples. - Handler-per-action pattern (create-provider, get-transcript, list-meetings, webhook-handler). - Webhook handler for external event ingestion. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/meeting-recorder-providers`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.meeting-recorder-providers` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/connection.sample.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/meeting-recorder-providers.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./connection.sample` resolves through `./src/connection.sample.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/meeting-recorder-providers.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/create-provider` resolves through `./src/handlers/create-provider.ts`. - Export `./handlers/get-transcript` resolves through `./src/handlers/get-transcript.ts`. - Export `./handlers/list-meetings` resolves through `./src/handlers/list-meetings.ts`. - Export `./handlers/webhook-handler` resolves through `./src/handlers/webhook-handler.ts`. - Export `./meeting-recorder-providers.feature` resolves through `./src/meeting-recorder-providers.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-meeting-recorder`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.messaging-agent-actions Description: Safe messaging agent actions example with fixed intents, allowlisted actions, workflow dispatch, and deterministic replies. Path: examples/messaging-agent-actions URL: /llms/example.messaging-agent-actions # @lssm-tech/example.messaging-agent-actions Safe messaging agent actions example with fixed intents, allowlisted action execution, workflow dispatch, and deterministic confirmation replies. ## What This Demonstrates - Inbound message normalization for Slack, WhatsApp, Telegram, or any messaging bridge. - Fixed intent parsing: `status`, `run action`, and `dispatch workflow`. - Allowlisted action and workflow routing instead of arbitrary tool execution. - Replayable meetup proof for the canonical status -> action -> workflow walkthrough. ## Running Locally From `examples/messaging-agent-actions`: - `bun run build` - `bun run test` - `bun run typecheck` - `bun run proof` - `bun run preflight` ## Usage Use this package when you need a conservative messaging demo that proves agent actions can stay safe, typed, and reviewable even when messages come from live provider webhooks. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./contracts` resolves through `./src/contracts/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./messaging-agent-actions.feature` resolves through `./src/messaging-agent-actions.feature.ts`. - Export `./proof/*` resolves through `./src/proof/*.ts`. ## Local Commands - `bun run build` — contractspec-bun-build build - `bun run test` — bun test - `bun run typecheck` — tsgo --noEmit - `bun run proof` — bun ../../scripts/generate-messaging-agent-actions-meetup-proof.ts - `bun run preflight` — bun run build && bun run typecheck && bun run test && bun run proof --- ## @lssm-tech/example.messaging-app Description: Thin messaging app example that composes reusable CommunicationOS messaging UI with deterministic fixture data. Path: examples/messaging-app URL: /llms/example.messaging-app # @lssm-tech/example.messaging-app Thin messaging application example for CommunicationOS UI composition. The reusable conversation list, thread, composer, and workspace live in `@lssm-tech/module.communication-os/ui`. This package only owns deterministic preview data and a small wrapper that demonstrates how an adopter wires the reusable UI. ## Entry Points - `.` - `./docs` - `./example` - `./ui` ## Commands - `bun run typecheck` - `bun run test` - `bun run build` ## Voice-originated messaging demo The messaging workspace now consumes the shared CommunicationOS `voiceSignal` summary. The first conversation reflects the Rivage security-answer escalation and renders the blocked customer-promise framing before the message composer policy ribbon. --- ## @lssm-tech/example.minimal Description: Minimal reference project demonstrating a complete ContractSpec workflow. Path: examples/minimal URL: /llms/example.minimal # @lssm-tech/example.minimal **Minimal ContractSpec example showing the simplest possible contract definition and build.** ## What This Demonstrates - Bare-minimum contract definition (user contract). - `contractspec build` and `contractspec validate` CLI usage. - Maintained example package included in the ContractSpec example registry. - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/minimal`: - `bun run build` - `bun run test` - `bun run typecheck` - `bun run smoke` - `bun run preflight` ## Usage Use `@lssm-tech/example.minimal` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/minimal.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/minimal.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./minimal.feature` resolves through `./src/minimal.feature.ts`. - Export `./contracts/user` resolves through `./src/contracts/user.ts`. ## Local Commands - `bun run build` — bun ../../packages/apps/cli-contractspec/src/cli.ts build src/contracts/user.ts - `bun run validate` — bun ../../packages/apps/cli-contractspec/src/cli.ts validate src/contracts/user.ts - `bun run typecheck` — tsgo --noEmit - `bun run test` — bun test - `bun run smoke` — bun test src/example.smoke.test.ts - `bun run preflight` — bun run build && bun run typecheck && bun run test && bun run validate && bun run smoke ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Stability. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`. --- ## @lssm-tech/example.openbanking-powens Description: OpenBanking Powens example: OAuth callback + webhook handler patterns (provider + workflows). Path: examples/openbanking-powens URL: /llms/example.openbanking-powens # @lssm-tech/example.openbanking-powens Website: https://contractspec.io **OpenBanking Powens example: OAuth callback + webhook handler patterns (provider + workflows).** ## What This Demonstrates - OAuth callback handler pattern for open banking. - Webhook handler for asynchronous bank event ingestion. - Canonical `job` export via `PowensSyncDispatchJob`. - Provider integration via contracts-integrations. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/openbanking-powens`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.openbanking-powens` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/jobs/` contains the exported Powens dispatch job spec. - `src/openbanking-powens.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/openbanking-powens.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/oauth-callback` resolves through `./src/handlers/oauth-callback.ts`. - Export `./handlers/webhook-handler` resolves through `./src/handlers/webhook-handler.ts`. - Export `./jobs` resolves through `./src/jobs/index.ts`. - Export `./jobs/powens-sync-dispatch.job` resolves through `./src/jobs/powens-sync-dispatch.job.ts`. - Export `./openbanking-powens.feature` resolves through `./src/openbanking-powens.feature.ts`. - The package publishes 8 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-openbanking`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.opencode-cli Description: Reference integration for using ContractSpec with the OpenCode CLI. Path: examples/opencode-cli URL: /llms/example.opencode-cli # @lssm-tech/example.opencode-cli **OpenCode CLI example showing agent-mode contract building and validation.** ## What This Demonstrates - Agent-mode (`--agent-mode opencode`) contract compilation. - Implementation checking via `--check-implementation`. - Maintained example package included in the ContractSpec example registry. - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/opencode-cli`: - `bun run build` - `bun run test` - `bun run typecheck` - `bun run smoke` - `bun run preflight` ## Usage Use `@lssm-tech/example.opencode-cli` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/contracts/` contains contract specs, operations, entities, and registry exports. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/opencode-cli.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./contracts/opencode` resolves through `./src/contracts/opencode.contracts.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/opencode-cli.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./opencode-cli.feature` resolves through `./src/opencode-cli.feature.ts`. ## Local Commands - `bun run build` — bun ../../packages/apps/cli-contractspec/src/cli.ts build src/contracts/opencode.contracts.ts --agent-mode opencode - `bun run validate` — bun ../../packages/apps/cli-contractspec/src/cli.ts validate src/contracts/opencode.contracts.ts --check-implementation --agent-mode opencode - `bun run typecheck` — tsgo --noEmit - `bun run test` — bun test - `bun run smoke` — bun test src/example.smoke.test.ts - `bun run preflight` — bun run build && bun run typecheck && bun run test && bun run validate && bun run smoke ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Stability. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`. --- ## @lssm-tech/example.organization-planning-agenda Description: Reference agenda workflow for ContractSpec organization-planning contracts. Path: examples/organization-planning-agenda URL: /llms/example.organization-planning-agenda # @lssm-tech/example.organization-planning-agenda Buildable OPA OS example for the local/manual Organization Planning Agenda loop. ## What this demonstrates - Hackathon EOD Mission Relay-style day plan generation. - NDconsulting-style agenda generation with private context redaction. - Axoperf-style deployment planning constraints and blocker evidence. - Customer-facing booking proposals blocked behind human approval. - Rich calendar roadmap lanes for focus blocks, agendas, booking proposals, approval gates, and audit artifacts. - Notion-ready markdown and audit payloads without calendar/provider writes. ## Flagship surface matrix proof The exported `organizationPlanningAgendaSurfaceMatrixProof` fixture documents the three flagship rows consumed by app smoke tests and docs: | Vertical | Web monolith | Mobile demo | Examples/docs | Managed CompanyOS seam | |---|---|---|---|---| | Hackathon EOD | `/companyos/opa-os` consumes `buildManagedCompanyOsOpaOsProof` from `@lssm-tech/bundle.managed-companyos`. | `mobile.opa.hackathon_eod.native` consumes the managed OPA view model. | Smoke fixture renders the day plan, markdown, approvals, and evidence IDs. | `managed-companyos.view-model.organization-planning.hackathon-eod` | | NDconsulting mission | `/companyos/opa-os` renders the client mission agenda from the managed bundle proof. | `mobile.opa.ndconsulting_mission.native` shows agenda and approval-denial state. | Smoke fixture proves agenda plus next meeting proposal. | `managed-companyos.view-model.organization-planning.ndconsulting-mission` | | Axoperf deployment | `/companyos/opa-os` keeps deployment blocker proof in provider-blocked/degraded mode. | `mobile.opa.axoperf_deployment.native` shows blocker priority and approval-only booking slots. | Smoke fixture documents blocker outputs and evidence IDs. | `managed-companyos.view-model.organization-planning.axoperf-deployment` | ## Evidence links - Rich calendar proof: `organizationPlanningRichCalendarRoadmapProof` exports provider-free lanes and approval-blocked calendar items for docs, sandbox, and managed-bundle consumers. - Web proof: `packages/apps/web-application-monolith/src/opa-os-route.test.tsx` validates that `/companyos/opa-os` consumes the managed bundle proof, emits redacted behavior signals, and keeps external effects approval-blocked. - Static safety: run `bun run opa-os:safety` from the repository root to verify the OPA no-provider, no-raw-secret, and no-live-send boundary before release handoff. ## Running locally From `examples/organization-planning-agenda`: - `bun run build` - `bun run typecheck` - `bun run test` - `bun run smoke` - `bun run preflight` ## Boundary This example is intentionally local and manual. It does not import provider SDKs, write calendars, send client messages, or approve external effects. Declaration builds use `build:types` through the shared Bun tool; `build` runs bundle and declaration generation. Declared exports are preserved. Generated artifacts exclude test-only files; tests/typecheck remain separate gates. --- ## @lssm-tech/example.osint-proof Description: (none) Path: examples/osint-proof URL: /llms/example.osint-proof # OSINT proof Deterministic conformance and scale qualification for the reusable company, job, and people system. The proof materializes 100 companies, 1,000 jobs, and 1,000 people with unique evidence locators; the scale pass processes 100,000 entity identities, 1,000,000 assertions, and 1,000,000 embedding identities. It also measures local detail and filtered-search work against the reference p95 budgets. `bun run proof` prints a synthetic JSON receipt. It is a deterministic development baseline only and never satisfies the production database gate. `bun run proof:france-corpus -- ` validates a live corpus receipt starting from `france-corpus.pending.json`. Qualification requires the exact release SHA, France/EU scope, live provider and source receipts, at least 100 companies, 1,000 active-or-recent jobs, and 1,000 policy-approved people. Collector, identity resolver, and reviewer must be independent. Representative review must find zero false or name-only silent merges, zero unsupported fields, zero jobs closed without explicit evidence, and authorized evidence for every reviewed displayed fact. Pending, stale, malformed, or policy-pending receipts exit non-zero and never satisfy the production corpus gate. `bun run proof:postgres` is the opt-in managed qualification harness. It requires: - `OSINT_QUALIFICATION_DATABASE_URL`: migration-owner URL for replay-safe load and concurrent HNSW index creation; - `OSINT_QUALIFICATION_RUNTIME_DATABASE_URL`: distinct non-owner runtime URL for FORCE-RLS benchmark queries; - `OSINT_QUALIFICATION_CONFIRM_LOAD=YES`; - optional `OSINT_QUALIFICATION_DIMENSIONS` (default `1536`) and `OSINT_QUALIFICATION_BATCH_SIZE` (default `10000`). The loader writes a dedicated qualification scope, 100,000 projections, 1,000,000 evidence-linked assertions, and 1,000,000 evidence-linked vectors. It is idempotent, cancellable between batches, creates a generation-specific HNSW index, verifies exact cardinalities, then captures detail/hybrid p95 latency and `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` plans through the runtime role. A missing URL, explicit load confirmation, pgvector/migration, target count, or latency budget fails closed. Credentialed providers, object storage, and the France corpus remain separate live gates. `bun run proof:postgres:docker` runs the same 100k/1m/1m loader and benchmark against a pinned disposable pgvector container, using a unique host temporary data directory and distinct runtime login. Its default 64-dimensional vector profile is a real PostgreSQL scale/concurrency proof designed for bounded local resources; it does not replace the managed 1536-dimensional production gate. `OSINT_SCALE_DOCKER_DIMENSIONS` and `OSINT_SCALE_DOCKER_BATCH_SIZE` may increase the local profile deliberately. The runner never prunes or reuses Docker state. `OSINT_RECOVERY_RELEASE_SHA=$(git rev-parse HEAD) bun run proof:recovery:docker` performs a separate bounded local restore proof. It applies every migration, seeds canonical evidence/projection/vector/audit/outbox state whose snapshot references a real content-addressed object in a separately pinned disposable MinIO service, dumps the source, and restores into a fresh sibling database. It compares exact row and row-content checksums, downloads and rehashes the unchanged evidence object after restore, verifies that both source and restored snapshot references match its manifest, verifies pgvector and HNSW restoration, then proves correct-scope visibility and wrong-scope denial through `osint_runtime`. It requires a clean worktree and emits a `local_disposable_sibling` receipt; it does not satisfy managed fresh-environment RPO/RTO, evidence-bucket restore, or application smoke gates. --- ## @lssm-tech/example.personalization Description: Personalization examples: behavior tracking, overlay customization, workflow extension. Path: examples/personalization URL: /llms/example.personalization # @lssm-tech/example.personalization Website: https://contractspec.io **Personalization examples: behavior tracking, overlay customization, workflow extension.** ## What This Demonstrates - Behavior tracking integration pattern. - Canonical `experiment` export via `PersonalizationExperiment`. - Overlay customization via overlay-engine. - Canonical `theme` export via `PersonalizationTheme`. - Workflow extension via workflow-composer. - Multi-lib composition in a single example. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/personalization`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.personalization` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/behavior-tracking.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/overlay-customization.ts` is part of the package's public or composition surface. - `src/personalization.experiment.ts` defines the exported experiment spec. - `src/personalization.feature.ts` defines a feature entrypoint. - `src/personalization.theme.ts` defines the exported theme spec. - `src/workflow-extension.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./behavior-tracking` resolves through `./src/behavior-tracking.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/personalization.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./overlay-customization` resolves through `./src/overlay-customization.ts`. - Export `./personalization.experiment` resolves through `./src/personalization.experiment.ts`. - Export `./personalization.feature` resolves through `./src/personalization.feature.ts`. - Export `./personalization.theme` resolves through `./src/personalization.theme.ts`. - Export `./workflow-extension` resolves through `./src/workflow-extension.ts`. - The package publishes 9 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.logger`, `@lssm-tech/lib.overlay-engine`, `@lssm-tech/lib.personalization`, `@lssm-tech/lib.workflow-composer`, ... --- ## @lssm-tech/example.pipeline-reality-router-reference Description: Deterministic neutral Layer 1 reference harness over public CompanyOS Layer 0 exports. Path: examples/pipeline-reality-router-reference URL: /llms/example.pipeline-reality-router-reference # Pipeline Reality Router Reference A small Layer 1 example harness that consumes public CompanyOS Layer 0 exports. It runs one deterministic neutral document-review/onboarding-handoff path with mock adapters, an in-memory store, and stable JSON output. ## Run ```bash bun run --cwd examples/pipeline-reality-router-reference preflight bun run --cwd examples/pipeline-reality-router-reference process-neutral-signal ``` ## Boundaries - CLI/importable example only; no app, UI, deployment, auth, billing, or tenant logic. - Public package imports only from CompanyOS Layer 0 packages. - No network calls, credentials, provider SDKs, or outbound writes. - Neutral fixture data only. See `docs/layer-boundary.md`, `docs/export-standalone.md`, and `docs/disclosure.md` for operating notes. --- ## @lssm-tech/example.pocket-family-office Description: Pocket Family Office example - personal finance automation with open banking Path: examples/pocket-family-office URL: /llms/example.pocket-family-office # @lssm-tech/example.pocket-family-office Website: https://contractspec.io **Pocket Family Office example - personal finance automation with open banking.** ## What This Demonstrates - Workflow-driven open banking integration (sync accounts, transactions, balances). - Financial summary and overview generation workflows. - Document processing and email thread ingestion. - Capability and feature definition patterns. - Canonical `telemetry` export via `pocketFamilyOfficeTelemetry`. - Sample tenant and connection configuration. - An inline `PocketFamilyOfficePreview` UI for template and example browsers. ## Running Locally From `examples/pocket-family-office`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.pocket-family-office` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/blueprint.ts` is part of the package's public or composition surface. - `src/connections` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/knowledge` is part of the package's public or composition surface. - `src/operations` is part of the package's public or composition surface. - `src/telemetry.ts` defines the exported telemetry spec. - `src/ui/` contains the inline preview surface for catalog and template browsers. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./blueprint` resolves through `./src/blueprint.ts`. - Export `./connections/samples` resolves through `./src/connections/samples.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/pocket-family-office.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./knowledge/sources.sample` resolves through `./src/knowledge/sources.sample.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./pocket-family-office.capability` resolves through `./src/pocket-family-office.capability.ts`. - Export `./pocket-family-office.feature` resolves through `./src/pocket-family-office.feature.ts`. - Export `./telemetry` resolves through `./src/telemetry.ts`. - Export `./tenant.sample` resolves through `./src/tenant.sample.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - Export `./ui/PocketFamilyOfficePreview` resolves through `./src/ui/PocketFamilyOfficePreview.tsx`. - Export `./ui/pocket-family-office-preview.data` resolves through `./src/ui/pocket-family-office-preview.data.ts`. - Export `./workflows` resolves through `./src/workflows/index.ts`. - The package publishes 24 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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` — bun 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. - Missing contract layers. - Resolve lint/test regressions after voice capability updates. - Major change to content generation. ## Notes - Works alongside `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.knowledge`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.policy-safe-knowledge-assistant Description: All-in-one template example: policy-safe knowledge assistant with locale/jurisdiction gating, versioned KB snapshots, HITL update pipeline, and learning hub. Path: examples/policy-safe-knowledge-assistant URL: /llms/example.policy-safe-knowledge-assistant # @lssm-tech/example.policy-safe-knowledge-assistant Website: https://contractspec.io **All-in-one template example: policy-safe knowledge assistant with locale/jurisdiction gating, versioned KB snapshots, HITL update pipeline, and learning hub.** ## What This Demonstrates - Composition of multiple example packages into a full-stack assistant. - Orchestrator pattern (`buildAnswer`) for policy-gated responses. - React dashboard with hooks and UI components. - Seed data and fixture patterns. - Feature definition aggregating sub-features. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/policy-safe-knowledge-assistant`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.policy-safe-knowledge-assistant` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/integration.test.ts` is part of the package's public or composition surface. - `src/orchestrator` is part of the package's public or composition surface. - `src/policy-safe-knowledge-assistant.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/policy-safe-knowledge-assistant.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./handlers/policy-safe-knowledge-assistant.handlers` resolves through `./src/handlers/policy-safe-knowledge-assistant.handlers.ts`. - Export `./orchestrator/buildAnswer` resolves through `./src/orchestrator/buildAnswer.ts`. - Export `./policy-safe-knowledge-assistant.feature` resolves through `./src/policy-safe-knowledge-assistant.feature.ts`. - Export `./seed` resolves through `./src/seed/index.ts`. - Export `./seed/fixtures` resolves through `./src/seed/fixtures.ts`. - The package publishes 14 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/example.kb-update-pipeline`, `@lssm-tech/example.learning-patterns`, `@lssm-tech/example.locale-jurisdiction-gate`, `@lssm-tech/example.versioned-knowledge-base`, `@lssm-tech/lib.contracts-spec`, ... --- ## @lssm-tech/example.product-intent Description: Product intent example: evidence ingestion and prompt-ready outputs. Path: examples/product-intent URL: /llms/example.product-intent # @lssm-tech/example.product-intent Website: https://contractspec.io **Product intent example: evidence ingestion and prompt-ready outputs.** ## What This Demonstrates - Canonical `product-intent` export via `ProductIntentDiscoverySpec`. - Evidence loading and ingestion pipeline. - PostHog signal extraction for product analytics. - Action synchronization across tools. - Script-based execution pattern. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/product-intent`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.product-intent` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/load-evidence.test.ts` is part of the package's public or composition surface. - `src/load-evidence.ts` is part of the package's public or composition surface. - `src/posthog-signals.ts` is part of the package's public or composition surface. - `src/product-intent.discovery.ts` defines the exported product-intent spec. - `src/product-intent.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/product-intent.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./load-evidence` resolves through `./src/load-evidence.ts`. - Export `./posthog-signals` resolves through `./src/posthog-signals.ts`. - Export `./product-intent.discovery` resolves through `./src/product-intent.discovery.ts`. - Export `./product-intent.feature` resolves through `./src/product-intent.feature.ts`. - Export `./script` resolves through `./src/script.ts`. - Export `./sync-actions` resolves through `./src/sync-actions.ts`. - The package publishes 9 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Stability. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-analytics`, `@lssm-tech/integration.provider-project-management`, `@lssm-tech/lib.ai-agent`, `@lssm-tech/lib.analytics`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, ... --- ## @lssm-tech/example.project-management-sync Description: Project management sync example: Linear, Jira, and Notion work item creation. Path: examples/project-management-sync URL: /llms/example.project-management-sync # @lssm-tech/example.project-management-sync Website: https://contractspec.io **Project management sync example: Linear, Jira, and Notion work item creation.** ## What This Demonstrates - Multi-provider sync pattern (Linear, Jira, Notion). - Work item creation from contract definitions. - Run script for one-shot execution. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Preview / export workflow Project Management Sync previews must never instantiate Linear, Jira, Notion, or other provider SDK clients. A future `./ui` export should render local sync overview, provider mapping, conflict review, and draft work-item approval fixtures only. Keep provider writes represented as draft/approval states, not real network execution. Public key behavior is compatibility-sensitive because current catalog consumers may resolve both `examples.project-management-sync` and normalized keys. ## Running Locally From `examples/project-management-sync`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.project-management-sync` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/project-management-sync.feature.ts` defines a feature entrypoint. - `src/run.ts` is part of the package's public or composition surface. - `src/sync.ts` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/project-management-sync.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./project-management-sync.feature` resolves through `./src/project-management-sync.feature.ts`. - Export `./run` resolves through `./src/run.ts`. - Export `./sync` resolves through `./src/sync.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/integration.provider-project-management`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/module.examples Description: Example contract specifications collection Path: examples/registry URL: /llms/module.examples # @lssm-tech/module.examples Website: https://contractspec.io **Catalog-first ContractSpec example metadata, with optional runtime helpers for rich example surfaces.** ## What It Provides - **Layer**: module. - **Consumers**: CLIs, editor bridges, apps, docs, and rich sandbox/template surfaces. - Related ContractSpec packages include `@lssm-tech/example.agent-console`, `@lssm-tech/example.ai-chat-assistant`, `@lssm-tech/example.ai-support-bot`, `@lssm-tech/example.analytics-dashboard`, `@lssm-tech/example.calendar-google`, `@lssm-tech/example.content-generation`, ... - `agent-console` is the default autonomous-agent showcase surfaced through `/sandbox`. - `data-grid-showcase` is the canonical ContractSpec table showcase surfaced through `/sandbox?template=data-grid-showcase` and `/docs/examples/data-grid-showcase`. ## Installation `npm install @lssm-tech/module.examples` or `bun add @lssm-tech/module.examples` ## Usage Use the root entrypoint or `@lssm-tech/module.examples/catalog` for metadata-only discovery. Use `@lssm-tech/module.examples/runtime` only when rendering rich template previews or sandbox runtime surfaces. The catalog also exposes shared preview-surface helpers so apps can show every discoverable example while loading rich UI only for packages that export `./ui`. ```ts import { getExample, listExamples } from '@lssm-tech/module.examples/catalog'; ``` ```ts import { ExampleWebPreview, TemplateRuntimeProvider, listTemplates } from '@lssm-tech/module.examples/runtime'; ``` ### Host ports Apps and bundles that render a specific example read it through a named host port instead of importing `@lssm-tech/example.*` packages, which the package-layer boundary check rejects. Each port re-exports only what hosts use and is split by runtime: | Entrypoint | Runtime | Contents | |---|---|---| | `./runtime/native-previews` | native, browser, server | Example contracts, visualization specs and deterministic sample data for native preview panels. No web UI or template providers. | | `./runtime/feature-hub-reference` | native, server | `installFeatureHubCompositionReference` and `FEATURE_HUB_REFERENCE_ROUTE_IDS`. | | `./runtime/companyos-ai-solutions-engineer-poc` | browser, server | The hosted-demo contract: `COMPANYOS_ACME_PROFILE`, `compileCanonicalPreparedProof`, the outcome-pack schema and the demo runtime contract. | | `./runtime/companyos-ai-solutions-engineer-poc/server` | Node only | The proof runtime: call runtime, preflight probe, proof session authority, browser fixture and approved-proof runner. | | `./runtime/companyos-ai-solutions-engineer-poc/ui` | client components | `RequestToVerifiedProofPreview`. | ```ts import { CRM_PIPELINE_DEALS } from '@lssm-tech/module.examples/runtime/native-previews'; import { COMPANYOS_ACME_PROFILE } from '@lssm-tech/module.examples/runtime/companyos-ai-solutions-engineer-poc'; ``` The example packages stay optional peers: a host installs the examples whose port it imports. The catalog contains source metadata for each example. CLI users can fetch a full example only when needed: ```sh contractspec examples download minimal --out-dir ./examples/minimal ``` ## Public preview/export workflow Template, docs, and sandbox previews are generated from package-owned example metadata: 1. Example packages expose catalog metadata through `./example` and docs through `./docs` when they should appear in public template/docs surfaces. 2. Rich inline previews are opt-in public surfaces. A package that adds `./ui` must keep that export package-native, deterministic, fixture-backed, and mirrored in `publishConfig.exports`. 3. `scripts/generate-example-registry.ts` is the only writer for generated catalog and preview registry artifacts; run `bun run --cwd examples/registry generate:registry` after changing example exports. 4. Preview consumers should use catalog helpers for discoverability and `supportsInlineExamplePreview()` / `getExamplePreviewSurface()` before loading runtime UI. Keep docs, sandbox, LLMS, and source fallback links available for examples without inline UI. 5. Do not introduce live backend calls, provider credentials, or production actions in preview fixtures. Provider-oriented examples must render local replay/fixture data only. ### Generation and build preflight Registry generation is an explicit repository operation. Run the existing root `bun run examples:sync-registry` command, or the package's `generate:registry`, after changing example metadata, exports or runtime ports. It manages exactly the CLI catalog's `src/example-catalog/builtins.ts`, the registry's `src/runtime/previews.generated.ts`, `src/preview-catalog.generated.ts`, `package.json` optional peers and `turbo.json` dependency edges. Package prebuild now runs `check:registry` before the canonical artifact builder. That comparison reports stale managed outputs and does not regenerate them. Output leaves and their ancestors must not be symlinks; generation rejects an unsafe output before evaluating example modules or changing another output. Both explicit generation and comparison still import eligible declared workspace `src/example.ts` modules. Those are trusted executable project code, not inert JSON. Comparison's absence of managed writes is not a filesystem or network sandbox and does not replace the task's execution-authority review. ## Architecture - `src/builtins.ts` is a generated literal catalog and must not statically import `@lssm-tech/example.*` packages. - `src/catalog.ts` is the metadata-only public surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/registry.test.ts` is part of the package's public or composition surface. - `src/registry.ts` is part of the package's public or composition surface. - `src/runtime` is the optional rich runtime surface for consumers that intentionally install example packages. ## Public Entry Points - Export `.` resolves through `./src/index.ts` and is catalog-only. - Export `./catalog` resolves through `./src/catalog.ts`. - Export `./runtime` resolves through `./src/runtime/index.ts`. - Exports `./runtime/native-previews`, `./runtime/feature-hub-reference`, `./runtime/companyos-ai-solutions-engineer-poc`, `./runtime/companyos-ai-solutions-engineer-poc/server` and `./runtime/companyos-ai-solutions-engineer-poc/ui` are the host ports described under Usage. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 generate:registry` — bun ../../scripts/generate-example-registry.ts --write - `bun run check:registry` — bun ../../scripts/generate-example-registry.ts --check - `bun run prebuild` — bun run check:registry && contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. - Add table capabilities. - Stability. - Vnext ai-native. ## Notes - This module is a thin catalog/runtime bridge -- business logic belongs in individual example packages under `examples/`. - Adding a new example requires creating the example package and regenerating the catalog with `bun run generate:registry`; do not add it as a direct dependency here. - Root/catalog imports must remain metadata-only. Rich runtime consumers should import `@lssm-tech/module.examples/runtime` (or a host port) and own any required `@lssm-tech/example.*` dependencies directly. - The meetup-ready autonomous-agent path is the deterministic `agent-console` sandbox plus its replay proof lane. - The shared ContractSpec table stack is demonstrated directly by `data-grid-showcase` and reused in `analytics-dashboard`, `crm-pipeline`, `integration-hub`, and `agent-console`. The registry generator also owns optional example-runtime peers and this package's Turbo task dependencies. Optional peers preserve catalog-only installation while letting declaration builds resolve the installed example declaration surfaces. The generated task edges build those declarations before the runtime bridge; example packages remain responsible for validating their own implementations. Run `generate:registry` after changing preview exports or runtime example imports. Do not hand-edit the managed example peers or `turbo.json`. --- ## @lssm-tech/example.saas-boilerplate Description: SaaS Boilerplate - Users, Orgs, Projects, Billing, Settings Path: examples/saas-boilerplate URL: /llms/example.saas-boilerplate # @lssm-tech/example.saas-boilerplate Website: https://contractspec.io **SaaS Boilerplate - Users, Orgs, Projects, Billing, Settings.** ## What This Demonstrates - Multi-domain SaaS architecture (billing, project, settings, dashboard). - Per-domain entity/enum/event/handler/operations/presentation/schema pattern. - React UI with hooks, modals, overlays, renderers, and dashboard. - Contract-backed visualizations for portfolio status, tier mix, usage, and recent project activity. - Feature definition, seeders, and test-spec patterns. - RBAC, audit trail, and notification module integration. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/saas-boilerplate`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.saas-boilerplate` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/billing` is part of the package's public or composition surface. - `src/dashboard` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/presentations` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./billing` resolves through `./src/billing/index.ts`. - Export `./billing/billing.entity` resolves through `./src/billing/billing.entity.ts`. - Export `./billing/billing.enum` resolves through `./src/billing/billing.enum.ts`. - Export `./billing/billing.event` resolves through `./src/billing/billing.event.ts`. - Export `./billing/billing.handler` resolves through `./src/billing/billing.handler.ts`. - Export `./billing/billing.operations` resolves through `./src/billing/billing.operations.ts`. - Export `./billing/billing.presentation` resolves through `./src/billing/billing.presentation.ts`. - Export `./billing/billing.schema` resolves through `./src/billing/billing.schema.ts`. - Export `./dashboard` resolves through `./src/dashboard/index.ts`. - The package publishes 48 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.identity-rbac`, `@lssm-tech/lib.jobs`, ... --- ## @lssm-tech/example.service-business-os Description: Service Business OS example (clients, quotes, jobs, invoices) for ContractSpec Path: examples/service-business-os URL: /llms/example.service-business-os # @lssm-tech/example.service-business-os Website: https://contractspec.io **Service Business OS example (clients, quotes, jobs, invoices) for ContractSpec.** ## What This Demonstrates - Multi-entity domain modeling (client, quote, job, invoice, payment). - Per-entity schema and operations pattern. - Capability and feature definition patterns. - Presentation layer and event-driven architecture. - Handler aggregation. - `src/docs/` contains docblocks and documentation-facing exports. ## Preview / export workflow Service Business OS already publishes `./presentations` for deterministic service-business screens. The package-native `./ui` preview wraps service-business panels in the shared `NestedCommandShell` from `@lssm-tech/lib.example-shared-ui`; keep compatible inline preview work on that reusable nested-safe shell and use an explicitly approved module/examples presentation renderer only when the registry owns the replay adapter. Keep preview data local and deterministic across client, quote, job, invoice, and payment states. Docs, sandbox, LLMS, and source fallback links should remain visible even when a host renders the richer inline preview. ## Running Locally From `examples/service-business-os`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.service-business-os` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/client` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./client` resolves through `./src/client/index.ts`. - Export `./client/client.operations` resolves through `./src/client/client.operations.ts`. - Export `./client/client.schema` resolves through `./src/client/client.schema.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/service-business-os.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - The package publishes 26 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/lib.example-shared-ui Description: Shared UI examples demonstrating reusable ContractSpec component composition. Path: examples/shared-ui URL: /llms/lib.example-shared-ui # @lssm-tech/lib.example-shared-ui **Shared React components and hooks for ContractSpec example apps. Provides the common layout, editors, and overlays used across all examples.** ## What It Provides - **Layer**: lib. - **Consumers**: example apps. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.surface-runtime`, `@lssm-tech/lib.ui-kit-web`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.surface-runtime`, `@lssm-tech/lib.ui-kit-web`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/lib.example-shared-ui` or `bun add @lssm-tech/lib.example-shared-ui` ## Usage Import the root entrypoint from `@lssm-tech/lib.example-shared-ui`, or choose a documented subpath when you only need one part of the package surface. Use `NestedCommandShell` for embedded example previews that need command search and sectional navigation without mounting the app-level design-system `AppShell`/sidebar provider. ## Architecture - `src/bundles/` contains bundle definitions and composition entrypoints. - `src/EvolutionDashboard.tsx` is part of the package's public or composition surface. - `src/EvolutionSidebar.tsx` is part of the package's public or composition surface. - `src/hooks/` contains custom hooks for host applications. - `src/index.ts` is the root public barrel and package entrypoint. - `src/lib/` contains package-local helper utilities and adapters. - `src/LocalDataIndicator.tsx` is part of the package's public or composition surface. - `src/NestedCommandShell.tsx` provides an embedded, nested-safe command/navigation shell for examples that must not mount the app-level `AppShell` sidebar. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./bundles` resolves through `./src/bundles/index.ts`. - Export `./bundles/ExampleTemplateBundle` resolves through `./src/bundles/ExampleTemplateBundle.ts`. - Export `./EvolutionDashboard` resolves through `./src/EvolutionDashboard.tsx`. - Export `./EvolutionSidebar` resolves through `./src/EvolutionSidebar.tsx`. - Export `./hooks` resolves through `./src/hooks/index.ts`. - Export `./hooks/useBehaviorTracking` resolves through `./src/hooks/useBehaviorTracking.ts`. - Export `./hooks/useEvolution` resolves through `./src/hooks/useEvolution.ts`. - Export `./hooks/useRegistryTemplates` resolves through `./src/hooks/useRegistryTemplates.ts`. - Export `./hooks/useSpecContent` resolves through `./src/hooks/useSpecContent.ts`. - The package publishes 30 total export subpaths; keep docs aligned with `package.json`. ## Public Shell Contract `TemplateShell` is the reusable, nested-safe preview shell for example packages. It renders only content-scoped header, main, and optional aside regions, so embedded previews can sit inside host apps such as `ExampleWebPreview` or `web-landing` without creating another app-level `AppShell`, `SidebarProvider`, fixed application sidebar, or global navigation frame. Import it from either the root package or the documented subpath: ```tsx import { TemplateShell } from '@lssm-tech/lib.example-shared-ui'; // or import { TemplateShell } from '@lssm-tech/lib.example-shared-ui/TemplateShell'; ``` Public props: - `title` and optional `description` fill the content-scoped preview header. - `actions` renders header actions without taking ownership of host navigation. - `sidebar` renders a bounded in-card aside beside the preview content. - `showRuntimeIndicator` toggles the local-data indicator for sandboxes that already provide equivalent status chrome. - `showSaveAction` and `saveProps` control the optional Studio save affordance. - `children` render inside the preview main region. Use `SpecDrivenTemplateShell` when a preview needs a `surface-runtime` bundle plan, but keep the same containment rule: shared example shells own preview content only, not app-level navigation. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 changesets and apply pending fixes. - Contracts context, bundle exports, surface-runtime docs. ## Notes - Low blast radius — only example apps depend on this package. - `TemplateShell` is the shared layout for all examples; structural changes affect every example app. --- ## @lssm-tech/example.special-ops-cockpit Description: French fake-data Special Ops Cockpit template for mission dashboards, private daily journals, review workflows, playbooks, weekly reporting, AI governance, and roadmap planning. Path: examples/special-ops-cockpit URL: /llms/example.special-ops-cockpit # @lssm-tech/example.special-ops-cockpit **Special Ops Cockpit** est une maquette ContractSpec headless, en français et avec données fictives, pour piloter une mission de retournement PME sans transformer l'IA en chatbot ni en outil de surveillance. Elle matérialise une mission expert-service design partner comme un système pilotable : dashboard, journal privé, structuration des actions, cartes de revue, playbook 48h, synthèse hebdomadaire, gouvernance IA et feuille de route de modules futurs. ## Pourquoi cet exemple existe Les missions de crise mélangent décisions rapides, preuves terrain, risques cash, reporting incomplet et transmission de méthode. Sans structure, les informations restent dans des notes, des mails, des tableurs ou des conversations dispersées. Ce cockpit montre comment ContractSpec peut rendre ces workflows explicites : - les opérations sont déclarées comme contrats ; - les handlers restent déterministes et testables ; - les données sont synthétiques, françaises et démonstratives ; - les éléments soumis deviennent auditables ; - les brouillons et suggestions restent privés tant qu'ils ne sont pas soumis ; - la validation humaine reste obligatoire avant toute synthèse ou action de pilotage. ## Ce que la démo démontre - **Mission Dashboard** — état de mission visible par Nathalie, limité aux artefacts soumis et revus. - **Journal de mission** — brouillon privé pour Hugo, avec structuration assistée des actions, risques, prochaines étapes et preuves de valeur. - **Trust Panel** — séparation explicite entre ce qui est visible, non visible, auditable et interdit. - **Review Cards** — cartes soumises avec source attachée, décision humaine et options approuver / modifier / rejeter / inclure / créer action / escalader. - **Playbook 48h** — jalons de retournement, preuves attendues, blocages et manques d'information. - **Weekly Report** — synthèse hebdomadaire uniquement à partir de cartes approuvées, export Markdown stable, statut brouillon jusqu'à validation. - **AI Stack Governance** — lecture des profils d'équipe, niveaux de maturité IA, risques de données et besoins de formation sans recommandation fournisseur définitive. - **Future Modules** — roadmap Cash Scenario Simulator, Qualiopi, onboarding, PO/ARC matching, e-invoicing, knowledge base, mission playbook et offre Mission Control. ## Modèle de confiance Doc route: `/docs/examples/special-ops-cockpit/trust-model`. Ce n'est pas un dispositif de contrôle salarié. Le cockpit est auditable au niveau mission, pas intrusif au niveau individu. Le système **ne montre pas** à Nathalie : - les brouillons privés non soumis ; - les suggestions ignorées ; - les captures d'écran ; - l'historique navigateur ; - les temps d'activité ; - les scores de productivité ; - les notes brutes avant soumission. Le système **montre uniquement** : - les artefacts explicitement soumis ; - les cartes de revue créées depuis ces artefacts ; - les décisions de validation ; - les preuves attachées à une action mission ; - les manques de preuve nécessaires pour piloter la mission. ## Mapping ContractSpec | Concept ContractSpec | Rôle dans l'exemple | | --- | --- | | `defineExample` | Déclare le template public `special-ops-cockpit`. | | `defineFeature` | Regroupe les neuf opérations cockpit. | | Operation contracts | Formalisent dashboard, journal, revue, playbook, rapport, gouvernance et roadmap. | | Fixtures | Fournissent la mission fictive `Fonderie Atlantique`, les dix personas et les notes terrain. | | Handlers | Produisent des résultats déterministes, sans réseau, LLM, base de données ni fichiers. | | Render models | Exposent les écrans headless que l'UI future pourra consommer. | | Docblocks | Publient l'overview, le modèle de confiance et le script de démo. | ## Ce qui est simulé - Client fictif : `Fonderie Atlantique`, PME industrielle de 85 salariés et 14M€ de CA. - Mission : crise cash, départ RAF, reporting absent, litiges fournisseurs et risque approvisionnement. - Données : notes terrain synthétiques, montants de démonstration `42k€`, `28k€`, `18k€`. - Acteurs : Nathalie D., Hugo V., Marc P., Fritz L., Léa G. et autres personas fictifs. - IA : assistance structurante simulée, jamais autonome, toujours sous revue humaine. ## Running Locally Depuis `examples/special-ops-cockpit` : - `bun run build` - `bun run typecheck` - `bun run test` - `bun run smoke` - `bun run preflight` Depuis la racine du monorepo, si le workspace est disponible : - `bun ./node_modules/turbo/bin/turbo run typecheck --filter=@lssm-tech/example.special-ops-cockpit` - `bun ./node_modules/turbo/bin/turbo run build --filter=@lssm-tech/example.special-ops-cockpit` - `bun ./node_modules/turbo/bin/turbo run test --filter=@lssm-tech/example.special-ops-cockpit` ## Déroulé de démo 10 minutes Doc route: `/docs/examples/special-ops-cockpit/demo-script`. Le script importable vit dans `@lssm-tech/example.special-ops-cockpit/docs/demo-script-expert-network`. 1. **Positionner la promesse** — présenter une maquette fonctionnelle de cockpit mission, pas un produit fini ni un chatbot. 2. **Ouvrir le Mission Dashboard** — montrer l'état de la mission, les risques cash et les artefacts visibles par Nathalie. 3. **Passer au Journal de mission** — montrer l’espace et la frontière de brouillon privé sans exposer son contenu, puis expliquer que rien ne remonte sans soumission. 4. **Structurer une note terrain** — transformer une note brute en action, risque, preuve et prochaine étape. 5. **Soumettre une entrée** — créer une trace auditée et des cartes de revue. 6. **Afficher le Trust Panel** — expliciter ce qui est visible, non visible et interdit. 7. **Revoir les cartes** — Nathalie approuve, modifie, rejette ou escalade des éléments soumis. 8. **Lire le Playbook 48h** — relier les entrées soumises aux jalons et preuves attendues. 9. **Composer la synthèse hebdo** — inclure uniquement les cartes approuvées et garder le rapport en brouillon. 10. **Terminer par la roadmap** — relier le pilote à l'offre Mission Control : cash scenario, Qualiopi, onboarding, PO/ARC, e-invoicing et knowledge base. ## Script commercial court > J'ai préparé une maquette fonctionnelle, pas comme un produit fini, mais pour matérialiser ce que pourrait être un cockpit Special Ops. L'idée n'est pas un chatbot ni un outil de surveillance. L'idée est de transformer une mission en système pilotable : playbook, journal de mission, validation, synthèse et capitalisation. Le bon premier pilote serait une mission réelle ou anonymisée avec journal de mission, review Nathalie, playbook 48h et synthèse hebdo. ## Pilote expert-service design partner suggéré - **Semaine 1** : choisir une mission réelle ou anonymisée, cadrer le journal de mission et les cartes de revue. - **Semaine 2** : valider le playbook 48h, les preuves attendues et la synthèse hebdomadaire. - **Semaine 3** : tester la gouvernance IA par persona et choisir les deux modules suivants. - **Semaine 4** : transformer les apprentissages en offre Expert Mission Control Sprint. ## Public Entry Points - `@lssm-tech/example.special-ops-cockpit` - `@lssm-tech/example.special-ops-cockpit/contracts` - `@lssm-tech/example.special-ops-cockpit/docs` - `@lssm-tech/example.special-ops-cockpit/docs/special-ops-cockpit.docblock` (alias of `./docs`) - `@lssm-tech/example.special-ops-cockpit/docs/demo-script-expert-network` - `@lssm-tech/example.special-ops-cockpit/example` - `@lssm-tech/example.special-ops-cockpit/fixtures` - `@lssm-tech/example.special-ops-cockpit/handlers` - `@lssm-tech/example.special-ops-cockpit/proof` - `@lssm-tech/example.special-ops-cockpit/special-ops-cockpit.feature` - `@lssm-tech/example.special-ops-cockpit/ui` - `@lssm-tech/example.special-ops-cockpit/ui/SpecialOpsCockpitPreview` - `@lssm-tech/example.special-ops-cockpit/ui/special-ops-cockpit-preview.data` ## Preview / export workflow The public template preview for this example is package-native: the `./ui` export renders a contained interactive cockpit with nested navigation, a landing screen, and eight workflow-specific targets for mission dashboard, journal, trust panel, review cards, 48h playbook, weekly report, AI governance, and future modules from deterministic fixtures already owned by this package. The sidebar is scoped to the preview surface so hosts can embed it below their own headers without viewport overlap. The eight operational screen keys and order remain the compatibility contract; landing and navigation data are additive. Reusable shell exception: unlike compatible examples such as Integration Hub, BillingOS France SME, and Service Business OS, this preview intentionally does not wrap the cockpit in `NestedCommandShell`. Its local shell owns a contained nested navigation rail so host pages can embed the cockpit below their own headers without fixed-position overlap, viewport takeover, or leakage of private-draft trust boundaries. Keep the local navigation exception documented here unless those containment guardrails move into the shared nested-safe shell contract. Consumers should keep the docs, sandbox, LLMS, source, preview, and render-model fallback links visible. A registry refresh must be produced by the generator rather than by hand-editing generated files. ## Notes d'implémentation - Les fixtures restent fictives et ne doivent pas contenir de données client réelles. - Les handlers doivent rester purs, déterministes et sans accès réseau, LLM, DB, filesystem ou environnement. - Les exports publics incluent `./ui` : les écrans restent alimentés par des fixtures déterministes et des render models de démo. - Toute refresh de registry doit passer par le générateur, jamais par édition manuelle. - Les changements de démo et de metadata doivent rester cohérents avec `AGENTS.md`, `CHANGELOG.md`, `package.json`, les docblocks et les exports publics. Declaration publication uses `contractspec-bun-build types` through `build:types`; `build` runs bundle and declaration generation. The build config preserves declared exports and excludes test-only files from generated build artifacts. Package tests and typecheck remain separate verification gates. --- ## @lssm-tech/example.team-hub Description: Team Hub example with spaces, tasks, rituals, and announcements Path: examples/team-hub URL: /llms/example.team-hub # @lssm-tech/example.team-hub Website: https://contractspec.io **Team Hub example with spaces, tasks, rituals, and announcements.** ## What This Demonstrates - Multi-entity team collaboration domain (space, task, ritual, announcement). - Per-entity schema and operations pattern. - Capability and feature definition patterns. - Presentation layer with team-hub presentation. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/team-hub`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.team-hub` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/announcement` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./announcement` resolves through `./src/announcement/index.ts`. - Export `./announcement/announcement.operations` resolves through `./src/announcement/announcement.operations.ts`. - Export `./announcement/announcement.schema` resolves through `./src/announcement/announcement.schema.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/team-hub.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - The package publishes 23 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.versioned-knowledge-base Description: Example: curated, versioned knowledge base with immutable sources, rule versions, and published snapshots. Path: examples/versioned-knowledge-base URL: /llms/example.versioned-knowledge-base # @lssm-tech/example.versioned-knowledge-base Website: https://contractspec.io **Example: curated, versioned knowledge base with immutable sources, rule versions, and published snapshots.** ## What This Demonstrates - Immutable source and versioned rule management. - Snapshot publishing pattern. - Canonical `migration` export via `KnowledgeSnapshotPublicationMigration`. - Entity models for KB domain. - Memory-based handler implementation. - Feature definition and event-driven architecture. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/versioned-knowledge-base`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.versioned-knowledge-base` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/knowledge-snapshot-publication.migration.ts` defines the exported migration spec. - `src/operations` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/versioned-knowledge-base.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./entities/models` resolves through `./src/entities/models.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./handlers/memory.handlers` resolves through `./src/handlers/memory.handlers.ts`. - Export `./knowledge-snapshot-publication.migration` resolves through `./src/knowledge-snapshot-publication.migration.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./operations/kb` resolves through `./src/operations/kb.ts`. - Export `./versioned-knowledge-base.feature` resolves through `./src/versioned-knowledge-base.feature.ts`. - The package publishes 12 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.schema`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.video-api-showcase Description: Generate API documentation videos from contract spec definitions using the ApiOverview composition. Path: examples/video-api-showcase URL: /llms/example.video-api-showcase # @lssm-tech/example.video-api-showcase Website: https://contractspec.io **Generate API documentation videos from contract spec definitions using the ApiOverview composition.** ## What This Demonstrates - Video generation pipeline from contract specs. - ApiOverview composition pattern. - Sample spec definitions for video input. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/video-api-showcase`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.video-api-showcase` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/build-api-video.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/index.ts` is the root public barrel and package entrypoint. - `src/sample-specs.ts` is part of the package's public or composition surface. - `src/video-api-showcase.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./build-api-video` resolves through `./src/build-api-video.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/video-api-showcase.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./sample-specs` resolves through `./src/sample-specs.ts`. - Export `./video-api-showcase.feature` resolves through `./src/video-api-showcase.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.video-gen`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.video-docs-terminal Description: Generate terminal demo videos from CLI walkthroughs using the TerminalDemo composition and ScriptGenerator. Path: examples/video-docs-terminal URL: /llms/example.video-docs-terminal # @lssm-tech/example.video-docs-terminal Website: https://contractspec.io **Generate terminal demo videos from CLI walkthroughs using the TerminalDemo composition and ScriptGenerator.** ## What This Demonstrates - Terminal demo video generation pipeline. - Narration generation from CLI walkthroughs. - Sample tutorial definitions for video input. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/video-docs-terminal`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.video-docs-terminal` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/build-tutorial.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/generate-narration.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/sample-tutorials.ts` is part of the package's public or composition surface. - `src/video-docs-terminal.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./build-tutorial` resolves through `./src/build-tutorial.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/video-docs-terminal.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./generate-narration` resolves through `./src/generate-narration.ts`. - Export `./sample-tutorials` resolves through `./src/sample-tutorials.ts`. - Export `./video-docs-terminal.feature` resolves through `./src/video-docs-terminal.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.content-gen`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.video-gen`, `@lssm-tech/tool.bun`, ... --- ## @lssm-tech/example.video-marketing-clip Description: Generate short-form marketing videos from content briefs using the video-gen pipeline. Path: examples/video-marketing-clip URL: /llms/example.video-marketing-clip # @lssm-tech/example.video-marketing-clip Website: https://contractspec.io **Generate short-form marketing videos from content briefs using the video-gen pipeline.** ## What This Demonstrates - Marketing clip generation from content briefs. - Brief definition pattern for video input. - Video-gen pipeline consumption. - `src/docs/` contains docblocks and documentation-facing exports. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/video-marketing-clip`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.video-marketing-clip` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/briefs.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/generate-clip.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/video-marketing-clip.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./briefs` resolves through `./src/briefs.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/video-marketing-clip.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./generate-clip` resolves through `./src/generate-clip.ts`. - Export `./video-marketing-clip.feature` resolves through `./src/video-marketing-clip.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.content-gen`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.video-gen`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.visualization-showcase Description: Focused visualization showcase for ContractSpec primitives and design-system wrappers Path: examples/visualization-showcase URL: /llms/example.visualization-showcase # Visualization Showcase `@lssm-tech/example.visualization-showcase` is the focused reference package for ContractSpec's visualization layer. It demonstrates: - Contract-owned `VisualizationSpec` primitives - Shared visualization registries and refs - Design-system wrappers like `VisualizationCard`, `VisualizationGrid`, `ComparisonView`, and `TimelineView` - Markdown summaries for non-React surfaces Use this package when you want a lightweight, deterministic reference for the visualization contract model without the heavier domain logic of `analytics-dashboard`. ## Running Locally From `examples/visualization-showcase`: - `bun run build` - `bun run typecheck` - `bun run test` - `bun run preflight` runs build, typecheck and test before a release. --- ## @lssm-tech/example.voice-providers Description: Voice provider example: Gradium and Fal text-to-speech integration patterns. Path: examples/voice-providers URL: /llms/example.voice-providers # @lssm-tech/example.voice-providers Website: https://contractspec.io **Voice provider example: Gradium and Fal text-to-speech integration patterns.** ## What This Demonstrates - TTS provider integration pattern with connection samples. - Handler-per-action pattern (create-provider, list-voices, synthesize). - Run script for one-shot execution. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/docs/` contains docblocks and documentation-facing exports. ## Running Locally From `examples/voice-providers`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.voice-providers` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/connection.sample.ts` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/run.ts` is part of the package's public or composition surface. - `src/voice-providers.feature.ts` defines a feature entrypoint. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./connection.sample` resolves through `./src/connection.sample.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/voice-providers.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers/create-provider` resolves through `./src/handlers/create-provider.ts`. - Export `./handlers/list-voices` resolves through `./src/handlers/list-voices.ts`. - Export `./handlers/synthesize` resolves through `./src/handlers/synthesize.ts`. - Export `./run` resolves through `./src/run.ts`. - Export `./voice-providers.feature` resolves through `./src/voice-providers.feature.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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. - Missing contract layers. - Major change to content generation. ## Notes - Works alongside `@lssm-tech/integration.provider-voice`, `@lssm-tech/lib.contracts-integrations`, `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. --- ## @lssm-tech/example.voiceops-operating-graph Description: VoiceOps operating graph example: conversation → governed operating graph (DataViewGraphSpec canary replacing hackathon GraphCanvas) Path: examples/voiceops-operating-graph URL: /llms/example.voiceops-operating-graph # @lssm-tech/example.voiceops-operating-graph **VoiceOps operating graph — `DataViewGraphSpec` canary replacing the hackathon `GraphCanvas`.** ## What This Demonstrates - `voiceOpsOperatingGraphView: DataViewGraphSpec` with `inline-op` source and `author` layout. - The 10 VoiceOps node kinds: `voiceSignal`, `transcript`, `customerPain`, `productGap`, `sensitiveData`, `internalTask`, `customerCommitment`, `policyGate`, `approvalGate`, `evidenceReceipt`. - How a conversation becomes a governed operating graph: captured → extracted → classified → gated → approved → evidenced. ## Feature Parity (pending Phase 3 renderer) | Feature | Status | |---------|--------| | Search by id/label/kind | Spec declared — renderer P3/W3.2 | | Kind filter dropdown | Spec declared — renderer P3/W3.2 | | Node selection → inspector | `inspector: 'panel'` declared | | Edge selection → inspector | Spec declared | | Pulse on customerCommitment + policyGate | `experiments` metadata — renderer P3/W3.2 | | ARIA `role="application"` + keyboard | Renderer responsibility (P3/W3.2) | | Author-supplied layout | `layout: 'author'` declared | ## Running Locally From `examples/voiceops-operating-graph`: ```bash bun run typecheck bun run test ``` ## Architecture - `src/voiceOpsOperatingGraphView.ts` — spec, node kind constants, DocBlock - `src/index.ts` — public barrel ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`. - Full RTL parity test suite lands in #43 (P6/W6.3). - Replaces `companyos-ai-os-proofs/src/ui/operating-graph-canvas.tsx` import dependency. Declaration builds use `build:types` through the shared Bun tool; `build` runs bundle and declaration generation. Declared exports are preserved. Generated artifacts exclude test-only files; tests/typecheck remain separate gates. --- ## @lssm-tech/example.wealth-snapshot Description: Wealth Snapshot mini-app for accounts, assets, liabilities, and goals Path: examples/wealth-snapshot URL: /llms/example.wealth-snapshot # @lssm-tech/example.wealth-snapshot Website: https://contractspec.io **Wealth Snapshot mini-app for accounts, assets, liabilities, and goals.** ## What This Demonstrates - Financial entity modeling (accounts, assets, liabilities, goals). - Capability and feature definition patterns. - Presentation layer and event-driven architecture. - RBAC, audit trail, and notification module integration. - An inline `WealthSnapshotPreview` UI for template and example browsers. - `src/docs/` contains docblocks and documentation-facing exports. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. ## Running Locally From `examples/wealth-snapshot`: - `bun run dev` - `bun run build` - `bun run typecheck` - `bun run test` ## Usage Use `@lssm-tech/example.wealth-snapshot` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/events.ts` is package-level event definitions. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/operations` is part of the package's public or composition surface. - `src/ui/` contains the inline preview surface for catalog and template browsers. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/wealth-snapshot.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - Export `./events` resolves through `./src/events.ts`. - Export `./example` resolves through `./src/example.ts`. - Export `./handlers` resolves through `./src/handlers/index.ts`. - Export `./operations` resolves through `./src/operations/index.ts`. - Export `./presentations` resolves through `./src/presentations.ts`. - Export `./ui` resolves through `./src/ui/index.ts`. - Export `./ui/WealthSnapshotPreview` resolves through `./src/ui/WealthSnapshotPreview.tsx`. - Export `./ui/wealth-snapshot-preview.data` resolves through `./src/ui/wealth-snapshot-preview.data.ts`. - Export `./wealth-snapshot.capability` resolves through `./src/wealth-snapshot.capability.ts`. - Export `./wealth-snapshot.feature` resolves through `./src/wealth-snapshot.feature.ts`. - The package publishes 14 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 test` — bun test - `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. - Missing contract layers. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.identity-rbac`, `@lssm-tech/lib.notification`, `@lssm-tech/lib.schema`, `@lssm-tech/module.audit-trail`, ... --- ## @lssm-tech/example.workflow-system Description: Workflow and approval system example for ContractSpec - State machine with role-based transitions Path: examples/workflow-system URL: /llms/example.workflow-system # @lssm-tech/example.workflow-system Website: https://contractspec.io **Workflow and approval system example for ContractSpec - State machine with role-based transitions.** ## What This Demonstrates - **Rich Landing Screen**: Product introduction explaining workflow orchestration concepts, demo path, and navigation. - **Navigation Rail**: Clear sidebar navigation between Overview, Templates, Instances, Approvals, and Analytics. - **State Machine Pattern**: Workflow transitions with defined states and allowed transitions. - **Approval Flow**: Role-based access control for approval decisions. - **Multi-Entity Domain**: Workflow definitions, instances, steps, and approvals. - **React UI**: WorkflowDashboard with templates, instances, and visualizations. - **Contract-Backed Visualizations**: Status, throughput, and workload analysis. - **Demo Scenarios**: Expense Approval, Vendor Onboarding, and Policy Exception workflows with sample data. ## Canonical Demo Path 1. **Landing Screen** - Start on the product introduction explaining workflow orchestration. 2. **Navigation** - Use the sidebar rail to explore Templates, Instances, and Approvals. 3. **Templates** - View workflow definitions (Expense Approval, Vendor Onboarding, Policy Exception). 4. **Instances** - See running workflows with their current states. 5. **Approvals** - Review pending approvals and role-based access. 6. **Analytics** - View throughput metrics and workload analysis. ### New Features - **LandingScreen**: Product-style introduction with value proposition and demo path. - **WorkflowSystemPreviewV2**: Enhanced preview with sidebar navigation. - **WorkflowNav**: Navigation rail for moving between workflow sections. - **Demo Scenarios**: Three complete workflow examples with sample instances. ## Running Locally From `examples/workflow-system`: - `bun run dev` - `bun run build` - `bun run test` - `bun run typecheck` ## Usage Use `@lssm-tech/example.workflow-system` as a reference implementation, or import its exported surfaces into a workspace that composes ContractSpec examples and bundles. ## Architecture - `src/approval` is part of the package's public or composition surface. - `src/docs/` contains docblocks and documentation-facing exports. - `src/entities/` contains domain entities and value objects. - `src/example.ts` is the runnable example entrypoint. - `src/handlers/` contains handlers or demo adapters wired to contract surfaces. - `src/index.ts` is the root public barrel and package entrypoint. - `src/instance` is part of the package's public or composition surface. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./approval` resolves through `./src/approval/index.ts`. - Export `./approval/approval.enum` resolves through `./src/approval/approval.enum.ts`. - Export `./approval/approval.event` resolves through `./src/approval/approval.event.ts`. - Export `./approval/approval.handler` resolves through `./src/approval/approval.handler.ts`. - Export `./approval/approval.operations` resolves through `./src/approval/approval.operations.ts`. - Export `./approval/approval.schema` resolves through `./src/approval/approval.schema.ts`. - Export `./docs` resolves through `./src/docs/index.ts`. - Export `./docs/workflow-system.docblock` is an alias of `./docs` and resolves through `./src/docs/index.ts`. - Export `./entities` resolves through `./src/entities/index.ts`. - The package publishes 44 total export subpaths; keep docs aligned with `package.json`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - `bun run test` — bun test ## Recent Updates - **UI Improvements**: Added LandingScreen, WorkflowNav, and WorkflowSystemPreviewV2 with enhanced navigation. - **Demo Scenarios**: Complete workflow examples with Expense Approval, Vendor Onboarding, and Policy Exception. - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Works alongside `@lssm-tech/lib.contracts-spec`, `@lssm-tech/lib.design-system`, `@lssm-tech/lib.example-shared-ui`, `@lssm-tech/lib.runtime-sandbox`, `@lssm-tech/lib.schema`, ... --- ## @lssm-tech/lib.agent-runtime-conformance Description: Cross-runtime lifecycle conformance suite for ContractSpec agent runtime adapters Path: packages/tools/agent-runtime-conformance URL: /llms/lib.agent-runtime-conformance # @lssm-tech/lib.agent-runtime-conformance Cross-runtime lifecycle conformance suite for ContractSpec agent runtime adapters. Makes "portable across runtimes" **falsifiable** instead of asserted: any adapter that claims compatibility must pass this suite. ## Usage ```ts import { runAgentRuntimeConformanceSuite } from '@lssm-tech/lib.agent-runtime-conformance'; import { createSqliteWorkflowDevkitTarget } from '@lssm-tech/lib.agent-runtime-conformance/fixtures'; const report = await runAgentRuntimeConformanceSuite( createSqliteWorkflowDevkitTarget({ file: './agent.db' }) ); console.log(report.summary.single_adapter_lifecycle_conformance_rate); // 16/19 ``` ## The 19 cases (spec 04) Cases 1-15 plus the mandatory **case 5b** (effect-replay safety) are testable for every durable target. Cases 16-17 remain `NOT_APPLICABLE_THIS_RELEASE`; case 18 becomes mandatory when an integration-local two-adapter target supplies runtime-probed portable evidence. - **1-3** create session, stream lifecycle events, invoke an operation-backed tool - **4** checkpoint round-trip through `AgentCheckpointPort` - **5** survive forced process death (real `SIGKILL` child; durable backing only) - **5b** effect-replay safety on resume — the recorded result is replayed via the `(nonce, stepInstanceId)` key so an approval-gated `sendMessage` is never double-sent. Its **inverse sub-case** (`5b-inverse`) proves two distinct approval-authorized identical-input sends both fire (nonce-scoped, not input-scoped). - **6** resume from durable recovery - **7-8** suspend for human input / approval - **9-12** reject missing / wrong-input / replayed approval; resume with valid approval - **13** cancel (side effect must not fire once cancelled) - **14-15** emit artifacts and evidence refs - **16-17** execution receipt / outcome linkage — `NOT_APPLICABLE_THIS_RELEASE` - **18** cross-adapter portability — compares runtime-probed lifecycle, approval, effect replay, artifact/evidence, replay, and explicitly contracted loss diagnostics ## Metric `single_adapter_lifecycle_conformance_rate = passing / 19`. Target this release is **16/19 ≈ 0.84** for the Phase-1 Workflow DevKit gate. Integration-local EVE and Workflow DevKit targets additionally run case 18, producing **17/19** with cases 16-17 explicitly not applicable. ## Targets - `createInMemoryWorkflowDevkitTarget()` — baseline; cannot survive process death, so cases 5/5b/6 report `NOT_APPLICABLE`. - `createSqliteWorkflowDevkitTarget({ file })` — durable; the canonical gate. Vendor-specific targets remain in their integration packages. Case 18 uses `runPortableAdapterProbe()` and fails on any unclassified field or declared-loss difference; integrations must supply an exact expected-loss contract. --- ## @lssm-tech/agentpack.contractspec Description: Canonical repository-local Claude, Codex, and agent guidance for ContractSpec consumers. Path: packages/tools/agentpack-contractspec URL: /llms/agentpack.contractspec # `@lssm-tech/agentpack.contractspec` Canonical repository-local guidance for teams consuming ContractSpec packages. It supplies marker-owned Claude Code, Codex, OpenCode, and Cursor rules, compact catalog memory, adoption hooks, one adoption skill, and local MCP wiring. `contractspec init` materializes this pack into the repository-local agentpacks cache and invokes the existing agentpacks compiler. User-owned `AGENTS.md` and `CLAUDE.md` content is preserved by agentpacks managed markers. The pack never writes global Claude Desktop or Codex configuration. Claude Code hooks use the Claude blocking protocol (`--host claudecode`), so an adoption denial actually blocks in Claude Code instead of surfacing as a non-blocking exit code, and an adoption review follows the session permission mode (no prompt in `bypassPermissions`/`dontAsk`, where the review is deferred and recorded; a prompt in `default`; a deny in `plan`). A workspace that has not enabled Connect (`connect.enabled`, off by default) is not prompted: the adoption hooks stay silent there. The shell hook matches both `Bash` and `PowerShell`, and `SessionStart` runs `contractspec can-help catalog status --host claudecode`, which adds one line of catalog context (version, source, freshness, content hash, counts, and the `can-help` discovery command) instead of raw JSON. These hooks need a ContractSpec CLI that supports `can-help catalog status --host` and `connect hook adoption ... --host`. The catalog memory rule loads only when package manifests or `.contractspec/**` files are read. The adoption skill activates for capability selection, replacement, or a new public surface/dependency. It uses current catalog provenance and task-bound Connect decisions, then verifies affected consumers. Routine unrelated edits do not need an adoption ceremony. Published rule/skill files and the materialized `contractSpecAgentPackFiles` map are one surface; `bun test src/index.test.ts` checks their parity. --- ## @lssm-tech/agentpacks Description: Composable AI agent configuration manager. Pack-based rules, commands, skills, hooks, and MCP sync across OpenCode, Cursor, Claude Code, Codex, Gemini, Copilot, and more. Path: packages/tools/agentpacks URL: /llms/agentpacks # agentpacks Website: https://github.com/lssm-tech/contractspec/tree/main/packages/tools/agentpacks **Composable AI agent configuration manager that merges packs into target-specific tool configuration, rules, hooks, skills, and AGENTS output.** ## What It Provides - Loads, merges, and resolves agent packs into Cursor, Claude Code, Codex, Copilot, Gemini, OpenCode, registry, and AGENTS targets. - Publishes a CLI plus a broad programmatic API for pack loading, sources, targets, importers, and exporters. - Compiles canonical filesystem-authored agent applications from `agent/{instructions.md,agent.ts,tools,skills,connections,sandbox,channels,subagents,schedules}` and `evals/` into deterministic AgentSpec/WorkflowSpec configuration. - Recently expanded around AI-native flows, model guidance, Cursor plugin output, and compatibility hardening. - Related ContractSpec packages include `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install agentpacks` or `bun add agentpacks` ## Usage ```bash npx agentpacks --help # or bunx agentpacks --help ``` ### Generate and RTK refresh After a successful non-dry-run `agentpacks generate` writes files, the CLI runs `rtk init` and then `rtk init --codex` to refresh Claude Code and Codex RTK guidance. Dry runs, diff-only runs, no-op generations, and partial generations with target errors skip the RTK refresh. RTK command failures are reported as warnings after generation output is written. `agentpacks generate --diff` uses a non-writing filesystem overlay. It reports added, modified, and deleted generated artifacts without changing files or directories, and exits non-zero when drift is present so it can be used as a CI check. ### Complete skill bundles Skills may include nested `references/`, `scripts/`, `assets/`, and `agents/openai.yaml` beside `SKILL.md`. Claude, Codex, Cursor, OpenCode, Copilot, Gemini, and Mistral targets preserve these files byte-for-byte, including executable permissions. Gemini writes `.gemini/skills//`. Existing skill importers and Cursor plugin export preserve the same bundles. Resource files receive no generated header and are never executed during generation. Keep relative links within the skill directory. Generation validates bundles before target cleanup and rejects symlinks, non-regular files, and unsafe paths. `--diff` detects binary and permission changes without printing binary contents or modifying files. Existing single-file skills retain their output format. Custom `GenerationFileSystem` adapters may implement the optional `readBytes`, `writeBytes` (with a `mode` option), and `statMode` methods. Resource-bearing generation requires all three and fails before mutation when they are absent; the text-only API remains compatible. `GenerateResult.artifactSources` maps each skill output path to its exact source paths for generation evidence. Resource digests hash raw bytes; existing UTF-8 text digests remain unchanged. For repository authoring, use `maintain-agentpacks` and edit canonical pack sources. Keep descriptions specific, route conditional details to references, and update `feature-units.json` when adding or removing resources. Verify generated links and behavior as well as schema validity. ## Governed generation evidence Production generation can emit a canonical `AgentpackGenerationTraceManifestV1`. Evidence mode is fail closed: the exact Connect decision and replay artifacts plus `SOURCE_DATE_EPOCH` are required, and preview modes never write a manifest. ```bash SOURCE_DATE_EPOCH=1700000000 agentpacks generate \ --targets codexcli \ --trace-manifest .agentpacks/traces/generation.json \ --connect-decision .contractspec/connect/decision.json \ --connect-replay .contractspec/connect/replay.json ``` Each trace binds normalized source paths, source digests, target capability, output action and digest, deterministic time, and Connect evidence. Evidence contains references and digests—not source contents, credentials, prompts, or secret values. RTK refresh completes before output digests are recorded. Create and independently verify an `AgentpackAiAuditReceiptV1` against an exact commit SHA and exact changed-path scope: ```bash agentpacks ai-audit create \ --output .agentpacks/audit.json \ --trace-manifests .agentpacks/traces/generation.json \ --baseline 0123456789abcdef0123456789abcdef01234567 agentpacks ai-audit verify \ --receipt .agentpacks/audit.json \ --expected-sha 89abcdef0123456789abcdef0123456789abcdef \ --baseline 0123456789abcdef0123456789abcdef01234567 ``` Verification re-hashes active `AGENTS.md` rules, manifests, their source and Connect references, and generated artifacts. A stale SHA, changed path scope, missing evidence, invalid schema, or digest mismatch fails verification. Root Claude and Codex context is maintained inside explicit agentpacks-managed Markdown blocks in `CLAUDE.md` and `AGENTS.md`. Content outside those blocks, including repository boundaries, package guidance, and RTK instructions, is preserved across regeneration. Generated Markdown keeps YAML frontmatter on the first line; the `Generated by agentpacks` header follows the frontmatter so hosts can parse skill, agent, command, and rule metadata. Claude Code agents receive `name`, `description`, and a Claude-compatible `model`: an explicit `claudecode.model` (including `inherit`) wins, the models.json profile model applies only when the agent sets none, and non-Anthropic profile models fall back to the session model. Claude Code detail rules with `globs` (or `claudecode.paths`) emit `paths:` and load only for matching files; rules with no globs or `**/*` stay always loaded. `pack validate` warns about a rule with no globs, no `claudecode.paths`, and Cursor `alwaysApply: false`; set `claudecode.paths: ['**/*']` to keep such a rule always loaded on purpose. Model guidance (`model-config`) loads only for `**/models.json` and `agentpacks.jsonc` in Claude Code and Cursor. ## Platform compatibility and canonical packs Agentpacks is migrating from file-only pack prose toward typed all-content feature units that can render or transform platform-native artifacts without semantic drift or silent loss. The public contract is: - canonical production guidance lives in three pack families: ContractSpec-specific, software best practices, and monorepo-specific ContractSpec mission/goals/constraints; - each canonical pack includes `feature-units.json` as the typed all-content migration baseline; - every meaningful prose feature unit must keep a shared invariant and explicit Claude plus Codex/GPT variants; - OpenCode selects the Codex/GPT operational variant by default; - Codex CLI generation treats root `AGENTS.md` as the primary operational guidance surface and may also emit `.codex/*` artifacts; - structural feature units such as hooks, MCP, model profiles, plugins, ignore files, assets, manifests, and exported docs require target capability status, transform/loss policy, diagnostics, and trace evidence; - generated files must preserve traceability back to feature-unit ids and Connect parity evidence; - `agentpacks:all` is the selected core-target smoke run, while `agentpacks:compat:all-targets` is the exhaustive registered-target compatibility run. See `docs/agentpacks-platform-compatibility.md` and `packs/README.md` in the ContractSpec repository for the canonical taxonomy, legacy-pack disposition, and release gates. ## Architecture `src/application/` is a data-only compiler. It rejects executable expressions, computed keys, methods, spread, template literals, unsafe sandbox policy, secret literals, and unresolved references instead of evaluating authored source. Successful output is passed through the canonical `defineAgent()` and `defineWorkflow()` entry points before it is returned. Protocol V1 applications may declare the existing `AgentSpec.protocol` and `communicationProfileRef` fields in `agent/agent.ts`. Their compiler caller must supply an explicit `compiledAt` evidence timestamp. The compiler then emits a canonical application manifest and permission summary that bind the source, tools, connections, communication profiles, automations, subagents, evaluations, and protocol policy references by SHA-256. Legacy applications remain unchanged and do not receive Protocol V1 evidence implicitly. Filesystem applications may declare a stable `applicationId` distinct from their legacy `meta.key`. This is opt-in for Protocol V1 and lets an existing public agent key remain compatible while lifecycle and qualification bind the canonical installed application identity. Protocol V1 schedules may opt into a `governance` block with timezone, objective, policy and evidence refs, risk and approval requirements, bounded run count and active days, and delivery requirements. Agentpacks compiles those sources into immutable `AgentAutomationDefinitionV1` artifacts bound to the exact application manifest. Legacy schedules without governance compile as before and do not become materializable automation definitions implicitly. Compiler output never deploys a schedule or grants effect authority; Agent Host and the selected policy owner must separately preview, authorize, materialize, persist, and qualify it. - `src/cli/` contains command implementations for init, generate, install, publish, search, and pack subcommands. - `src/core/` handles config loading, dependency resolution, pack loading, typed feature-unit coverage validation, lockfiles, and feature merging. - `src/features/`, `src.sources/`, `src.targets/`, `src.importers/`, and `src.exporters/` implement the pack pipeline. - `src.utils/` contains credentials, diffing, markdown, registry, and model-helper utilities. - `src/index.ts` is the root public barrel and package entrypoint. ## Public Entry Points - Exports the CLI binary plus API, core, features, targets, sources, importers, exporters, and utility subpaths. - Binary `agentpacks` points to `./dist/index.js`. - Export `.` resolves through `./src/index.ts`. - Export `./api` resolves through `./src/api.ts`. - Export `./cli/export-cmd` resolves through `./src/cli/export-cmd.ts`. - Export `./cli/generate` resolves through `./src/cli/generate.ts`. - Export `./cli/ai-audit` resolves through `./src/cli/ai-audit.ts`. - Export `./evidence` exposes generation trace and AI-audit APIs. - Export `./cli/import-cmd` resolves through `./src/cli/import-cmd.ts`. - Export `./cli/info` resolves through `./src/cli/info.ts`. - Export `./cli/init` resolves through `./src/cli/init.ts`. - Export `./cli/install` resolves through `./src/cli/install.ts`. - Export `./cli/login` resolves through `./src/cli/login.ts`. - Export `./cli/models-explain` resolves through `./src/cli/models-explain.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Use the Biome-only lint and formatting workflow in pack guidance and generated targets. - Vnext ai-native. - Add latest models and align defaults. - Harden AgentSkills compatibility in agentpacks. - Add first-class mistral provider support. - Align cursor plugin export and hooks output. ## Notes - Do not modify target output formats without updating the corresponding target writer, capability matrix, trace/loss diagnostics, and release evidence. - Pack schema changes must stay backward-compatible (see `schema.json`) unless the release capsule explicitly declares the public compatibility-surface migration and migration evidence. - Never hard-code model names; use `utils/model-allowlist` and `utils/model-guidance`. --- ## @lssm-tech/biome-config Description: Biome presets, Grit plugins, and policy manifest for ContractSpec repositories. Path: packages/tools/biome-config URL: /llms/biome-config # @lssm-tech/biome-config Website: https://contractspec.io **Typed ContractSpec lint-policy package that generates Biome presets, Grit plugins, and AI-facing rule summaries.** ## What It Provides - Acts as the source of truth for repository and consumer Biome policy artifacts. - Publishes generated presets, Grit plugins, and AI summaries alongside the typed manifest and generation helpers. - Requires artifact synchronization whenever the typed policy manifest changes so committed outputs stay aligned. - Enforces React and React Native compatible JSX in shared presentation packages by preferring layout primitives (`HStack`, `VStack`, `Box`) over raw `
` and requiring visible text to sit inside `Text` or approved typography components. Repository app packages are excluded by default and can be opted in with the policy allowlist. - Related ContractSpec packages include `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/biome-config` or `bun add @lssm-tech/biome-config` ## Usage Import the root entrypoint from `@lssm-tech/biome-config`, or choose a documented subpath when you only need one part of the package surface. ### JSX Primitive Fixer The Biome Grit plugins emit diagnostics only. To apply conservative native HTML replacement fixes, run: `bun run jsx:fix-primitives` or from this package: `bun run fix:jsx-primitives` By default the fixer scans `packages/bundles`, `packages/examples`, and `packages/modules`. It skips `packages/apps` unless an app is explicitly allowlisted: `bun run jsx:fix-primitives -- --allow-app web-landing` Use `--check` for a dry run. The fixer preserves original attributes and className by default, infers safe list props from simple class strings, rewrites generic `` elements to inline-safe `Text`, maps native HTML controls to design-system controls (including the cross-platform `NativeSelect` family), and wraps raw text with context awareness: block-safe containers keep `...`, while mixed-content contexts use inline-safe `...`. Semantic form roots remain diagnostic-only when no behavior-preserving design-system replacement exists. ## Architecture - `src/policies.ts` defines the typed policy manifest. - `src/generate.ts` and `src/sync.ts` generate and synchronize derived artifacts. - `src/fix-jsx-primitives.ts` provides the conservative companion codemod for deterministic JSX primitive replacements. - `src/types.ts` and `src/index.ts` expose the public API for generation and policy consumption. - `presets/`, `plugins/`, and `ai/` contain committed generated artifacts consumed by downstream tools. ## Public Entry Points - Exports the root library API and ships generated presets, Grit plugins, and AI-facing summaries as committed package artifacts. - Export `.` resolves through `./src/index.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `bun run test` — bun test - `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 fix:jsx-primitives` — apply conservative JSX primitive replacements. - `bun run typecheck` — tsgo --noEmit - `bun run sync:artifacts` — bun src/sync.ts - `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` — bun run sync:artifacts && contractspec-bun-build prebuild ## Recent Updates - Add cross-platform JSX layout and text guardrails for React and React Native compatibility. - Add a conservative JSX primitive fixer command for deterministic native HTML replacements. - Replace eslint+prettier by biomejs to optimize speed. ## Notes - The committed `presets/`, `plugins/`, and `ai/` artifacts are intended for downstream scaffolding without code execution. --- ## @lssm-tech/tool.bun Description: Shared Bun build presets and CLI for ContractSpec packages Path: packages/tools/bun URL: /llms/tool.bun # @lssm-tech/tool.bun Website: https://contractspec.io **Shared Bun build presets and CLI for ContractSpec packages. Provides the `contractspec-bun-build` binary used by nearly every package's `build`, `dev`, and `prebuild` scripts.** ## What It Provides - **Layer**: tool - **Consumers**: all monorepo packages (via `contractspec-bun-build` in their scripts) ## Installation `npm install @lssm-tech/tool.bun` or `bun add @lssm-tech/tool.bun` ## Usage ```bash npx contractspec-bun-build --help # or bunx contractspec-bun-build --help ``` ## Typed Config The ordered configuration filenames are owned by this package's `contractspec.development.configInputs` manifest binding. Runtime discovery uses this validated list. The pending affected-work planner integration can use the same authority to bind configuration dependencies to the invoking workspace. This metadata describes dependencies; it does not authorize execution or waive artifact qualification. The root package export includes TypeScript declarations for config presets: ```ts import { defineConfig, moduleLibrary, type BuildConfig, } from "@lssm-tech/tool.bun"; const config: BuildConfig = { ...moduleLibrary, styleMode: "copy", }; export default defineConfig(() => config); ``` ## Pack Staging Helpers `@lssm-tech/tool.bun/pack-staging` holds the contributor helpers that package pack verifiers share: `stageBuiltPackage`, `stageWorkspaceDependencies`, `workspacePackageRoots`, `literalize`, `catalogVersions` and `run`. They run under Bun inside a repository workspace, rewrite `workspace:`/`catalog:` ranges to publishable ranges in staged copies and never publish anything. `stageWorkspaceDependencies(root, run, manifestRoot)` stages the transitive `workspace:` runtime closure of the manifest you name explicitly. ```ts import { run, stageBuiltPackage, stageWorkspaceDependencies, } from "@lssm-tech/tool.bun/pack-staging"; const staged = await stageBuiltPackage(packageRoot, join(temporaryRoot, "pkg")); const closure = await stageWorkspaceDependencies(artifacts, run, packageRoot); ``` ## Pack Verification Helpers `@lssm-tech/tool.bun/pack-verification` holds the production-pack verifier that package `pack:verify` scripts share. It runs under Bun inside a repository workspace, works in a temporary directory you own and never publishes. - `packReproducibly(packageRoot, root, run)` stages the built package (dist without test or build-state files, README, production manifest) and packs it twice with `npm pack --ignore-scripts`. It fails unless both tarballs are byte-identical and the source manifest is unchanged. - `inspectPackedArtifact(tarball, root, run, { requiredDependencies })` rejects source, test or build-state entries, private dependency protocols, source export targets, missing required direct dependencies and undeclared runtime imports in the emitted JavaScript. - `verifyPackConsumer(packageRoot, root, tarball, manifest, run)` builds and packs the workspace dependency closure, installs everything into a clean consumer, imports every declared subpath in Node and Bun and type-checks them with the nearest `node_modules/.bin/tsgo` up to the workspace root. The install resolves third-party dependencies from the npm registry. The production manifest uses `publishConfig.exports`, writes `workspace:` ranges as `^` and `catalog:` ranges as the catalog's verbatim value, and drops dev dependencies, scripts and `publishConfig`. A closure dependency that declares a `pack:production` script produces its own tarball. `packProductionPackage`, `stageProductionPackage`, `stageLocalDependencies`, `productionManifest`, `assertRuntimeImportClosure` and `runCommand` are the building blocks. ```ts import { inspectPackedArtifact, packReproducibly, runCommand, verifyPackConsumer, } from "@lssm-tech/tool.bun/pack-verification"; const { tarball, sha256 } = await packReproducibly(packageRoot, root, runCommand); const manifest = await inspectPackedArtifact(tarball, root, runCommand, { requiredDependencies: ["@lssm-tech/lib.schema"], }); await verifyPackConsumer(packageRoot, root, tarball, manifest, runCommand); ``` ## Private Build Entries Declaration builds resolve dev-only workspace dependencies from the selected TypeScript build project's source and compiler configuration. Test-only dependencies excluded by that project do not trigger unrelated declaration builds. Runtime dependencies and required peers retain their artifact checks, and optional peers retain their type-only reference checks. Computed module expressions or relative imports outside the resolved project retain all dev dependencies conservatively. Test workflows continue to use the package's complete declared dependencies. Non-UI packages can opt into `entryMode: 'module-closure'` with explicit literal `entry` paths and `exports: { rewrite: false }`. The existing manifest is the authority for supported exports: source export targets remain compatibility roots, including subpaths that the root barrel does not export. Runtime-relative imports are followed and each reachable module is emitted once per target. A new private helper never becomes a package export merely because it exists. Edit the manifest deliberately when adding a public entry. An exact subpath blocked with `null` in both frozen source and published maps adds no closure or emitted target. A block present in only one map fails validation. This mode implies no-bundle emission and uses sequential worker batches capped at 64 files or 8 MiB of source. A single module larger than 8 MiB fails explicitly in this opt-in mode. For mixed packages, browser emission starts only at exact frozen exports that advertise a browser target and follows their private dependencies. Unrelated Node-only public roots still build for Bun and Node and remain part of declaration emission. Shared-package inference retains browser output for those advertised roots; explicitly disabling browser remains an error. Node-only imports reachable from any browser root are rejected, and full-graph source validation still applies to backend roots. Direct entry mode retains its existing target inference. Single-entry tsconfig-override builds honor `noBundle` just like the normal CLI path and explicit closure batches. Local helpers stay separate, so React contexts and shared module state retain their identity. Bundled builds keep their existing behavior. The override worker resolves configured local TypeScript aliases to relative emitted modules while keeping declared external packages external; missing emitted helpers or assets fail validation. Platform entry selection, native worklets, client directives and explicit style copying remain separate parts of the existing build pipeline. ```js export default defineConfig({ ...moduleLibrary, entry: ['src/index.ts', 'src/service.ts'], entryMode: 'module-closure', exports: { rewrite: false }, }); ``` The initial opt-in supports non-UI relative JavaScript/TypeScript graphs and declared external packages. Computed imports/requires, local aliases, wildcard exports, assets and unadvertised platform-suffixed source graphs fail explicitly. An exact frozen public native/ios/android implementation root may use its `dist/native` layout; an exact web/browser root may use its existing root/browser layout. Only those advertised files are admitted, never private platform siblings or platform discovery. Published target paths must match the existing entry selection, and disabled targets still fail. Platform declaration aliases remain unsupported. Frozen conditional source exports retain every branch as a closure and declaration root. Each published condition must point to its matching source branch, honoring source condition order and default fallback. Browser reachability starts at that condition's source rather than unrelated native or backend branches. Multi-source maps are checked across every combination of their source/published condition names, including custom conditions, up to twelve distinct names per export. Larger or conflicting layouts fail explicitly and can use direct mode. Keep other platform graphs in `direct` mode. This does not change UI/Metro conditional exports or the existing direct-mode watcher. Declarations continue to use the package's complete TypeScript configuration. Full builds retain transactional rollback, and standalone transpile failures must never be treated as usable outputs. Closure mode freezes manifest bytes even when `prebuild` runs; it validates both source and published export mappings instead. Advertised runtime conditions must have enabled build targets. Browser claims are checked against the complete compatibility closure, not only intentional entries: a legacy-only Node builtin import fails before output is replaced. Its dev watcher recomputes reachability on source edits, including newly imported private files, serializes producers and retains the previous good output after a failed rebuild. It builds the Bun target by default (`--all-targets` includes the advertised targets). Manifest/compiler/build-config edits require restarting dev and terminate the watcher explicitly instead of using stale configuration. Packages can emit implementation-only files without adding them to generated package exports. Use `exports.exclude` for files that public entries import relatively but consumers must not import as package subpaths: ```js export default { entry: ['src/**/*.ts', 'src/**/*.tsx'], exports: { rewrite: true, exclude: ['src/**/internal/**'], }, }; ``` The files still build into `dist`, but `prebuild` omits matching paths from `exports` and `publishConfig.exports`. ## Node ESM Relative Specifiers Declared dependencies, optional dependencies and peers are explicitly external for JavaScript builds, including their subpaths. This preserves package boundaries when workspace TypeScript paths point at dependency source files: bundling local code must not inline a dependency and leak its transitive imports into the caller. Custom `external` entries remain additive. Development-only packages are not automatically treated as runtime dependencies. Bun resolves TypeScript aliases before external flags. A temporary resolved tsconfig removes aliases belonging to external packages while retaining local aliases, so package boundaries survive that resolution order. The source config is not edited, and temporary configuration is removed after success or failure. Shared-target inference follows runtime imports through local barrels, including literal dynamic imports and NodeNext `.js` specifiers resolving to TypeScript. Unselected tests remain excluded; custom source layouts and import cycles are supported. This is local source inference, not qualification of external packages or dynamic nonliteral imports for browser execution. Executable shebangs are normalized only in scanner input; source files remain unchanged and continue to build as CLI entry points. Presets and default configuration share build-entry pattern definitions, including `.spec.tsx` and `.test-support.ts`/`.test-support.tsx` exclusions. Test helpers are not production entries, generated public subpaths, or target-inference roots. Keep test helpers excluded from package declaration tsconfigs as well. Explicit entry overrides remain supported, and test-runner discovery is independent of these build/export patterns. Every production transpile target normalizes emitted relative ESM specifiers after Bun writes the complete target. Static imports, re-exports, and literal dynamic imports, and declaration import types (`import("./module").Type` and `typeof import("./module")`) resolve in this deterministic order: 1. an existing exact file; 2. a sibling `.js` file; 3. an `index.js` file in the referenced directory. Exact `.` and `..` directory references resolve only to their index, never a similarly named sibling file. Declaration-only sidecars retain the same public types while their emitted specifiers use NodeNext-compatible `.js` paths. Query strings and URL fragments are preserved. The normalizer is idempotent and syntax-aware, so import-shaped comments and ordinary strings are not changed. If any relative specifier cannot be resolved, the target fails before any emitted file is rewritten; incomplete Node ESM graphs cannot be published accidentally. The TypeScript 7 parser and declaration emitter prefer the native binding for the current runtime architecture. If the package manager ran under a compatible alternate architecture (for example, x64 Node under Rosetta with arm64 Bun), the tool deterministically falls back to the installed same-platform binding. ## Style Exports `contractspec-bun-build` scans public CSS style entries separately from TypeScript entries so style files do not affect JavaScript output roots. Default style entries: - `styles/**/*.css` - `src/*.css` - `!**/*.module.css` Packages can override or disable style entries from their build config: ```js export default { styleEntry: ['styles/**/*.css'], // or: styles: { entry: ['styles/**/*.css'] }, // or: styleEntry: false, }; ``` By default, style entries are processed with `bun build`. Packages that need to preserve CSS directives for another processor, such as Tailwind `@source`, `@custom-variant`, `@theme`, or `@tailwind`, can copy style files unchanged: ```js export default { styleEntry: ['src/styles/**/*.css'], styleMode: 'copy', // or: styles: { entry: ['src/styles/**/*.css'], mode: 'copy' }, }; ``` Style entries are exported under the `style` and `default` conditions, for example `./styles/globals.css`. ## Type Declaration Emit `contractspec-bun-build types` emits package declarations with stable TypeScript 7 (`tsc`) by generating a temporary declaration-only tsconfig and writing `.d.ts` files to `dist`. ## Platform Variants `contractspec-bun-build` recognizes platform suffixes in public TypeScript entries and emits conditional exports plus matching build outputs: | Source suffix | Export condition | Build output | | --- | --- | --- | | `.web` | `browser` | `dist/browser/*` plus the Bun default when no base entry exists | | `.native` | `react-native` | `dist/native/*` | | `.ios` | `ios` | `dist/native/*` | | `.android` | `android` | `dist/native/*` | Exact subpaths such as `./foo.web`, `./foo.native`, `./foo.ios`, and `./foo.android` are exported alongside canonical subpaths such as `./foo`. ## Public Entry Points - `contractspec-bun-build` -> `./bin/contractspec-bun-build.mjs` - `.` — `./index.js` ## Local Commands - `bun run test` — bun test - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary ## Recent Updates - Normalize emitted relative Node ESM specifiers and fail closed on incomplete graphs - Add copy mode for public CSS style files that must preserve framework directives - Add direct CSS style subpath exports for public style files - Replace eslint+prettier by biomejs to optimize speed - Add multi platform support to bun build - Use-client within lib surface-runtime ## Notes - Changes here affect every package's build pipeline -- test broadly before merging - Do not remove or rename CLI sub-commands (`transpile`, `types`, `dev`, `prebuild`) without updating all consumers - Keep runtime dependencies deliberate: `glob` powers source discovery and stable `typescript` powers declaration emit and artifact parsing - The published package contains only the binary, runtime library, typed root export, README, and changelog; conformance tests stay in the repository ### Artifact normalization snapshots Relative-import normalization uses the same source snapshot as its AST offsets. A concurrent normalizer that already produced the identical output is an idempotent no-op. If a file differs from both the parsed source and expected normalized output at publication checks, normalization reparses the graph up to three attempts. Continuous conflicts fail with an explicit changed-artifact error and preserve the observed newer file. A successful normalization is not a lock against arbitrary external emitters; build orchestration must still isolate output directories during emission. ### Artifact parser deadlines Each emitted-artifact parse has a two-minute I/O deadline. Snapshot disposal and API shutdown each have a two-second grace period before process termination and workspace cleanup. Timeout is an error, never successful artifact validation, and the serialized parser queue remains usable after rejection. Large graphs and NodeNext/native specifier checks remain in the conformance suite. Compiler stdout is drained concurrently. If its pipe remains open ten seconds after the compiler exits, the build fails explicitly and cancels the reader. This deadline does not limit compilation time and never treats missing output as a successful build. Parser RPC failures include the current snapshot/project/file-batch phase. A parser process exit rejects pending RPCs immediately with its exit status and bounded stderr tail, rather than waiting silently until the I/O deadline. Multi-file artifact validation partitions native parser projects by source bytes (8 MiB) and file count (16). A single larger file remains intact. Projects close between groups, preserving ordered AST results and full validation while avoiding one native project retaining a large monorepo's repeated bundled source graphs. ### One artifact parser server per task A `build`, `transpile` or `types` run starts at most one native parser server and reuses it for module-closure checks, dangling-export checks and output normalization; a standalone `parseJavaScriptFiles` call reuses one server across its batches. Each batch is its own project: the previous project closes and the server invalidates every cached file first, so a reused server reads the same bytes a fresh one would. The server lives only in the build process and its temporary workspace is deleted when the task ends, when the process exits, or when the task is interrupted by SIGINT or SIGTERM (the signal is then raised again, so the task still ends with it); no parser state is persisted between tasks. If stopping the server fails after the task itself failed, the failure is logged and the task's own error is reported. A batch failure stops the server, and the retry or the next parse starts a new one; a server that exits while idle is replaced the same way. `dev` keeps one server per parse call while it watches. Declaration and JavaScript output are byte-identical to per-batch servers. Declaration compilation uses `noEmitOnError` so type/root-boundary failures cannot write partial declarations, including escaped output in sibling source trees. Consumers must still honor the nonzero build result; previous valid artifacts do not qualify a new source revision. Concrete published declaration paths are required once a dependency declares a `build:types` producer. Missing artifacts fail before consumer compilation instead of silently falling back to sibling sources. Source-only dependencies remain supported. Standalone `.d.ts`/`.d.mts`/`.d.cts` inputs retain their suffix and are copied after successful type checking; generated sibling declarations take priority. Dependency freshness checks read the same discovered source timestamps with at most eight concurrent metadata reads. They preserve the maximum timestamp and first source-order error, and settle every started read before returning. Standalone declaration copying uses TypeScript's resolved input list. This covers custom layouts such as root-level `ui/` and respects explicit project exclusions instead of assuming every package uses `src/`. Unused optional workspace peers do not impose declaration-build prerequisites. The builder conservatively checks selected source files and resolved compiler options for peer references, including type-only imports. Required dependencies and referenced optional peers still require their advertised declaration artifacts. Types-only builds materialize configured style entries before relative-import validation, using the same copy/build mode as JavaScript bundles. A cold checkout therefore includes styles referenced by emitted declarations without weakening artifact-integrity checks. Artifact parsing explicitly opens the temporary tsconfig project and selects that project for every batch. It never relies on emitted files finding an ancestor or inferred project. Each project contains the requested JavaScript/declaration roots only, with dependency resolution, ambient type discovery, and default libraries disabled. All requested roots must still yield ASTs, and relative-import closure validation still rejects unresolved artifacts before writes. This isolates parsing from consumer tsconfig exclusions and keeps byte/file batch limits effective. ### Full package output rebuilds Standard consumers run `contractspec-bun-build build` from their `build` script. Bun still runs package `prebuild` lifecycle hooks; custom pipelines retain their explicit stages. This source-distributed tool has no build script. Run conformance with `bun run test` separately. Turbo hashes builder runtime sources directly. `contractspec-bun-build build` saves the previous `dist`, emits JavaScript and declarations into a fresh output tree, and validates both stages before discarding the previous tree. A failed stage restores the previous output. This removes obsolete nested declarations after output layouts change without guessing whether individual declaration-only modules are stale. Standalone `transpile` retains its Turbo declaration-preservation behavior. Hand-authored declarations belong in the configured source inputs so successful type generation copies them into output. An exclusive `.contractspec-build.lock` records the owner PID, hostname, and unique token. Concurrent full producers wait up to five minutes and then fail explicitly; every successful caller runs its own build. Only a same-host owner whose PID probe returns ESRCH is automatically recovered. Live/reused PIDs, permission failures, and foreign-host ownership never authorize reclamation. A dead owner's interrupted output is rolled back before rebuilding. A commit marker distinguishes completed builds from interrupted backup cleanup. Recovery claims serialize competing reclaimers, and lock directories retire by atomic rename before deletion. Retired `.released-*` and `.recovered-*` directories may remain after process termination; they are ignored by Git and preserve any remaining backup for inspection. Ownerless legacy locks, invalid journals, failed rollback, and interrupted recovery claims require manual recovery: first inspect live producers, preserve both current output and the lock directory outside the package, restore the previous `lock/dist` when present, and only remove the lock after establishing that no producer is using it. Never delete a live lock or infer death from age. The standalone `transpile` and `types` commands take the same lock, so a bundle-only or declaration-only writer never interleaves with a full rebuild or with each other in one package. They update `dist` in place without a backup journal, so a crashed partial writer leaves nothing to restore. Watch-mode `dev` and Turbo cache restoration are not serialized by this lock. Use one workspace build owner when consumers must read dependency output while it remains stable. ### Bun override builds Bun 1.4.2 can emit `directory mismatch` when its CLI reads a `--tsconfig-override` file ([upstream report](https://github.com/oven-sh/bun/issues/25730)). The shared builder runs builds requiring an override through `Bun.build()` in an isolated child process. A resolver marks declared external package imports and their subpaths external before workspace aliases can inline them; local aliases remain available. This also preserves boundaries on Bun versions whose JavaScript API does not honor the custom tsconfig option. The source tsconfig remains unchanged, temporary configs are cleaned after success or failure, and build diagnostics remain visible. Builds without an override continue to use the Bun CLI. This is a compatible internal fix with no consumer configuration changes. Declaration resolution honors a dependency's explicit published export map. Packages with intentional roots receive exact aliases, so inferred declaration references cannot choose an implicit wildcard pointing at unpublished private files. Existing declared wildcard maps and legacy packages without a published map retain their previous fallback resolution. On Windows, the native TypeScript artifact parser detects named-pipe readiness without opening the pipe, preserving the connection for the actual API client. Workspace dependency identities use portable repository-relative paths on every host. Neither correction changes package exports or builder commands. --- ## @lssm-tech/tool.contracts-mcp-gen Description: Generator that walks ContractSpec defineCommand/defineQuery specs and produces MCP-compatible tool schemas. Path: packages/tools/contracts-mcp-gen URL: /llms/tool.contracts-mcp-gen (No README.md) --- ## @lssm-tech/tools.contractspec-codemods Description: Codemods + import-graph scanner that mechanically migrate consumers of the rich-reference legacy surfaces (CodeBlock, DiffBlock, ObjectReferenceHandler, RichContentReference, rich-code-preferences) to the post-S-8 surface (RichBlock, RichRef, RichReference, rich-reference/preferences). Path: packages/tools/contractspec-codemods URL: /llms/tools.contractspec-codemods # `@lssm-tech/tools.contractspec-codemods` Codemods + import-graph scan that mechanically migrate consumers of the pre-S-8 rich-reference legacy surface (`CodeBlock`, `DiffBlock`, `ObjectReferenceHandler/Panel`, `RichContentReference`, `rich-code-preferences`) to the post-S-8 surface (`RichBlock`, `RichRef`, `PreviewPanel`, `RichReference`, `rich-reference/preferences`). See [`MIGRATION.md`](./MIGRATION.md) for the full migration guide, before/after examples, and human-follow-up cases. ## Quick start ```bash # Discover legacy call sites (writes discovery-list.json) bun run scripts/discover.ts --roots packages/ --out discovery-list.json # Dry-run the codemods bun run scripts/apply.ts --roots packages/ --dry # Apply the codemods in place bun run scripts/apply.ts --roots packages/ ``` ## Codemods - `codemod-code-block` — `CodeBlock` → ``. - `codemod-diff-block` — `DiffBlock` → `` (incl. `DiffBlock.web` / `DiffBlock.native` platform splits). - `codemod-object-reference` — `ObjectReferenceHandler` → `` and `ObjectReferencePanel` → ``. - `codemod-rich-content-references` — `RichContentReference` / `RichCodeBlockModel` / `RichDiffBlockModel` / `redactRichCodeBlock` / `redactRichDiffBlock` → new rich-reference + ui-kit-core equivalents. - `codemod-personalization-imports` — `rich-code-preferences` subpath → `rich-reference/preferences`. Each codemod is pure (string → string) and idempotent. Run them in the canonical `STANDARD_CODEMODS` pipeline, or call them individually. ## Safety The codemods are regex/string-based with a brace-balanced JSX attribute parser. They use a context scanner that: - skips strings, template literals, and comments (so docs-page example template strings stay intact); - newline-terminates string scanning (defends against JSX-text apostrophes such as "What you'll build" — JS strings cannot contain raw newlines per spec, so this is correct in addition to defensive); - inserts new imports after the last REAL top-level import, never inside a template literal. ## CI gate (AC-17) - Per-PR: `bun run discover` is informational; growth should be flagged. - Per-release: the migration regression test (`__tests__/migration-regression.test.ts`) asserts that every entry in `discovery-list.json` was migrated. Zero hits required to ship. ## Files ``` src/ legacy-symbols.ts # canonical migration map parse-helpers.ts # safe-span scanner + JSX tag parser codemod-runner.ts # CodemodResult + pipeline helper codemod-code-block.ts codemod-diff-block.ts codemod-object-reference.ts codemod-rich-content-references.ts codemod-personalization-imports.ts import-graph-scan.ts # AST-ish + string-literal scanner index.ts # public surface scripts/ discover.ts # writes discovery-list.json apply.ts # writes codemod output in place __tests__/ # fixture tests + migration regression ``` --- ## @lssm-tech/tool.contractspec-drizzle-gen Description: Generator that compiles ContractSpec defineDatabaseTable specs into Drizzle pgTable definitions, relations, and an RLS adapter manifest. Path: packages/tools/contractspec-drizzle-gen URL: /llms/tool.contractspec-drizzle-gen # `@lssm-tech/tool.contractspec-drizzle-gen` Deterministically compile ContractSpec physical-table declarations into typed Drizzle `pgTable` definitions and an optional tenant-RLS evidence manifest. ## Usage ```ts import { defineDatabaseTable, defineUnscopedDatabaseTable, } from "@lssm-tech/lib.contracts-spec/database"; import { generateContractSpecDrizzle } from "@lssm-tech/tool.contractspec-drizzle-gen"; const claims = defineDatabaseTable({ name: "grace_claims", columns: [ { name: "id", type: "uuid", nullable: false }, { name: "tenant_id", type: "uuid", nullable: false }, { name: "status", type: "text", nullable: false, enumValues: ["draft", "submitted"], }, ], primaryKey: ["id"], foreignKeys: [], tenantColumn: "tenant_id", }); const principals = defineUnscopedDatabaseTable({ name: "grace_business_principals", columns: [ { name: "id", type: "uuid", nullable: false }, { name: "email", type: "text", nullable: false }, ], primaryKey: ["id"], foreignKeys: [], }); const artifacts = generateContractSpecDrizzle({}, [claims, principals]); ``` `schemaSource` contains the generated Drizzle module. The RLS manifest contains only tables declared through `defineDatabaseTable`; unscoped tables never gain invented tenant authority. Commit generated schema source and compare a fresh in-memory generation byte-for-byte in CI. This tool does not replace a migration authority. Consumers may retain dbmate, Drizzle Kit, or another reviewed migration workflow while using generated Drizzle models for typed queries. --- ## @lssm-tech/tool.create-contractspec-plugin Description: CLI tool for creating ContractSpec plugins from templates Path: packages/tools/create-contractspec-plugin URL: /llms/tool.create-contractspec-plugin # @lssm-tech/tool.create-contractspec-plugin Website: https://contractspec.io **CLI tool for creating ContractSpec plugins from templates.** ## What It Provides - **Layer**: tool. - **Consumers**: plugin authors (via `create-contractspec-plugin` CLI). - 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/tool.create-contractspec-plugin` or `bun add @lssm-tech/tool.create-contractspec-plugin` ## Usage ```bash npx create-contractspec-plugin --help # or bunx create-contractspec-plugin --help ``` ## Architecture - `src/index.ts` is the root public barrel and package entrypoint. - `src/templates` is part of the package's public or composition surface. - `src/utils.ts` is part of the package's public or composition surface. ## Public Entry Points - Binary `create-contractspec-plugin` points to `./dist/index.js`. - Export `.` resolves through `./src/index.ts`. - Export `./templates/example-generator` resolves through `./src/templates/example-generator.ts`. - Export `./utils` resolves through `./src/utils.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Template files live in `templates/` -- keep them in sync with the current plugin contract. - Do not change interactive prompts without updating the corresponding template variables. - Depends on `@lssm-tech/lib.contracts-spec` and `@lssm-tech/lib.schema` -- respect their APIs. --- ## @lssm-tech/tool.docs-generator Description: CLI tool for generating docs artifacts from ContractSpec specs and DocBlocks Path: packages/tools/docs-generator URL: /llms/tool.docs-generator # @lssm-tech/tool.docs-generator Website: https://contractspec.io **CLI tool for generating docs artifacts from ContractSpec specs and DocBlocks.** ## What It Provides - **Layer**: tool. - **Consumers**: docs pipeline (`bun run docs:generate`), CI. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. - Related ContractSpec packages include `@lssm-tech/lib.contracts-spec`, `@lssm-tech/tool.bun`, `@lssm-tech/tool.typescript`. ## Installation `npm install @lssm-tech/tool.docs-generator` or `bun add @lssm-tech/tool.docs-generator` ## Usage ```bash npx contractspec-docs --help # or bunx contractspec-docs --help ``` ## Architecture - `src/fs.ts` is part of the package's public or composition surface. - `src/generate.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/markdown.test.ts` is part of the package's public or composition surface. - `src/markdown.ts` is part of the package's public or composition surface. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Binary `contractspec-docs` points to `./dist/index.js`. - Export `.` resolves through `./src/index.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 docs:generate` — bun src/index.ts generate --source "../../../generated/docs" --out "../../../packages/bundles/library/src/components/docs/generated" --content-root "../../../generated/docs" - `bun run prebuild` — contractspec-bun-build prebuild ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed. ## Notes - DocBlock IDs keep their identity and routes. Generated content paths replace dots with directory separators and colons with hyphens so namespaced IDs such as `doc:sop.generation-sources` can be checked out on Windows. - Output paths are configured via CLI flags -- do not hard-code destination directories. - Depends on `@lssm-tech/lib.contracts-spec` for spec parsing -- changes there may require updates here. - The `docs:generate` script references relative paths to `generated/docs` and the library bundle; verify paths if the monorepo structure changes. --- ## @lssm-tech/tools.eslint-plugin-i18n Description: ESLint rules enforcing i18n hygiene: no module-scope translation calls and no raw Accept-Language reads. Path: packages/tools/eslint-plugin-i18n URL: /llms/tools.eslint-plugin-i18n (No README.md) --- ## @lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields Description: ESLint rule enforcing that every defineReferenceKind() call declares an explicit sensitiveFields array (closes F-4). Path: packages/tools/eslint-plugin-no-implicit-sensitivefields URL: /llms/tools.eslint-plugin-no-implicit-sensitivefields # @lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields ESLint plugin that enforces explicit `sensitiveFields` declarations on every `defineReferenceKind()` call from `@lssm-tech/lib.contracts-spec/rich-reference`. Closes plan slice S-1b (architect NR-2 / F-4 mitigation): the contracts-spec runtime already throws when `sensitiveFields` is missing or non-array, but the runtime cannot enforce the additional repository policy that an empty array (`sensitiveFields: []`) must be accompanied by an inline confirmation comment. This rule catches both issues at lint time. ## Install ```bash bun add -d @lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields ``` `eslint` (>=8, <11) is a peer dependency. ## Flat config (ESLint 9+) ```js import noImplicitSensitiveFields from '@lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields'; export default [ { plugins: { 'no-implicit-sensitivefields': noImplicitSensitiveFields }, rules: { 'no-implicit-sensitivefields/no-implicit-sensitivefields': 'error' }, }, ]; ``` Or apply the bundled `recommended` flat config in one line: ```js import { configs } from '@lssm-tech/tools.eslint-plugin-no-implicit-sensitivefields'; export default [configs.recommended]; ``` ## What the rule does For every call expression whose callee is `defineReferenceKind` (or `.defineReferenceKind`): 1. If the object literal argument lacks a `sensitiveFields` property → reports `missing`. 2. If `sensitiveFields: []` appears without a nearby comment containing `confirmed: no sensitive fields` → reports `emptyWithoutComment`. A "nearby" comment is one whose line number is within ±1 line of the `sensitiveFields` property — covering the common authoring shapes: a leading comment, a same-line trailing comment, or an in-block comment immediately after. ### Valid ```ts defineReferenceKind({ id: 'ticket', schema, sensitiveFields: ['title'], defaultPreview: 'inline-card', defaultPanel: 'drawer', icon: 'ticket', }); defineReferenceKind({ id: 'public-doc', schema, // confirmed: no sensitive fields sensitiveFields: [], defaultPreview: 'inline-card', defaultPanel: 'drawer', icon: 'doc', }); defineReferenceKind({ id: 'public-doc-2', schema, sensitiveFields: [], // confirmed: no sensitive fields defaultPreview: 'inline-card', defaultPanel: 'drawer', icon: 'doc', }); ``` ### Invalid ```ts // Missing sensitiveFields entirely defineReferenceKind({ id: 'bad-1', schema, defaultPreview: 'inline-card', defaultPanel: 'drawer', icon: 'bad', }); // error: missing // Empty list without the confirmation marker defineReferenceKind({ id: 'bad-2', schema, sensitiveFields: [], defaultPreview: 'inline-card', defaultPanel: 'drawer', icon: 'bad', }); // error: emptyWithoutComment ``` ## Test ```bash bun test ``` --- ## @lssm-tech/tool.i18n-dead-key-pruner Description: Build-time tool that prunes unreferenced translation catalog keys using RouteShardManifest reachability and t('key') source scanning Path: packages/tools/i18n-dead-key-pruner URL: /llms/tool.i18n-dead-key-pruner (No README.md) --- ## @lssm-tech/tool.icon-gen Description: Cross-platform CLI to generate PWA / web icon sets from a source logo (favicon.ico, PNG variants, apple-touch-icon, maskable). Uses sharp + a pure-JS ICO writer — no macOS-only sips dependency. Path: packages/tools/icon-gen URL: /llms/tool.icon-gen (No README.md) --- ## @lssm-tech/lib.source-extractors Description: Extract contract candidates from TypeScript source code across multiple frameworks (NestJS, Express, Fastify, Hono, Elysia, tRPC, Next.js) Path: packages/tools/source-extractors URL: /llms/lib.source-extractors # @lssm-tech/lib.source-extractors This contributor/compiler package is owned at `packages/tools/source-extractors`. Its published package name and documented import paths remain unchanged. Website: https://contractspec.io **Extract contract candidates from TypeScript source code across multiple frameworks (NestJS, Express, Fastify, Hono, Elysia, tRPC, Next.js).** ## What It Provides - **Layer**: lib. - **Consumers**: CLI, 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.source-extractors` or `bun add @lssm-tech/lib.source-extractors` ## Usage Import the root entrypoint from `@lssm-tech/lib.source-extractors`, or choose a documented subpath when you only need one part of the package surface. ## Architecture - `src/__fixtures__` is part of the package's public or composition surface. - `src/__snapshots__` is part of the package's public or composition surface. - `src/codegen` is part of the package's public or composition surface. - `src/codegen.test.ts` is part of the package's public or composition surface. - `src/detect.test.ts` is part of the package's public or composition surface. - `src/detect.ts` is part of the package's public or composition surface. - `src/edge-cases.test.ts` is part of the package's public or composition surface. - `src/index.ts` is the root public barrel and package entrypoint. - `src/types.ts` is shared public type definitions. ## Public Entry Points - Export `.` resolves through `./src/index.ts`. - Export `./codegen` resolves through `./src/codegen/index.ts`. - Export `./extractors` resolves through `./src/extractors/index.ts`. - Export `./types` resolves through `./src/types.ts`. ## Local Commands - `bun run dev` — contractspec-bun-build dev - `bun run build` — contractspec-bun-build build - `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 - Replace eslint+prettier by biomejs to optimize speed. ## Notes - Extractor interface must support multiple frameworks — keep it generic. - Codegen output must stay deterministic (same input → same output, always). ### Internal source ownership Detection rules, input strategies and project discovery have private source owners. IR metadata, candidate shapes and extraction results remain available through the existing type barrel. No package identity, public entrypoint or output changes. Original focused test paths aggregate the same suites after cohesive splitting. --- ## @lssm-tech/tool.test-redaction-rules Description: Credential-pattern regex corpus for CI telemetry redaction sweeps (T.3). Path: packages/tools/test-redaction-rules URL: /llms/tool.test-redaction-rules (No README.md) --- ## @lssm-tech/lib.testing-helpers Description: Shared test infrastructure helpers for Phase 1 / Phase 3 cockpit-kit extraction Path: packages/tools/testing-helpers URL: /llms/lib.testing-helpers (No README.md) --- ## @lssm-tech/tool.tsdown Description: Shared tsdown config presets for LSSM monorepo Path: packages/tools/tsdown URL: /llms/tool.tsdown # @lssm-tech/tool.tsdown Website: https://contractspec.io **Shared tsdown configuration presets for the ContractSpec monorepo. Packages that use tsdown for bundling import this preset to keep build config consistent.** ## What It Provides - **Layer**: tool - **Consumers**: packages using tsdown (typically libs with `tsdown.config.js`) ## Installation `npm install @lssm-tech/tool.tsdown` or `bun add @lssm-tech/tool.tsdown` ## Usage Import the root entrypoint from `@lssm-tech/tool.tsdown`, or use one of the documented subpaths when you want a narrower surface area. ## Public Entry Points - `.` — `./index.js` ## Local Commands - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - PublishConfig not supported by bun - Add examples of integration ## Notes - Changes affect every tsdown consumer's build output -- test downstream packages before merging - Peer-depends on `tsdown ^0.21` -- keep in sync with the workspace catalog version - Keep the preset minimal; package-specific overrides belong in each consumer's `tsdown.config.js` --- ## @lssm-tech/tool.typescript Description: Pinned TypeScript tooling and shared compiler configuration for ContractSpec packages. Path: packages/tools/typescript URL: /llms/tool.typescript # @lssm-tech/tool.typescript Website: https://contractspec.io **Shared TypeScript configuration presets (base, nextjs, react-library) extended by every package's `tsconfig.json` in the monorepo.** ## What It Provides - **Layer**: tool - **Consumers**: all monorepo packages (via `"extends": "@lssm-tech/tool.typescript/..."`) ## Installation `npm install @lssm-tech/tool.typescript` or `bun add @lssm-tech/tool.typescript` ## Local Commands - `bun run build` — validate every published shared config as a hashable Turbo dependency task - `bun run typecheck` — run the same deterministic config validation - `bun run publish:pkg` — bun publish --tolerate-republish --ignore-scripts --verbose - `bun run publish:pkg:canary` — bun publish:pkg --tag canary ## Recent Updates - Replace eslint+prettier by biomejs to optimize speed - PublishConfig not supported by bun - Migrate non-app builds to shared Bun toolchain ## TypeScript 7 The monorepo uses the stable TypeScript 7 compiler for apps, packages, declaration emit, and repository tooling. Run the broad non-app compiler check from the repository root: ```sh bun run typecheck:typescript:not-apps ``` This command scans `packages/libs`, `packages/modules`, and `packages/bundles`, uses each package's existing typecheck project (`tsconfig.build.json` when the package script selects it), and intentionally skips `packages/apps`. Use `bun run typecheck:typescript:not-apps:sample` for a fast representative smoke check. `contractspec-bun-build types` emits declarations with the stable TypeScript 7 `tsc` binary. TypeScript 7.0's programmatic API is explicitly unstable. Repository code that needs AST or project access must use an owned adapter boundary rather than importing the removed legacy `typescript` compiler API. ## Notes - Compiler option changes propagate to every package -- verify with `bun run typecheck` across the repo - Do not weaken strict-mode settings (`strict`, `noUncheckedIndexedAccess`, etc.) - Adding a new preset file requires documenting which packages should use it --- ## @lssm-tech/lib.typescript-runtime Description: Owned TypeScript compiler API boundary for ContractSpec tooling Path: packages/tools/typescript-runtime URL: /llms/lib.typescript-runtime # @lssm-tech/lib.typescript-runtime Owned runtime boundary for TypeScript compiler and AST access. Consumers import AST helpers and source parsing from this package so TypeScript upgrades have one repair point. The adapter isolates TypeScript 7's unstable AST and asynchronous compiler APIs while preserving a stable asynchronous parser contract for callers. ```ts import { TypeScriptSourceParser, isVariableStatement, } from "@lssm-tech/lib.typescript-runtime"; ``` Call `close()` on long-lived parsers after use. The explicit server-only `@lssm-tech/lib.typescript-runtime/docs-manifest-builder` entry owns compiler-backed same-file DocBlock extraction and package manifest generation. It exports `extractModuleDocData` and `buildPackageDocManifest` with their existing asynchronous signatures and is the canonical import path. The deprecated `@lssm-tech/lib.contracts-spec/docs/manifest-builder` subpath forwards the same function identities until the next major release of `@lssm-tech/lib.contracts-spec` removes it; new code imports this entry. This entry rejects browser resolution and is not reexported by the root AST adapter. Manifest and DocBlock types remain owned by surface-runtime and contracts-spec-core, respectively. `buildPackageDocManifest({ followReexports: true, ... })` additionally follows static value reexports to canonical same-file DocBlocks. The option is additive and defaults to `false`; existing callers keep their source-root-only behavior. The compatibility package's `docs:manifest` producer imports this entry directly and enables it so moving a contract into its canonical owner does not remove its documentation. Traversal does not execute source modules or scan private sibling files. Named aliases, cycles, and explicit export precedence are respected; ambiguous documentation bindings, duplicate identifiers/routes, and missing references fail validation. DocBlock identifiers and payloads are preserved, while `sourceModule` identifies the canonical package and source file for documentation outside the input root. Each parser owns an isolated temporary workspace and native TypeScript session. On Windows, the adapter uses the compiler client's supported stdio transport; other platforms retain Unix sockets. This avoids Windows named-pipe readiness and naming races without changing the asynchronous parser API or snapshot semantics. The matching native TypeScript executable must be installed. The root build targets Node-compatible server execution (including Bun). It requires filesystem, process, or native compiler facilities and does not advertise a browser export condition. Browser applications should use the relevant browser-safe contracts or UI entry points instead of importing this server root. --- ## @lssm-tech/integration.agent-durable-store Description: Durable SQLite and Postgres session and checkpoint stores for @lssm-tech/lib.ai-agent Path: packages/integrations/agent-durable-store URL: /llms/integration.agent-durable-store # @lssm-tech/integration.agent-durable-store Durable implementations of `@lssm-tech/lib.ai-agent`'s `AgentSessionStore` and `AgentCheckpointPort`. Choose embedded SQLite for a single durable worker or a provider-neutral Postgres adapter for horizontally scaled runtimes. ## SQLite ```ts import { createSqliteAgentCheckpointStore, createSqliteAgentSessionStore, } from "@lssm-tech/integration.agent-durable-store"; const sessions = createSqliteAgentSessionStore({ file: "./agent.db" }); const checkpoints = createSqliteAgentCheckpointStore({ file: "./agent.db" }); ``` Both factories accept the same `file` and can share one database file. Pass `createSqliteAgentSessionStore({ file })` wherever `new InMemorySessionStore()` is currently constructed. Each SQLite store also exposes `close()` (typed `SqliteDurableStoreLifecycle`), which releases its database handle. Close every store opened on a file before deleting it: Windows refuses to remove a database that still has an open handle (`EBUSY`/`EPERM`). `close()` is idempotent; using a closed store throws. ## Durability The database opens in WAL journal mode with `synchronous = NORMAL`, so a committed write is recoverable after a hard process kill. A fresh process pointed at the same file recovers the last committed session and checkpoint — see `src/sqlite/process-death.test.ts` (agent runtime conformance case 5). ## Effect-replay safety `AgentCheckpointEnvelope.effectResults` (keyed by `${nonce}:${stepInstanceId}`) is persisted verbatim, so approval-gated side-effecting steps replay their recorded result on resume instead of re-firing. The dedup/replay logic lives in `@lssm-tech/integration.workflow-devkit`; this package only persists the field. ## Postgres The Postgres adapter accepts the repository's `DatabaseProvider` port, so the same store works with Supabase Postgres, self-hosted Postgres, Railway Postgres, or another compatible provider. ```ts import { SupabasePostgresProvider } from "@lssm-tech/integration.provider-supabase"; import { createPostgresAgentCheckpointStore, createPostgresAgentSessionStore, migratePostgresAgentDurableStore, } from "@lssm-tech/integration.agent-durable-store/postgres"; const database = new SupabasePostgresProvider({ connectionString: process.env.SUPABASE_DATABASE_URL, }); await migratePostgresAgentDurableStore(database); const sessions = createPostgresAgentSessionStore({ database, tenantId: "tenant-123", }); const checkpoints = createPostgresAgentCheckpointStore({ database, tenantId: "tenant-123", }); ``` Each store instance is bound to one non-empty tenant identifier. Every query includes that scope, persisted payloads are checked against it, session writes use optimistic revisions, and message/step histories are bounded. The adapter does not make deployment-specific security promises: the host remains responsible for credentials, TLS, database roles and RLS, backups, retention, regional placement, and tested RPO/RTO. The same Postgres entrypoint also exposes durable stores for multiplayer collaboration sessions/events, governed improvement work orders, and tamper-evident audit events. Audit records form a per-tenant hash chain and support head verification; every adapter remains tenant-bound and uses optimistic concurrency where the domain contract requires it. ```ts import { createPostgresAgentAuditStore, createPostgresCollaborationStore, createPostgresImprovementWorkOrderStore, createPostgresImprovementWorkOrderStoreV2, } from "@lssm-tech/integration.agent-durable-store/postgres"; const collaboration = createPostgresCollaborationStore({ database, tenantId: "tenant-123", }); const improvement = createPostgresImprovementWorkOrderStore({ database, tenantId: "tenant-123", }); const adaptiveImprovement = createPostgresImprovementWorkOrderStoreV2({ database, tenantId: "tenant-123", }); const audit = createPostgresAgentAuditStore({ database, tenantId: "tenant-123", }); ``` Call the migration through a serialized deployment step before serving traffic. Use a shared external Postgres service for multiple workers; do not place the SQLite file on an ephemeral or multi-writer filesystem. The V2 improvement store uses the same table with an explicit contract-version discriminator. V1 and V2 queries are isolated, CAS remains revision-bound, and due `observing` work survives process restarts without duplicate scheduling. ## Governed self-improvement lifecycle `migratePostgresSelfImprovementStore` creates tenant/workspace-scoped program, candidate, signal, and append-only lifecycle tables. By default, the migration applies and forces database-enforced tenant and workspace policies for least-privilege runtime roles. Every repository transaction establishes both claims locally before querying. `createPostgresSelfImprovementStores` returns typed program, candidate, and signal ports. Candidate transitions are fenced by their previous status, state digest, and timestamp, so duplicate identifiers and stale, reordered, invalid, non-monotonic, or tampered receipts are rejected transactionally. The candidate store also implements `SelfImprovementLifecycleStorePortV1`. Call `state(id)` to obtain the fenced status, digest, sequence, and immutable initial state, and `receipts(id)` to load the ordered append-only chain for exact replay. These reads remain tenant/workspace scoped and do not grant execution authority. The returned program, candidate, and signal stores also implement the additive query ports. Lists are deterministic, tenant/workspace scoped, and bounded to 500 records per request. Candidate list results overlay the current fenced status on the immutable candidate document; they do not rewrite its canonical fingerprint or lifecycle receipts. ## Protocol artifact persistence `migratePostgresAgentProtocolArtifactStore` creates tenant-, space-, product-, application-, purpose-, session-, run-, kind-, and artifact-scoped head and append-only revision tables. `createPostgresAgentProtocolArtifactStore` stores context manifests, model capability profiles, routes, qualifications, evaluation decisions, canary states, selections, fallback decisions, execution plans, plan validations, run budgets, bounded epochs, checkpoints, progress, reflections, help requests, help responses, context projections, task graphs, delegations, task results, team syntheses, immutable Agent Host application bindings, terminal decisions, protocol run state, memory proposals, owner decisions, mutation receipts, projections, projection revocations, automation definitions, previews, materializations, lifecycle transitions, claims, run receipts, and follow-ups without gaining execution authority. Every write binds the contract identity digest to the payload, computes an independent canonical payload digest, rejects raw credential fields and common credential values, and uses optimistic revisions. Context manifests, routes, selections, evaluation decisions, and fallback decisions are immutable and idempotent. Model qualification and canary records evolve only through append-only CAS revisions. Epoch and run-state records also evolve through append-only CAS. Automation lifecycle state is the only mutable automation artifact and also evolves through append-only CAS; its definitions, previews, materializations, transitions, claims, receipts, and follow-ups are immutable. Every other execution artifact is immutable. Reads revalidate both digests before returning data. Protocol state binds the exact historical epoch revision and digest, so a crash after an epoch write but before the state commit can retry idempotently without accepting substituted work. The migration enables and forces RLS by default and scopes policies to transaction-local tenant and space settings. The runtime still includes exact scope predicates on every query. For Supabase, keep these tables server-side, do not grant browser roles access, and pass only opaque `secretRef` values—never database URLs, provider keys, access tokens, or refresh tokens. ## Founder-operations stores `migratePostgresFounderOpsStore` (migration `founder-ops-v1`) creates three tenant-scoped tables: `agent_supervised_coding_sessions`, `agent_proactive_proposals` and `agent_workflow_improvement_briefs`. Table names and the schema are configurable, and the usual role grants and tenant RLS options apply. Run it as a serialized deployment step after the existing agent migrations. The tables do not depend on earlier agent tables. The stores are structurally typed. The owning module supplies a codec that validates every payload read back, so this integration never imports a product module: ```ts import { createPostgresProactiveProposalLedger, createPostgresSupervisedCodingSessionStore, createPostgresWorkflowImprovementBriefStore, migratePostgresFounderOpsStore, } from "@lssm-tech/integration.agent-durable-store/postgres"; import { proactiveLedgerRecordCodecV1, supervisedCodingSessionCodecV1, workflowImprovementBriefCodecV1, } from "@lssm-tech/module.agent-fleet/core"; await migratePostgresFounderOpsStore(database); const sessions = createPostgresSupervisedCodingSessionStore({ database, tenantId, codec: supervisedCodingSessionCodecV1, }); ``` Session and ledger `compareAndSet` calls require `next.revision` to be exactly `expectedRevision + 1` and update only when the stored revision matches. This means concurrent supervisors apply a coding-wait answer exactly once. Briefs keep the first write, so a frozen success criterion cannot be replaced. --- ## @lssm-tech/integration.agent-sandbox Description: Deny-by-default Docker and development sandbox adapters for @lssm-tech/lib.ai-agent Path: packages/integrations/agent-sandbox URL: /llms/integration.agent-sandbox # @lssm-tech/integration.agent-sandbox Production Docker and development-fixture implementations of `@lssm-tech/lib.ai-agent` sandbox ports. ## Scope - `DockerAgentSandbox` creates one OS-contained container per workspace with a read-only root, private tmpfs workspace, dropped capabilities, `no-new-privileges`, non-root execution, and explicit memory/PID/output/time limits. - Docker networking is deny-all by default. Each allowlisted TCP target is DNS-pinned before attachment and exposed through a dedicated restricted sidecar on an internal-only network, preventing direct DNS/IP bypass. - Commands, read/write roots, network targets, and secrets are deny-by-default. Secrets are resolved by reference for one command, redacted from output, and rejected from reads or artifact extraction if a command persisted them. - Extracts immutable artifacts through `@lssm-tech/lib.files`. - `LocalDevelopmentSandbox` remains an honest policy/redaction fixture and rejects isolation, egress, and quota claims it cannot prove. ## Containment conformance `bun test src/docker-agent-sandbox.test.ts` runs the adapter in an external fixture against a live Docker daemon. It covers command denial, traversal and symlink attacks, DNS/IP egress bypass, positive network allowlisting, child-process fanout, memory/CPU/output limits, cancellation, teardown, secret scrubbing, and artifact integrity. UDP allowlisting is rejected rather than silently weakened. Docker teardown now verifies container and network absence through inventory. A failed removal acknowledgement is recoverable only when absence is confirmed. Unconfirmed teardown throws and retains the workspace handle for retry. This is removal verification, not durable restart discovery or executor fencing. Docker CLI operations default to a five-minute deadline. Sandbox commands use the policy timeout plus 30 seconds for transport. Deadline and input failures kill the CLI client and report an unknown external outcome; they neither retry the command nor prove the daemon-side process stopped. Reconcile the workspace before resuming effects. Network and proxy names are tracked before allocation so lost creation acknowledgements retain cleanup targets. Container creation failures also enter cleanup. This process-local tracking does not yet provide restart discovery. Containment conformance fails on teardown errors instead of suppressing them. --- ## @lssm-tech/integration.app-store-connect Description: Read-first App Store Connect API integration for ReviewReady app submission readiness, with deterministic mocks and secret-ref-only credentials. Path: packages/integrations/app-store-connect URL: /llms/integration.app-store-connect # @lssm-tech/integration.app-store-connect Read-first App Store Connect integration for ReviewReady app submission readiness. It maps supported metadata reads to the ContractSpec provider capability registry and returns typed capability results for everything the official API does not safely expose. ## Safety policy - **Read-first / write-disabled.** The port exposes no write/update operations. Provider writes are out of scope for this package. - **Mock-by-default.** Tests and CI use `createMockAppStoreConnectClient`, which performs no network access and is fully deterministic (injected clock + ids). - **Live calls are opt-in.** `createAppStoreConnectClient` only attempts live access when `enableLiveCalls` is true, secret-ref auth is present, and a secret resolver is supplied. Otherwise reads return typed `degraded` results. - **No faked data.** Fields the API cannot supply (e.g. App Privacy answers) return a typed `manual-required` / `unsupported` / `degraded` capability result, never a silent success. ## Secret handling Auth config carries **secret references only** (`privateKeySecretRefId`). Raw `.p8` private keys, JWTs, and headers are never accepted as config fields, and never appear in snapshots, logs, or fixtures. Log entries record only `provider`, `operation`, `status`, `correlationId`, and `capabilityId`. ## Usage ```ts import { createMockAppStoreConnectClient } from "@lssm-tech/integration.app-store-connect"; const client = createMockAppStoreConnectClient({ now: "2026-06-07T12:00:00.000Z", correlationId: "corr-001", }); const metadata = await client.getAppMetadata({ appId: "1234567890" }); const privacy = await client.getAppPrivacyAnswers({ appId: "1234567890" }); // privacy.status === "manual-required" ``` Source: https://developer.apple.com/documentation/appstoreconnectapi/ --- ## @lssm-tech/integration.authos-better-auth Description: Better Auth bridge that maps AuthOS contracts to provider configuration, plugins, and redacted events. Path: packages/integrations/authos-better-auth URL: /llms/integration.authos-better-auth # `@lssm-tech/integration.authos-better-auth` Better Auth bridge for AuthOS Broad V0. The web bridge preserves legacy `signIn.oauth2({ providerId })` and `oauth2.link({ providerId })` callers through Better Auth 1.7's supported `signIn.social`/`linkSocial` endpoints. It no longer imports the removed `genericOAuthClient`. Provider callback registration/schema migration remains a separate host rollout requirement. This package turns AuthOS contracts into Better Auth configuration and maps Better Auth-like user/session/events back to AuthOS contracts. Canonical models stay in `@lssm-tech/lib.authos-spec`; pure projections and security gates stay in `@lssm-tech/lib.authos-runtime`. `advanced.cookiePrefix` passes the host-selected namespace to Better Auth. Preview hosts can combine a distinct prefix with secure cookies and disabled cross-subdomain cookies. This separates cookie names and host scope; data/secret isolation must still be provisioned and verified independently. ## Maturity - Core email/password, magic link, email OTP, organization/team, admin, OAuth/OIDC client, MFA, and WebAuthn passkeys are runtime-backed through Better Auth (passkeys live-verified on Managed CompanyOS 2026-08-14). - The bridge can also wire the `phoneNumber` and `oneTap` plugins, but no LSSM deployment enables them or has live-verified them: Managed CompanyOS does not list them in `companyOsEnabledPlugins`, and the generic `authOsV0Fixture` marks phone OTP/verification and one-tap `fixture-backed`. Phone OTP also needs a host `sendPhoneOtp` delivery callback. - Connect with LSSM / LSSM-as-IdP (`@better-auth/oauth-provider`) stays `contract-only` for Managed CompanyOS until `enableLssmIdp` and a security review reference are configured. - Built-in social login is typed for Apple, Discord, Facebook, GitHub, Railway, Google, Linear, LinkedIn, Microsoft, Notion, PayPal, Reddit, Slack, TikTok, Twitter/X (`twitter`), and Vercel. Hosts may retain `genericOAuth` for additional providers. - Generic OIDC hosts can opt into `profileNameFallback: "email"` for legacy identities without a display name. The bridge reuses the provider email verbatim and never infers a human name. - Invite-only hosts set `disableSignUp`; verified-email providers may resolve an existing verified identity, while TikTok and missing-email LinkedIn/Facebook identities require an explicit authenticated account link. - Passkeys use the matching `@better-auth/passkey` server and browser plugins. Hosts must apply the provider's `passkey` table migration before enabling enrollment. - SSO and SCIM remain declared external plugin capabilities until their production package wiring is separately reviewed. - LSSM-as-IdP uses the supported `@better-auth/oauth-provider` OAuth 2.1/OIDC runtime, with dynamic registration disabled, PKCE/S256 provider defaults, pairwise subject derivation, asymmetric JWT/JWKS support, explicit login/consent routes, and resource audiences. It remains contract-only unless `securityReviewRef` and a server-only pairwise secret are present and production enablement is explicitly gated. - IdP hosts may supply a product-access policy. Without one, post-login always redirects to the configured access boundary. Reviewed hosts can publish explicit product scopes, bind consent to an entitlement reference, and emit only coarse application/tier/entitlement claims after the host confirms active access. - Product membership handoffs expose a bounded, bearer-authenticated internal handler. It accepts only an RP-specific pairwise subject and idempotent provisioning scope; canonical identity IDs, local role authority, and secret material are excluded from its contracts and replay evidence. - `./relying-party-reconciliation` prepares the exact catalog-owned Better Auth OAuth client record for an operator-controlled host reconciliation. It hashes the confidential client secret with the provider's SHA-256/base64url format, keeps dynamic registration disabled, and exposes only a secret-free configuration digest and evidence reference. ## Optional central identity plugins The pinned runtime is Better Auth 1.7.14, with matching OAuth-provider, passkey, SSO, API-key and i18n packages; Agent Auth is pinned independently to 0.6.2. Add `i18n`, `api-key`, `agent-auth`, or `multi-session` to `enabledPlugins` to request a plugin. The default plugin list and CompanyOS deployment list do not activate these new capabilities automatically. - `i18n` defaults to EN/FR/ES with `NEXT_LOCALE` cookie then `Accept-Language`. Authentication delivery callbacks receive the negotiated `locale` separately from secret challenge material. Hosts own localized emails and branding. - `apiKey` accepts the official options and requires `authorizePluginRequest`. Existing CompanyOS `cos_pk_` credentials retain their separate verifier. - `agentAuth` requires capability validation, execution and host authorization callbacks. Hosts must qualify durable replay protection and Connect checks before enabling it across server instances. Package installation alone does not qualify delegated or autonomous execution. - `multiSession` requires host authorization so switching a stored session cannot bypass assurance or carry the previous identity's authority. - `authorizePluginRequest` runs before protected official plugin endpoints, including server API calls. `disabledPluginPaths` closes HTTP paths while retaining guarded server APIs. Hosts must distinguish global operators, organization permissions and user-owned grants. Apple providers can supply `resolveClientSecret` for short-lived signed client assertions. Central hosts use `allowMissingEmail: false` and `accountLinking.disableImplicitLinking: true`; a missing email must be completed through verified registration rather than a fabricated address. Existing product fallbacks remain available for compatibility. `enforcePasswordlessMfa: true` extends enrolled TOTP enforcement to email OTP, magic links, passkey authentication and multi-session activation/removal. Supply `twoFactorChallengePage` on the same host as the post-login continuation. These options require actual host routes, database models and consumer qualification. ## Referral and affiliate handoff `attribution` configuration composes with an existing Better Auth `databaseHooks.user.create.after` hook. When a host resolves a valid signed acquisition token, the bridge calls `onIdentityCreated` after email/password or OAuth identity creation. The callback receives the opaque token and classified flow; the bridge does not persist, decode, or emit the token. ## Native bearer sessions `./native-session-client` exposes a storage-port-driven Better Auth client for Expo, Tauri, and other trusted native shells. Email/password and TOTP flows capture `set-auth-token` and the bounded `set-mfa-authority` projection, while the host-supplied vault keeps both values device-only. Credentials are sent only in JSON request bodies to the configured AuthOS origin and never enter URLs, logs, events, or replay evidence. ## Entry points: server and client - `./server` is the server-only surface: `createBetterAuthInstance`, `buildBetterAuthOptions`, database hooks, OAuth provider discovery, resource-token policy and the development registration helpers. Its source file uses the `.server.ts` suffix, so the package boundary check fails any client (`'use client'` / `.client.ts`) graph that reaches it. - `./client` (`createAuthClient`, `createBetterAuthBridgeClient`) and `./native-session-client` are the browser and native clients; `./bridge-plan` and `./edge-cookie` are pure and safe in any runtime. - The root entry stays a compatibility barrel that re-exports `./server` plus both clients. Server hosts may keep importing it; client code must use the explicit client entries. ## Verification ```bash bun run lint:check bun run typecheck bun run test bun run build ``` ## Schema check rehearsal `./server` exports two read-only helpers for operator rehearsals. `runBetterAuthSchemaCheck(await auth.$context)` returns `clean`, `unregistered` (an adapter wrapper dropped the check) or `mismatch` with Better Auth's findings. With the Drizzle adapter that check compares only the Drizzle schema object, never the database, so `findBetterAuthStoreSchemaProblems(options, tables)` runs Better Auth's own diff against tables introspected from the live store (in the adapter's logical names). The CompanyOS API uses both in `scripts/better-auth-schema-rehearsal.ts`. ## Pure bridge-plan inspection Use `@lssm-tech/integration.authos-better-auth/bridge-plan` for browser/native inspection of provider plugin plans. It retains `buildBetterAuthBridgePlan` behavior without importing Better Auth server initialization, database adapters or Next.js cookie integration. The existing root/config exports remain compatible for server consumers. Native preview imports must use this pure entry point; a build-boundary test guards against server code re-entering the graph. ## Better Auth 1.7 client compatibility The shared bridge no longer imports the removed `genericOAuthClient` plugin. Existing `signIn.oauth2({ providerId, ...options })` and `oauth2.link({ providerId, ...options })` bridge calls are retained as adapters to Better Auth's supported `signIn.social` and `linkSocial` methods. They translate `providerId` to `provider`, preserve request options and return provider errors. Other dynamic client methods retain their original behavior. This client repair does not migrate provider registrations, callback forwarding routes, native clients built directly on Better Auth, or account identity data. Review those separately using the [Better Auth 1.7 upgrade guide](https://better-auth.com/docs/guides/1-7-upgrade-guide) before qualifying live OAuth. No production identity records were changed. ### Server-side bearer session reads `createBetterAuthBearerSessionReader` resolves a bearer through the configured AuthOS `/api/auth/get-session?disableCookieCache=true` endpoint and maps it to the canonical `AuthOsSession`. It requires HTTPS except loopback development, forbids redirects, bounds time/body size, and rejects expired, banned or mismatched user sessions. Tokens, email and role strings are not returned. This is authentication only: callers must separately resolve current tenant-scoped permissions and must not infer fleet-management access from the identity or provider role. ## Verified social registration and assurance `centralIdentityAuthOsSpec`, `centralIdentityAuthOsCapabilities` and `centralIdentityEnabledPlugins` describe the central LSSM ID implementation independently of CompanyOS. `createCentralIdentityAuthOsSpec` projects the actual host signup-admission flag. All sixteen native providers support proven-subject resolution and verified registration; deployment credentials, approvals and real OAuth canaries determine which providers can be advertised. `runtime-backed` describes local implementation, never production qualification. The declaration contains no users, sessions, product access or production approval. Central SMS and product SSO provisioning remain disabled; CompanyOS declarations are unchanged. Native PayPal references accept `environment: 'live' | 'sandbox'` and default to live, with `openid profile email` login scopes unless the host supplies its reviewed scope list. Sandbox must be selected explicitly. These scopes provide identity, name and email attributes according to [PayPal's scope reference](https://developer.paypal.com/log-in/references). The pinned SDK ignores its PayPal `scope` option, so the bridge uses the supported authorization-endpoint override with that same host-owned scope query. The native SDK still constructs state, PKCE and the callback and performs the token exchange. Live Log in with PayPal still requires [PayPal app review](https://developer.paypal.com/log-in/build#app-review); the native configuration and a successful authorization start do not prove approval. Central hosts can supply `missingEmailRegistration` to capture a native provider's proven subject after Better Auth consumes browser-bound OAuth state and verifies the code, PKCE and profile. The host persists a token-free pending registration and verifies the person's local email. Existing linked subjects resolve only through the exact provider/account owner; this never merges users by email or creates placeholder addresses. Explicit links with missing, unverified or different provider email use the same host proof boundary. `requireSocialEmailVerification: true` separately requires a verified email for native social sign-in. Better Auth sends the host's verification email when a provider returns an unverified address and withholds the session until it is verified. Credential `requireEmailVerification` does not enable this OAuth policy. Existing hosts retain their previous behavior when the social option is omitted; central hosts also set `allowMissingEmail: false` and disable implicit account linking. Native OAuth client and resource management is denied by default, including client creation, metadata updates, deletion, credential rotation and resource links. The host's reviewed application registry owns these operations. Disabling dynamic registration alone does not close the SDK's other management routes. An admitted resource-token policy retains its explicit client/resource privilege callbacks and native management behavior. Hosts can supply Better Auth's `logger` option to route authentication diagnostics through their structured logger. The host must redact provider errors and database parameters before logging; these can contain personal data or credential hashes. The optional `onAPIError` setting also passes through, allowing a host to rethrow unexpected SDK failures into its redacting HTTP boundary. `advanced.backgroundTasks.handler` passes through to the SDK so a host can track background writes in a request-scoped authority fence and drain them before its lock is released. Omitting the handler retains the SDK's background-task behavior. `twoFactor` passes the official plugin options through. Central hosts can opt into `allowPasswordless: true` for OTP, magic-link and social identities. They must guard initial enrollment with fresh verified primary-session proof and protect disable and reenrollment with fresh completed MFA; the option itself grants no host authority. Accounts with a credential password still prove their real password. `guardCredentialManagement: true` routes native MFA, passkey registration/removal, social account linking/unlinking and password management through `authorizePluginRequest` as `credential-management` before SDK effects. It also guards the pathless server-only `setPassword` and `viewBackupCodes` operations. Challenge verification, authentication and email reset flows keep their ordinary proof handling. This opt-in requires a host callback; product defaults are unchanged. The same classification covers `/get-access-token` and `/refresh-token`. Central hosts deny these exports even for the account owner, so login-provider tokens cannot substitute for separately consented platform connections. SDK-internal login refresh and the connection broker retain their own lifecycle paths. Generic OIDC references with an expected `issuer` are bound to that exact issuer after discovery and every retry. `requireIssuerValidation` requires the callback issuer; `requireIdTokenVerification` also requires the signed ID token and its state-bound nonce before userinfo is trusted. Strict confidential web consumers complete the state/PKCE flow and cannot substitute browser-submitted ID tokens or fall back to access-token-only userinfo. Cryptographic checks remain SDK-owned. For these strict references, userinfo's raw `sub` must match the cryptographically verified token subject exactly. Strict account keys use that subject even when discovery omits the native SDK's OIDC-detection hint. Verified subjects are invocation-local, and host claim-policy callbacks remain effective without being allowed to replace the captured signed subject. Native Apple is verified before pending registration: the SDK-generated nonce is sent to Apple and checked with the official signature/issuer/audience verifier. When a host supplies `resolveClientSecret`, every token exchange and refresh gets a newly resolved assertion; the SDK's startup options cache cannot strand a warm process with an expired short-lived Apple assertion. Native Linear uses the SDK's authorization and token helpers with its original state-bound verifier in both directions. This repairs the pinned native provider's missing PKCE parameters while keeping its profile, immutable subject and refresh behavior. The compatibility wrapper runs before verified pending registration. Central hosts set `enforceSocialAuthorizationCodeFlow: true` to reject requested scope additions and direct ID-token inputs at native login/link endpoints, including server API calls. Empty or omitted scopes keep the ordinary SDK code flow and host-reviewed provider defaults. Other hosts keep their existing policy when this opt-in is omitted; delegated platform scopes belong to the connection broker. With `minimalSocialLoginScopes: true`, native Google login also sends no `include_granted_scopes`, so earlier incremental grants for that client are never folded into the login token. Google requests `openid email profile` with S256 PKCE; LinkedIn (Sign In with LinkedIn using OpenID Connect) requests `openid profile email`, reads `https://api.linkedin.com/v2/userinfo` and relies on the confidential client secret plus browser-bound state, as the pinned SDK sends no PKCE challenge to LinkedIn. `POST /api/auth/authos/registration/complete` consumes the host's verified proof and invokes the official OAuth provisioning helper inside one adapter transaction. The host's `complete` callback must use `getCurrentAdapter` for its pending-row compare-and-set and return `selectedIdentityId` only after fresh browser/session proof. Production refuses adapters without real transaction support. Cookies are written after commit, and enrolled MFA still challenges before sign-in. `autoSignInAfterVerification` is opt-in and its verification session also passes the passwordless MFA gate. `onSessionAssuranceVerified` receives only final successful TOTP, recovery-code or passkey sessions. Hosts can persist this proof for account switching. Authenticated TOTP and recovery step-up refresh proof for the exact current session, after matching the official verifier's returned token and user. Failed factors never refresh it. `agentAssertionStorage` supplies the Agent Auth plugin's replay cache without moving browser sessions into secondary storage. Host plugin authority runs after official assertion verification and before execution. ## Proposed reviewed development resource authority Both development registration recipes require the same canonical reviewed-profile verifier as the optional resource-token factory. Missing/non-function verification or any result other than literal true rejects before store, provider, resource-link or secret-manager calls. Actual canonical registry, admin/lifecycle serialization and resumable cleanup adapters remain required and unqualified. PROPOSED_NOT_ADMITTED private development resource authority: optional canonical AuthOS resource JWT/workload profiles; exact <=300-second TTL and registered resource/claim validation; durable scoped OSINT receipts preserve SAME active decisionRef and terminal expiry/revocation. Existing defaults and production RP catalog remain unchanged. Real adoption, security review, TLS/registration, canonical lifecycle/obligation/evidence adapters, migration admission and runtime qualification are required before enablement. Product entitlement is not an OSINT effect grant. No issuer, key, token, grant or database has been created or verified by this source preparation. The proposed development composition adds a current canonical reviewed-profile registry verifier and serialized workload registration journal recipe. The recipe resumes persisted safe phases, verifies actual native client/resource configuration and quarantines orphan clients. It requires a genuine privileged provider/store adapter, secret manager, serialized durable journal and atomic canonical registration completion. These source helpers do not approve a security review, create trust or enable the issuer. Adoption and runtime admission remain required. Pure binding checks for host adapters ship through `./server` (and the root barrel), still PROPOSED_NOT_ADMITTED and side-effect free: `assertNativeAccessTokenClaimsBindingV1`/`nativeIssuanceNotBeforeV1` (single lane resource, scope subset, unchanged identity, exact workload metadata, one safe DB clock row); the `dev-registration-binding` checks behind `SerializedDevRegistrationAdminV1` (client_credentials-only creation, resource and lookup binding, the 4096-client inventory bound, exact native client and current reviewed resource/link); and `admitApprovedDevSecurityReviewV1` with the database-system and installer-window assertions (canonical JSON that rejects rather than omits non-JSON content, approved SHA-256 and profile digest binding). Hosts keep the SQL, locks, roles and DB clock reads. The app custody adapter can complete a fresh registration after checking immutable GCP-version bytes against the genuine one-time native client secret. Persisted resume currently quarantines: a nonempty version alone cannot prove the native credential still matches. A genuine provider verification context is required before enabling recovery. Native policy/key callbacks commit their read transactions before issuance completes, so actual issuance/revocation concurrency remains an explicit qualification requirement. ## Proposed local disposable custody Local disposable custody successor: an additive V2 whole-review arm admits only the genuine Windows DPAPI CurrentUser provider, exact owner SID/owner-only ACL, local namespace/root and immutable pairwise/issuer ciphertext digests. V1 review syntax and generic SecretProvider interface remain unchanged. Only explicit local-disposable host composition admits the factory-branded provider; native signing, reserved claims, canonical SQL locks/policies and revocation remain. This source proposal is unapproved and unqualified. Source/runtime/security admission, actual DB/TLS/native key installation and mandatory real issuance, revocation/custody/cleanup acceptance remain required. No cloud backend is impersonated, production admission introduced, keys generated or review installed. ## Exact issuer login witness (opt in) After applying the native RP store's private session-column migration, strict OIDC hosts may set `requireIssuerSessionWitness: true` on their existing verified provider reference. The SDK's signature, exact issuer, client audience, expiry and state-bound nonce verification must yield a nonempty signed `sid`. The existing callback then writes token-free metadata on the native RP session before issuing its cookie. Missing SID refuses that sign-in. Existing sessions have no witness and must sign in again; account tokens are never backfilled. The native issuer client prepared by `prepareBetterAuthRelyingPartyClient` enables end-session support, which makes the pinned OAuth provider emit `sid`. `readBetterAuthIssuerSessionWitness` from `./server` accepts native adapter session/account rows and the expected provider/issuer/client/RP session/identity. Read those rows within the host's current authority fence. The witness retains the original login's issuer SID across later logins of the same account. It is private (`input: false`, `returned: false`) and is absent from public session responses and cache cookies: both plugin schema and native session.additionalFields apply the private output filter. Deleting the native session removes its witness. Unlinked or replaced accounts refuse. The reader grants no access: separately recheck the exact live issuer session, reciprocal pairwise link and current product entitlement before releasing a private response. Never use a later account access token as the original session's issuer witness. ### Native RP session store migration (owner: this package) This package owns the native RP session/account custody that `createAuthOsResourceRelyingParty` creates, so it also owns the private column's forward SQL: `migrations/0002_authos_rp_session_issuer_witness.sql` in the `authos-better-auth` migration series (allocated by the integrator; the series is registered in `scripts/delivery/migration-registry`). The file targets each product host's existing native Better Auth RP database (never the central identity database), resolves `session` in the connection's current schema like the native adapter, adds a nullable `text` column without default or backfill, and refuses an existing column of another type, nullability or default. A store generated fresh from the RP's own options by Better Auth's native migration already includes the column; the SQL is idempotent there. Applying it is owner-operated: no host auto-migrates, and this package ships no loader. Sessions created before it keep a NULL witness and refuse until a fresh sign-in. Roll back the host first; dropping the column afterwards refuses every RP session. For read-only HOME resolution, set native `session.deferSessionRefresh: true` and read with `disableCookieCache: true` and `disableRefresh: true`. The former also prevents GET from deleting an expired stored session; the two query flags alone do not. The host keeps Set-Cookie output out of the HOME response and must not call get-access-token/refresh-token, provision entitlement, or persist consent. These source capabilities do not authorize a native store, host rollout or production activation. `createAuthOsRpRequestAuthority` from `./server` composes the request-local server ports a career host hands to the existing P-01n processor binding: `principal.readCurrentPrincipal()` and `admissions.resolveCurrentAdmission()` / `verify()`. Both re-read `readAuthOsRpRequestIdentity` for the original cookie on every call, use only that witness's raw pairwise subject and user credential, and return an admission only if the same RP session, issuer SID, account and raw subject are still current afterwards. They carry identity and admission evidence only; consent and candidate scope stay with P-01n. ## Native resource relying-party schema `migrations/0001_resource_relying_party_native_schema.sql` (series `authos-better-auth`, number 0001 allocated by the integrator) is the operator-applied native schema behind `createAuthOsResourceRelyingParty`: Better Auth's core `user`, `session`, `account` and `verification` tables with their default field names, plus the private nullable `session.authos_issuer_session_witness` column. It is brand-neutral, targets one dedicated host-local RP database (first consumer: `tafio-web`), carries a paired `.down.sql` usable only before sign-ins are served, and is never applied by a host at runtime. The `.down.sql` refuses to drop anything when `public.oauth_client` exists (the central identity database) or when `public.session` holds a row. A store that Better Auth's own native migration already created records 0001 as its baseline and applies only 0002. The api-application-monolith PGlite test proves Better Auth reports no pending table, column or index once it is applied. --- ## @lssm-tech/integration.billing-subscriptions-postgres Description: FORCE-RLS Postgres adapter for the BillingOS SubscriptionStorePort (billing_subscription schema and migration series). Path: packages/integrations/billing-subscriptions-postgres URL: /llms/integration.billing-subscriptions-postgres # @lssm-tech/integration.billing-subscriptions-postgres FORCE-RLS Postgres adapter for the BillingOS `SubscriptionStorePort` declared by `@lssm-tech/lib.billing-runtime/subscriptions/durable` (BILLING-01b, D-125). The billing runtime keeps the port, the engines and the in-memory reference store; this package owns the `billing_subscription` schema, its runtime role and its migration series under `migrations/`. ## Store `PostgresSubscriptionStore` has the same semantics as `InMemorySubscriptionStore` and runs over an injected `SubscriptionSqlDatabase` (no driver import): - Plan versions are insert-only (`INSERT … ON CONFLICT DO NOTHING`, then a digest comparison raises `PLAN_VERSION_CONFLICT`). Plans are product catalog data shared by every tenant of a product: readable by the runtime role, not tenant-scoped. - One subscription row per tenant, product and subject under a revision compare-and-set (`REVISION_CONFLICT`). The scope is serialized by `pg_advisory_xact_lock` plus `SELECT … FOR UPDATE`; nothing commits unless the unit of work succeeds. - State events are unique per tenant, source and event id with a payload digest (`SUBSCRIPTION_EVENT_CONFLICT`). A revoked grant is final. - One checkout intent per tenant, product and subject atomically excludes overlapping starts across offers and host processes. Claims are committed before provider I/O, renewed per stage, owner-fenced on completion, and recoverable after release or lease expiry. - Subscriptions, state events, grants and checkout intents are tenant-private: FORCE ROW LEVEL SECURITY for the NOLOGIN NOSUPERUSER NOBYPASSRLS runtime role `billing_subscription_runtime`, which has no DELETE right. A unit of work binds one tenant; touching another throws. Triggers keep plans insert-only, event payloads unchangeable and revoked grants final, even for the owner. - The store refuses to run when the effective role is a superuser or bypasses RLS. Pass `assumeRuntimeRole: true` when the login role is a member of the runtime role. ```ts import { PostgresSubscriptionStore } from '@lssm-tech/integration.billing-subscriptions-postgres'; import { applySubscriptionStateEvent } from '@lssm-tech/lib.billing-runtime/subscriptions/durable'; const store = new PostgresSubscriptionStore(database, { assumeRuntimeRole: true }); await applySubscriptionStateEvent(store, event); ``` ## Migrations `migrations/0001_billing_subscription.sql` is the `buildSubscriptionStoreDdl()` output for the default schema and role; `src/migrations.test.ts` fails when it drifts. Later numbers are allocated by the integration owner. `migrations/0002_autoapply_candidate_credits.sql` (allocated by the g8 train from the autoapply lane's proposed `9xxx_` file; applies after 0001; creates no role) is the `buildCandidateCreditStoreDdl()` output: the durable BillingOS candidate credit store (`PostgresCandidateCreditStoreV1`, `CandidateCreditStorePortV1`, D-239 precondition 0d). Periods, bonus balances and per-cycle reservations live in `billing_subscription.candidate_credit_*` under FORCE RLS for the same runtime role (SELECT, INSERT, UPDATE; no DELETE); CHECK constraints keep balances integer and non-negative and a partial unique index keeps one current period per scope. Each unit of work takes a transaction advisory lock on its scope (the owner lock) and commits only when the work resolves. `src/candidate-credit-store.pglite.test.ts` runs one scripted port run against this store and `InMemoryCandidateCreditStoreV1` and requires identical answers; the same file fails when 0002 drifts from the builder. `src/migrations.test.ts` pins the series order. The career billing packet (`deploy/career-billing`) requires and verifies the files, and the host probe profile `CAREER_BILLING_RUNTIME_GRANTS_V1` lists the credit tables. `migrations/0003_checkout_intents.sql` is the additive `buildCheckoutIntentStoreDdl()` output. Its one subject-scoped `checkout_intent` row is under FORCE RLS for the same role, with SELECT, INSERT, UPDATE and no DELETE. `src/checkout-intent.pglite.test.ts` runs the shared claim/expiry/stale-owner conformance cases. `scripts/rehearse-checkout-intents.zsh` applies the series twice to disposable native PostgreSQL and races two independent Bun processes through the real app/store path with a fake provider. ## Checks `bun test` runs the shared billing-runtime conformance suites (`@lssm-tech/lib.billing-runtime/subscriptions/durable/conformance`) and the RLS suite on PGlite under the runtime role. PGlite has one connection, so concurrency is shown serialized; cross-process checkout exclusion is rehearsed on native PostgreSQL with two independent connections. --- ## @lssm-tech/integration.builder-telegram Description: Telegram Builder control-channel integration. Path: packages/integrations/builder-telegram URL: /llms/integration.builder-telegram # @lssm-tech/integration.builder-telegram Telegram webhook normalization and Builder control-channel envelope mapping. --- ## @lssm-tech/integration.builder-voice Description: Voice Builder input integration. Path: packages/integrations/builder-voice URL: /llms/integration.builder-voice # @lssm-tech/integration.builder-voice Browser and uploaded voice helpers for Builder transcription flows. --- ## @lssm-tech/integration.builder-whatsapp Description: WhatsApp Builder control-channel integration. Path: packages/integrations/builder-whatsapp URL: /llms/integration.builder-whatsapp # @lssm-tech/integration.builder-whatsapp Meta and Twilio WhatsApp normalization for Builder control-channel workflows. --- ## @lssm-tech/integration.cli-contractspec-ai Description: Optional AI command pack for the ContractSpec CLI Path: packages/integrations/cli-contractspec-ai URL: /llms/integration.cli-contractspec-ai # @lssm-tech/integration.cli-contractspec-ai Optional `agent`, `chat`, `llm`, `mcp`, and `vibe` commands plus AI extensions for the ContractSpec CLI's core authoring, build, test, and validation commands. The default and `command-pack` entrypoints synchronously register the canonical AI integration commands. Existing custom Commander hosts retain concrete AI commands and the core authoring, build, test, and validation extensions without adding host bindings. For hosts that need declarations and help separately from concrete services, `@lssm-tech/lib.cli-runtime/optional-command-declarations/ai` supplies fresh command trees with the same nested help, arguments, aliases, and option defaults. This additive entry resolves explicit host actions when invoked. Host and pack builds must share the external canonical CLI runtime. Command implementations, provider adapters, MCP assembly, and the concrete operation-client environment binding live in this integration. The former workspace bundle paths forward to these same implementations. Generic LLM authoring, workflow execution, and MCP builders live in narrow CLI runtime entries; the integration does not import a bundle or host. The owning `prebuild` generates the offline MCP knowledge corpus through `scripts/generate-cli-mcp-knowledge.ts`. The generated corpus remains static at runtime. The existing transpilation workflow preserves one canonical module instance across command-pack and command subpath imports. --- ## @lssm-tech/integration.cli-contractspec-builder Description: Optional Builder command pack for the ContractSpec CLI Path: packages/integrations/cli-contractspec-builder URL: /llms/integration.cli-contractspec-builder # @lssm-tech/integration.cli-contractspec-builder Optional Builder, delivery, control-plane, execution-lane, harness, and intelligence commands for the ContractSpec CLI. `commandPack.register(program)` synchronously registers the canonical integration's six command objects and concrete handlers, including for a custom Commander host. The order remains Builder, Builder delivery, control plane, execution lanes, harness, and intelligence. Workspace CLI composition forwards to these same objects; callers do not need to bind action suppliers for this existing entry. The canonical implementation lives in `packages/integrations/cli-contractspec-builder`. Builder production execution imports the existing Codex and OpenCode Go adapters from their canonical leaf owners, `@lssm-tech/integration.provider-codex` and `@lssm-tech/integration.provider-opencode-go`, so installing this command pack does not pull in the full `@lssm-tech/integration.providers-impls` provider collection (the `/builder-execution` collection entry remains available to other callers). Settings, approvals, visibility policy, and runtime authority retain their existing behavior. ## Lazy adapters Registering the pack, rendering help and running commands that execute no adapter never evaluate `@lssm-tech/integration.harness-runtime`, `@lssm-tech/integration.runtime`, `@lssm-tech/integration.provider-codex` or `@lssm-tech/integration.provider-opencode-go`. Each one loads through a literal dynamic import when a command action needs it: `harness eval` loads the harness runtime, `control-plane` commands load the channel runtime, and the Builder production commands, preflight and doctor load the Codex and OpenCode Go providers. Settings resolution loads the Codex provider only to default the model of a configured quality gate that names none. The pack's registration graph also stays clear of `@lssm-tech/lib.contractspec-catalog`, `@lssm-tech/lib.contracts-runtime-server-mcp` and `@lssm-tech/lib.logger`. The adapters remain regular dependencies, so installs and command behavior are unchanged. If an adapter package itself cannot be resolved, the command fails with a `BuilderAdapterUnavailableError` (code `builderAdapterUnavailable`) naming the package and the command. Only a not-found error whose unresolved specifier is that package or one of its subpaths is mapped; a missing dependency of an installed adapter and every other load error propagate unchanged. `./commands/builder/production/provider` keeps `createCodexOpenCodeProviderPort` synchronous with both providers imported by that entry, so a fresh port serves every method, including `createCompletionReceipt`. The Builder commands use `./commands/builder/production/provider-port` instead: `loadCodexOpenCodeProviderPort` loads both providers and builds the same port, and `createCodexOpenCodeProviderPortWithAdapters` builds it from adapters the caller already holds. `resolveOpenCodeCliModel` now lives in `./commands/builder/production/preflight` next to the other OpenCode model checks. Portable declarations are available separately from `@lssm-tech/lib.cli-runtime/optional-command-declarations/builder`. This additive entry creates fresh complete command trees without constructing workspace services. A host using the portable entry supplies actions explicitly through `bindHostCommandPackActions`; an unbound action rejects with `missingHostBinding`, while registration and help remain available. Harness commands consume the canonical scenario and suite registry classes from @lssm-tech/lib.harness/harness/types. Registry identity and approval behavior are unchanged; the command pack no longer declares a direct compatibility-facade dependency. --- ## @lssm-tech/integration.cli-contractspec-design Description: Optional design command pack for the ContractSpec CLI Path: packages/integrations/cli-contractspec-design URL: /llms/integration.cli-contractspec-design # @lssm-tech/integration.cli-contractspec-design Optional `design` command pack for the slim ContractSpec CLI host. ```sh bun add @lssm-tech/app.cli-contractspec @lssm-tech/integration.cli-contractspec-design ``` The host discovers this package only when it is a direct consumer dependency. Use `.contractsrc.commandPacks.exclude` to disable it explicitly. --- ## @lssm-tech/integration.cli-contractspec-examples Description: Optional examples command pack for the ContractSpec CLI Path: packages/integrations/cli-contractspec-examples URL: /llms/integration.cli-contractspec-examples # @lssm-tech/integration.cli-contractspec-examples The existing public pack automatically registers the canonical workspace actions on custom Commander hosts. It requires no new binding. New portable hosts can separately use `@lssm-tech/lib.cli-runtime/optional-command-declarations/examples` to inspect complete command help and supply explicit action bindings. Optional examples browsing and example-backed onboarding commands for the ContractSpec CLI. The package owns the concrete Examples and onboarding Commander commands and their synchronous registration function. The workspace CLI's previous paths forward to these same objects. Metadata discovery uses the canonical literal catalog in CLI runtime; runnable example previews remain optional and separate. This ownership move preserves command-pack id/version, command order, callbacks and bare-Commander registration. The lower authoring dependency join, builds, declarations and resulting-tree consumer qualification remain pending. --- ## @lssm-tech/integration.communication-channel-core Description: Shared ChannelAdapter port + registry types for CommunicationOS channel integrations (INTERNAL/UNSTABLE until P2-S4 freezes it). Path: packages/integrations/communication-channel-core URL: /llms/integration.communication-channel-core (No README.md) --- ## @lssm-tech/integration.communication-channel-discord Description: Observe-only multi-guild Discord Gateway integration for CommunicationOS. Path: packages/integrations/communication-channel-discord URL: /llms/integration.communication-channel-discord # CommunicationOS Discord channel integration Observe-only Discord Gateway integration for multi-guild community intelligence. It captures an explicit event set, applies guild and channel policy before normalization, and reports sequence gaps and coverage degradation. It never sends messages or performs moderation actions. The runtime can consume an asynchronous per-guild policy authority. It refreshes source status, installation health, channel rules, and policy version immediately before raw persistence. Coverage counters are reported per guild, and backfill, persistence, publication, and coverage failures use content-free phase/code records. The worker requires Node.js 24, one bot token per trust zone, and read-only Discord permissions (`ViewChannel`, `ReadMessageHistory`, `ViewAuditLog`). Message content is a privileged intent and must be enabled for content analysis. Default history backfill is 30 days (configurable from 0 through 90 days). Audit-log reconciliation is capped at Discord's 45-day availability window. --- ## @lssm-tech/integration.communication-channel-email Description: CommunicationOS email channel adapter: inbound normalization (provider-email Gmail parse), outbound send (Postmark/Resend), and documented-retention erasure. Path: packages/integrations/communication-channel-email URL: /llms/integration.communication-channel-email (No README.md) --- ## @lssm-tech/integration.communication-channel-slack Description: CommunicationOS Slack channel adapter: inbound normalization (Events API + signing-secret verify), outbound send (chat.postMessage), and best-effort erasure (chat.delete). Path: packages/integrations/communication-channel-slack URL: /llms/integration.communication-channel-slack (No README.md) --- ## @lssm-tech/integration.communication-channel-sms Description: CommunicationOS SMS channel adapter: inbound normalization (Twilio webhook parse), outbound send (provider-sms/Twilio), and documented-retention erasure. Path: packages/integrations/communication-channel-sms URL: /llms/integration.communication-channel-sms # CommunicationOS SMS channel This package owns the canonical Twilio SMS channel adapter for CommunicationOS. It supports signature-verified inbound form webhooks, provider-backed outbound delivery, normalized ecosystem events and receipts, and explicit provider-retention behavior. The adapter uses an explicit Node-compatible build profile, including Bun server hosts. Its credential and webhook boundary does not advertise a browser export condition. Existing package entry points and provider contracts remain unchanged. ## Ecosystem composition Use `createTwilioSmsEcosystemAdapter` from `@lssm-tech/integration.communication-channel-sms/ecosystem-adapter` when composing the current CommunicationOS ecosystem port. The adapter requires an injected `SmsProvider`, an E.164 sender number, and the Twilio auth token used to verify inbound signatures. Managed connections store only an opaque credential reference. The resolved secret document is expected to contain: ```json { "network": "sms", "provider": "twilio", "accountSid": "...", "authToken": "...", "fromNumber": "+..." } ``` The managed API accepts only `application/x-www-form-urlencoded` payloads with an `X-Twilio-Signature` that verifies against the exact callback URL. The managed worker rejects other providers or incomplete credential material. Local conformance is not live provider qualification. Production activation still requires consent and opt-out enforcement, credentialed callback/send tests, delivery-status reconciliation, and an accepted Runtime Node effect path. --- ## @lssm-tech/integration.communication-channel-telegram Description: CommunicationOS Telegram channel adapter: inbound normalization (builder-telegram), outbound + erasure via the Telegram Bot API. Path: packages/integrations/communication-channel-telegram URL: /llms/integration.communication-channel-telegram (No README.md) --- ## @lssm-tech/integration.communication-os-agent Description: Governed agent binding that drafts CommunicationOS replies via the ai-agent runtime, using the fail-closed command-inbox as the approval seam and a SovereigntyProfile-driven sovereign LLM (Mistral EU default, Claude alternative) — with no outbound send authority. Path: packages/integrations/communication-os-agent URL: /llms/integration.communication-os-agent # @lssm-tech/integration.communication-os-agent Governed agent binding for CommunicationOS (plan P1-S2 + P1-S3, AC1.2, AC1.4). It wires the `@lssm-tech/lib.ai-agent` runtime so it drafts replies and extracts decisions/risks/actions/summaries/intent for CommunicationOS — using the fail-closed governed command-inbox as the approval seam and a `SovereigntyProfile`-driven sovereign LLM (Mistral EU by default, Claude as a config-only alternative) — **without ever giving the agent outbound send authority**. ## Why this is an integration package This package binds three reusable libs (`ai-agent`, `ai-providers`, `communication-runtime`) plus the `communication-spec` contracts to a concrete runtime target (the governed agent). It introduces no new domain contracts and depends only downward (libs + spec), matching `package-architecture.md` for the `integrations/` layer. It is the glue between the generic agent runtime and the CommunicationOS governance surface; it does not belong in a lib (it composes several libs) nor in a bundle/app (it is reusable across verticals). ## Safety invariants (non-negotiable) 1. **Allowlist, not denylist (pre-mortem #3, R3).** `createCommunicationAgentOperationRegistry()` builds the agent's `operationRegistry` from an explicit allowlist: `reply.draft`, `summary.generate`, `intent.classify`, `action.extract`, `decision.extract`, `risk.extract`. The outbound `communication.reply.send` operation is structurally absent — it is never registered, so the agent can never resolve it into a tool. A future send-like operation cannot leak in by omission. 2. **Inbox-backed approval seam (architect MUST-FIX 1).** `CommunicationInboxApprovalStore implements ApprovalStore`. Every approval request is projected through `createCommunicationCommandInboxItem`, producing a fail-closed inbox item (`canExecute: false`). The agent can only *create* pending records; it cannot transition them to approved and holds no send tool. The store is wrapped as `new ApprovalWorkflow(store)` and passed as `approvalWorkflow` — the inbox object is never passed directly. 3. **Send is a separate port the agent cannot call.** Outbound delivery is reachable only by an inbox approval transition driven by a human or an explicitly authorized policy — never by the agent. ## Sovereign model binding (P1-S3, AC1.4) `resolveSovereignDefaultModel` / `createSovereignModelSelector` resolve the `LanguageModel` from the tenant `SovereigntyProfile.llmProviderId`: Mistral (sovereign EU) by default, Claude (`anthropic`) as the alternative, switchable by config only. On-prem/self-host hosting routes through a `provider-local-model` OpenAI-compatible `baseUrl`. ## Thread assist over the Vercel AI Gateway `./thread-assist-gateway` exports `createGatewayThreadAssistModels()`. It returns a read/draft-only thread assist port for any entry of `COMMUNICATION_OS_AI_MODEL_CATALOG` (`@lssm-tech/lib.communication-spec/contracts/ai-model-catalog`), built on the shared `createVercelGatewayModel` adapter. Every call carries the enforced Gateway policy: EU inference zone, zero data retention, no training, and only the catalog's inference providers. There is no direct-provider key and no automatic fallback model. Ports are cached per model id, so switching models per request does not rebuild clients. Omit `apiKey` to let the Gateway SDK use `AI_GATEWAY_API_KEY` or Vercel OIDC. CommunicationOS API uses this binding for summaries, drafts and inbox triage. The port's `triage()` (`./thread-triage`) requests strict structured output (`Output.object` with the `communicationThreadTriageJsonSchema()` schema) and validates the label again, so invalid output always rejects. The sovereign binding below remains for the governed agent. ## Usage ```ts import { createCommunicationOsAgent } from '@lssm-tech/integration.communication-os-agent'; const { factory, approvalStore, approvalWorkflow } = createCommunicationOsAgent({ models: { sovereignty: { llmProviderId: 'mistral', hostingMode: 'saas' }, providers: { mistral: { apiKey: process.env.MISTRAL_API_KEY }, anthropic: { apiKey: process.env.ANTHROPIC_API_KEY }, }, }, inbox: { log: { events: [], version: 0 } }, }); ``` --- ## @lssm-tech/integration.communication-os-client Description: Browser-safe typed REST and realtime client for CommunicationOS. Path: packages/integrations/communication-os-client URL: /llms/integration.communication-os-client # CommunicationOS client Browser-safe typed client for the central CommunicationOS REST and realtime surfaces. Authentication is injected; service secrets and raw provider credentials never enter this package. Room list projections include `messageCount` and optional `lastActivityAt` as authorized summary metadata. Hosts can render complete conversation ledgers without fetching message bodies for every room; only the selected room needs a message-list request. The root client exposes typed `bootstrapScope`, `listSpaces`, `listRooms`, `listMessages`, `sendMessage`, `listEvents`, and single-use realtime-ticket helpers. Effect-bearing requests carry caller-supplied idempotency keys and always omit browser cookies. The `/v2/community` surface exposes typed Discord installation authorization, policy update, revocation, coverage, insight, staff-scorecard, and Kaizen-digest methods. Tenant, workspace, space, actor, and trust-zone authority remain server-derived. Mutation idempotency keys are sent only in the `idempotency-key` header, and public installation responses intentionally omit credential references. Message search and send use the canonical `communication.message.search@3.0.0` and `communication.message.send@3.0.0` REST operations. The authenticated host derives tenant and author authority; callers select only an authorized workspace, space, and room. The API must be upgraded before this client so the `/communication/message/*/v3.0.0` routes are available during rollout. `uploadAttachment`, attachment-aware `sendMessage`, and `downloadAttachment` keep file access behind the authenticated, scope-bound API. Messages expose only opaque file metadata; provider and storage URLs are never part of the client contract. `resolveAuthorizedThreadRoomId` keeps canonical thread deep links distinct from room identifiers. It returns a room only when an active server projection binds the opaque external thread reference to a room already present in the caller's authorized room list; inactive, missing, and cross-scope-looking references fail closed. `startProviderOAuth(scope, { network, placement, providerKey, returnPath })` starts the official provider flow without accepting tokens or vault references from the public UI. `providerKey` selects a provider inside a network (`google` or `microsoft` for `email`, `microsoft` for `teams`); without it the API uses the first configured provider of the network. Provider callbacks return to the origin the API maps to the session's host-exchange issuer (`COMMUNICATION_OS_OAUTH_HOST_ORIGINS`, for example CompanyOS at `/companyos/communication-os/connections`) or to the standalone shell, with `?oauth=connected|provider_denied&network=…`; the client never receives the PKCE verifier or exchanged credentials. Threads: the v2 API groups conversations by room and exposes no separate thread list. Messages may carry `replyToMessageId` (reply chains inside a room) and room-channel bindings may carry `externalThreadId` (a provider thread mirrored into a room), so hosts render one room as one thread and use `resolveAuthorizedThreadRoomId` for provider thread deep links. `exchangeDirectSession()` uses the first-party AuthOS cookie on web. Native shells pass their device-vault-backed AuthOS session token to `exchangeDirectSession(sessionToken)`; that transport omits cookies and sends the session only in the authorization header. CompanyOS-owned native shells configure `nativeSessionExchangeUrl` to the protected CompanyOS BFF. The BFF verifies the device bearer, derives the active organization scope, and performs the server-secret host assertion exchange; the client receives only the short-lived CommunicationOS grant. Canonical v2 request, result, error, cursor, and projection DTOs are re-exported from the client. Journal, encrypted-envelope, and realtime payloads are JSON-safe `CommunicationJsonObjectDto` values; unsupported provider behavior is represented by the explicit `unsupported_feature` error code. Realtime reconnect retains a bounded event-ID window in addition to the server cursor. A gateway replay of the boundary event advances the cursor but does not notify the host twice, preventing duplicate refresh or mutation effects. ## Session engine `@lssm-tech/integration.communication-os-client/session-engine` is the React-free client session engine shared by the standalone web/PWA, desktop and mobile shells. `createCommunicationOsSessionEngine` owns: - grant exchange through the first-party cookie (web) or a vault-held native session token, with `refreshSkewMs` re-exchange for web and fixed native grants whose `requestHeaders()` fail closed once expired; - scoped bearer headers for sibling surfaces (forms, meetings, support); - workspace load with initial room precedence (authorized requested room, then an actively bound thread room, then an authorized stored room, then the bootstrap or first room); - send-or-queue under one idempotency key, ordered outbox replay that stops at the first failure, and `createCommunicationOsDurableOutbox` for principal-scoped durable storage with quarantine of malformed rows; - platform-neutral per-row payload sealing for durable outboxes: `CommunicationOsOutboxPayloadCipher`, the scope-bound AES-GCM additional data (`communicationOsOutboxAdditionalData`: tenant, workspace, space, principal, room, idempotency key), the `v2..` envelope codec and a strict, `TextDecoder`-free UTF-8 codec. Hosts keep the crypto adapter (WebCrypto on desktop, expo-crypto on mobile) and the key custody; - governed-work transitions, including identity-review approve/reject mapped to merge/reject. - `BrowserMessageOutbox`, a bounded (50 rows per key), scope-keyed browser storage outbox that never throws on blocked or full storage and stores only message bodies and ids, with `browserSessionOutbox` for the engine; and `classifyCommunicationOsSendFailure`, which maps a failed `message.send` to `denied` (403, terminal), `unauthorized` (401), `rejected` (other 4xx) or `transient` (network, 408/425/429, 5xx). Capabilities come only from the server-issued grant. On a 401 the engine drops its grant and, when the host provides `onUnauthorized`, lets the host revoke its stored credential. Hosts keep React state, storage keys, timers, window and network listeners, file encoding and redirects. ## Workspace projection `@lssm-tech/integration.communication-os-client/workspace-projection` loads the read model embedded hosts render: `loadCommunicationOsLiveRoom` binds the scope and bootstrap within a read deadline (default 4 s), loads spaces, rooms, connections, bindings, contacts, governed work and events as optional projections, keeps an authorized requested room, and reports `threadCollectionState` / `messageCollectionState` as `partial` instead of an empty success when a projection stalls. Hosts inject the client (transport and origin) and the scope loader. --- ## @lssm-tech/integration.communication-os-host-auth Description: Scoped host-session and access-token exchange for CommunicationOS embeds. Path: packages/integrations/communication-os-host-auth URL: /llms/integration.communication-os-host-auth (No README.md) --- ## @lssm-tech/integration.communication-os-persistence Description: Server-only persistence binding that executes CommunicationOS governed-mutation descriptors against a database, with self-host (PgLite) and managed Postgres support. Path: packages/integrations/communication-os-persistence URL: /llms/integration.communication-os-persistence # @lssm-tech/integration.communication-os-persistence Server-only persistence binding for CommunicationOS. It executes the `createCommunicationOsMutationDescriptor(...)` governed-mutation descriptors from `@lssm-tech/lib.communication-spec` against a database via `executeGovernedMutation`, enforcing the spec `deploymentMode` (managed / BYOK) itself — the executor never validates it. The server-only database surface also provides additive multi-guild Discord community stores for guild sources and installations, protected raw Gateway envelopes, stable provider identities, coverage evidence, and redacted community-intelligence records. Public projections never return credential references or raw staff content. The Discord worker uses a dedicated observer database role whose RLS policies bind both `app.tenant_id` and `app.trust_zone`; the tenant-wide application role remains reserved for authorized API management and portfolio queries. ## Surfaces - **Root (`.`)** — browser-safe. Pure types + helpers only: - `persistCommunicationOsMutation(descriptor, runtime, options?)` - `adaptCommunicationOsDescriptor`, `enforceDeploymentMode` - `buildSchemaContributionDdl` - `CommunicationOsDeploymentModeError`, `COMMUNICATION_OS_PERSISTENCE_MODES` - **`./database`** — SERVER-ONLY (node-only). Reached only via this subpath, never re-exported from the root (pre-mortem #1: no node-only DB in browser bundles): - `createPgLitePersistenceProvider` (self-host, in-process Postgres/WASM) - `migrateCommunicationOsSchema` (applies `communicationOsSchemaContribution`) - `createCommunicationOsPostgresProvider` (the single reviewed raw-provider construction boundary for schema bootstrap and service queues; tenant records still require the scoped wrapper) - `createPostgresCommunicationOAuthReplayStore` (atomic, expiring, network-bound one-time OAuth state fingerprints; no scope, verifier, or provider token content is persisted) - `createPostgresCommunicationRealtimeTicketReplayStore` (atomic, database-clock-expiring single-use ticket IDs shared by every realtime replica; no token, principal, scope, or message content is persisted) - `createPostgresCommunicationSecretProvider` (portable AES-GCM credential vault for managed Postgres and self-host PgLite; references are hashed and the external master key and plaintext never enter the database) - `./database/product-membership-store` — `HcircleProductMembershipStore` (SQL `AuthOsProductMembershipStore` for hCircle: idempotent provisioning with unique-violation conflicts, linked-user role lookup, verified bootstrap-owner reconciliation and meeting authority derivation) and `COMMUNICATION_PRODUCT_MEMBERSHIP_MIGRATION_SQL` (table, authority index, legacy backfill). Hosts bind a query function and run the migration after their Better Auth `communication_auth."user"`/`account` tables. - `createManagedCommunicationOsPersistence` (wraps the managed `createDatabaseRuntime` from `@lssm-tech/integration.runtime-managed/database`) - `createPostgresCommunicationAttachmentStore` (digest-verified binary content, scope isolation, upload idempotency, and immutable message linking) - `createPostgresCommunicationSupportInternalNoteStore` (encrypted immutable private-note content, exact replay/conflict detection, forced RLS, a redacted journal event, and body-free verification evidence) - canonical agent conversation, lifecycle, ingress receipt/context/decision, and surface-control stores over the tenant/workspace/space journal; stable logical replay keys reject digest substitution and control claims are transactionally single-winner - `createPostgresCommunicationDeliveryArtifactStoreV1` persists revision-CAS preference sets and immutable prepared/fallback routing artifacts in that same scoped journal; restart replay revalidates every digest and binding - `createPostgresCommunicationAgentHostExecutionStateV1` persists the scoped Runtime Node provider reservation, attempt, indeterminate recovery, and exact receipt replay state; same-digest substitution and cross-tenant reads fail closed, and the managed role is protected by forced RLS - `createPostgresCommunicationOutboxStore` persists indeterminate provider outcomes as exact, idempotent `reconciliation_pending` custody; those rows cannot be reclaimed after lease expiry, and accepted-result reconciliation binds outbox identity, idempotency key, work-order digest, provider ID, and the immutable observation ref/digest/time. Definitive failure uses the same exact transition without inventing a delivery receipt. `bun run qualify:outbox-reclaim-kill` (env `COMMUNICATION_OS_QUALIFY_POSTGRES_URL`, a disposable server whose role may create databases) SIGKILLs a worker inside an open claim or completion and after it committed, then proves on a fresh provider that nothing open survives, a dead owner's lease is respected, reclaimed only after expiry, held for reconciliation and fenced, and no provider effect runs twice - `COMMUNICATION_OS_MIGRATIONS` (digest-pinned baseline, private-note, and RLS migrations with immutable `communication_os.schema_migrations` receipts) - `eraseCommunicationOsTenant` (`./database/tenant-erasure-store`) runs `communication.tenant.erase` only through the SECURITY DEFINER `communication_os.erase_tenant(text)`, owned by the NOLOGIN NOSUPERUSER NOBYPASSRLS `communication_os_tenant_eraser` and executable only by `communication_os_tenant_erasure_caller`; the app role cannot delete support notes or devices. - **`./transport`** — server-only ContractSpec REST binding: - `createCommunicationOsEcosystemCoreRestRegistry` exposes the canonical v3 space, room, account, contact, message-search, and message-send operations, plus the canonical v2 governed-work lifecycle. - `createCommunicationOsEcosystemCoreRestHandler` derives actor, tenant, workspace, space, and principal context from the authenticated host. Room creation accepts only replay-safe client intent. - The narrower `createCommunicationOsEcosystemMessageRestRegistry` and handler remain exported for consumers migrating message transport first. ## Disposable PostgreSQL qualification target contract Provider-account identity tests always run on PgLite. Server execution requires the explicit `COMMUNICATION_OS_IDENTITY_TEST_DATABASE_URL`; generic application `DATABASE_URL` never selects a test target. The data database must be named `communication_os_identity_test_` (lowercase alphanumeric/underscore run suffix) or the qualification-owned `communication_os_outbox_kill__