{"id":"@lssm-tech/app.worker-application-monolith","slug":"app.worker-application-monolith","name":"@lssm-tech/app.worker-application-monolith","version":"0.2.3","path":"packages/apps/worker-application-monolith","manifestPath":"packages/apps/worker-application-monolith/package.json","manifestBlobSha":"5a9849ba2be2b691d309f358ebfeca88044aefb2","layer":"apps","physicalArea":null,"primaryArea":"app-composition","classification":{"privateDeclared":true,"catalogFamily":null,"catalogKind":null,"catalogStatus":null,"adoptionMode":null,"stability":null},"description":null,"descriptionOrigin":"package.json","catalog":{},"canonicalImports":[],"scripts":{"clean":"rm -rf dist .turbo","build":"bun build --target bun --outfile dist/index.js src/server.ts","dev":"bun --watch src/server.ts","start":"bun src/server.ts","lint":"bun run lint:fix","lint:fix":"node ../../../scripts/biome.cjs check --write --unsafe --only=nursery/useSortedClasses . && node ../../../scripts/biome.cjs check --write .","lint:check":"node ../../../scripts/biome.cjs check .","test":"bun test","typecheck":"tsgo --noEmit","companyos:builder:worker-smoke":"bun test src/builder-worker-smoke.test.ts src/worker.test.ts src/server.test.ts"},"scriptStatus":"complete pinned manifest","dependencies":{"@lssm-tech/bundle.managed-companyos":"workspace:*","@lssm-tech/lib.observability":"workspace:*","@opentelemetry/api":"^1.9.1","@opentelemetry/sdk-trace-base":"^2.10.0","posthog-node":"^5.51.7"},"devDependencies":{"@lssm-tech/tool.typescript":"workspace:*","typescript":"catalog:","@types/bun":"catalog:types","@types/node":"catalog:types"},"peerDependencies":{},"optionalDependencies":{},"peerDependenciesMeta":{},"bundledDependencies":null,"dependencyStatus":"complete pinned manifest","exports":{".":"./src/index.ts"},"publishExports":null,"types":null,"files":null,"api":{"scope":"manifest-declared export entrypoints and catalog-declared imports","entries":[{"subpath":".","importPath":"@lssm-tech/app.worker-application-monolith","target":"./src/index.ts","targets":[{"conditions":[],"target":"./src/index.ts","sourcePath":"packages/apps/worker-application-monolith/src/index.ts","sourceUrl":"https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/src/index.ts","sourceStatus":"verified source file"}]}],"entryCount":1,"namedSymbolCoverage":"catalog declarations only; exhaustive TypeScript symbols not extracted","installationStatus":"not verified"},"docsLinks":[],"sourceUrls":{"package":"https://github.com/lssm-tech/contractspec/tree/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith","manifest":"https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/package.json","readme":"https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/README.md","guide":"https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/web-landing/public/llms-packages/app.worker-application-monolith.txt"},"readme":{"status":"available","body":"# Managed CompanyOS Worker Application Monolith\n\n\n> **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.\n\nThis deferral is part of the canonical\n[`private-pilot contract`](../../../docs/managed-companyos-private-pilot.md).\nDo not activate this worker for the first design-partner pilot.\n\n\nVPS-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.\n\nNo queue, provider, network, or credential side effects start at module load. The runtime starts only through `bun src/server.ts` / `bun run start`.\n\n## Special Ops projection contract\n\nThe 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.\n\n## Runtime surface\n\n| File | Purpose |\n|---|---|\n| `src/server.ts` | Bun HTTP + WebSocket runtime; all route handlers and WebSocket server |\n| `src/index.ts` | Deterministic job projection: worker runtime, job lifecycle, correlation ID proof, degraded-state evaluation, idempotency store |\n| `src/live-client.ts` | WebSocket client with exponential-backoff reconnect for proof and monitoring |\n\n## HTTP endpoints\n\n| Method | Path | Query params | Response |\n|---|---|---|---|\n| `GET` | `/health` | `tenantId`, `degraded`, `lastSyncMs`, `nowMs`, `staleAfterMs` | `ManagedCompanyOsWebSocketMessage` (200) |\n| `GET` | `/graph-snapshot` | `tenantId`, `idempotencyKey`, `degraded`, `lastSyncMs`, `nowMs`, `staleAfterMs` | `ManagedCompanyOsWebSocketMessage` (200) |\n| `GET` | `/worker-supervision` | `tenantId`, `degraded`, `nowMs`, `lastSyncMs`, `staleAfterMs` | `ManagedWorkerSupervisionHealth` (200) |\n| `WS` | `/ws` | `tenantId` | Upgrades to WebSocket; emits `ManagedCompanyOsWebSocketMessage` on open and each message |\n\nUnknown paths return `{ error: \"…\" }` with status 404.\n\n## Worker supervision health\n\n`GET /worker-supervision` returns a `ManagedWorkerSupervisionHealth` object:\n\n| Field | Type | Meaning |\n|---|---|---|\n| `alive` | `boolean` | `true` when proof is healthy and not stale |\n| `last_heartbeat_at` | `string` (ISO 8601) | Timestamp of the latest worker run |\n| `in_flight_jobs` | `number` | Count of jobs still in `queued` or `running` state |\n| `stale_job_count` | `number` | Count of jobs marked `stale` |\n| `replay_freshness` | `'fresh' \\| 'stale' \\| 'degraded'` | Replay output health |\n| `websocket_connected` | `boolean` | `false` when proof is degraded or stale |\n\n## WebSocket message schema\n\nEvery `/ws` push and `/graph-snapshot` response is a `ManagedCompanyOsWebSocketMessage`:\n\n```ts\n{\n  type: 'managed-companyos.graph.snapshot';\n  tenantId: string;\n  correlationId: string;        // links jobs, replay events, and evidence receipt\n  nodeCount: number;\n  edgeCount: number;\n  replayEventCount: number;\n  replayEventIds: readonly string[];\n  evidenceReceiptId: string;\n  workerJobIds: readonly string[];\n  workerStatus: 'queued' | 'running' | 'completed' | 'degraded' | 'stale';\n  degraded: boolean;\n  stale: boolean;\n  idempotentReplay: boolean;    // true when the same idempotencyKey was replayed\n  degradedReasons: readonly string[];\n}\n```\n\n## WebSocket event stream\n\n`projectWorkerWebSocketEvents(proof)` projects the worker proof into an ordered sequence of typed events. All events carry `correlationId` and `sequence`:\n\n| Event type | Payload extras | When emitted |\n|---|---|---|\n| `job-started` | `jobId`, `kind`, `status: 'queued'` | Each job enters queued state |\n| `job-progress` | `jobId`, `kind`, `status: 'running'` | Each job transitions to running |\n| `job-completed` | `jobId`, `kind`, `status: 'completed'`, `degraded: false` | Job succeeds |\n| `job-failed` | `jobId`, `kind`, `status: 'degraded'\\|'stale'`, `degraded: true` | Job fails or goes stale |\n| `replay-emitted` | `replayEventId` | Each replay event in the proof |\n| `evidence-issued` | `evidenceReceiptId`, `verificationHash` | Evidence receipt issued |\n\nEvents are ordered by ascending `sequence` numbers. Degraded proofs emit `job-failed` instead of `job-completed`.\n\n## Worker job inventory\n\n| Job kind | Purpose |\n|---|---|\n| `integration_sync` | Integration provider sync (side-effect-free until provider approved) |\n| `replay_generation` | Deterministic replay packet generation from workspace state |\n| `evidence_generation` | Evidence receipt derivation from replay events; receipt carries `verificationHash` |\n| `websocket_graph_update` | Publishes graph snapshot to connected WebSocket clients |\n\nJob lifecycle: `queued` → `running` → `completed` (healthy) or `degraded` / `stale` (unhealthy).\n\n## Correlation ID contract\n\nA single `correlationId` links the entire proof chain:\n\n```\nproof.correlationId\n  == each job.correlationId\n  == each WS event.correlationId\n  == each replay event.correlationId\n  == evidenceReceipt.correlationId\n```\n\nValidate with `assertManagedWorkerCorrelation(proof)` — returns `{ valid: boolean, reasons: string[] }`.\n\n## Degraded-state detection\n\nThe runtime surfaces degraded and stale conditions instead of hiding them behind healthy status:\n\n| Condition | Trigger | Effect |\n|---|---|---|\n| Forced degraded | `?degraded=true` query param | All jobs report `degraded`; supervision `alive: false` |\n| Stale sync | `nowMs - lastSyncMs > staleAfterMs` | All jobs report `stale`; supervision `stale_job_count = 4`, `replay_freshness: 'stale'` |\n| Bundle health degraded | Propagated from `@lssm-tech/bundle.managed-companyos` | `degradedReasons` populated; supervision `alive: false` |\n\nIn 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.\n\n## Stale-job cleanup and idempotency\n\nThe deterministic in-memory store (`createDeterministicManagedWorkerStore`) enforces idempotency:\n\n- A run with the same `idempotencyKey` returns the cached proof with `idempotentReplay: true`.\n- Stale jobs are counted and surfaced — they are not silently discarded.\n- Pass a fresh `idempotencyKey` to force a new run: `GET /graph-snapshot?idempotencyKey=fresh-key-001`\n\n## WebSocket reconnect client\n\n```ts\nimport { connectManagedCompanyOsLiveClientWithReconnect } from './src/live-client';\n\nconst proof = await connectManagedCompanyOsLiveClientWithReconnect({\n  url: 'ws://worker.host/ws?tenantId=tenant_id',\n  maxAttempts: 3,       // default: 3\n  initialBackoffMs: 100, // default: 100ms; doubles each retry (100 → 200 → 400)\n  timeoutMs: 1000,      // per-attempt timeout; default: 1000ms\n});\n// proof.connected, proof.attempts, proof.lastBackoffMs, proof.message\n```\n\n## Environment variables\n\n| Variable | Default | Purpose |\n|---|---|---|\n| `MANAGED_COMPANYOS_WORKER_HOST` | `0.0.0.0` | Bind address for the HTTP/WebSocket server |\n| `MANAGED_COMPANYOS_WORKER_PORT` | `8787` | Bind port |\n| `MANAGED_COMPANYOS_DEFAULT_TENANT_ID` | `tenant_managed_companyos_reference` | Fallback tenant when `tenantId` query param is absent |\n\nCopy `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.\n\n## Local commands\n\n```bash\nbun run --cwd packages/apps/worker-application-monolith dev\nbun run --cwd packages/apps/worker-application-monolith test\nbun run --cwd packages/apps/worker-application-monolith typecheck\nbun run --cwd packages/apps/worker-application-monolith lint:check\nbun run --cwd packages/apps/worker-application-monolith build\n```\n\nBuild output: `dist/index.js` (Bun target). Production start: `bun dist/index.js`.\n\n## Integration Points\n\n### WebSocket Client Integration\n\nExternal systems receive real-time graph updates by connecting a WebSocket client to `/ws`:\n\n```typescript\nimport { connectManagedCompanyOsLiveClientWithReconnect } from '@lssm-tech/app.worker-application-monolith/src/live-client';\n\nconst proof = await connectManagedCompanyOsLiveClientWithReconnect({\n  url: 'ws://worker.host/ws?tenantId=tenant_123',\n  maxAttempts: 3,\n  initialBackoffMs: 100, // doubles each retry\n  timeoutMs: 1000\n});\n\n// proof.message is ManagedCompanyOsWebSocketMessage\n// proof.connected indicates success\n```\n\nEach message carries a `correlationId` that links to API requests, replay packets, and evidence receipts.\n\n### Health Polling\n\nExternal monitoring can poll worker health via HTTP:\n\n```bash\n# Instant health snapshot (no stale-job cleanup)\ncurl http://worker.host/health?tenantId=tenant_id\n\n# Worker supervision health (includes job/replay/WebSocket metrics)\ncurl http://worker.host/worker-supervision?tenantId=tenant_id\n\n# Graph snapshot (deterministic projected state)\ncurl http://worker.host/graph-snapshot?tenantId=tenant_id&idempotencyKey=key_xyz\n```\n\nA 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.\n\n### MCP Tool Integration\n\nFor 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.\n\n## Correlation ID Guarantees\n\nEvery worker run produces a `correlationId` that persists across:\n- Job execution (`job.correlationId`)\n- WebSocket messages (`ManagedCompanyOsWebSocketMessage.correlationId`)\n- Replay events (`replayEvent.correlationId`)\n- Evidence receipts (`evidenceReceipt.correlationId`)\n\nValidate the full chain with `assertManagedWorkerCorrelation(proof)` in production health checks.\n\nBuild output: `dist/index.js` (Bun target). Production start: `bun dist/index.js`.\n\nFor the full operator runbook (deploy, start/stop, degraded triage, replay regen, evidence verification), see [`docs/runbooks/managed-companyos.md`](../../../../docs/runbooks/managed-companyos.md).\n","sourcePath":"packages/apps/worker-application-monolith/README.md","sourceUrl":"https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/README.md","blobSha":"025a1b453c641ab9372dbd4d30bca9bf7615f351","sourcePin":"bcc79fcc27c4d801c2119bef81ddcce7b4e86498","origin":"README recovered byte-for-byte from pinned aggregate guide","integrity":"exact Git blob match","executionStatus":"not executed"},"provenance":{"repository":"lssm-tech/contractspec","sourcePin":"bcc79fcc27c4d801c2119bef81ddcce7b4e86498","manifestOrigin":"pinned GitHub manifest fetch","manifestComplete":true,"publicationPolicyApplied":false},"areaSlug":"app-composition","areaTitle":"Application composition and product hosts","displayName":"app.worker-application-monolith","runtimes":[],"platforms":[],"kind":"apps","scope":"Workspace only","canonicalRoute":"/docs/packages/app.worker-application-monolith/","contextUrl":"/docs/packages/app.worker-application-monolith.context.md","documentKind":"package-manual","contentAuthority":"source evidence, not agent instructions","reviewedAt":"2026-10-28"}