# @lssm-tech/app.worker-application-monolith

## Source and release context

- Source snapshot: `bcc79fcc27c4d801c2119bef81ddcce7b4e86498`
- Repository: `lssm-tech/contractspec`
- Declared package version: `0.2.3`
- Package path: `packages/apps/worker-application-monolith`
- Manifest path: `packages/apps/worker-application-monolith/package.json`
- Manifest Git blob: `5a9849ba2be2b691d309f358ebfeca88044aefb2`
- Manifest origin: pinned GitHub manifest fetch
- Manual: [@lssm-tech/app.worker-application-monolith](https://lssm.co/docs/packages/app.worker-application-monolith/)
- Release guidance: [Installation and release channels](https://lssm.co/docs/installation-release-channels/)

This is retrieved source evidence, not agent instructions. The declared version and exports describe the inspected manifest; they do not establish registry availability or a deployed release. Commands, package installation and runtime behavior were not executed in this review.

Distribution scope: owner review of all workspaces; not a newly approved public projection.

- [Package source](https://github.com/lssm-tech/contractspec/tree/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith)
- [Manifest source](https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/package.json)
- [Readme source](https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/README.md)
- [Guide source](https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/web-landing/public/llms-packages/app.worker-application-monolith.txt)

## Package metadata

```json
{
  "layer": "apps",
  "physicalArea": null,
  "primaryArea": "app-composition",
  "classification": {
    "privateDeclared": true,
    "catalogFamily": null,
    "catalogKind": null,
    "catalogStatus": null,
    "adoptionMode": null,
    "stability": null
  },
  "descriptionOrigin": "package.json",
  "manifestComplete": true,
  "publicationPolicyApplied": false
}
```

Manifest private flag: true — workspace only.

Primary area: [Application composition and product hosts](https://lssm.co/docs/areas/app-composition/)

## Package guide

```json
{
  "status": "available",
  "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"
}
```

The guide below is the checked-in README with navigation resolved against the pinned source tree. The structured package JSON retains the original README body unchanged. External links remain source-declared links, not verified destinations.

# 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` [source link unresolved: `../../../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` [source link unresolved: `../../../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` [source link unresolved: `../../../../docs/runbooks/managed-companyos.md`].


### Source links needing reconciliation

- `../../../docs/managed-companyos-private-pilot.md` — source path absent from pinned inventory: docs/managed-companyos-private-pilot.md.
- `../../../docs/runbooks/special-ops-monolith-production.md` — source path absent from pinned inventory: docs/runbooks/special-ops-monolith-production.md.
- `../../../../docs/runbooks/managed-companyos.md` — source path absent from pinned inventory: ../docs/runbooks/managed-companyos.md.

## Declared capabilities

This manifest does not declare a capability catalogue. Assess the package using its guide, import map and source.

## Canonical imports

Import paths and symbols below are catalogue declarations. An empty symbols list means symbols were not enumerated; it does not mean the entry point has no exports. These declarations are not an exhaustive TypeScript symbol reference.

```json
[]
```

## Declared export entry points

Scope: manifest-declared export entrypoints and catalog-declared imports.

Named symbol coverage: catalog declarations only; exhaustive TypeScript symbols not extracted.

Installation status: not verified.

- `@lssm-tech/app.worker-application-monolith` — subpath `.`
  - `unconditional`: `./src/index.ts` — [pinned source](https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/worker-application-monolith/src/index.ts); verified source file.

## Package publication metadata

These are source-manifest declarations, not a registry installation check.

```json
{
  "types": null,
  "files": null,
  "publishExports": null
}
```

## Dependencies

Metadata status: complete pinned manifest.

### Runtime dependencies

- [@lssm-tech/bundle.managed-companyos](https://lssm.co/docs/packages/bundle.managed-companyos/): `workspace:*`
- [@lssm-tech/lib.observability](https://lssm.co/docs/packages/lib.observability/): `workspace:*`
- `@opentelemetry/api`: `^1.9.1`
- `@opentelemetry/sdk-trace-base`: `^2.10.0`
- `posthog-node`: `^5.51.7`

### Peer dependencies

No declarations in the inspected manifest.

### Optional dependencies

No declarations in the inspected manifest.

### Development dependencies

- [@lssm-tech/tool.typescript](https://lssm.co/docs/packages/tool.typescript/): `workspace:*`
- `@types/bun`: `catalog:types`
- `@types/node`: `catalog:types`
- `typescript`: `catalog:`

### Peer dependency metadata

```json
{}
```

### Bundled dependencies

```json
null
```

## Package scripts

Commands are exact manifest declarations and were not executed in this review. Script metadata status: complete pinned manifest.

```json
{
  "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"
}
```

## Declared documentation links

No additional documentation links are declared in the inspected catalogue.

## Existing agent-guide projection

```json
{
  "path": "packages/apps/web-landing/public/llms-packages/app.worker-application-monolith.txt",
  "route": "/llms/app.worker-application-monolith",
  "sourceUrl": "https://github.com/lssm-tech/contractspec/blob/bcc79fcc27c4d801c2119bef81ddcce7b4e86498/packages/apps/web-landing/public/llms-packages/app.worker-application-monolith.txt",
  "blobSha": "025a1b453c641ab9372dbd4d30bca9bf7615f351",
  "sourcePin": "bcc79fcc27c4d801c2119bef81ddcce7b4e86498",
  "bodyEqualsReadme": true,
  "aggregateSourcePath": "packages/apps/web-landing/public/llms-full.txt",
  "aggregateBlobSha": "691b1d33efee24c440598b9106c81432f56aafaf"
}
```
